civetweb.c 569 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465
  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 "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 headerNo, idx;
  11170. size_t len;
  11171. const char *sep, *curSubProtocol,
  11172. *acceptedWebSocketSubprotocol = NULL;
  11173. /* look for matching subprotocol */
  11174. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11175. /* There might be multiple headers ... */
  11176. const char *protocol = protocols[headerNo];
  11177. curSubProtocol = protocol;
  11178. /* ... and in every header there might be a , separated list */
  11179. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11180. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11181. curSubProtocol++;
  11182. sep = strchr(curSubProtocol, ',');
  11183. if (sep) {
  11184. len = (size_t)(sep - curSubProtocol);
  11185. } else {
  11186. len = strlen(curSubProtocol);
  11187. }
  11188. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11189. // COMPARE: curSubProtocol ==
  11190. // subprotocols->subprotocols[idx]
  11191. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11192. && (strncmp(curSubProtocol,
  11193. subprotocols->subprotocols[idx],
  11194. len)
  11195. == 0)) {
  11196. acceptedWebSocketSubprotocol =
  11197. subprotocols->subprotocols[idx];
  11198. break;
  11199. }
  11200. }
  11201. curSubProtocol += len;
  11202. }
  11203. }
  11204. conn->request_info.acceptedWebSocketSubprotocol =
  11205. acceptedWebSocketSubprotocol;
  11206. }
  11207. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11208. websocket_deflate_negotiate(conn);
  11209. #endif
  11210. if ((ws_connect_handler != NULL)
  11211. && (ws_connect_handler(conn, cbData) != 0)) {
  11212. /* C callback has returned non-zero, do not proceed with
  11213. * handshake.
  11214. */
  11215. /* Note that C callbacks are no longer called when Lua is
  11216. * responsible, so C can no longer filter callbacks for Lua. */
  11217. return;
  11218. }
  11219. }
  11220. #if defined(USE_LUA)
  11221. /* Step 3: No callback. Check if Lua is responsible. */
  11222. else {
  11223. /* Step 3.1: Check if Lua is responsible. */
  11224. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11225. lua_websock = match_prefix_strlen(
  11226. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11227. }
  11228. if (lua_websock) {
  11229. /* Step 3.2: Lua is responsible: call it. */
  11230. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11231. if (!conn->lua_websocket_state) {
  11232. /* Lua rejected the new client */
  11233. return;
  11234. }
  11235. }
  11236. }
  11237. #endif
  11238. /* Step 4: Check if there is a responsible websocket handler. */
  11239. if (!is_callback_resource && !lua_websock) {
  11240. /* There is no callback, and Lua is not responsible either. */
  11241. /* Reply with a 404 Not Found. We are still at a standard
  11242. * HTTP request here, before the websocket handshake, so
  11243. * we can still send standard HTTP error replies. */
  11244. mg_send_http_error(conn, 404, "%s", "Not found");
  11245. return;
  11246. }
  11247. /* Step 5: The websocket connection has been accepted */
  11248. if (!send_websocket_handshake(conn, websock_key)) {
  11249. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11250. return;
  11251. }
  11252. /* Step 6: Call the ready handler */
  11253. if (is_callback_resource) {
  11254. if (ws_ready_handler != NULL) {
  11255. ws_ready_handler(conn, cbData);
  11256. }
  11257. #if defined(USE_LUA)
  11258. } else if (lua_websock) {
  11259. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11260. /* the ready handler returned false */
  11261. return;
  11262. }
  11263. #endif
  11264. }
  11265. /* Step 7: Enter the read loop */
  11266. if (is_callback_resource) {
  11267. read_websocket(conn, ws_data_handler, cbData);
  11268. #if defined(USE_LUA)
  11269. } else if (lua_websock) {
  11270. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11271. #endif
  11272. }
  11273. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11274. /* Step 8: Close the deflate & inflate buffers */
  11275. if (conn->websocket_deflate_initialized) {
  11276. deflateEnd(&conn->websocket_deflate_state);
  11277. inflateEnd(&conn->websocket_inflate_state);
  11278. }
  11279. #endif
  11280. /* Step 9: Call the close handler */
  11281. if (ws_close_handler) {
  11282. ws_close_handler(conn, cbData);
  11283. }
  11284. }
  11285. #endif /* !USE_WEBSOCKET */
  11286. /* Is upgrade request:
  11287. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11288. * 1 = upgrade to websocket
  11289. * 2 = upgrade to HTTP/2
  11290. * -1 = upgrade to unknown protocol
  11291. */
  11292. static int
  11293. should_switch_to_protocol(const struct mg_connection *conn)
  11294. {
  11295. const char *upgrade, *connection;
  11296. /* A websocket protocoll has the following HTTP headers:
  11297. *
  11298. * Connection: Upgrade
  11299. * Upgrade: Websocket
  11300. */
  11301. connection = mg_get_header(conn, "Connection");
  11302. if (connection == NULL) {
  11303. return PROTOCOL_TYPE_HTTP1;
  11304. }
  11305. if (!mg_strcasestr(connection, "upgrade")) {
  11306. return PROTOCOL_TYPE_HTTP1;
  11307. }
  11308. upgrade = mg_get_header(conn, "Upgrade");
  11309. if (upgrade == NULL) {
  11310. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11311. return -1;
  11312. }
  11313. /* Upgrade to ... */
  11314. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11315. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11316. * "Sec-WebSocket-Version" are also required.
  11317. * Don't check them here, since even an unsupported websocket protocol
  11318. * request still IS a websocket request (in contrast to a standard HTTP
  11319. * request). It will fail later in handle_websocket_request.
  11320. */
  11321. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11322. }
  11323. if (0 != mg_strcasestr(upgrade, "h2")) {
  11324. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11325. }
  11326. /* Upgrade to another protocol */
  11327. return -1;
  11328. }
  11329. static int
  11330. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11331. {
  11332. int n;
  11333. unsigned int a, b, c, d, slash;
  11334. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11335. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11336. // integer value, but function will not report conversion
  11337. // errors; consider using 'strtol' instead
  11338. slash = 32;
  11339. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11340. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11341. // an integer value, but function will not report conversion
  11342. // errors; consider using 'strtol' instead
  11343. n = 0;
  11344. }
  11345. }
  11346. if ((n > 0) && ((size_t)n == vec->len)) {
  11347. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11348. /* IPv4 format */
  11349. if (sa->sa.sa_family == AF_INET) {
  11350. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11351. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11352. | ((uint32_t)c << 8) | (uint32_t)d;
  11353. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11354. return (ip & mask) == net;
  11355. }
  11356. return 0;
  11357. }
  11358. }
  11359. #if defined(USE_IPV6)
  11360. else {
  11361. char ad[50];
  11362. const char *p;
  11363. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11364. slash = 128;
  11365. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11366. n = 0;
  11367. }
  11368. }
  11369. if ((n <= 0) && no_strict) {
  11370. /* no square brackets? */
  11371. p = strchr(vec->ptr, '/');
  11372. if (p && (p < (vec->ptr + vec->len))) {
  11373. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11374. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11375. n += (int)(p - vec->ptr);
  11376. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11377. } else {
  11378. n = 0;
  11379. }
  11380. } else if (vec->len < sizeof(ad)) {
  11381. n = (int)vec->len;
  11382. slash = 128;
  11383. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11384. }
  11385. }
  11386. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11387. p = ad;
  11388. c = 0;
  11389. /* zone indexes are unsupported, at least two colons are needed */
  11390. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11391. if (*(p++) == ':') {
  11392. c++;
  11393. }
  11394. }
  11395. if ((*p == '\0') && (c >= 2)) {
  11396. struct sockaddr_in6 sin6;
  11397. unsigned int i;
  11398. /* for strict validation, an actual IPv6 argument is needed */
  11399. if (sa->sa.sa_family != AF_INET6) {
  11400. return 0;
  11401. }
  11402. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11403. /* IPv6 format */
  11404. for (i = 0; i < 16; i++) {
  11405. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11406. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11407. uint8_t mask = 0;
  11408. if (8 * i + 8 < slash) {
  11409. mask = 0xFFu;
  11410. } else if (8 * i < slash) {
  11411. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11412. }
  11413. if ((ip & mask) != net) {
  11414. return 0;
  11415. }
  11416. }
  11417. return 1;
  11418. }
  11419. }
  11420. }
  11421. }
  11422. #else
  11423. (void)no_strict;
  11424. #endif
  11425. /* malformed */
  11426. return -1;
  11427. }
  11428. static int
  11429. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11430. {
  11431. int throttle = 0;
  11432. struct vec vec, val;
  11433. char mult;
  11434. double v;
  11435. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11436. mult = ',';
  11437. if ((val.ptr == NULL)
  11438. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11439. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11440. // to an integer value, but function will not report
  11441. // conversion errors; consider using 'strtol' instead
  11442. || (v < 0)
  11443. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11444. && (mult != ','))) {
  11445. continue;
  11446. }
  11447. v *= (lowercase(&mult) == 'k')
  11448. ? 1024
  11449. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11450. if (vec.len == 1 && vec.ptr[0] == '*') {
  11451. throttle = (int)v;
  11452. } else {
  11453. int matched = parse_match_net(&vec, rsa, 0);
  11454. if (matched >= 0) {
  11455. /* a valid IP subnet */
  11456. if (matched) {
  11457. throttle = (int)v;
  11458. }
  11459. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11460. throttle = (int)v;
  11461. }
  11462. }
  11463. }
  11464. return throttle;
  11465. }
  11466. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11467. #include "handle_form.inl"
  11468. static int
  11469. get_first_ssl_listener_index(const struct mg_context *ctx)
  11470. {
  11471. unsigned int i;
  11472. int idx = -1;
  11473. if (ctx) {
  11474. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11475. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11476. }
  11477. }
  11478. return idx;
  11479. }
  11480. /* Return host (without port) */
  11481. static void
  11482. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11483. {
  11484. const char *host_header =
  11485. get_header(ri->http_headers, ri->num_headers, "Host");
  11486. host->ptr = NULL;
  11487. host->len = 0;
  11488. if (host_header != NULL) {
  11489. const char *pos;
  11490. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11491. * is found. */
  11492. if (*host_header == '[') {
  11493. pos = strchr(host_header, ']');
  11494. if (!pos) {
  11495. /* Malformed hostname starts with '[', but no ']' found */
  11496. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11497. return;
  11498. }
  11499. /* terminate after ']' */
  11500. host->ptr = host_header;
  11501. host->len = (size_t)(pos + 1 - host_header);
  11502. } else {
  11503. /* Otherwise, a ':' separates hostname and port number */
  11504. pos = strchr(host_header, ':');
  11505. if (pos != NULL) {
  11506. host->len = (size_t)(pos - host_header);
  11507. } else {
  11508. host->len = strlen(host_header);
  11509. }
  11510. host->ptr = host_header;
  11511. }
  11512. }
  11513. }
  11514. static int
  11515. switch_domain_context(struct mg_connection *conn)
  11516. {
  11517. struct vec host;
  11518. get_host_from_request_info(&host, &conn->request_info);
  11519. if (host.ptr) {
  11520. if (conn->ssl) {
  11521. /* This is a HTTPS connection, maybe we have a hostname
  11522. * from SNI (set in ssl_servername_callback). */
  11523. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11524. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11525. /* We are not using the default domain */
  11526. if ((strlen(sslhost) != host.len)
  11527. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11528. /* Mismatch between SNI domain and HTTP domain */
  11529. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11530. sslhost,
  11531. (int)host.len,
  11532. host.ptr);
  11533. return 0;
  11534. }
  11535. }
  11536. } else {
  11537. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11538. while (dom) {
  11539. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  11540. size_t domNameLen = strlen(domName);
  11541. if ((domNameLen == host.len)
  11542. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  11543. /* Found matching domain */
  11544. DEBUG_TRACE("HTTP domain %s found",
  11545. dom->config[AUTHENTICATION_DOMAIN]);
  11546. /* TODO: Check if this is a HTTP or HTTPS domain */
  11547. conn->dom_ctx = dom;
  11548. break;
  11549. }
  11550. mg_lock_context(conn->phys_ctx);
  11551. dom = dom->next;
  11552. mg_unlock_context(conn->phys_ctx);
  11553. }
  11554. }
  11555. DEBUG_TRACE("HTTP%s Host: %.*s",
  11556. conn->ssl ? "S" : "",
  11557. (int)host.len,
  11558. host.ptr);
  11559. } else {
  11560. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11561. return 1;
  11562. }
  11563. return 1;
  11564. }
  11565. static void
  11566. redirect_to_https_port(struct mg_connection *conn, int port)
  11567. {
  11568. char target_url[MG_BUF_LEN];
  11569. int truncated = 0;
  11570. const char *expect_proto =
  11571. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11572. /* Use "308 Permanent Redirect" */
  11573. int redirect_code = 308;
  11574. /* In any case, close the current connection */
  11575. conn->must_close = 1;
  11576. /* Send host, port, uri and (if it exists) ?query_string */
  11577. if (mg_construct_local_link(
  11578. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11579. < 0) {
  11580. truncated = 1;
  11581. } else if (conn->request_info.query_string != NULL) {
  11582. size_t slen1 = strlen(target_url);
  11583. size_t slen2 = strlen(conn->request_info.query_string);
  11584. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11585. target_url[slen1] = '?';
  11586. memcpy(target_url + slen1 + 1,
  11587. conn->request_info.query_string,
  11588. slen2);
  11589. target_url[slen1 + slen2 + 1] = 0;
  11590. } else {
  11591. truncated = 1;
  11592. }
  11593. }
  11594. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11595. * is used as buffer size) */
  11596. if (truncated) {
  11597. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11598. return;
  11599. }
  11600. /* Use redirect helper function */
  11601. mg_send_http_redirect(conn, target_url, redirect_code);
  11602. }
  11603. static void
  11604. mg_set_handler_type(struct mg_context *phys_ctx,
  11605. struct mg_domain_context *dom_ctx,
  11606. const char *uri,
  11607. int handler_type,
  11608. int is_delete_request,
  11609. mg_request_handler handler,
  11610. struct mg_websocket_subprotocols *subprotocols,
  11611. mg_websocket_connect_handler connect_handler,
  11612. mg_websocket_ready_handler ready_handler,
  11613. mg_websocket_data_handler data_handler,
  11614. mg_websocket_close_handler close_handler,
  11615. mg_authorization_handler auth_handler,
  11616. void *cbdata)
  11617. {
  11618. struct mg_handler_info *tmp_rh, **lastref;
  11619. size_t urilen = strlen(uri);
  11620. if (handler_type == WEBSOCKET_HANDLER) {
  11621. DEBUG_ASSERT(handler == NULL);
  11622. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11623. || ready_handler != NULL || data_handler != NULL
  11624. || close_handler != NULL);
  11625. DEBUG_ASSERT(auth_handler == NULL);
  11626. if (handler != NULL) {
  11627. return;
  11628. }
  11629. if (!is_delete_request && (connect_handler == NULL)
  11630. && (ready_handler == NULL) && (data_handler == NULL)
  11631. && (close_handler == NULL)) {
  11632. return;
  11633. }
  11634. if (auth_handler != NULL) {
  11635. return;
  11636. }
  11637. } else if (handler_type == REQUEST_HANDLER) {
  11638. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11639. && data_handler == NULL && close_handler == NULL);
  11640. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11641. DEBUG_ASSERT(auth_handler == NULL);
  11642. if ((connect_handler != NULL) || (ready_handler != NULL)
  11643. || (data_handler != NULL) || (close_handler != NULL)) {
  11644. return;
  11645. }
  11646. if (!is_delete_request && (handler == NULL)) {
  11647. return;
  11648. }
  11649. if (auth_handler != NULL) {
  11650. return;
  11651. }
  11652. } else if (handler_type == AUTH_HANDLER) {
  11653. DEBUG_ASSERT(handler == NULL);
  11654. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11655. && data_handler == NULL && close_handler == NULL);
  11656. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  11657. if (handler != NULL) {
  11658. return;
  11659. }
  11660. if ((connect_handler != NULL) || (ready_handler != NULL)
  11661. || (data_handler != NULL) || (close_handler != NULL)) {
  11662. return;
  11663. }
  11664. if (!is_delete_request && (auth_handler == NULL)) {
  11665. return;
  11666. }
  11667. } else {
  11668. /* Unknown handler type. */
  11669. return;
  11670. }
  11671. if (!phys_ctx || !dom_ctx) {
  11672. /* no context available */
  11673. return;
  11674. }
  11675. mg_lock_context(phys_ctx);
  11676. /* first try to find an existing handler */
  11677. do {
  11678. lastref = &(dom_ctx->handlers);
  11679. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11680. tmp_rh = tmp_rh->next) {
  11681. if (tmp_rh->handler_type == handler_type
  11682. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11683. if (!is_delete_request) {
  11684. /* update existing handler */
  11685. if (handler_type == REQUEST_HANDLER) {
  11686. /* Wait for end of use before updating */
  11687. if (tmp_rh->refcount) {
  11688. mg_unlock_context(phys_ctx);
  11689. mg_sleep(1);
  11690. mg_lock_context(phys_ctx);
  11691. /* tmp_rh might have been freed, search again. */
  11692. break;
  11693. }
  11694. /* Ok, the handler is no more use -> Update it */
  11695. tmp_rh->handler = handler;
  11696. } else if (handler_type == WEBSOCKET_HANDLER) {
  11697. tmp_rh->subprotocols = subprotocols;
  11698. tmp_rh->connect_handler = connect_handler;
  11699. tmp_rh->ready_handler = ready_handler;
  11700. tmp_rh->data_handler = data_handler;
  11701. tmp_rh->close_handler = close_handler;
  11702. } else { /* AUTH_HANDLER */
  11703. tmp_rh->auth_handler = auth_handler;
  11704. }
  11705. tmp_rh->cbdata = cbdata;
  11706. } else {
  11707. /* remove existing handler */
  11708. if (handler_type == REQUEST_HANDLER) {
  11709. /* Wait for end of use before removing */
  11710. if (tmp_rh->refcount) {
  11711. tmp_rh->removing = 1;
  11712. mg_unlock_context(phys_ctx);
  11713. mg_sleep(1);
  11714. mg_lock_context(phys_ctx);
  11715. /* tmp_rh might have been freed, search again. */
  11716. break;
  11717. }
  11718. /* Ok, the handler is no more used */
  11719. }
  11720. *lastref = tmp_rh->next;
  11721. mg_free(tmp_rh->uri);
  11722. mg_free(tmp_rh);
  11723. }
  11724. mg_unlock_context(phys_ctx);
  11725. return;
  11726. }
  11727. lastref = &(tmp_rh->next);
  11728. }
  11729. } while (tmp_rh != NULL);
  11730. if (is_delete_request) {
  11731. /* no handler to set, this was a remove request to a non-existing
  11732. * handler */
  11733. mg_unlock_context(phys_ctx);
  11734. return;
  11735. }
  11736. tmp_rh =
  11737. (struct mg_handler_info *)mg_calloc_ctx(1,
  11738. sizeof(struct mg_handler_info),
  11739. phys_ctx);
  11740. if (tmp_rh == NULL) {
  11741. mg_unlock_context(phys_ctx);
  11742. mg_cry_ctx_internal(phys_ctx,
  11743. "%s",
  11744. "Cannot create new request handler struct, OOM");
  11745. return;
  11746. }
  11747. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11748. if (!tmp_rh->uri) {
  11749. mg_unlock_context(phys_ctx);
  11750. mg_free(tmp_rh);
  11751. mg_cry_ctx_internal(phys_ctx,
  11752. "%s",
  11753. "Cannot create new request handler struct, OOM");
  11754. return;
  11755. }
  11756. tmp_rh->uri_len = urilen;
  11757. if (handler_type == REQUEST_HANDLER) {
  11758. tmp_rh->refcount = 0;
  11759. tmp_rh->removing = 0;
  11760. tmp_rh->handler = handler;
  11761. } else if (handler_type == WEBSOCKET_HANDLER) {
  11762. tmp_rh->subprotocols = subprotocols;
  11763. tmp_rh->connect_handler = connect_handler;
  11764. tmp_rh->ready_handler = ready_handler;
  11765. tmp_rh->data_handler = data_handler;
  11766. tmp_rh->close_handler = close_handler;
  11767. } else { /* AUTH_HANDLER */
  11768. tmp_rh->auth_handler = auth_handler;
  11769. }
  11770. tmp_rh->cbdata = cbdata;
  11771. tmp_rh->handler_type = handler_type;
  11772. tmp_rh->next = NULL;
  11773. *lastref = tmp_rh;
  11774. mg_unlock_context(phys_ctx);
  11775. }
  11776. void
  11777. mg_set_request_handler(struct mg_context *ctx,
  11778. const char *uri,
  11779. mg_request_handler handler,
  11780. void *cbdata)
  11781. {
  11782. mg_set_handler_type(ctx,
  11783. &(ctx->dd),
  11784. uri,
  11785. REQUEST_HANDLER,
  11786. handler == NULL,
  11787. handler,
  11788. NULL,
  11789. NULL,
  11790. NULL,
  11791. NULL,
  11792. NULL,
  11793. NULL,
  11794. cbdata);
  11795. }
  11796. void
  11797. mg_set_websocket_handler(struct mg_context *ctx,
  11798. const char *uri,
  11799. mg_websocket_connect_handler connect_handler,
  11800. mg_websocket_ready_handler ready_handler,
  11801. mg_websocket_data_handler data_handler,
  11802. mg_websocket_close_handler close_handler,
  11803. void *cbdata)
  11804. {
  11805. mg_set_websocket_handler_with_subprotocols(ctx,
  11806. uri,
  11807. NULL,
  11808. connect_handler,
  11809. ready_handler,
  11810. data_handler,
  11811. close_handler,
  11812. cbdata);
  11813. }
  11814. void
  11815. mg_set_websocket_handler_with_subprotocols(
  11816. struct mg_context *ctx,
  11817. const char *uri,
  11818. struct mg_websocket_subprotocols *subprotocols,
  11819. mg_websocket_connect_handler connect_handler,
  11820. mg_websocket_ready_handler ready_handler,
  11821. mg_websocket_data_handler data_handler,
  11822. mg_websocket_close_handler close_handler,
  11823. void *cbdata)
  11824. {
  11825. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11826. && (data_handler == NULL)
  11827. && (close_handler == NULL);
  11828. mg_set_handler_type(ctx,
  11829. &(ctx->dd),
  11830. uri,
  11831. WEBSOCKET_HANDLER,
  11832. is_delete_request,
  11833. NULL,
  11834. subprotocols,
  11835. connect_handler,
  11836. ready_handler,
  11837. data_handler,
  11838. close_handler,
  11839. NULL,
  11840. cbdata);
  11841. }
  11842. void
  11843. mg_set_auth_handler(struct mg_context *ctx,
  11844. const char *uri,
  11845. mg_authorization_handler handler,
  11846. void *cbdata)
  11847. {
  11848. mg_set_handler_type(ctx,
  11849. &(ctx->dd),
  11850. uri,
  11851. AUTH_HANDLER,
  11852. handler == NULL,
  11853. NULL,
  11854. NULL,
  11855. NULL,
  11856. NULL,
  11857. NULL,
  11858. NULL,
  11859. handler,
  11860. cbdata);
  11861. }
  11862. static int
  11863. get_request_handler(struct mg_connection *conn,
  11864. int handler_type,
  11865. mg_request_handler *handler,
  11866. struct mg_websocket_subprotocols **subprotocols,
  11867. mg_websocket_connect_handler *connect_handler,
  11868. mg_websocket_ready_handler *ready_handler,
  11869. mg_websocket_data_handler *data_handler,
  11870. mg_websocket_close_handler *close_handler,
  11871. mg_authorization_handler *auth_handler,
  11872. void **cbdata,
  11873. struct mg_handler_info **handler_info)
  11874. {
  11875. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11876. if (request_info) {
  11877. const char *uri = request_info->local_uri;
  11878. size_t urilen = strlen(uri);
  11879. struct mg_handler_info *tmp_rh;
  11880. int step, matched;
  11881. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11882. return 0;
  11883. }
  11884. mg_lock_context(conn->phys_ctx);
  11885. for (step = 0; step < 3; step++) {
  11886. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11887. tmp_rh = tmp_rh->next) {
  11888. if (tmp_rh->handler_type != handler_type) {
  11889. continue;
  11890. }
  11891. if (step == 0) {
  11892. /* first try for an exact match */
  11893. matched = (tmp_rh->uri_len == urilen)
  11894. && (strcmp(tmp_rh->uri, uri) == 0);
  11895. } else if (step == 1) {
  11896. /* next try for a partial match, we will accept
  11897. uri/something */
  11898. matched =
  11899. (tmp_rh->uri_len < urilen)
  11900. && (uri[tmp_rh->uri_len] == '/')
  11901. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  11902. } else {
  11903. /* finally try for pattern match */
  11904. matched =
  11905. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  11906. }
  11907. if (matched) {
  11908. if (handler_type == WEBSOCKET_HANDLER) {
  11909. *subprotocols = tmp_rh->subprotocols;
  11910. *connect_handler = tmp_rh->connect_handler;
  11911. *ready_handler = tmp_rh->ready_handler;
  11912. *data_handler = tmp_rh->data_handler;
  11913. *close_handler = tmp_rh->close_handler;
  11914. } else if (handler_type == REQUEST_HANDLER) {
  11915. if (tmp_rh->removing) {
  11916. /* Treat as none found */
  11917. step = 2;
  11918. break;
  11919. }
  11920. *handler = tmp_rh->handler;
  11921. /* Acquire handler and give it back */
  11922. tmp_rh->refcount++;
  11923. *handler_info = tmp_rh;
  11924. } else { /* AUTH_HANDLER */
  11925. *auth_handler = tmp_rh->auth_handler;
  11926. }
  11927. *cbdata = tmp_rh->cbdata;
  11928. mg_unlock_context(conn->phys_ctx);
  11929. return 1;
  11930. }
  11931. }
  11932. }
  11933. mg_unlock_context(conn->phys_ctx);
  11934. }
  11935. return 0; /* none found */
  11936. }
  11937. /* Check if the script file is in a path, allowed for script files.
  11938. * This can be used if uploading files is possible not only for the server
  11939. * admin, and the upload mechanism does not check the file extension.
  11940. */
  11941. static int
  11942. is_in_script_path(const struct mg_connection *conn, const char *path)
  11943. {
  11944. /* TODO (Feature): Add config value for allowed script path.
  11945. * Default: All allowed. */
  11946. (void)conn;
  11947. (void)path;
  11948. return 1;
  11949. }
  11950. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  11951. static int
  11952. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  11953. int bits,
  11954. char *data,
  11955. size_t len,
  11956. void *cbdata)
  11957. {
  11958. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11959. if (pcallbacks->websocket_data) {
  11960. return pcallbacks->websocket_data(conn, bits, data, len);
  11961. }
  11962. /* No handler set - assume "OK" */
  11963. return 1;
  11964. }
  11965. static void
  11966. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  11967. void *cbdata)
  11968. {
  11969. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11970. if (pcallbacks->connection_close) {
  11971. pcallbacks->connection_close(conn);
  11972. }
  11973. }
  11974. #endif
  11975. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  11976. */
  11977. static void
  11978. release_handler_ref(struct mg_connection *conn,
  11979. struct mg_handler_info *handler_info)
  11980. {
  11981. if (handler_info != NULL) {
  11982. /* Use context lock for ref counter */
  11983. mg_lock_context(conn->phys_ctx);
  11984. handler_info->refcount--;
  11985. mg_unlock_context(conn->phys_ctx);
  11986. }
  11987. }
  11988. /* This is the heart of the Civetweb's logic.
  11989. * This function is called when the request is read, parsed and validated,
  11990. * and Civetweb must decide what action to take: serve a file, or
  11991. * a directory, or call embedded function, etcetera. */
  11992. static void
  11993. handle_request(struct mg_connection *conn)
  11994. {
  11995. struct mg_request_info *ri = &conn->request_info;
  11996. char path[UTF8_PATH_MAX];
  11997. int uri_len, ssl_index;
  11998. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11999. is_put_or_delete_request = 0, is_callback_resource = 0,
  12000. is_template_text_file = 0;
  12001. int i;
  12002. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12003. mg_request_handler callback_handler = NULL;
  12004. struct mg_handler_info *handler_info = NULL;
  12005. struct mg_websocket_subprotocols *subprotocols;
  12006. mg_websocket_connect_handler ws_connect_handler = NULL;
  12007. mg_websocket_ready_handler ws_ready_handler = NULL;
  12008. mg_websocket_data_handler ws_data_handler = NULL;
  12009. mg_websocket_close_handler ws_close_handler = NULL;
  12010. void *callback_data = NULL;
  12011. mg_authorization_handler auth_handler = NULL;
  12012. void *auth_callback_data = NULL;
  12013. int handler_type;
  12014. time_t curtime = time(NULL);
  12015. char date[64];
  12016. char *tmp;
  12017. path[0] = 0;
  12018. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12019. conn->request_state = 0;
  12020. /* 1. get the request url */
  12021. /* 1.1. split into url and query string */
  12022. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12023. != NULL) {
  12024. *((char *)conn->request_info.query_string++) = '\0';
  12025. }
  12026. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12027. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12028. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12029. if (ssl_index >= 0) {
  12030. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12031. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12032. redirect_to_https_port(conn, port);
  12033. } else {
  12034. /* A http to https forward port has been specified,
  12035. * but no https port to forward to. */
  12036. mg_send_http_error(conn,
  12037. 503,
  12038. "%s",
  12039. "Error: SSL forward not configured properly");
  12040. mg_cry_internal(conn,
  12041. "%s",
  12042. "Can not redirect to SSL, no SSL port available");
  12043. }
  12044. return;
  12045. }
  12046. uri_len = (int)strlen(ri->local_uri);
  12047. /* 1.3. decode url (if config says so) */
  12048. if (should_decode_url(conn)) {
  12049. mg_url_decode(
  12050. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12051. }
  12052. /* URL decode the query-string only if explicity set in the configuration */
  12053. if (conn->request_info.query_string) {
  12054. if (should_decode_query_string(conn)) {
  12055. url_decode_in_place((char *)conn->request_info.query_string);
  12056. }
  12057. }
  12058. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12059. * possible. The fact that we cleaned the URI is stored in that the
  12060. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12061. * ri->local_uri_raw still points to memory allocated in
  12062. * worker_thread_run(). ri->local_uri is private to the request so we
  12063. * don't have to use preallocated memory here. */
  12064. tmp = mg_strdup(ri->local_uri_raw);
  12065. if (!tmp) {
  12066. /* Out of memory. We cannot do anything reasonable here. */
  12067. return;
  12068. }
  12069. remove_dot_segments(tmp);
  12070. ri->local_uri = tmp;
  12071. /* step 1. completed, the url is known now */
  12072. DEBUG_TRACE("URL: %s", ri->local_uri);
  12073. /* 2. if this ip has limited speed, set it for this connection */
  12074. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12075. &conn->client.rsa,
  12076. ri->local_uri);
  12077. /* 3. call a "handle everything" callback, if registered */
  12078. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12079. /* Note that since V1.7 the "begin_request" function is called
  12080. * before an authorization check. If an authorization check is
  12081. * required, use a request_handler instead. */
  12082. i = conn->phys_ctx->callbacks.begin_request(conn);
  12083. if (i > 0) {
  12084. /* callback already processed the request. Store the
  12085. return value as a status code for the access log. */
  12086. conn->status_code = i;
  12087. if (!conn->must_close) {
  12088. discard_unread_request_data(conn);
  12089. }
  12090. return;
  12091. } else if (i == 0) {
  12092. /* civetweb should process the request */
  12093. } else {
  12094. /* unspecified - may change with the next version */
  12095. return;
  12096. }
  12097. }
  12098. /* request not yet handled by a handler or redirect, so the request
  12099. * is processed here */
  12100. /* 4. Check for CORS preflight requests and handle them (if configured).
  12101. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12102. */
  12103. if (!strcmp(ri->request_method, "OPTIONS")) {
  12104. /* Send a response to CORS preflights only if
  12105. * access_control_allow_methods is not NULL and not an empty string.
  12106. * In this case, scripts can still handle CORS. */
  12107. const char *cors_meth_cfg =
  12108. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12109. const char *cors_orig_cfg =
  12110. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12111. const char *cors_origin =
  12112. get_header(ri->http_headers, ri->num_headers, "Origin");
  12113. const char *cors_acrm = get_header(ri->http_headers,
  12114. ri->num_headers,
  12115. "Access-Control-Request-Method");
  12116. /* Todo: check if cors_origin is in cors_orig_cfg.
  12117. * Or, let the client check this. */
  12118. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12119. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12120. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12121. /* This is a valid CORS preflight, and the server is configured
  12122. * to handle it automatically. */
  12123. const char *cors_acrh =
  12124. get_header(ri->http_headers,
  12125. ri->num_headers,
  12126. "Access-Control-Request-Headers");
  12127. gmt_time_string(date, sizeof(date), &curtime);
  12128. mg_printf(conn,
  12129. "HTTP/1.1 200 OK\r\n"
  12130. "Date: %s\r\n"
  12131. "Access-Control-Allow-Origin: %s\r\n"
  12132. "Access-Control-Allow-Methods: %s\r\n"
  12133. "Content-Length: 0\r\n"
  12134. "Connection: %s\r\n",
  12135. date,
  12136. cors_orig_cfg,
  12137. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12138. suggest_connection_header(conn));
  12139. if (cors_acrh != NULL) {
  12140. /* CORS request is asking for additional headers */
  12141. const char *cors_hdr_cfg =
  12142. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12143. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12144. /* Allow only if access_control_allow_headers is
  12145. * not NULL and not an empty string. If this
  12146. * configuration is set to *, allow everything.
  12147. * Otherwise this configuration must be a list
  12148. * of allowed HTTP header names. */
  12149. mg_printf(conn,
  12150. "Access-Control-Allow-Headers: %s\r\n",
  12151. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12152. : cors_hdr_cfg));
  12153. }
  12154. }
  12155. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12156. mg_printf(conn, "\r\n");
  12157. return;
  12158. }
  12159. }
  12160. /* 5. interpret the url to find out how the request must be handled
  12161. */
  12162. /* 5.1. first test, if the request targets the regular http(s)://
  12163. * protocol namespace or the websocket ws(s):// protocol namespace.
  12164. */
  12165. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12166. #if defined(USE_WEBSOCKET)
  12167. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12168. #else
  12169. handler_type = REQUEST_HANDLER;
  12170. #endif /* defined(USE_WEBSOCKET) */
  12171. if (is_websocket_request) {
  12172. HTTP1_only;
  12173. }
  12174. /* 5.2. check if the request will be handled by a callback */
  12175. if (get_request_handler(conn,
  12176. handler_type,
  12177. &callback_handler,
  12178. &subprotocols,
  12179. &ws_connect_handler,
  12180. &ws_ready_handler,
  12181. &ws_data_handler,
  12182. &ws_close_handler,
  12183. NULL,
  12184. &callback_data,
  12185. &handler_info)) {
  12186. /* 5.2.1. A callback will handle this request. All requests
  12187. * handled by a callback have to be considered as requests
  12188. * to a script resource. */
  12189. is_callback_resource = 1;
  12190. is_script_resource = 1;
  12191. is_put_or_delete_request = is_put_or_delete_method(conn);
  12192. } else {
  12193. no_callback_resource:
  12194. /* 5.2.2. No callback is responsible for this request. The URI
  12195. * addresses a file based resource (static content or Lua/cgi
  12196. * scripts in the file system). */
  12197. is_callback_resource = 0;
  12198. interpret_uri(conn,
  12199. path,
  12200. sizeof(path),
  12201. &file.stat,
  12202. &is_found,
  12203. &is_script_resource,
  12204. &is_websocket_request,
  12205. &is_put_or_delete_request,
  12206. &is_template_text_file);
  12207. }
  12208. /* 6. authorization check */
  12209. /* 6.1. a custom authorization handler is installed */
  12210. if (get_request_handler(conn,
  12211. AUTH_HANDLER,
  12212. NULL,
  12213. NULL,
  12214. NULL,
  12215. NULL,
  12216. NULL,
  12217. NULL,
  12218. &auth_handler,
  12219. &auth_callback_data,
  12220. NULL)) {
  12221. if (!auth_handler(conn, auth_callback_data)) {
  12222. /* Callback handler will not be used anymore. Release it */
  12223. release_handler_ref(conn, handler_info);
  12224. return;
  12225. }
  12226. } else if (is_put_or_delete_request && !is_script_resource
  12227. && !is_callback_resource) {
  12228. HTTP1_only;
  12229. /* 6.2. this request is a PUT/DELETE to a real file */
  12230. /* 6.2.1. thus, the server must have real files */
  12231. #if defined(NO_FILES)
  12232. if (1) {
  12233. #else
  12234. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12235. #endif
  12236. /* This code path will not be called for request handlers */
  12237. DEBUG_ASSERT(handler_info == NULL);
  12238. /* This server does not have any real files, thus the
  12239. * PUT/DELETE methods are not valid. */
  12240. mg_send_http_error(conn,
  12241. 405,
  12242. "%s method not allowed",
  12243. conn->request_info.request_method);
  12244. return;
  12245. }
  12246. #if !defined(NO_FILES)
  12247. /* 6.2.2. Check if put authorization for static files is
  12248. * available.
  12249. */
  12250. if (!is_authorized_for_put(conn)) {
  12251. send_authorization_request(conn, NULL);
  12252. return;
  12253. }
  12254. #endif
  12255. } else {
  12256. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12257. * or it is a PUT or DELETE request to a resource that does not
  12258. * correspond to a file. Check authorization. */
  12259. if (!check_authorization(conn, path)) {
  12260. send_authorization_request(conn, NULL);
  12261. /* Callback handler will not be used anymore. Release it */
  12262. release_handler_ref(conn, handler_info);
  12263. return;
  12264. }
  12265. }
  12266. /* request is authorized or does not need authorization */
  12267. /* 7. check if there are request handlers for this uri */
  12268. if (is_callback_resource) {
  12269. HTTP1_only;
  12270. if (!is_websocket_request) {
  12271. i = callback_handler(conn, callback_data);
  12272. /* Callback handler will not be used anymore. Release it */
  12273. release_handler_ref(conn, handler_info);
  12274. if (i > 0) {
  12275. /* Do nothing, callback has served the request. Store
  12276. * then return value as status code for the log and discard
  12277. * all data from the client not used by the callback. */
  12278. conn->status_code = i;
  12279. if (!conn->must_close) {
  12280. discard_unread_request_data(conn);
  12281. }
  12282. } else {
  12283. /* The handler did NOT handle the request. */
  12284. /* Some proper reactions would be:
  12285. * a) close the connections without sending anything
  12286. * b) send a 404 not found
  12287. * c) try if there is a file matching the URI
  12288. * It would be possible to do a, b or c in the callback
  12289. * implementation, and return 1 - we cannot do anything
  12290. * here, that is not possible in the callback.
  12291. *
  12292. * TODO: What would be the best reaction here?
  12293. * (Note: The reaction may change, if there is a better
  12294. * idea.)
  12295. */
  12296. /* For the moment, use option c: We look for a proper file,
  12297. * but since a file request is not always a script resource,
  12298. * the authorization check might be different. */
  12299. interpret_uri(conn,
  12300. path,
  12301. sizeof(path),
  12302. &file.stat,
  12303. &is_found,
  12304. &is_script_resource,
  12305. &is_websocket_request,
  12306. &is_put_or_delete_request,
  12307. &is_template_text_file);
  12308. callback_handler = NULL;
  12309. /* Here we are at a dead end:
  12310. * According to URI matching, a callback should be
  12311. * responsible for handling the request,
  12312. * we called it, but the callback declared itself
  12313. * not responsible.
  12314. * We use a goto here, to get out of this dead end,
  12315. * and continue with the default handling.
  12316. * A goto here is simpler and better to understand
  12317. * than some curious loop. */
  12318. goto no_callback_resource;
  12319. }
  12320. } else {
  12321. #if defined(USE_WEBSOCKET)
  12322. handle_websocket_request(conn,
  12323. path,
  12324. is_callback_resource,
  12325. subprotocols,
  12326. ws_connect_handler,
  12327. ws_ready_handler,
  12328. ws_data_handler,
  12329. ws_close_handler,
  12330. callback_data);
  12331. #endif
  12332. }
  12333. return;
  12334. }
  12335. /* 8. handle websocket requests */
  12336. #if defined(USE_WEBSOCKET)
  12337. if (is_websocket_request) {
  12338. HTTP1_only;
  12339. if (is_script_resource) {
  12340. if (is_in_script_path(conn, path)) {
  12341. /* Websocket Lua script */
  12342. handle_websocket_request(conn,
  12343. path,
  12344. 0 /* Lua Script */,
  12345. NULL,
  12346. NULL,
  12347. NULL,
  12348. NULL,
  12349. NULL,
  12350. conn->phys_ctx->user_data);
  12351. } else {
  12352. /* Script was in an illegal path */
  12353. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12354. }
  12355. } else {
  12356. mg_send_http_error(conn, 404, "%s", "Not found");
  12357. }
  12358. return;
  12359. } else
  12360. #endif
  12361. #if defined(NO_FILES)
  12362. /* 9a. In case the server uses only callbacks, this uri is
  12363. * unknown.
  12364. * Then, all request handling ends here. */
  12365. mg_send_http_error(conn, 404, "%s", "Not Found");
  12366. #else
  12367. /* 9b. This request is either for a static file or resource handled
  12368. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12369. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12370. mg_send_http_error(conn, 404, "%s", "Not Found");
  12371. return;
  12372. }
  12373. /* 10. Request is handled by a script */
  12374. if (is_script_resource) {
  12375. HTTP1_only;
  12376. handle_file_based_request(conn, path, &file);
  12377. return;
  12378. }
  12379. /* 11. Handle put/delete/mkcol requests */
  12380. if (is_put_or_delete_request) {
  12381. HTTP1_only;
  12382. /* 11.1. PUT method */
  12383. if (!strcmp(ri->request_method, "PUT")) {
  12384. put_file(conn, path);
  12385. return;
  12386. }
  12387. /* 11.2. DELETE method */
  12388. if (!strcmp(ri->request_method, "DELETE")) {
  12389. delete_file(conn, path);
  12390. return;
  12391. }
  12392. /* 11.3. MKCOL method */
  12393. if (!strcmp(ri->request_method, "MKCOL")) {
  12394. mkcol(conn, path);
  12395. return;
  12396. }
  12397. /* 11.4. PATCH method
  12398. * This method is not supported for static resources,
  12399. * only for scripts (Lua, CGI) and callbacks. */
  12400. mg_send_http_error(conn,
  12401. 405,
  12402. "%s method not allowed",
  12403. conn->request_info.request_method);
  12404. return;
  12405. }
  12406. /* 11. File does not exist, or it was configured that it should be
  12407. * hidden */
  12408. if (!is_found || (must_hide_file(conn, path))) {
  12409. mg_send_http_error(conn, 404, "%s", "Not found");
  12410. return;
  12411. }
  12412. /* 12. Directory uris should end with a slash */
  12413. if (file.stat.is_directory && (uri_len > 0)
  12414. && (ri->local_uri[uri_len - 1] != '/')) {
  12415. size_t len = strlen(ri->request_uri);
  12416. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12417. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12418. if (!new_path) {
  12419. mg_send_http_error(conn, 500, "out or memory");
  12420. } else {
  12421. memcpy(new_path, ri->request_uri, len);
  12422. new_path[len] = '/';
  12423. new_path[len + 1] = 0;
  12424. if (ri->query_string) {
  12425. new_path[len + 1] = '?';
  12426. /* Copy query string including terminating zero */
  12427. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12428. }
  12429. mg_send_http_redirect(conn, new_path, 301);
  12430. mg_free(new_path);
  12431. }
  12432. return;
  12433. }
  12434. /* 13. Handle other methods than GET/HEAD */
  12435. /* 13.1. Handle PROPFIND */
  12436. if (!strcmp(ri->request_method, "PROPFIND")) {
  12437. handle_propfind(conn, path, &file.stat);
  12438. return;
  12439. }
  12440. /* 13.2. Handle OPTIONS for files */
  12441. if (!strcmp(ri->request_method, "OPTIONS")) {
  12442. /* This standard handler is only used for real files.
  12443. * Scripts should support the OPTIONS method themselves, to allow a
  12444. * maximum flexibility.
  12445. * Lua and CGI scripts may fully support CORS this way (including
  12446. * preflights). */
  12447. send_options(conn);
  12448. return;
  12449. }
  12450. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12451. if ((0 != strcmp(ri->request_method, "GET"))
  12452. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12453. mg_send_http_error(conn,
  12454. 405,
  12455. "%s method not allowed",
  12456. conn->request_info.request_method);
  12457. return;
  12458. }
  12459. /* 14. directories */
  12460. if (file.stat.is_directory) {
  12461. /* Substitute files have already been handled above. */
  12462. /* Here we can either generate and send a directory listing,
  12463. * or send an "access denied" error. */
  12464. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12465. "yes")) {
  12466. handle_directory_request(conn, path);
  12467. } else {
  12468. mg_send_http_error(conn,
  12469. 403,
  12470. "%s",
  12471. "Error: Directory listing denied");
  12472. }
  12473. return;
  12474. }
  12475. /* 15. Files with search/replace patterns: LSP and SSI */
  12476. if (is_template_text_file) {
  12477. HTTP1_only;
  12478. handle_file_based_request(conn, path, &file);
  12479. return;
  12480. }
  12481. /* 16. Static file - maybe cached */
  12482. #if !defined(NO_CACHING)
  12483. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12484. /* Send 304 "Not Modified" - this must not send any body data */
  12485. handle_not_modified_static_file_request(conn, &file);
  12486. return;
  12487. }
  12488. #endif /* !NO_CACHING */
  12489. /* 17. Static file - not cached */
  12490. handle_static_file_request(conn, path, &file, NULL, NULL);
  12491. #endif /* !defined(NO_FILES) */
  12492. }
  12493. #if !defined(NO_FILESYSTEMS)
  12494. static void
  12495. handle_file_based_request(struct mg_connection *conn,
  12496. const char *path,
  12497. struct mg_file *file)
  12498. {
  12499. #if !defined(NO_CGI)
  12500. unsigned char cgi_config_idx, inc, max;
  12501. #endif
  12502. if (!conn || !conn->dom_ctx) {
  12503. return;
  12504. }
  12505. #if defined(USE_LUA)
  12506. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12507. path)
  12508. > 0) {
  12509. if (is_in_script_path(conn, path)) {
  12510. /* Lua server page: an SSI like page containing mostly plain
  12511. * html code plus some tags with server generated contents. */
  12512. handle_lsp_request(conn, path, file, NULL);
  12513. } else {
  12514. /* Script was in an illegal path */
  12515. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12516. }
  12517. return;
  12518. }
  12519. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  12520. > 0) {
  12521. if (is_in_script_path(conn, path)) {
  12522. /* Lua in-server module script: a CGI like script used to
  12523. * generate the entire reply. */
  12524. mg_exec_lua_script(conn, path, NULL);
  12525. } else {
  12526. /* Script was in an illegal path */
  12527. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12528. }
  12529. return;
  12530. }
  12531. #endif
  12532. #if defined(USE_DUKTAPE)
  12533. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12534. path)
  12535. > 0) {
  12536. if (is_in_script_path(conn, path)) {
  12537. /* Call duktape to generate the page */
  12538. mg_exec_duktape_script(conn, path);
  12539. } else {
  12540. /* Script was in an illegal path */
  12541. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12542. }
  12543. return;
  12544. }
  12545. #endif
  12546. #if !defined(NO_CGI)
  12547. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  12548. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  12549. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  12550. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  12551. if (match_prefix_strlen(
  12552. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  12553. path)
  12554. > 0) {
  12555. if (is_in_script_path(conn, path)) {
  12556. /* CGI scripts may support all HTTP methods */
  12557. handle_cgi_request(conn, path, 0);
  12558. } else {
  12559. /* Script was in an illegal path */
  12560. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12561. }
  12562. return;
  12563. }
  12564. }
  12565. }
  12566. #endif /* !NO_CGI */
  12567. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  12568. if (is_in_script_path(conn, path)) {
  12569. handle_ssi_file_request(conn, path, file);
  12570. } else {
  12571. /* Script was in an illegal path */
  12572. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12573. }
  12574. return;
  12575. }
  12576. #if !defined(NO_CACHING)
  12577. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  12578. /* Send 304 "Not Modified" - this must not send any body data */
  12579. handle_not_modified_static_file_request(conn, file);
  12580. return;
  12581. }
  12582. #endif /* !NO_CACHING */
  12583. handle_static_file_request(conn, path, file, NULL, NULL);
  12584. }
  12585. #endif /* NO_FILESYSTEMS */
  12586. static void
  12587. close_all_listening_sockets(struct mg_context *ctx)
  12588. {
  12589. unsigned int i;
  12590. if (!ctx) {
  12591. return;
  12592. }
  12593. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12594. closesocket(ctx->listening_sockets[i].sock);
  12595. #if defined(USE_X_DOM_SOCKET)
  12596. /* For unix domain sockets, the socket name represents a file that has
  12597. * to be deleted. */
  12598. /* See
  12599. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12600. */
  12601. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12602. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12603. IGNORE_UNUSED_RESULT(
  12604. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12605. }
  12606. #endif
  12607. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12608. }
  12609. mg_free(ctx->listening_sockets);
  12610. ctx->listening_sockets = NULL;
  12611. mg_free(ctx->listening_socket_fds);
  12612. ctx->listening_socket_fds = NULL;
  12613. }
  12614. /* Valid listening port specification is: [ip_address:]port[s]
  12615. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12616. * Examples for IPv6: [::]:80, [::1]:80,
  12617. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12618. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12619. * In order to bind to both, IPv4 and IPv6, you can either add
  12620. * both ports using 8080,[::]:8080, or the short form +8080.
  12621. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12622. * one only accepting IPv4 the other only IPv6. +8080 creates
  12623. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12624. * environment, they might work differently, or might not work
  12625. * at all - it must be tested what options work best in the
  12626. * relevant network environment.
  12627. */
  12628. static int
  12629. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12630. {
  12631. unsigned int a, b, c, d;
  12632. unsigned port;
  12633. unsigned long portUL;
  12634. int ch, len;
  12635. const char *cb;
  12636. char *endptr;
  12637. #if defined(USE_IPV6)
  12638. char buf[100] = {0};
  12639. #endif
  12640. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12641. * Also, all-zeroes in the socket address means binding to all addresses
  12642. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12643. memset(so, 0, sizeof(*so));
  12644. so->lsa.sin.sin_family = AF_INET;
  12645. *ip_version = 0;
  12646. /* Initialize len as invalid. */
  12647. port = 0;
  12648. len = 0;
  12649. /* Test for different ways to format this string */
  12650. if (sscanf(vec->ptr,
  12651. "%u.%u.%u.%u:%u%n",
  12652. &a,
  12653. &b,
  12654. &c,
  12655. &d,
  12656. &port,
  12657. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12658. // to an integer value, but function will not report
  12659. // conversion errors; consider using 'strtol' instead
  12660. == 5) {
  12661. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12662. so->lsa.sin.sin_addr.s_addr =
  12663. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12664. so->lsa.sin.sin_port = htons((uint16_t)port);
  12665. *ip_version = 4;
  12666. #if defined(USE_IPV6)
  12667. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12668. && ((size_t)len <= vec->len)
  12669. && mg_inet_pton(
  12670. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12671. /* IPv6 address, examples: see above */
  12672. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12673. */
  12674. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12675. *ip_version = 6;
  12676. #endif
  12677. } else if ((vec->ptr[0] == '+')
  12678. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  12679. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12680. // string to an integer value, but function will not
  12681. // report conversion errors; consider using 'strtol'
  12682. // instead
  12683. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12684. /* Add 1 to len for the + character we skipped before */
  12685. len++;
  12686. #if defined(USE_IPV6)
  12687. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12688. so->lsa.sin6.sin6_family = AF_INET6;
  12689. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12690. *ip_version = 4 + 6;
  12691. #else
  12692. /* Bind to IPv4 only, since IPv6 is not built in. */
  12693. so->lsa.sin.sin_port = htons((uint16_t)port);
  12694. *ip_version = 4;
  12695. #endif
  12696. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12697. && (vec->ptr != endptr)) {
  12698. len = (int)(endptr - vec->ptr);
  12699. port = (uint16_t)portUL;
  12700. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12701. so->lsa.sin.sin_port = htons((uint16_t)port);
  12702. *ip_version = 4;
  12703. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12704. /* String could be a hostname. This check algotithm
  12705. * will only work for RFC 952 compliant hostnames,
  12706. * starting with a letter, containing only letters,
  12707. * digits and hyphen ('-'). Newer specs may allow
  12708. * more, but this is not guaranteed here, since it
  12709. * may interfere with rules for port option lists. */
  12710. /* According to RFC 1035, hostnames are restricted to 255 characters
  12711. * in total (63 between two dots). */
  12712. char hostname[256];
  12713. size_t hostnlen = (size_t)(cb - vec->ptr);
  12714. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12715. /* This would be invalid in any case */
  12716. *ip_version = 0;
  12717. return 0;
  12718. }
  12719. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12720. if (mg_inet_pton(
  12721. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12722. if (sscanf(cb + 1, "%u%n", &port, &len)
  12723. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  12724. // string to an integer value, but function will not
  12725. // report conversion errors; consider using 'strtol'
  12726. // instead
  12727. *ip_version = 4;
  12728. so->lsa.sin.sin_port = htons((uint16_t)port);
  12729. len += (int)(hostnlen + 1);
  12730. } else {
  12731. len = 0;
  12732. }
  12733. #if defined(USE_IPV6)
  12734. } else if (mg_inet_pton(AF_INET6,
  12735. hostname,
  12736. &so->lsa.sin6,
  12737. sizeof(so->lsa.sin6),
  12738. 1)) {
  12739. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12740. *ip_version = 6;
  12741. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12742. len += (int)(hostnlen + 1);
  12743. } else {
  12744. len = 0;
  12745. }
  12746. #endif
  12747. } else {
  12748. len = 0;
  12749. }
  12750. #if defined(USE_X_DOM_SOCKET)
  12751. } else if (vec->ptr[0] == 'x') {
  12752. /* unix (linux) domain socket */
  12753. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  12754. len = vec->len;
  12755. so->lsa.sun.sun_family = AF_UNIX;
  12756. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  12757. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  12758. port = 0;
  12759. *ip_version = 99;
  12760. } else {
  12761. /* String too long */
  12762. len = 0;
  12763. }
  12764. #endif
  12765. } else {
  12766. /* Parsing failure. */
  12767. len = 0;
  12768. }
  12769. /* sscanf and the option splitting code ensure the following condition
  12770. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12771. if ((len > 0) && is_valid_port(port)
  12772. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  12773. /* Next character after the port number */
  12774. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12775. so->is_ssl = (ch == 's');
  12776. so->ssl_redir = (ch == 'r');
  12777. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12778. return 1;
  12779. }
  12780. }
  12781. /* Reset ip_version to 0 if there is an error */
  12782. *ip_version = 0;
  12783. return 0;
  12784. }
  12785. /* Is there any SSL port in use? */
  12786. static int
  12787. is_ssl_port_used(const char *ports)
  12788. {
  12789. if (ports) {
  12790. /* There are several different allowed syntax variants:
  12791. * - "80" for a single port using every network interface
  12792. * - "localhost:80" for a single port using only localhost
  12793. * - "80,localhost:8080" for two ports, one bound to localhost
  12794. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12795. * to IPv4 localhost, one to IPv6 localhost
  12796. * - "+80" use port 80 for IPv4 and IPv6
  12797. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12798. * for both: IPv4 and IPv4
  12799. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12800. * additionally port 8080 bound to localhost connections
  12801. *
  12802. * If we just look for 's' anywhere in the string, "localhost:80"
  12803. * will be detected as SSL (false positive).
  12804. * Looking for 's' after a digit may cause false positives in
  12805. * "my24service:8080".
  12806. * Looking from 's' backward if there are only ':' and numbers
  12807. * before will not work for "24service:8080" (non SSL, port 8080)
  12808. * or "24s" (SSL, port 24).
  12809. *
  12810. * Remark: Initially hostnames were not allowed to start with a
  12811. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12812. * Section 2.1).
  12813. *
  12814. * To get this correct, the entire string must be parsed as a whole,
  12815. * reading it as a list element for element and parsing with an
  12816. * algorithm equivalent to parse_port_string.
  12817. *
  12818. * In fact, we use local interface names here, not arbitrary
  12819. * hostnames, so in most cases the only name will be "localhost".
  12820. *
  12821. * So, for now, we use this simple algorithm, that may still return
  12822. * a false positive in bizarre cases.
  12823. */
  12824. int i;
  12825. int portslen = (int)strlen(ports);
  12826. char prevIsNumber = 0;
  12827. for (i = 0; i < portslen; i++) {
  12828. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12829. return 1;
  12830. }
  12831. if (ports[i] >= '0' && ports[i] <= '9') {
  12832. prevIsNumber = 1;
  12833. } else {
  12834. prevIsNumber = 0;
  12835. }
  12836. }
  12837. }
  12838. return 0;
  12839. }
  12840. static int
  12841. set_ports_option(struct mg_context *phys_ctx)
  12842. {
  12843. const char *list;
  12844. int on = 1;
  12845. #if defined(USE_IPV6)
  12846. int off = 0;
  12847. #endif
  12848. struct vec vec;
  12849. struct socket so, *ptr;
  12850. struct mg_pollfd *pfd;
  12851. union usa usa;
  12852. socklen_t len;
  12853. int ip_version;
  12854. int portsTotal = 0;
  12855. int portsOk = 0;
  12856. const char *opt_txt;
  12857. long opt_listen_backlog;
  12858. if (!phys_ctx) {
  12859. return 0;
  12860. }
  12861. memset(&so, 0, sizeof(so));
  12862. memset(&usa, 0, sizeof(usa));
  12863. len = sizeof(usa);
  12864. list = phys_ctx->dd.config[LISTENING_PORTS];
  12865. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12866. portsTotal++;
  12867. if (!parse_port_string(&vec, &so, &ip_version)) {
  12868. mg_cry_ctx_internal(
  12869. phys_ctx,
  12870. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12871. (int)vec.len,
  12872. vec.ptr,
  12873. portsTotal,
  12874. "[IP_ADDRESS:]PORT[s|r]");
  12875. continue;
  12876. }
  12877. #if !defined(NO_SSL)
  12878. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12879. mg_cry_ctx_internal(phys_ctx,
  12880. "Cannot add SSL socket (entry %i)",
  12881. portsTotal);
  12882. continue;
  12883. }
  12884. #endif
  12885. /* Create socket. */
  12886. /* For a list of protocol numbers (e.g., TCP==6) see:
  12887. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  12888. */
  12889. if ((so.sock =
  12890. socket(so.lsa.sa.sa_family,
  12891. SOCK_STREAM,
  12892. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  12893. == INVALID_SOCKET) {
  12894. mg_cry_ctx_internal(phys_ctx,
  12895. "cannot create socket (entry %i)",
  12896. portsTotal);
  12897. continue;
  12898. }
  12899. #if defined(_WIN32)
  12900. /* Windows SO_REUSEADDR lets many procs binds to a
  12901. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12902. * if someone already has the socket -- DTL */
  12903. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12904. * Windows might need a few seconds before
  12905. * the same port can be used again in the
  12906. * same process, so a short Sleep may be
  12907. * required between mg_stop and mg_start.
  12908. */
  12909. if (setsockopt(so.sock,
  12910. SOL_SOCKET,
  12911. SO_EXCLUSIVEADDRUSE,
  12912. (SOCK_OPT_TYPE)&on,
  12913. sizeof(on))
  12914. != 0) {
  12915. /* Set reuse option, but don't abort on errors. */
  12916. mg_cry_ctx_internal(
  12917. phys_ctx,
  12918. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12919. portsTotal);
  12920. }
  12921. #else
  12922. if (setsockopt(so.sock,
  12923. SOL_SOCKET,
  12924. SO_REUSEADDR,
  12925. (SOCK_OPT_TYPE)&on,
  12926. sizeof(on))
  12927. != 0) {
  12928. /* Set reuse option, but don't abort on errors. */
  12929. mg_cry_ctx_internal(
  12930. phys_ctx,
  12931. "cannot set socket option SO_REUSEADDR (entry %i)",
  12932. portsTotal);
  12933. }
  12934. #endif
  12935. #if defined(USE_X_DOM_SOCKET)
  12936. if (ip_version == 99) {
  12937. /* Unix domain socket */
  12938. } else
  12939. #endif
  12940. if (ip_version > 4) {
  12941. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12942. #if defined(USE_IPV6)
  12943. if (ip_version > 6) {
  12944. if (so.lsa.sa.sa_family == AF_INET6
  12945. && setsockopt(so.sock,
  12946. IPPROTO_IPV6,
  12947. IPV6_V6ONLY,
  12948. (void *)&off,
  12949. sizeof(off))
  12950. != 0) {
  12951. /* Set IPv6 only option, but don't abort on errors. */
  12952. mg_cry_ctx_internal(phys_ctx,
  12953. "cannot set socket option "
  12954. "IPV6_V6ONLY=off (entry %i)",
  12955. portsTotal);
  12956. }
  12957. } else {
  12958. if (so.lsa.sa.sa_family == AF_INET6
  12959. && setsockopt(so.sock,
  12960. IPPROTO_IPV6,
  12961. IPV6_V6ONLY,
  12962. (void *)&on,
  12963. sizeof(on))
  12964. != 0) {
  12965. /* Set IPv6 only option, but don't abort on errors. */
  12966. mg_cry_ctx_internal(phys_ctx,
  12967. "cannot set socket option "
  12968. "IPV6_V6ONLY=on (entry %i)",
  12969. portsTotal);
  12970. }
  12971. }
  12972. #else
  12973. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12974. closesocket(so.sock);
  12975. so.sock = INVALID_SOCKET;
  12976. continue;
  12977. #endif
  12978. }
  12979. if (so.lsa.sa.sa_family == AF_INET) {
  12980. len = sizeof(so.lsa.sin);
  12981. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12982. mg_cry_ctx_internal(phys_ctx,
  12983. "cannot bind to %.*s: %d (%s)",
  12984. (int)vec.len,
  12985. vec.ptr,
  12986. (int)ERRNO,
  12987. strerror(errno));
  12988. closesocket(so.sock);
  12989. so.sock = INVALID_SOCKET;
  12990. continue;
  12991. }
  12992. }
  12993. #if defined(USE_IPV6)
  12994. else if (so.lsa.sa.sa_family == AF_INET6) {
  12995. len = sizeof(so.lsa.sin6);
  12996. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12997. mg_cry_ctx_internal(phys_ctx,
  12998. "cannot bind to IPv6 %.*s: %d (%s)",
  12999. (int)vec.len,
  13000. vec.ptr,
  13001. (int)ERRNO,
  13002. strerror(errno));
  13003. closesocket(so.sock);
  13004. so.sock = INVALID_SOCKET;
  13005. continue;
  13006. }
  13007. }
  13008. #endif
  13009. #if defined(USE_X_DOM_SOCKET)
  13010. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13011. len = sizeof(so.lsa.sun);
  13012. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13013. mg_cry_ctx_internal(phys_ctx,
  13014. "cannot bind to unix socket %s: %d (%s)",
  13015. so.lsa.sun.sun_path,
  13016. (int)ERRNO,
  13017. strerror(errno));
  13018. closesocket(so.sock);
  13019. so.sock = INVALID_SOCKET;
  13020. continue;
  13021. }
  13022. }
  13023. #endif
  13024. else {
  13025. mg_cry_ctx_internal(
  13026. phys_ctx,
  13027. "cannot bind: address family not supported (entry %i)",
  13028. portsTotal);
  13029. closesocket(so.sock);
  13030. so.sock = INVALID_SOCKET;
  13031. continue;
  13032. }
  13033. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13034. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13035. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13036. mg_cry_ctx_internal(phys_ctx,
  13037. "%s value \"%s\" is invalid",
  13038. config_options[LISTEN_BACKLOG_SIZE].name,
  13039. opt_txt);
  13040. closesocket(so.sock);
  13041. so.sock = INVALID_SOCKET;
  13042. continue;
  13043. }
  13044. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13045. mg_cry_ctx_internal(phys_ctx,
  13046. "cannot listen to %.*s: %d (%s)",
  13047. (int)vec.len,
  13048. vec.ptr,
  13049. (int)ERRNO,
  13050. strerror(errno));
  13051. closesocket(so.sock);
  13052. so.sock = INVALID_SOCKET;
  13053. continue;
  13054. }
  13055. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13056. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13057. int err = (int)ERRNO;
  13058. mg_cry_ctx_internal(phys_ctx,
  13059. "call to getsockname failed %.*s: %d (%s)",
  13060. (int)vec.len,
  13061. vec.ptr,
  13062. err,
  13063. strerror(errno));
  13064. closesocket(so.sock);
  13065. so.sock = INVALID_SOCKET;
  13066. continue;
  13067. }
  13068. /* Update lsa port in case of random free ports */
  13069. #if defined(USE_IPV6)
  13070. if (so.lsa.sa.sa_family == AF_INET6) {
  13071. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13072. } else
  13073. #endif
  13074. {
  13075. so.lsa.sin.sin_port = usa.sin.sin_port;
  13076. }
  13077. if ((ptr = (struct socket *)
  13078. mg_realloc_ctx(phys_ctx->listening_sockets,
  13079. (phys_ctx->num_listening_sockets + 1)
  13080. * sizeof(phys_ctx->listening_sockets[0]),
  13081. phys_ctx))
  13082. == NULL) {
  13083. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13084. closesocket(so.sock);
  13085. so.sock = INVALID_SOCKET;
  13086. continue;
  13087. }
  13088. if ((pfd = (struct mg_pollfd *)
  13089. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13090. (phys_ctx->num_listening_sockets + 1)
  13091. * sizeof(phys_ctx->listening_socket_fds[0]),
  13092. phys_ctx))
  13093. == NULL) {
  13094. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13095. closesocket(so.sock);
  13096. so.sock = INVALID_SOCKET;
  13097. mg_free(ptr);
  13098. continue;
  13099. }
  13100. set_close_on_exec(so.sock, NULL, phys_ctx);
  13101. phys_ctx->listening_sockets = ptr;
  13102. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13103. phys_ctx->listening_socket_fds = pfd;
  13104. phys_ctx->num_listening_sockets++;
  13105. portsOk++;
  13106. }
  13107. if (portsOk != portsTotal) {
  13108. close_all_listening_sockets(phys_ctx);
  13109. portsOk = 0;
  13110. }
  13111. return portsOk;
  13112. }
  13113. static const char *
  13114. header_val(const struct mg_connection *conn, const char *header)
  13115. {
  13116. const char *header_value;
  13117. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13118. return "-";
  13119. } else {
  13120. return header_value;
  13121. }
  13122. }
  13123. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13124. #include "external_log_access.inl"
  13125. #elif !defined(NO_FILESYSTEMS)
  13126. static void
  13127. log_access(const struct mg_connection *conn)
  13128. {
  13129. const struct mg_request_info *ri;
  13130. struct mg_file fi;
  13131. char date[64], src_addr[IP_ADDR_STR_LEN];
  13132. struct tm *tm;
  13133. const char *referer;
  13134. const char *user_agent;
  13135. char log_buf[4096];
  13136. if (!conn || !conn->dom_ctx) {
  13137. return;
  13138. }
  13139. /* Set log message to "empty" */
  13140. log_buf[0] = 0;
  13141. #if defined(USE_LUA)
  13142. if (conn->phys_ctx->lua_bg_log_available) {
  13143. int ret;
  13144. struct mg_context *ctx = conn->phys_ctx;
  13145. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13146. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13147. /* call "log()" in Lua */
  13148. lua_getglobal(lstate, "log");
  13149. prepare_lua_request_info_inner(conn, lstate);
  13150. push_lua_response_log_data(conn, lstate);
  13151. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13152. if (ret == 0) {
  13153. int t = lua_type(lstate, -1);
  13154. if (t == LUA_TBOOLEAN) {
  13155. if (lua_toboolean(lstate, -1) == 0) {
  13156. /* log() returned false: do not log */
  13157. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13158. return;
  13159. }
  13160. /* log returned true: continue logging */
  13161. } else if (t == LUA_TSTRING) {
  13162. size_t len;
  13163. const char *txt = lua_tolstring(lstate, -1, &len);
  13164. if ((len == 0) || (*txt == 0)) {
  13165. /* log() returned empty string: do not log */
  13166. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13167. return;
  13168. }
  13169. /* Copy test from Lua into log_buf */
  13170. if (len >= sizeof(log_buf)) {
  13171. len = sizeof(log_buf) - 1;
  13172. }
  13173. memcpy(log_buf, txt, len);
  13174. log_buf[len] = 0;
  13175. }
  13176. } else {
  13177. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13178. }
  13179. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13180. }
  13181. #endif
  13182. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13183. if (mg_fopen(conn,
  13184. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13185. MG_FOPEN_MODE_APPEND,
  13186. &fi)
  13187. == 0) {
  13188. fi.access.fp = NULL;
  13189. }
  13190. } else {
  13191. fi.access.fp = NULL;
  13192. }
  13193. /* Log is written to a file and/or a callback. If both are not set,
  13194. * executing the rest of the function is pointless. */
  13195. if ((fi.access.fp == NULL)
  13196. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13197. return;
  13198. }
  13199. /* If we did not get a log message from Lua, create it here. */
  13200. if (!log_buf[0]) {
  13201. tm = localtime(&conn->conn_birth_time);
  13202. if (tm != NULL) {
  13203. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13204. } else {
  13205. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13206. date[sizeof(date) - 1] = '\0';
  13207. }
  13208. ri = &conn->request_info;
  13209. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13210. referer = header_val(conn, "Referer");
  13211. user_agent = header_val(conn, "User-Agent");
  13212. mg_snprintf(conn,
  13213. NULL, /* Ignore truncation in access log */
  13214. log_buf,
  13215. sizeof(log_buf),
  13216. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13217. " %s %s",
  13218. src_addr,
  13219. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13220. date,
  13221. ri->request_method ? ri->request_method : "-",
  13222. ri->request_uri ? ri->request_uri : "-",
  13223. ri->query_string ? "?" : "",
  13224. ri->query_string ? ri->query_string : "",
  13225. ri->http_version,
  13226. conn->status_code,
  13227. conn->num_bytes_sent,
  13228. referer,
  13229. user_agent);
  13230. }
  13231. /* Here we have a log message in log_buf. Call the callback */
  13232. if (conn->phys_ctx->callbacks.log_access) {
  13233. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13234. /* do not log if callack returns non-zero */
  13235. if (fi.access.fp) {
  13236. mg_fclose(&fi.access);
  13237. }
  13238. return;
  13239. }
  13240. }
  13241. /* Store in file */
  13242. if (fi.access.fp) {
  13243. int ok = 1;
  13244. flockfile(fi.access.fp);
  13245. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13246. ok = 0;
  13247. }
  13248. if (fflush(fi.access.fp) != 0) {
  13249. ok = 0;
  13250. }
  13251. funlockfile(fi.access.fp);
  13252. if (mg_fclose(&fi.access) != 0) {
  13253. ok = 0;
  13254. }
  13255. if (!ok) {
  13256. mg_cry_internal(conn,
  13257. "Error writing log file %s",
  13258. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13259. }
  13260. }
  13261. }
  13262. #else
  13263. #error "Either enable filesystems or provide a custom log_access implementation"
  13264. #endif /* Externally provided function */
  13265. /* Verify given socket address against the ACL.
  13266. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13267. */
  13268. static int
  13269. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13270. {
  13271. int allowed, flag, matched;
  13272. struct vec vec;
  13273. if (phys_ctx) {
  13274. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13275. /* If any ACL is set, deny by default */
  13276. allowed = (list == NULL) ? '+' : '-';
  13277. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13278. flag = vec.ptr[0];
  13279. matched = -1;
  13280. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13281. vec.ptr++;
  13282. vec.len--;
  13283. matched = parse_match_net(&vec, sa, 1);
  13284. }
  13285. if (matched < 0) {
  13286. mg_cry_ctx_internal(phys_ctx,
  13287. "%s: subnet must be [+|-]IP-addr[/x]",
  13288. __func__);
  13289. return -1;
  13290. }
  13291. if (matched) {
  13292. allowed = flag;
  13293. }
  13294. }
  13295. return allowed == '+';
  13296. }
  13297. return -1;
  13298. }
  13299. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13300. static int
  13301. set_uid_option(struct mg_context *phys_ctx)
  13302. {
  13303. int success = 0;
  13304. if (phys_ctx) {
  13305. /* We are currently running as curr_uid. */
  13306. const uid_t curr_uid = getuid();
  13307. /* If set, we want to run as run_as_user. */
  13308. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13309. const struct passwd *to_pw = NULL;
  13310. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13311. /* run_as_user does not exist on the system. We can't proceed
  13312. * further. */
  13313. mg_cry_ctx_internal(phys_ctx,
  13314. "%s: unknown user [%s]",
  13315. __func__,
  13316. run_as_user);
  13317. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13318. /* There was either no request to change user, or we're already
  13319. * running as run_as_user. Nothing else to do.
  13320. */
  13321. success = 1;
  13322. } else {
  13323. /* Valid change request. */
  13324. if (setgid(to_pw->pw_gid) == -1) {
  13325. mg_cry_ctx_internal(phys_ctx,
  13326. "%s: setgid(%s): %s",
  13327. __func__,
  13328. run_as_user,
  13329. strerror(errno));
  13330. } else if (setgroups(0, NULL) == -1) {
  13331. mg_cry_ctx_internal(phys_ctx,
  13332. "%s: setgroups(): %s",
  13333. __func__,
  13334. strerror(errno));
  13335. } else if (setuid(to_pw->pw_uid) == -1) {
  13336. mg_cry_ctx_internal(phys_ctx,
  13337. "%s: setuid(%s): %s",
  13338. __func__,
  13339. run_as_user,
  13340. strerror(errno));
  13341. } else {
  13342. success = 1;
  13343. }
  13344. }
  13345. }
  13346. return success;
  13347. }
  13348. #endif /* !_WIN32 */
  13349. static void
  13350. tls_dtor(void *key)
  13351. {
  13352. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13353. /* key == pthread_getspecific(sTlsKey); */
  13354. if (tls) {
  13355. if (tls->is_master == 2) {
  13356. tls->is_master = -3; /* Mark memory as dead */
  13357. mg_free(tls);
  13358. }
  13359. }
  13360. pthread_setspecific(sTlsKey, NULL);
  13361. }
  13362. #if defined(USE_MBEDTLS)
  13363. /* Check if SSL is required.
  13364. * If so, set up ctx->ssl_ctx pointer. */
  13365. static int
  13366. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13367. {
  13368. if (!phys_ctx) {
  13369. return 0;
  13370. }
  13371. if (!dom_ctx) {
  13372. dom_ctx = &(phys_ctx->dd);
  13373. }
  13374. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13375. /* No SSL port is set. No need to setup SSL. */
  13376. return 1;
  13377. }
  13378. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13379. if (dom_ctx->ssl_ctx == NULL) {
  13380. fprintf(stderr, "ssl_ctx malloc failed\n");
  13381. return 0;
  13382. }
  13383. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13384. == 0
  13385. ? 1
  13386. : 0;
  13387. }
  13388. #elif !defined(NO_SSL)
  13389. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13390. struct mg_domain_context *dom_ctx,
  13391. const char *pem,
  13392. const char *chain);
  13393. static const char *ssl_error(void);
  13394. static int
  13395. refresh_trust(struct mg_connection *conn)
  13396. {
  13397. struct stat cert_buf;
  13398. int64_t t = 0;
  13399. const char *pem;
  13400. const char *chain;
  13401. int should_verify_peer;
  13402. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13403. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13404. * refresh_trust still can not work. */
  13405. return 0;
  13406. }
  13407. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13408. if (chain == NULL) {
  13409. /* pem is not NULL here */
  13410. chain = pem;
  13411. }
  13412. if (*chain == 0) {
  13413. chain = NULL;
  13414. }
  13415. if (stat(pem, &cert_buf) != -1) {
  13416. t = (int64_t)cert_buf.st_mtime;
  13417. }
  13418. mg_lock_context(conn->phys_ctx);
  13419. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13420. conn->dom_ctx->ssl_cert_last_mtime = t;
  13421. should_verify_peer = 0;
  13422. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13423. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13424. == 0) {
  13425. should_verify_peer = 1;
  13426. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13427. "optional")
  13428. == 0) {
  13429. should_verify_peer = 1;
  13430. }
  13431. }
  13432. if (should_verify_peer) {
  13433. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13434. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13435. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13436. ca_file,
  13437. ca_path)
  13438. != 1) {
  13439. mg_unlock_context(conn->phys_ctx);
  13440. mg_cry_ctx_internal(
  13441. conn->phys_ctx,
  13442. "SSL_CTX_load_verify_locations error: %s "
  13443. "ssl_verify_peer requires setting "
  13444. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13445. "present in "
  13446. "the .conf file?",
  13447. ssl_error());
  13448. return 0;
  13449. }
  13450. }
  13451. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13452. mg_unlock_context(conn->phys_ctx);
  13453. return 0;
  13454. }
  13455. }
  13456. mg_unlock_context(conn->phys_ctx);
  13457. return 1;
  13458. }
  13459. #if defined(OPENSSL_API_1_1)
  13460. #else
  13461. static pthread_mutex_t *ssl_mutexes;
  13462. #endif /* OPENSSL_API_1_1 */
  13463. static int
  13464. sslize(struct mg_connection *conn,
  13465. int (*func)(SSL *),
  13466. const struct mg_client_options *client_options)
  13467. {
  13468. int ret, err;
  13469. int short_trust;
  13470. unsigned timeout = 1024;
  13471. unsigned i;
  13472. if (!conn) {
  13473. return 0;
  13474. }
  13475. short_trust =
  13476. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13477. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13478. if (short_trust) {
  13479. int trust_ret = refresh_trust(conn);
  13480. if (!trust_ret) {
  13481. return trust_ret;
  13482. }
  13483. }
  13484. mg_lock_context(conn->phys_ctx);
  13485. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13486. mg_unlock_context(conn->phys_ctx);
  13487. if (conn->ssl == NULL) {
  13488. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13489. OPENSSL_REMOVE_THREAD_STATE();
  13490. return 0;
  13491. }
  13492. SSL_set_app_data(conn->ssl, (char *)conn);
  13493. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13494. if (ret != 1) {
  13495. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13496. SSL_free(conn->ssl);
  13497. conn->ssl = NULL;
  13498. OPENSSL_REMOVE_THREAD_STATE();
  13499. return 0;
  13500. }
  13501. if (client_options) {
  13502. if (client_options->host_name) {
  13503. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13504. }
  13505. }
  13506. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13507. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13508. /* NOTE: The loop below acts as a back-off, so we can end
  13509. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13510. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13511. if (to >= 0) {
  13512. timeout = (unsigned)to;
  13513. }
  13514. }
  13515. /* SSL functions may fail and require to be called again:
  13516. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13517. * Here "func" could be SSL_connect or SSL_accept. */
  13518. for (i = 0; i <= timeout; i += 50) {
  13519. ERR_clear_error();
  13520. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13521. ret = func(conn->ssl);
  13522. if (ret != 1) {
  13523. err = SSL_get_error(conn->ssl, ret);
  13524. if ((err == SSL_ERROR_WANT_CONNECT)
  13525. || (err == SSL_ERROR_WANT_ACCEPT)
  13526. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13527. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13528. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13529. /* Don't wait if the server is going to be stopped. */
  13530. break;
  13531. }
  13532. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13533. /* Simply retry the function call. */
  13534. mg_sleep(50);
  13535. } else {
  13536. /* Need to retry the function call "later".
  13537. * See https://linux.die.net/man/3/ssl_get_error
  13538. * This is typical for non-blocking sockets. */
  13539. struct mg_pollfd pfd;
  13540. int pollres;
  13541. pfd.fd = conn->client.sock;
  13542. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13543. || (err == SSL_ERROR_WANT_WRITE))
  13544. ? POLLOUT
  13545. : POLLIN;
  13546. pollres =
  13547. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13548. if (pollres < 0) {
  13549. /* Break if error occured (-1)
  13550. * or server shutdown (-2) */
  13551. break;
  13552. }
  13553. }
  13554. } else if (err == SSL_ERROR_SYSCALL) {
  13555. /* This is an IO error. Look at errno. */
  13556. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13557. break;
  13558. } else {
  13559. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13560. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13561. break;
  13562. }
  13563. } else {
  13564. /* success */
  13565. break;
  13566. }
  13567. }
  13568. ERR_clear_error();
  13569. if (ret != 1) {
  13570. SSL_free(conn->ssl);
  13571. conn->ssl = NULL;
  13572. OPENSSL_REMOVE_THREAD_STATE();
  13573. return 0;
  13574. }
  13575. return 1;
  13576. }
  13577. /* Return OpenSSL error message (from CRYPTO lib) */
  13578. static const char *
  13579. ssl_error(void)
  13580. {
  13581. unsigned long err;
  13582. err = ERR_get_error();
  13583. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13584. }
  13585. static int
  13586. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13587. {
  13588. int i;
  13589. const char hexdigit[] = "0123456789abcdef";
  13590. if ((memlen <= 0) || (buflen <= 0)) {
  13591. return 0;
  13592. }
  13593. if (buflen < (3 * memlen)) {
  13594. return 0;
  13595. }
  13596. for (i = 0; i < memlen; i++) {
  13597. if (i > 0) {
  13598. buf[3 * i - 1] = ' ';
  13599. }
  13600. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13601. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13602. }
  13603. buf[3 * memlen - 1] = 0;
  13604. return 1;
  13605. }
  13606. static int
  13607. ssl_get_client_cert_info(const struct mg_connection *conn,
  13608. struct mg_client_cert *client_cert)
  13609. {
  13610. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13611. if (cert) {
  13612. char str_buf[1024];
  13613. unsigned char buf[256];
  13614. char *str_serial = NULL;
  13615. unsigned int ulen;
  13616. int ilen;
  13617. unsigned char *tmp_buf;
  13618. unsigned char *tmp_p;
  13619. /* Handle to algorithm used for fingerprint */
  13620. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13621. /* Get Subject and issuer */
  13622. X509_NAME *subj = X509_get_subject_name(cert);
  13623. X509_NAME *iss = X509_get_issuer_name(cert);
  13624. /* Get serial number */
  13625. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13626. /* Translate serial number to a hex string */
  13627. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13628. if (serial_bn) {
  13629. str_serial = BN_bn2hex(serial_bn);
  13630. BN_free(serial_bn);
  13631. }
  13632. client_cert->serial =
  13633. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13634. /* Translate subject and issuer to a string */
  13635. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13636. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13637. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13638. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13639. /* Calculate SHA1 fingerprint and store as a hex string */
  13640. ulen = 0;
  13641. /* ASN1_digest is deprecated. Do the calculation manually,
  13642. * using EVP_Digest. */
  13643. ilen = i2d_X509(cert, NULL);
  13644. tmp_buf = (ilen > 0)
  13645. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13646. conn->phys_ctx)
  13647. : NULL;
  13648. if (tmp_buf) {
  13649. tmp_p = tmp_buf;
  13650. (void)i2d_X509(cert, &tmp_p);
  13651. if (!EVP_Digest(
  13652. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13653. ulen = 0;
  13654. }
  13655. mg_free(tmp_buf);
  13656. }
  13657. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13658. *str_buf = 0;
  13659. }
  13660. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13661. client_cert->peer_cert = (void *)cert;
  13662. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13663. * see https://linux.die.net/man/3/bn_bn2hex */
  13664. OPENSSL_free(str_serial);
  13665. return 1;
  13666. }
  13667. return 0;
  13668. }
  13669. #if defined(OPENSSL_API_1_1)
  13670. #else
  13671. static void
  13672. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13673. {
  13674. (void)line;
  13675. (void)file;
  13676. if (mode & 1) {
  13677. /* 1 is CRYPTO_LOCK */
  13678. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13679. } else {
  13680. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13681. }
  13682. }
  13683. #endif /* OPENSSL_API_1_1 */
  13684. #if !defined(NO_SSL_DL)
  13685. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13686. static void *
  13687. load_tls_dll(char *ebuf,
  13688. size_t ebuf_len,
  13689. const char *dll_name,
  13690. struct ssl_func *sw,
  13691. int *feature_missing)
  13692. {
  13693. union {
  13694. void *p;
  13695. void (*fp)(void);
  13696. } u;
  13697. void *dll_handle;
  13698. struct ssl_func *fp;
  13699. int ok;
  13700. int truncated = 0;
  13701. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13702. mg_snprintf(NULL,
  13703. NULL, /* No truncation check for ebuf */
  13704. ebuf,
  13705. ebuf_len,
  13706. "%s: cannot load %s",
  13707. __func__,
  13708. dll_name);
  13709. return NULL;
  13710. }
  13711. ok = 1;
  13712. for (fp = sw; fp->name != NULL; fp++) {
  13713. #if defined(_WIN32)
  13714. /* GetProcAddress() returns pointer to function */
  13715. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13716. #else
  13717. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13718. * pointers to function pointers. We need to use a union to make a
  13719. * cast. */
  13720. u.p = dlsym(dll_handle, fp->name);
  13721. #endif /* _WIN32 */
  13722. /* Set pointer (might be NULL) */
  13723. fp->ptr = u.fp;
  13724. if (u.fp == NULL) {
  13725. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13726. if (feature_missing) {
  13727. feature_missing[fp->required]++;
  13728. }
  13729. if (fp->required == TLS_Mandatory) {
  13730. /* Mandatory function is missing */
  13731. if (ok) {
  13732. /* This is the first missing function.
  13733. * Create a new error message. */
  13734. mg_snprintf(NULL,
  13735. &truncated,
  13736. ebuf,
  13737. ebuf_len,
  13738. "%s: %s: cannot find %s",
  13739. __func__,
  13740. dll_name,
  13741. fp->name);
  13742. ok = 0;
  13743. } else {
  13744. /* This is yet anothermissing function.
  13745. * Append existing error message. */
  13746. size_t cur_len = strlen(ebuf);
  13747. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13748. mg_snprintf(NULL,
  13749. &truncated,
  13750. ebuf + cur_len,
  13751. ebuf_len - cur_len - 3,
  13752. ", %s",
  13753. fp->name);
  13754. if (truncated) {
  13755. /* If truncated, add "..." */
  13756. strcat(ebuf, "...");
  13757. }
  13758. }
  13759. }
  13760. }
  13761. }
  13762. }
  13763. if (!ok) {
  13764. (void)dlclose(dll_handle);
  13765. return NULL;
  13766. }
  13767. return dll_handle;
  13768. }
  13769. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13770. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13771. #endif /* NO_SSL_DL */
  13772. #if defined(SSL_ALREADY_INITIALIZED)
  13773. static volatile ptrdiff_t cryptolib_users =
  13774. 1; /* Reference counter for crypto library. */
  13775. #else
  13776. static volatile ptrdiff_t cryptolib_users =
  13777. 0; /* Reference counter for crypto library. */
  13778. #endif
  13779. static int
  13780. initialize_openssl(char *ebuf, size_t ebuf_len)
  13781. {
  13782. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13783. int i, num_locks;
  13784. size_t size;
  13785. #endif
  13786. if (ebuf_len > 0) {
  13787. ebuf[0] = 0;
  13788. }
  13789. #if !defined(NO_SSL_DL)
  13790. if (!cryptolib_dll_handle) {
  13791. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13792. cryptolib_dll_handle = load_tls_dll(
  13793. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13794. if (!cryptolib_dll_handle) {
  13795. mg_snprintf(NULL,
  13796. NULL, /* No truncation check for ebuf */
  13797. ebuf,
  13798. ebuf_len,
  13799. "%s: error loading library %s",
  13800. __func__,
  13801. CRYPTO_LIB);
  13802. DEBUG_TRACE("%s", ebuf);
  13803. return 0;
  13804. }
  13805. }
  13806. #endif /* NO_SSL_DL */
  13807. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13808. return 1;
  13809. }
  13810. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13811. /* Initialize locking callbacks, needed for thread safety.
  13812. * http://www.openssl.org/support/faq.html#PROG1
  13813. */
  13814. num_locks = CRYPTO_num_locks();
  13815. if (num_locks < 0) {
  13816. num_locks = 0;
  13817. }
  13818. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13819. /* allocate mutex array, if required */
  13820. if (num_locks == 0) {
  13821. /* No mutex array required */
  13822. ssl_mutexes = NULL;
  13823. } else {
  13824. /* Mutex array required - allocate it */
  13825. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13826. /* Check OOM */
  13827. if (ssl_mutexes == NULL) {
  13828. mg_snprintf(NULL,
  13829. NULL, /* No truncation check for ebuf */
  13830. ebuf,
  13831. ebuf_len,
  13832. "%s: cannot allocate mutexes: %s",
  13833. __func__,
  13834. ssl_error());
  13835. DEBUG_TRACE("%s", ebuf);
  13836. return 0;
  13837. }
  13838. /* initialize mutex array */
  13839. for (i = 0; i < num_locks; i++) {
  13840. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13841. mg_snprintf(NULL,
  13842. NULL, /* No truncation check for ebuf */
  13843. ebuf,
  13844. ebuf_len,
  13845. "%s: error initializing mutex %i of %i",
  13846. __func__,
  13847. i,
  13848. num_locks);
  13849. DEBUG_TRACE("%s", ebuf);
  13850. mg_free(ssl_mutexes);
  13851. return 0;
  13852. }
  13853. }
  13854. }
  13855. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13856. CRYPTO_set_id_callback(&mg_current_thread_id);
  13857. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  13858. #if !defined(NO_SSL_DL)
  13859. if (!ssllib_dll_handle) {
  13860. ssllib_dll_handle =
  13861. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13862. if (!ssllib_dll_handle) {
  13863. #if !defined(OPENSSL_API_1_1)
  13864. mg_free(ssl_mutexes);
  13865. #endif
  13866. DEBUG_TRACE("%s", ebuf);
  13867. return 0;
  13868. }
  13869. }
  13870. #endif /* NO_SSL_DL */
  13871. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  13872. && !defined(NO_SSL_DL)
  13873. /* Initialize SSL library */
  13874. OPENSSL_init_ssl(0, NULL);
  13875. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13876. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13877. NULL);
  13878. #else
  13879. /* Initialize SSL library */
  13880. SSL_library_init();
  13881. SSL_load_error_strings();
  13882. #endif
  13883. return 1;
  13884. }
  13885. static int
  13886. ssl_use_pem_file(struct mg_context *phys_ctx,
  13887. struct mg_domain_context *dom_ctx,
  13888. const char *pem,
  13889. const char *chain)
  13890. {
  13891. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13892. mg_cry_ctx_internal(phys_ctx,
  13893. "%s: cannot open certificate file %s: %s",
  13894. __func__,
  13895. pem,
  13896. ssl_error());
  13897. return 0;
  13898. }
  13899. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13900. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13901. mg_cry_ctx_internal(phys_ctx,
  13902. "%s: cannot open private key file %s: %s",
  13903. __func__,
  13904. pem,
  13905. ssl_error());
  13906. return 0;
  13907. }
  13908. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13909. mg_cry_ctx_internal(phys_ctx,
  13910. "%s: certificate and private key do not match: %s",
  13911. __func__,
  13912. pem);
  13913. return 0;
  13914. }
  13915. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13916. * chain files that contain private keys and certificates in
  13917. * SSL_CTX_use_certificate_chain_file.
  13918. * The CivetWeb-Server used pem-Files that contained both information.
  13919. * In order to make wolfSSL work, it is split in two files.
  13920. * One file that contains key and certificate used by the server and
  13921. * an optional chain file for the ssl stack.
  13922. */
  13923. if (chain) {
  13924. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13925. mg_cry_ctx_internal(phys_ctx,
  13926. "%s: cannot use certificate chain file %s: %s",
  13927. __func__,
  13928. chain,
  13929. ssl_error());
  13930. return 0;
  13931. }
  13932. }
  13933. return 1;
  13934. }
  13935. #if defined(OPENSSL_API_1_1)
  13936. static unsigned long
  13937. ssl_get_protocol(int version_id)
  13938. {
  13939. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13940. if (version_id > 0)
  13941. ret |= SSL_OP_NO_SSLv2;
  13942. if (version_id > 1)
  13943. ret |= SSL_OP_NO_SSLv3;
  13944. if (version_id > 2)
  13945. ret |= SSL_OP_NO_TLSv1;
  13946. if (version_id > 3)
  13947. ret |= SSL_OP_NO_TLSv1_1;
  13948. if (version_id > 4)
  13949. ret |= SSL_OP_NO_TLSv1_2;
  13950. #if defined(SSL_OP_NO_TLSv1_3)
  13951. if (version_id > 5)
  13952. ret |= SSL_OP_NO_TLSv1_3;
  13953. #endif
  13954. return ret;
  13955. }
  13956. #else
  13957. static long
  13958. ssl_get_protocol(int version_id)
  13959. {
  13960. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13961. if (version_id > 0)
  13962. ret |= SSL_OP_NO_SSLv2;
  13963. if (version_id > 1)
  13964. ret |= SSL_OP_NO_SSLv3;
  13965. if (version_id > 2)
  13966. ret |= SSL_OP_NO_TLSv1;
  13967. if (version_id > 3)
  13968. ret |= SSL_OP_NO_TLSv1_1;
  13969. if (version_id > 4)
  13970. ret |= SSL_OP_NO_TLSv1_2;
  13971. #if defined(SSL_OP_NO_TLSv1_3)
  13972. if (version_id > 5)
  13973. ret |= SSL_OP_NO_TLSv1_3;
  13974. #endif
  13975. return (long)ret;
  13976. }
  13977. #endif /* OPENSSL_API_1_1 */
  13978. /* SSL callback documentation:
  13979. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13980. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13981. * https://linux.die.net/man/3/ssl_set_info_callback */
  13982. /* Note: There is no "const" for the first argument in the documentation
  13983. * examples, however some (maybe most, but not all) headers of OpenSSL
  13984. * versions / OpenSSL compatibility layers have it. Having a different
  13985. * definition will cause a warning in C and an error in C++. Use "const SSL
  13986. * *", while automatical conversion from "SSL *" works for all compilers,
  13987. * but not other way around */
  13988. static void
  13989. ssl_info_callback(const SSL *ssl, int what, int ret)
  13990. {
  13991. (void)ret;
  13992. if (what & SSL_CB_HANDSHAKE_START) {
  13993. SSL_get_app_data(ssl);
  13994. }
  13995. if (what & SSL_CB_HANDSHAKE_DONE) {
  13996. /* TODO: check for openSSL 1.1 */
  13997. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13998. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13999. }
  14000. }
  14001. static int
  14002. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14003. {
  14004. #if defined(GCC_DIAGNOSTIC)
  14005. #pragma GCC diagnostic push
  14006. #pragma GCC diagnostic ignored "-Wcast-align"
  14007. #endif /* defined(GCC_DIAGNOSTIC) */
  14008. /* We used an aligned pointer in SSL_set_app_data */
  14009. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14010. #if defined(GCC_DIAGNOSTIC)
  14011. #pragma GCC diagnostic pop
  14012. #endif /* defined(GCC_DIAGNOSTIC) */
  14013. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14014. (void)ad;
  14015. (void)arg;
  14016. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14017. DEBUG_ASSERT(0);
  14018. return SSL_TLSEXT_ERR_NOACK;
  14019. }
  14020. conn->dom_ctx = &(conn->phys_ctx->dd);
  14021. /* Old clients (Win XP) will not support SNI. Then, there
  14022. * is no server name available in the request - we can
  14023. * only work with the default certificate.
  14024. * Multiple HTTPS hosts on one IP+port are only possible
  14025. * with a certificate containing all alternative names.
  14026. */
  14027. if ((servername == NULL) || (*servername == 0)) {
  14028. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14029. mg_lock_context(conn->phys_ctx);
  14030. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14031. mg_unlock_context(conn->phys_ctx);
  14032. return SSL_TLSEXT_ERR_NOACK;
  14033. }
  14034. DEBUG_TRACE("TLS connection to host %s", servername);
  14035. while (conn->dom_ctx) {
  14036. if (!mg_strcasecmp(servername,
  14037. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14038. /* Found matching domain */
  14039. DEBUG_TRACE("TLS domain %s found",
  14040. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14041. break;
  14042. }
  14043. mg_lock_context(conn->phys_ctx);
  14044. conn->dom_ctx = conn->dom_ctx->next;
  14045. mg_unlock_context(conn->phys_ctx);
  14046. }
  14047. if (conn->dom_ctx == NULL) {
  14048. /* Default domain */
  14049. DEBUG_TRACE("TLS default domain %s used",
  14050. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14051. conn->dom_ctx = &(conn->phys_ctx->dd);
  14052. }
  14053. mg_lock_context(conn->phys_ctx);
  14054. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14055. mg_unlock_context(conn->phys_ctx);
  14056. return SSL_TLSEXT_ERR_OK;
  14057. }
  14058. #if defined(USE_ALPN)
  14059. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14060. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14061. alpn_proto_list + 3 + 8,
  14062. NULL};
  14063. #if defined(USE_HTTP2)
  14064. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14065. alpn_proto_list + 3,
  14066. alpn_proto_list + 3 + 8,
  14067. NULL};
  14068. #endif
  14069. static int
  14070. alpn_select_cb(SSL *ssl,
  14071. const unsigned char **out,
  14072. unsigned char *outlen,
  14073. const unsigned char *in,
  14074. unsigned int inlen,
  14075. void *arg)
  14076. {
  14077. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14078. unsigned int i, j, enable_http2 = 0;
  14079. const char **alpn_proto_order = alpn_proto_order_http1;
  14080. struct mg_workerTLS *tls =
  14081. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14082. (void)ssl;
  14083. if (tls == NULL) {
  14084. /* Need to store protocol in Thread Local Storage */
  14085. /* If there is no Thread Local Storage, don't use ALPN */
  14086. return SSL_TLSEXT_ERR_NOACK;
  14087. }
  14088. #if defined(USE_HTTP2)
  14089. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14090. if (enable_http2) {
  14091. alpn_proto_order = alpn_proto_order_http2;
  14092. }
  14093. #endif
  14094. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14095. /* check all accepted protocols in this order */
  14096. const char *alpn_proto = alpn_proto_order[j];
  14097. /* search input for matching protocol */
  14098. for (i = 0; i < inlen; i++) {
  14099. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14100. *out = in + i + 1;
  14101. *outlen = in[i];
  14102. tls->alpn_proto = alpn_proto;
  14103. return SSL_TLSEXT_ERR_OK;
  14104. }
  14105. }
  14106. }
  14107. /* Nothing found */
  14108. return SSL_TLSEXT_ERR_NOACK;
  14109. }
  14110. static int
  14111. next_protos_advertised_cb(SSL *ssl,
  14112. const unsigned char **data,
  14113. unsigned int *len,
  14114. void *arg)
  14115. {
  14116. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14117. *data = (const unsigned char *)alpn_proto_list;
  14118. *len = (unsigned int)strlen((const char *)data);
  14119. (void)ssl;
  14120. (void)dom_ctx;
  14121. return SSL_TLSEXT_ERR_OK;
  14122. }
  14123. static int
  14124. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14125. {
  14126. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14127. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14128. (const unsigned char *)alpn_proto_list,
  14129. alpn_len);
  14130. if (ret != 0) {
  14131. mg_cry_ctx_internal(phys_ctx,
  14132. "SSL_CTX_set_alpn_protos error: %s",
  14133. ssl_error());
  14134. }
  14135. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14136. alpn_select_cb,
  14137. (void *)dom_ctx);
  14138. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14139. next_protos_advertised_cb,
  14140. (void *)dom_ctx);
  14141. return ret;
  14142. }
  14143. #endif
  14144. /* Setup SSL CTX as required by CivetWeb */
  14145. static int
  14146. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14147. struct mg_domain_context *dom_ctx,
  14148. const char *pem,
  14149. const char *chain)
  14150. {
  14151. int callback_ret;
  14152. int should_verify_peer;
  14153. int peer_certificate_optional;
  14154. const char *ca_path;
  14155. const char *ca_file;
  14156. int use_default_verify_paths;
  14157. int verify_depth;
  14158. struct timespec now_mt;
  14159. md5_byte_t ssl_context_id[16];
  14160. md5_state_t md5state;
  14161. int protocol_ver;
  14162. int ssl_cache_timeout;
  14163. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14164. && !defined(NO_SSL_DL)
  14165. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14166. mg_cry_ctx_internal(phys_ctx,
  14167. "SSL_CTX_new (server) error: %s",
  14168. ssl_error());
  14169. return 0;
  14170. }
  14171. #else
  14172. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14173. mg_cry_ctx_internal(phys_ctx,
  14174. "SSL_CTX_new (server) error: %s",
  14175. ssl_error());
  14176. return 0;
  14177. }
  14178. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14179. #if defined(SSL_OP_NO_TLSv1_3)
  14180. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14181. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14182. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14183. | SSL_OP_NO_TLSv1_3);
  14184. #else
  14185. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14186. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14187. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14188. #endif
  14189. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14190. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14191. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14192. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14193. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14194. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14195. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14196. #if defined(SSL_OP_NO_RENEGOTIATION)
  14197. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14198. #endif
  14199. #if !defined(NO_SSL_DL)
  14200. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14201. #endif /* NO_SSL_DL */
  14202. /* In SSL documentation examples callback defined without const
  14203. * specifier 'void (*)(SSL *, int, int)' See:
  14204. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14205. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14206. * But in the source code const SSL is used:
  14207. * 'void (*)(const SSL *, int, int)' See:
  14208. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14209. * Problem about wrong documentation described, but not resolved:
  14210. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14211. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14212. * But when compiled with modern C++ compiler, correct const should be
  14213. * provided
  14214. */
  14215. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14216. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14217. ssl_servername_callback);
  14218. /* If a callback has been specified, call it. */
  14219. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14220. ? 0
  14221. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14222. phys_ctx->user_data));
  14223. /* If callback returns 0, civetweb sets up the SSL certificate.
  14224. * If it returns 1, civetweb assumes the calback already did this.
  14225. * If it returns -1, initializing ssl fails. */
  14226. if (callback_ret < 0) {
  14227. mg_cry_ctx_internal(phys_ctx,
  14228. "SSL callback returned error: %i",
  14229. callback_ret);
  14230. return 0;
  14231. }
  14232. if (callback_ret > 0) {
  14233. /* Callback did everything. */
  14234. return 1;
  14235. }
  14236. /* If a domain callback has been specified, call it. */
  14237. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14238. ? 0
  14239. : (phys_ctx->callbacks.init_ssl_domain(
  14240. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14241. dom_ctx->ssl_ctx,
  14242. phys_ctx->user_data));
  14243. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14244. * If it returns 1, civetweb assumes the calback already did this.
  14245. * If it returns -1, initializing ssl fails. */
  14246. if (callback_ret < 0) {
  14247. mg_cry_ctx_internal(phys_ctx,
  14248. "Domain SSL callback returned error: %i",
  14249. callback_ret);
  14250. return 0;
  14251. }
  14252. if (callback_ret > 0) {
  14253. /* Domain callback did everything. */
  14254. return 1;
  14255. }
  14256. /* Use some combination of start time, domain and port as a SSL
  14257. * context ID. This should be unique on the current machine. */
  14258. md5_init(&md5state);
  14259. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14260. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14261. md5_append(&md5state,
  14262. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14263. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14264. md5_append(&md5state,
  14265. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14266. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14267. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14268. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14269. md5_finish(&md5state, ssl_context_id);
  14270. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14271. (unsigned char *)ssl_context_id,
  14272. sizeof(ssl_context_id));
  14273. if (pem != NULL) {
  14274. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14275. return 0;
  14276. }
  14277. }
  14278. /* Should we support client certificates? */
  14279. /* Default is "no". */
  14280. should_verify_peer = 0;
  14281. peer_certificate_optional = 0;
  14282. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14283. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14284. /* Yes, they are mandatory */
  14285. should_verify_peer = 1;
  14286. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14287. "optional")
  14288. == 0) {
  14289. /* Yes, they are optional */
  14290. should_verify_peer = 1;
  14291. peer_certificate_optional = 1;
  14292. }
  14293. }
  14294. use_default_verify_paths =
  14295. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14296. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14297. == 0);
  14298. if (should_verify_peer) {
  14299. ca_path = dom_ctx->config[SSL_CA_PATH];
  14300. ca_file = dom_ctx->config[SSL_CA_FILE];
  14301. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14302. != 1) {
  14303. mg_cry_ctx_internal(phys_ctx,
  14304. "SSL_CTX_load_verify_locations error: %s "
  14305. "ssl_verify_peer requires setting "
  14306. "either ssl_ca_path or ssl_ca_file. "
  14307. "Is any of them present in the "
  14308. ".conf file?",
  14309. ssl_error());
  14310. return 0;
  14311. }
  14312. if (peer_certificate_optional) {
  14313. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14314. } else {
  14315. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14316. SSL_VERIFY_PEER
  14317. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14318. NULL);
  14319. }
  14320. if (use_default_verify_paths
  14321. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14322. mg_cry_ctx_internal(phys_ctx,
  14323. "SSL_CTX_set_default_verify_paths error: %s",
  14324. ssl_error());
  14325. return 0;
  14326. }
  14327. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14328. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14329. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14330. }
  14331. }
  14332. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14333. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14334. dom_ctx->config[SSL_CIPHER_LIST])
  14335. != 1) {
  14336. mg_cry_ctx_internal(phys_ctx,
  14337. "SSL_CTX_set_cipher_list error: %s",
  14338. ssl_error());
  14339. }
  14340. }
  14341. /* SSL session caching */
  14342. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14343. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14344. : 0);
  14345. if (ssl_cache_timeout > 0) {
  14346. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14347. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14348. * default */
  14349. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14350. }
  14351. #if defined(USE_ALPN)
  14352. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14353. #if !defined(NO_SSL_DL)
  14354. if (!tls_feature_missing[TLS_ALPN])
  14355. #endif
  14356. {
  14357. init_alpn(phys_ctx, dom_ctx);
  14358. }
  14359. #endif
  14360. return 1;
  14361. }
  14362. /* Check if SSL is required.
  14363. * If so, dynamically load SSL library
  14364. * and set up ctx->ssl_ctx pointer. */
  14365. static int
  14366. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14367. {
  14368. void *ssl_ctx = 0;
  14369. int callback_ret;
  14370. const char *pem;
  14371. const char *chain;
  14372. char ebuf[128];
  14373. if (!phys_ctx) {
  14374. return 0;
  14375. }
  14376. if (!dom_ctx) {
  14377. dom_ctx = &(phys_ctx->dd);
  14378. }
  14379. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14380. /* No SSL port is set. No need to setup SSL. */
  14381. return 1;
  14382. }
  14383. /* Check for external SSL_CTX */
  14384. callback_ret =
  14385. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14386. ? 0
  14387. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14388. phys_ctx->user_data));
  14389. if (callback_ret < 0) {
  14390. /* Callback exists and returns <0: Initializing failed. */
  14391. mg_cry_ctx_internal(phys_ctx,
  14392. "external_ssl_ctx callback returned error: %i",
  14393. callback_ret);
  14394. return 0;
  14395. } else if (callback_ret > 0) {
  14396. /* Callback exists and returns >0: Initializing complete,
  14397. * civetweb should not modify the SSL context. */
  14398. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14399. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14400. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14401. return 0;
  14402. }
  14403. return 1;
  14404. }
  14405. /* If the callback does not exist or return 0, civetweb must initialize
  14406. * the SSL context. Handle "domain" callback next. */
  14407. /* Check for external domain SSL_CTX callback. */
  14408. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14409. ? 0
  14410. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14411. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14412. &ssl_ctx,
  14413. phys_ctx->user_data));
  14414. if (callback_ret < 0) {
  14415. /* Callback < 0: Error. Abort init. */
  14416. mg_cry_ctx_internal(
  14417. phys_ctx,
  14418. "external_ssl_ctx_domain callback returned error: %i",
  14419. callback_ret);
  14420. return 0;
  14421. } else if (callback_ret > 0) {
  14422. /* Callback > 0: Consider init done. */
  14423. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14424. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14425. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14426. return 0;
  14427. }
  14428. return 1;
  14429. }
  14430. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14431. * 0, CivetWeb should continue initializing SSL */
  14432. /* If PEM file is not specified and the init_ssl callbacks
  14433. * are not specified, setup will fail. */
  14434. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14435. && (phys_ctx->callbacks.init_ssl == NULL)
  14436. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14437. /* No certificate and no init_ssl callbacks:
  14438. * Essential data to set up TLS is missing.
  14439. */
  14440. mg_cry_ctx_internal(phys_ctx,
  14441. "Initializing SSL failed: -%s is not set",
  14442. config_options[SSL_CERTIFICATE].name);
  14443. return 0;
  14444. }
  14445. /* If a certificate chain is configured, use it. */
  14446. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14447. if (chain == NULL) {
  14448. /* Default: certificate chain in PEM file */
  14449. chain = pem;
  14450. }
  14451. if ((chain != NULL) && (*chain == 0)) {
  14452. /* If the chain is an empty string, don't use it. */
  14453. chain = NULL;
  14454. }
  14455. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14456. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14457. return 0;
  14458. }
  14459. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14460. }
  14461. static void
  14462. uninitialize_openssl(void)
  14463. {
  14464. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14465. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14466. /* Shutdown according to
  14467. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14468. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14469. */
  14470. CONF_modules_unload(1);
  14471. #else
  14472. int i;
  14473. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14474. /* Shutdown according to
  14475. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14476. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14477. */
  14478. CRYPTO_set_locking_callback(NULL);
  14479. CRYPTO_set_id_callback(NULL);
  14480. ENGINE_cleanup();
  14481. CONF_modules_unload(1);
  14482. ERR_free_strings();
  14483. EVP_cleanup();
  14484. CRYPTO_cleanup_all_ex_data();
  14485. OPENSSL_REMOVE_THREAD_STATE();
  14486. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14487. pthread_mutex_destroy(&ssl_mutexes[i]);
  14488. }
  14489. mg_free(ssl_mutexes);
  14490. ssl_mutexes = NULL;
  14491. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14492. }
  14493. }
  14494. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  14495. #if !defined(NO_FILESYSTEMS)
  14496. static int
  14497. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14498. {
  14499. if (phys_ctx) {
  14500. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14501. const char *path;
  14502. struct mg_connection fc;
  14503. if (!dom_ctx) {
  14504. dom_ctx = &(phys_ctx->dd);
  14505. }
  14506. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14507. if ((path != NULL)
  14508. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14509. mg_cry_ctx_internal(phys_ctx,
  14510. "Cannot open %s: %s",
  14511. path,
  14512. strerror(ERRNO));
  14513. return 0;
  14514. }
  14515. return 1;
  14516. }
  14517. return 0;
  14518. }
  14519. #endif /* NO_FILESYSTEMS */
  14520. static int
  14521. set_acl_option(struct mg_context *phys_ctx)
  14522. {
  14523. union usa sa;
  14524. memset(&sa, 0, sizeof(sa));
  14525. #if defined(USE_IPV6)
  14526. sa.sin6.sin6_family = AF_INET6;
  14527. #else
  14528. sa.sin.sin_family = AF_INET;
  14529. #endif
  14530. return check_acl(phys_ctx, &sa) != -1;
  14531. }
  14532. static void
  14533. reset_per_request_attributes(struct mg_connection *conn)
  14534. {
  14535. if (!conn) {
  14536. return;
  14537. }
  14538. conn->num_bytes_sent = conn->consumed_content = 0;
  14539. conn->path_info = NULL;
  14540. conn->status_code = -1;
  14541. conn->content_len = -1;
  14542. conn->is_chunked = 0;
  14543. conn->must_close = 0;
  14544. conn->request_len = 0;
  14545. conn->request_state = 0;
  14546. conn->throttle = 0;
  14547. conn->accept_gzip = 0;
  14548. conn->response_info.content_length = conn->request_info.content_length = -1;
  14549. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14550. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14551. conn->response_info.status_text = NULL;
  14552. conn->response_info.status_code = 0;
  14553. conn->request_info.remote_user = NULL;
  14554. conn->request_info.request_method = NULL;
  14555. conn->request_info.request_uri = NULL;
  14556. /* Free cleaned local URI (if any) */
  14557. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  14558. mg_free((void *)conn->request_info.local_uri);
  14559. conn->request_info.local_uri = NULL;
  14560. }
  14561. conn->request_info.local_uri = NULL;
  14562. #if defined(USE_SERVER_STATS)
  14563. conn->processing_time = 0;
  14564. #endif
  14565. }
  14566. static int
  14567. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14568. {
  14569. if ((so->lsa.sa.sa_family == AF_INET)
  14570. || (so->lsa.sa.sa_family == AF_INET6)) {
  14571. /* Only for TCP sockets */
  14572. if (setsockopt(so->sock,
  14573. IPPROTO_TCP,
  14574. TCP_NODELAY,
  14575. (SOCK_OPT_TYPE)&nodelay_on,
  14576. sizeof(nodelay_on))
  14577. != 0) {
  14578. /* Error */
  14579. return 1;
  14580. }
  14581. }
  14582. /* OK */
  14583. return 0;
  14584. }
  14585. #if !defined(__ZEPHYR__)
  14586. static void
  14587. close_socket_gracefully(struct mg_connection *conn)
  14588. {
  14589. #if defined(_WIN32)
  14590. char buf[MG_BUF_LEN];
  14591. int n;
  14592. #endif
  14593. struct linger linger;
  14594. int error_code = 0;
  14595. int linger_timeout = -2;
  14596. socklen_t opt_len = sizeof(error_code);
  14597. if (!conn) {
  14598. return;
  14599. }
  14600. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14601. * "Note that enabling a nonzero timeout on a nonblocking socket
  14602. * is not recommended.", so set it to blocking now */
  14603. set_blocking_mode(conn->client.sock);
  14604. /* Send FIN to the client */
  14605. shutdown(conn->client.sock, SHUTDOWN_WR);
  14606. #if defined(_WIN32)
  14607. /* Read and discard pending incoming data. If we do not do that and
  14608. * close
  14609. * the socket, the data in the send buffer may be discarded. This
  14610. * behaviour is seen on Windows, when client keeps sending data
  14611. * when server decides to close the connection; then when client
  14612. * does recv() it gets no data back. */
  14613. do {
  14614. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14615. } while (n > 0);
  14616. #endif
  14617. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14618. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14619. }
  14620. /* Set linger option according to configuration */
  14621. if (linger_timeout >= 0) {
  14622. /* Set linger option to avoid socket hanging out after close. This
  14623. * prevent ephemeral port exhaust problem under high QPS. */
  14624. linger.l_onoff = 1;
  14625. #if defined(_MSC_VER)
  14626. #pragma warning(push)
  14627. #pragma warning(disable : 4244)
  14628. #endif
  14629. #if defined(GCC_DIAGNOSTIC)
  14630. #pragma GCC diagnostic push
  14631. #pragma GCC diagnostic ignored "-Wconversion"
  14632. #endif
  14633. /* Data type of linger structure elements may differ,
  14634. * so we don't know what cast we need here.
  14635. * Disable type conversion warnings. */
  14636. linger.l_linger = (linger_timeout + 999) / 1000;
  14637. #if defined(GCC_DIAGNOSTIC)
  14638. #pragma GCC diagnostic pop
  14639. #endif
  14640. #if defined(_MSC_VER)
  14641. #pragma warning(pop)
  14642. #endif
  14643. } else {
  14644. linger.l_onoff = 0;
  14645. linger.l_linger = 0;
  14646. }
  14647. if (linger_timeout < -1) {
  14648. /* Default: don't configure any linger */
  14649. } else if (getsockopt(conn->client.sock,
  14650. SOL_SOCKET,
  14651. SO_ERROR,
  14652. #if defined(_WIN32) /* WinSock uses different data type here */
  14653. (char *)&error_code,
  14654. #else
  14655. &error_code,
  14656. #endif
  14657. &opt_len)
  14658. != 0) {
  14659. /* Cannot determine if socket is already closed. This should
  14660. * not occur and never did in a test. Log an error message
  14661. * and continue. */
  14662. mg_cry_internal(conn,
  14663. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14664. __func__,
  14665. strerror(ERRNO));
  14666. #if defined(_WIN32)
  14667. } else if (error_code == WSAECONNRESET) {
  14668. #else
  14669. } else if (error_code == ECONNRESET) {
  14670. #endif
  14671. /* Socket already closed by client/peer, close socket without linger
  14672. */
  14673. } else {
  14674. /* Set linger timeout */
  14675. if (setsockopt(conn->client.sock,
  14676. SOL_SOCKET,
  14677. SO_LINGER,
  14678. (char *)&linger,
  14679. sizeof(linger))
  14680. != 0) {
  14681. mg_cry_internal(
  14682. conn,
  14683. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14684. __func__,
  14685. linger.l_onoff,
  14686. linger.l_linger,
  14687. strerror(ERRNO));
  14688. }
  14689. }
  14690. /* Now we know that our FIN is ACK-ed, safe to close */
  14691. closesocket(conn->client.sock);
  14692. conn->client.sock = INVALID_SOCKET;
  14693. }
  14694. #endif
  14695. static void
  14696. close_connection(struct mg_connection *conn)
  14697. {
  14698. #if defined(USE_SERVER_STATS)
  14699. conn->conn_state = 6; /* to close */
  14700. #endif
  14701. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14702. if (conn->lua_websocket_state) {
  14703. lua_websocket_close(conn, conn->lua_websocket_state);
  14704. conn->lua_websocket_state = NULL;
  14705. }
  14706. #endif
  14707. mg_lock_connection(conn);
  14708. /* Set close flag, so keep-alive loops will stop */
  14709. conn->must_close = 1;
  14710. /* call the connection_close callback if assigned */
  14711. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14712. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14713. conn->phys_ctx->callbacks.connection_close(conn);
  14714. }
  14715. }
  14716. /* Reset user data, after close callback is called.
  14717. * Do not reuse it. If the user needs a destructor,
  14718. * it must be done in the connection_close callback. */
  14719. mg_set_user_connection_data(conn, NULL);
  14720. #if defined(USE_SERVER_STATS)
  14721. conn->conn_state = 7; /* closing */
  14722. #endif
  14723. #if defined(USE_MBEDTLS)
  14724. if (conn->ssl != NULL) {
  14725. mbed_ssl_close(conn->ssl);
  14726. conn->ssl = NULL;
  14727. }
  14728. #elif !defined(NO_SSL)
  14729. if (conn->ssl != NULL) {
  14730. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14731. */
  14732. SSL_shutdown(conn->ssl);
  14733. SSL_free(conn->ssl);
  14734. OPENSSL_REMOVE_THREAD_STATE();
  14735. conn->ssl = NULL;
  14736. }
  14737. #endif
  14738. if (conn->client.sock != INVALID_SOCKET) {
  14739. #if defined(__ZEPHYR__)
  14740. closesocket(conn->client.sock);
  14741. #else
  14742. close_socket_gracefully(conn);
  14743. #endif
  14744. conn->client.sock = INVALID_SOCKET;
  14745. }
  14746. /* call the connection_closed callback if assigned */
  14747. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  14748. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14749. conn->phys_ctx->callbacks.connection_closed(conn);
  14750. }
  14751. }
  14752. mg_unlock_connection(conn);
  14753. #if defined(USE_SERVER_STATS)
  14754. conn->conn_state = 8; /* closed */
  14755. #endif
  14756. }
  14757. void
  14758. mg_close_connection(struct mg_connection *conn)
  14759. {
  14760. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14761. return;
  14762. }
  14763. #if defined(USE_WEBSOCKET)
  14764. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14765. if (conn->in_websocket_handling) {
  14766. /* Set close flag, so the server thread can exit. */
  14767. conn->must_close = 1;
  14768. return;
  14769. }
  14770. }
  14771. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14772. unsigned int i;
  14773. /* client context: loops must end */
  14774. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14775. conn->must_close = 1;
  14776. /* We need to get the client thread out of the select/recv call
  14777. * here. */
  14778. /* Since we use a sleep quantum of some seconds to check for recv
  14779. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14780. /* join worker thread */
  14781. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14782. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14783. }
  14784. }
  14785. #endif /* defined(USE_WEBSOCKET) */
  14786. close_connection(conn);
  14787. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14788. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14789. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14790. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14791. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14792. }
  14793. #endif
  14794. #if defined(USE_WEBSOCKET)
  14795. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14796. mg_free(conn->phys_ctx->worker_threadids);
  14797. (void)pthread_mutex_destroy(&conn->mutex);
  14798. mg_free(conn);
  14799. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14800. (void)pthread_mutex_destroy(&conn->mutex);
  14801. mg_free(conn);
  14802. }
  14803. #else
  14804. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14805. (void)pthread_mutex_destroy(&conn->mutex);
  14806. mg_free(conn);
  14807. }
  14808. #endif /* defined(USE_WEBSOCKET) */
  14809. }
  14810. static struct mg_connection *
  14811. mg_connect_client_impl(const struct mg_client_options *client_options,
  14812. int use_ssl,
  14813. char *ebuf,
  14814. size_t ebuf_len)
  14815. {
  14816. struct mg_connection *conn = NULL;
  14817. SOCKET sock;
  14818. union usa sa;
  14819. struct sockaddr *psa;
  14820. socklen_t len;
  14821. unsigned max_req_size =
  14822. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14823. /* Size of structures, aligned to 8 bytes */
  14824. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14825. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14826. conn =
  14827. (struct mg_connection *)mg_calloc(1,
  14828. conn_size + ctx_size + max_req_size);
  14829. if (conn == NULL) {
  14830. mg_snprintf(NULL,
  14831. NULL, /* No truncation check for ebuf */
  14832. ebuf,
  14833. ebuf_len,
  14834. "calloc(): %s",
  14835. strerror(ERRNO));
  14836. return NULL;
  14837. }
  14838. #if defined(GCC_DIAGNOSTIC)
  14839. #pragma GCC diagnostic push
  14840. #pragma GCC diagnostic ignored "-Wcast-align"
  14841. #endif /* defined(GCC_DIAGNOSTIC) */
  14842. /* conn_size is aligned to 8 bytes */
  14843. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14844. #if defined(GCC_DIAGNOSTIC)
  14845. #pragma GCC diagnostic pop
  14846. #endif /* defined(GCC_DIAGNOSTIC) */
  14847. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14848. conn->buf_size = (int)max_req_size;
  14849. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14850. conn->dom_ctx = &(conn->phys_ctx->dd);
  14851. if (!connect_socket(conn->phys_ctx,
  14852. client_options->host,
  14853. client_options->port,
  14854. use_ssl,
  14855. ebuf,
  14856. ebuf_len,
  14857. &sock,
  14858. &sa)) {
  14859. /* ebuf is set by connect_socket,
  14860. * free all memory and return NULL; */
  14861. mg_free(conn);
  14862. return NULL;
  14863. }
  14864. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14865. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14866. && !defined(NO_SSL_DL)
  14867. if (use_ssl
  14868. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14869. == NULL) {
  14870. mg_snprintf(NULL,
  14871. NULL, /* No truncation check for ebuf */
  14872. ebuf,
  14873. ebuf_len,
  14874. "SSL_CTX_new error: %s",
  14875. ssl_error());
  14876. closesocket(sock);
  14877. mg_free(conn);
  14878. return NULL;
  14879. }
  14880. #else
  14881. if (use_ssl
  14882. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14883. == NULL) {
  14884. mg_snprintf(NULL,
  14885. NULL, /* No truncation check for ebuf */
  14886. ebuf,
  14887. ebuf_len,
  14888. "SSL_CTX_new error: %s",
  14889. ssl_error());
  14890. closesocket(sock);
  14891. mg_free(conn);
  14892. return NULL;
  14893. }
  14894. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14895. #endif /* NO_SSL */
  14896. #if defined(USE_IPV6)
  14897. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14898. : sizeof(conn->client.rsa.sin6);
  14899. psa = (sa.sa.sa_family == AF_INET)
  14900. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14901. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14902. #else
  14903. len = sizeof(conn->client.rsa.sin);
  14904. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14905. #endif
  14906. conn->client.sock = sock;
  14907. conn->client.lsa = sa;
  14908. if (getsockname(sock, psa, &len) != 0) {
  14909. mg_cry_internal(conn,
  14910. "%s: getsockname() failed: %s",
  14911. __func__,
  14912. strerror(ERRNO));
  14913. }
  14914. conn->client.is_ssl = use_ssl ? 1 : 0;
  14915. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14916. mg_snprintf(NULL,
  14917. NULL, /* No truncation check for ebuf */
  14918. ebuf,
  14919. ebuf_len,
  14920. "Can not create mutex");
  14921. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14922. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14923. #endif
  14924. closesocket(sock);
  14925. mg_free(conn);
  14926. return NULL;
  14927. }
  14928. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14929. if (use_ssl) {
  14930. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14931. * SSL_CTX_set_verify call is needed to switch off server
  14932. * certificate checking, which is off by default in OpenSSL and
  14933. * on in yaSSL. */
  14934. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14935. * SSL_VERIFY_PEER, verify_ssl_server); */
  14936. if (client_options->client_cert) {
  14937. if (!ssl_use_pem_file(conn->phys_ctx,
  14938. conn->dom_ctx,
  14939. client_options->client_cert,
  14940. NULL)) {
  14941. mg_snprintf(NULL,
  14942. NULL, /* No truncation check for ebuf */
  14943. ebuf,
  14944. ebuf_len,
  14945. "Can not use SSL client certificate");
  14946. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14947. closesocket(sock);
  14948. mg_free(conn);
  14949. return NULL;
  14950. }
  14951. }
  14952. if (client_options->server_cert) {
  14953. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14954. client_options->server_cert,
  14955. NULL)
  14956. != 1) {
  14957. mg_cry_internal(conn,
  14958. "SSL_CTX_load_verify_locations error: %s ",
  14959. ssl_error());
  14960. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14961. closesocket(sock);
  14962. mg_free(conn);
  14963. return NULL;
  14964. }
  14965. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14966. } else {
  14967. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14968. }
  14969. if (!sslize(conn, SSL_connect, client_options)) {
  14970. mg_snprintf(NULL,
  14971. NULL, /* No truncation check for ebuf */
  14972. ebuf,
  14973. ebuf_len,
  14974. "SSL connection error");
  14975. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14976. closesocket(sock);
  14977. mg_free(conn);
  14978. return NULL;
  14979. }
  14980. }
  14981. #endif
  14982. return conn;
  14983. }
  14984. CIVETWEB_API struct mg_connection *
  14985. mg_connect_client_secure(const struct mg_client_options *client_options,
  14986. char *error_buffer,
  14987. size_t error_buffer_size)
  14988. {
  14989. return mg_connect_client_impl(client_options,
  14990. 1,
  14991. error_buffer,
  14992. error_buffer_size);
  14993. }
  14994. struct mg_connection *
  14995. mg_connect_client(const char *host,
  14996. int port,
  14997. int use_ssl,
  14998. char *error_buffer,
  14999. size_t error_buffer_size)
  15000. {
  15001. struct mg_client_options opts;
  15002. memset(&opts, 0, sizeof(opts));
  15003. opts.host = host;
  15004. opts.port = port;
  15005. return mg_connect_client_impl(&opts,
  15006. use_ssl,
  15007. error_buffer,
  15008. error_buffer_size);
  15009. }
  15010. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15011. struct mg_connection *
  15012. mg_connect_client2(const char *host,
  15013. const char *protocol,
  15014. int port,
  15015. const char *path,
  15016. struct mg_init_data *init,
  15017. struct mg_error_data *error)
  15018. {
  15019. (void)path;
  15020. (void)init;
  15021. int is_ssl, is_ws;
  15022. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15023. if (error != NULL) {
  15024. error->code = 0;
  15025. if (error->text_buffer_size > 0) {
  15026. *error->text = 0;
  15027. }
  15028. }
  15029. if ((host == NULL) || (protocol == NULL)) {
  15030. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15031. mg_snprintf(NULL,
  15032. NULL, /* No truncation check for error buffers */
  15033. error->text,
  15034. error->text_buffer_size,
  15035. "%s",
  15036. "Invalid parameters");
  15037. }
  15038. return NULL;
  15039. }
  15040. /* check all known protocolls */
  15041. if (!mg_strcasecmp(protocol, "http")) {
  15042. is_ssl = 0;
  15043. is_ws = 0;
  15044. } else if (!mg_strcasecmp(protocol, "https")) {
  15045. is_ssl = 1;
  15046. is_ws = 0;
  15047. #if defined(USE_WEBSOCKET)
  15048. } else if (!mg_strcasecmp(protocol, "ws")) {
  15049. is_ssl = 0;
  15050. is_ws = 1;
  15051. } else if (!mg_strcasecmp(protocol, "wss")) {
  15052. is_ssl = 1;
  15053. is_ws = 1;
  15054. #endif
  15055. } else {
  15056. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15057. mg_snprintf(NULL,
  15058. NULL, /* No truncation check for error buffers */
  15059. error->text,
  15060. error->text_buffer_size,
  15061. "Protocol %s not supported",
  15062. protocol);
  15063. }
  15064. return NULL;
  15065. }
  15066. /* TODO: The current implementation here just calls the old
  15067. * implementations, without using any new options. This is just a first
  15068. * step to test the new interfaces. */
  15069. #if defined(USE_WEBSOCKET)
  15070. if (is_ws) {
  15071. /* TODO: implement all options */
  15072. return mg_connect_websocket_client(
  15073. host,
  15074. port,
  15075. is_ssl,
  15076. ((error != NULL) ? error->text : NULL),
  15077. ((error != NULL) ? error->text_buffer_size : 0),
  15078. (path ? path : ""),
  15079. NULL /* TODO: origin */,
  15080. experimental_websocket_client_data_wrapper,
  15081. experimental_websocket_client_close_wrapper,
  15082. (void *)init->callbacks);
  15083. }
  15084. #else
  15085. (void)is_ws;
  15086. #endif
  15087. /* TODO: all additional options */
  15088. struct mg_client_options opts;
  15089. memset(&opts, 0, sizeof(opts));
  15090. opts.host = host;
  15091. opts.port = port;
  15092. return mg_connect_client_impl(&opts,
  15093. is_ssl,
  15094. ((error != NULL) ? error->text : NULL),
  15095. ((error != NULL) ? error->text_buffer_size
  15096. : 0));
  15097. }
  15098. #endif
  15099. static const struct {
  15100. const char *proto;
  15101. size_t proto_len;
  15102. unsigned default_port;
  15103. } abs_uri_protocols[] = {{"http://", 7, 80},
  15104. {"https://", 8, 443},
  15105. {"ws://", 5, 80},
  15106. {"wss://", 6, 443},
  15107. {NULL, 0, 0}};
  15108. /* Check if the uri is valid.
  15109. * return 0 for invalid uri,
  15110. * return 1 for *,
  15111. * return 2 for relative uri,
  15112. * return 3 for absolute uri without port,
  15113. * return 4 for absolute uri with port */
  15114. static int
  15115. get_uri_type(const char *uri)
  15116. {
  15117. int i;
  15118. const char *hostend, *portbegin;
  15119. char *portend;
  15120. unsigned long port;
  15121. /* According to the HTTP standard
  15122. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15123. * URI can be an asterisk (*) or should start with slash (relative uri),
  15124. * or it should start with the protocol (absolute uri). */
  15125. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15126. /* asterisk */
  15127. return 1;
  15128. }
  15129. /* Valid URIs according to RFC 3986
  15130. * (https://www.ietf.org/rfc/rfc3986.txt)
  15131. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15132. * and unreserved characters A-Z a-z 0-9 and -._~
  15133. * and % encoded symbols.
  15134. */
  15135. for (i = 0; uri[i] != 0; i++) {
  15136. if (uri[i] < 33) {
  15137. /* control characters and spaces are invalid */
  15138. return 0;
  15139. }
  15140. /* Allow everything else here (See #894) */
  15141. }
  15142. /* A relative uri starts with a / character */
  15143. if (uri[0] == '/') {
  15144. /* relative uri */
  15145. return 2;
  15146. }
  15147. /* It could be an absolute uri: */
  15148. /* This function only checks if the uri is valid, not if it is
  15149. * addressing the current server. So civetweb can also be used
  15150. * as a proxy server. */
  15151. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15152. if (mg_strncasecmp(uri,
  15153. abs_uri_protocols[i].proto,
  15154. abs_uri_protocols[i].proto_len)
  15155. == 0) {
  15156. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15157. if (!hostend) {
  15158. return 0;
  15159. }
  15160. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15161. if (!portbegin) {
  15162. return 3;
  15163. }
  15164. port = strtoul(portbegin + 1, &portend, 10);
  15165. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15166. return 0;
  15167. }
  15168. return 4;
  15169. }
  15170. }
  15171. return 0;
  15172. }
  15173. /* Return NULL or the relative uri at the current server */
  15174. static const char *
  15175. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15176. {
  15177. const char *server_domain;
  15178. size_t server_domain_len;
  15179. size_t request_domain_len = 0;
  15180. unsigned long port = 0;
  15181. int i, auth_domain_check_enabled;
  15182. const char *hostbegin = NULL;
  15183. const char *hostend = NULL;
  15184. const char *portbegin;
  15185. char *portend;
  15186. auth_domain_check_enabled =
  15187. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15188. /* DNS is case insensitive, so use case insensitive string compare here
  15189. */
  15190. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15191. if (mg_strncasecmp(uri,
  15192. abs_uri_protocols[i].proto,
  15193. abs_uri_protocols[i].proto_len)
  15194. == 0) {
  15195. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15196. hostend = strchr(hostbegin, '/');
  15197. if (!hostend) {
  15198. return 0;
  15199. }
  15200. portbegin = strchr(hostbegin, ':');
  15201. if ((!portbegin) || (portbegin > hostend)) {
  15202. port = abs_uri_protocols[i].default_port;
  15203. request_domain_len = (size_t)(hostend - hostbegin);
  15204. } else {
  15205. port = strtoul(portbegin + 1, &portend, 10);
  15206. if ((portend != hostend) || (port <= 0)
  15207. || !is_valid_port(port)) {
  15208. return 0;
  15209. }
  15210. request_domain_len = (size_t)(portbegin - hostbegin);
  15211. }
  15212. /* protocol found, port set */
  15213. break;
  15214. }
  15215. }
  15216. if (!port) {
  15217. /* port remains 0 if the protocol is not found */
  15218. return 0;
  15219. }
  15220. /* Check if the request is directed to a different server. */
  15221. /* First check if the port is the same. */
  15222. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15223. /* Request is directed to a different port */
  15224. return 0;
  15225. }
  15226. /* Finally check if the server corresponds to the authentication
  15227. * domain of the server (the server domain).
  15228. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15229. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15230. * but do not allow substrings (like
  15231. * http://notmydomain.com/path/file.ext
  15232. * or http://mydomain.com.fake/path/file.ext).
  15233. */
  15234. if (auth_domain_check_enabled) {
  15235. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15236. server_domain_len = strlen(server_domain);
  15237. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15238. return 0;
  15239. }
  15240. if ((request_domain_len == server_domain_len)
  15241. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15242. /* Request is directed to this server - full name match. */
  15243. } else {
  15244. if (request_domain_len < (server_domain_len + 2)) {
  15245. /* Request is directed to another server: The server name
  15246. * is longer than the request name.
  15247. * Drop this case here to avoid overflows in the
  15248. * following checks. */
  15249. return 0;
  15250. }
  15251. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15252. /* Request is directed to another server: It could be a
  15253. * substring
  15254. * like notmyserver.com */
  15255. return 0;
  15256. }
  15257. if (0
  15258. != memcmp(server_domain,
  15259. hostbegin + request_domain_len - server_domain_len,
  15260. server_domain_len)) {
  15261. /* Request is directed to another server:
  15262. * The server name is different. */
  15263. return 0;
  15264. }
  15265. }
  15266. }
  15267. return hostend;
  15268. }
  15269. static int
  15270. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15271. {
  15272. if (ebuf_len > 0) {
  15273. ebuf[0] = '\0';
  15274. }
  15275. *err = 0;
  15276. reset_per_request_attributes(conn);
  15277. if (!conn) {
  15278. mg_snprintf(conn,
  15279. NULL, /* No truncation check for ebuf */
  15280. ebuf,
  15281. ebuf_len,
  15282. "%s",
  15283. "Internal error");
  15284. *err = 500;
  15285. return 0;
  15286. }
  15287. /* Set the time the request was received. This value should be used for
  15288. * timeouts. */
  15289. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15290. conn->request_len =
  15291. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15292. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15293. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15294. mg_snprintf(conn,
  15295. NULL, /* No truncation check for ebuf */
  15296. ebuf,
  15297. ebuf_len,
  15298. "%s",
  15299. "Invalid message size");
  15300. *err = 500;
  15301. return 0;
  15302. }
  15303. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15304. mg_snprintf(conn,
  15305. NULL, /* No truncation check for ebuf */
  15306. ebuf,
  15307. ebuf_len,
  15308. "%s",
  15309. "Message too large");
  15310. *err = 413;
  15311. return 0;
  15312. }
  15313. if (conn->request_len <= 0) {
  15314. if (conn->data_len > 0) {
  15315. mg_snprintf(conn,
  15316. NULL, /* No truncation check for ebuf */
  15317. ebuf,
  15318. ebuf_len,
  15319. "%s",
  15320. "Malformed message");
  15321. *err = 400;
  15322. } else {
  15323. /* Server did not recv anything -> just close the connection */
  15324. conn->must_close = 1;
  15325. mg_snprintf(conn,
  15326. NULL, /* No truncation check for ebuf */
  15327. ebuf,
  15328. ebuf_len,
  15329. "%s",
  15330. "No data received");
  15331. *err = 0;
  15332. }
  15333. return 0;
  15334. }
  15335. return 1;
  15336. }
  15337. static int
  15338. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15339. {
  15340. const char *cl;
  15341. conn->connection_type =
  15342. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15343. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15344. return 0;
  15345. }
  15346. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15347. <= 0) {
  15348. mg_snprintf(conn,
  15349. NULL, /* No truncation check for ebuf */
  15350. ebuf,
  15351. ebuf_len,
  15352. "%s",
  15353. "Bad request");
  15354. *err = 400;
  15355. return 0;
  15356. }
  15357. /* Message is a valid request */
  15358. if (!switch_domain_context(conn)) {
  15359. mg_snprintf(conn,
  15360. NULL, /* No truncation check for ebuf */
  15361. ebuf,
  15362. ebuf_len,
  15363. "%s",
  15364. "Bad request: Host mismatch");
  15365. *err = 400;
  15366. return 0;
  15367. }
  15368. #if USE_ZLIB
  15369. if (((cl = get_header(conn->request_info.http_headers,
  15370. conn->request_info.num_headers,
  15371. "Accept-Encoding"))
  15372. != NULL)
  15373. && strstr(cl, "gzip")) {
  15374. conn->accept_gzip = 1;
  15375. }
  15376. #endif
  15377. if (((cl = get_header(conn->request_info.http_headers,
  15378. conn->request_info.num_headers,
  15379. "Transfer-Encoding"))
  15380. != NULL)
  15381. && mg_strcasecmp(cl, "identity")) {
  15382. if (mg_strcasecmp(cl, "chunked")) {
  15383. mg_snprintf(conn,
  15384. NULL, /* No truncation check for ebuf */
  15385. ebuf,
  15386. ebuf_len,
  15387. "%s",
  15388. "Bad request");
  15389. *err = 400;
  15390. return 0;
  15391. }
  15392. conn->is_chunked = 1;
  15393. conn->content_len = 0; /* not yet read */
  15394. } else if ((cl = get_header(conn->request_info.http_headers,
  15395. conn->request_info.num_headers,
  15396. "Content-Length"))
  15397. != NULL) {
  15398. /* Request has content length set */
  15399. char *endptr = NULL;
  15400. conn->content_len = strtoll(cl, &endptr, 10);
  15401. if ((endptr == cl) || (conn->content_len < 0)) {
  15402. mg_snprintf(conn,
  15403. NULL, /* No truncation check for ebuf */
  15404. ebuf,
  15405. ebuf_len,
  15406. "%s",
  15407. "Bad request");
  15408. *err = 411;
  15409. return 0;
  15410. }
  15411. /* Publish the content length back to the request info. */
  15412. conn->request_info.content_length = conn->content_len;
  15413. } else {
  15414. /* There is no exception, see RFC7230. */
  15415. conn->content_len = 0;
  15416. }
  15417. return 1;
  15418. }
  15419. /* conn is assumed to be valid in this internal function */
  15420. static int
  15421. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15422. {
  15423. const char *cl;
  15424. conn->connection_type =
  15425. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15426. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15427. return 0;
  15428. }
  15429. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15430. <= 0) {
  15431. mg_snprintf(conn,
  15432. NULL, /* No truncation check for ebuf */
  15433. ebuf,
  15434. ebuf_len,
  15435. "%s",
  15436. "Bad response");
  15437. *err = 400;
  15438. return 0;
  15439. }
  15440. /* Message is a valid response */
  15441. if (((cl = get_header(conn->response_info.http_headers,
  15442. conn->response_info.num_headers,
  15443. "Transfer-Encoding"))
  15444. != NULL)
  15445. && mg_strcasecmp(cl, "identity")) {
  15446. if (mg_strcasecmp(cl, "chunked")) {
  15447. mg_snprintf(conn,
  15448. NULL, /* No truncation check for ebuf */
  15449. ebuf,
  15450. ebuf_len,
  15451. "%s",
  15452. "Bad request");
  15453. *err = 400;
  15454. return 0;
  15455. }
  15456. conn->is_chunked = 1;
  15457. conn->content_len = 0; /* not yet read */
  15458. } else if ((cl = get_header(conn->response_info.http_headers,
  15459. conn->response_info.num_headers,
  15460. "Content-Length"))
  15461. != NULL) {
  15462. char *endptr = NULL;
  15463. conn->content_len = strtoll(cl, &endptr, 10);
  15464. if ((endptr == cl) || (conn->content_len < 0)) {
  15465. mg_snprintf(conn,
  15466. NULL, /* No truncation check for ebuf */
  15467. ebuf,
  15468. ebuf_len,
  15469. "%s",
  15470. "Bad request");
  15471. *err = 411;
  15472. return 0;
  15473. }
  15474. /* Publish the content length back to the response info. */
  15475. conn->response_info.content_length = conn->content_len;
  15476. /* TODO: check if it is still used in response_info */
  15477. conn->request_info.content_length = conn->content_len;
  15478. /* TODO: we should also consider HEAD method */
  15479. if (conn->response_info.status_code == 304) {
  15480. conn->content_len = 0;
  15481. }
  15482. } else {
  15483. /* TODO: we should also consider HEAD method */
  15484. if (((conn->response_info.status_code >= 100)
  15485. && (conn->response_info.status_code <= 199))
  15486. || (conn->response_info.status_code == 204)
  15487. || (conn->response_info.status_code == 304)) {
  15488. conn->content_len = 0;
  15489. } else {
  15490. conn->content_len = -1; /* unknown content length */
  15491. }
  15492. }
  15493. return 1;
  15494. }
  15495. int
  15496. mg_get_response(struct mg_connection *conn,
  15497. char *ebuf,
  15498. size_t ebuf_len,
  15499. int timeout)
  15500. {
  15501. int err, ret;
  15502. char txt[32]; /* will not overflow */
  15503. char *save_timeout;
  15504. char *new_timeout;
  15505. if (ebuf_len > 0) {
  15506. ebuf[0] = '\0';
  15507. }
  15508. if (!conn) {
  15509. mg_snprintf(conn,
  15510. NULL, /* No truncation check for ebuf */
  15511. ebuf,
  15512. ebuf_len,
  15513. "%s",
  15514. "Parameter error");
  15515. return -1;
  15516. }
  15517. /* Reset the previous responses */
  15518. conn->data_len = 0;
  15519. /* Implementation of API function for HTTP clients */
  15520. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15521. if (timeout >= 0) {
  15522. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15523. new_timeout = txt;
  15524. } else {
  15525. new_timeout = NULL;
  15526. }
  15527. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15528. ret = get_response(conn, ebuf, ebuf_len, &err);
  15529. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15530. /* TODO: here, the URI is the http response code */
  15531. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15532. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15533. /* TODO (mid): Define proper return values - maybe return length?
  15534. * For the first test use <0 for error and >0 for OK */
  15535. return (ret == 0) ? -1 : +1;
  15536. }
  15537. struct mg_connection *
  15538. mg_download(const char *host,
  15539. int port,
  15540. int use_ssl,
  15541. char *ebuf,
  15542. size_t ebuf_len,
  15543. const char *fmt,
  15544. ...)
  15545. {
  15546. struct mg_connection *conn;
  15547. va_list ap;
  15548. int i;
  15549. int reqerr;
  15550. if (ebuf_len > 0) {
  15551. ebuf[0] = '\0';
  15552. }
  15553. va_start(ap, fmt);
  15554. /* open a connection */
  15555. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15556. if (conn != NULL) {
  15557. i = mg_vprintf(conn, fmt, ap);
  15558. if (i <= 0) {
  15559. mg_snprintf(conn,
  15560. NULL, /* No truncation check for ebuf */
  15561. ebuf,
  15562. ebuf_len,
  15563. "%s",
  15564. "Error sending request");
  15565. } else {
  15566. /* make sure the buffer is clear */
  15567. conn->data_len = 0;
  15568. get_response(conn, ebuf, ebuf_len, &reqerr);
  15569. /* TODO: here, the URI is the http response code */
  15570. conn->request_info.local_uri = conn->request_info.request_uri;
  15571. }
  15572. }
  15573. /* if an error occurred, close the connection */
  15574. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15575. mg_close_connection(conn);
  15576. conn = NULL;
  15577. }
  15578. va_end(ap);
  15579. return conn;
  15580. }
  15581. struct websocket_client_thread_data {
  15582. struct mg_connection *conn;
  15583. mg_websocket_data_handler data_handler;
  15584. mg_websocket_close_handler close_handler;
  15585. void *callback_data;
  15586. };
  15587. #if defined(USE_WEBSOCKET)
  15588. #if defined(_WIN32)
  15589. static unsigned __stdcall websocket_client_thread(void *data)
  15590. #else
  15591. static void *
  15592. websocket_client_thread(void *data)
  15593. #endif
  15594. {
  15595. struct websocket_client_thread_data *cdata =
  15596. (struct websocket_client_thread_data *)data;
  15597. void *user_thread_ptr = NULL;
  15598. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15599. struct sigaction sa;
  15600. /* Ignore SIGPIPE */
  15601. memset(&sa, 0, sizeof(sa));
  15602. sa.sa_handler = SIG_IGN;
  15603. sigaction(SIGPIPE, &sa, NULL);
  15604. #endif
  15605. mg_set_thread_name("ws-clnt");
  15606. if (cdata->conn->phys_ctx) {
  15607. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15608. /* 3 indicates a websocket client thread */
  15609. /* TODO: check if conn->phys_ctx can be set */
  15610. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15611. cdata->conn->phys_ctx, 3);
  15612. }
  15613. }
  15614. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15615. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15616. if (cdata->close_handler != NULL) {
  15617. cdata->close_handler(cdata->conn, cdata->callback_data);
  15618. }
  15619. /* The websocket_client context has only this thread. If it runs out,
  15620. set the stop_flag to 2 (= "stopped"). */
  15621. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15622. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15623. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15624. 3,
  15625. user_thread_ptr);
  15626. }
  15627. mg_free((void *)cdata);
  15628. #if defined(_WIN32)
  15629. return 0;
  15630. #else
  15631. return NULL;
  15632. #endif
  15633. }
  15634. #endif
  15635. static struct mg_connection *
  15636. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15637. int use_ssl,
  15638. char *error_buffer,
  15639. size_t error_buffer_size,
  15640. const char *path,
  15641. const char *origin,
  15642. const char *extensions,
  15643. mg_websocket_data_handler data_func,
  15644. mg_websocket_close_handler close_func,
  15645. void *user_data)
  15646. {
  15647. struct mg_connection *conn = NULL;
  15648. #if defined(USE_WEBSOCKET)
  15649. struct websocket_client_thread_data *thread_data;
  15650. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15651. const char *host = client_options->host;
  15652. int i;
  15653. #if defined(__clang__)
  15654. #pragma clang diagnostic push
  15655. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15656. #endif
  15657. /* Establish the client connection and request upgrade */
  15658. conn = mg_connect_client_impl(client_options,
  15659. use_ssl,
  15660. error_buffer,
  15661. error_buffer_size);
  15662. /* Connection object will be null if something goes wrong */
  15663. if (conn == NULL) {
  15664. /* error_buffer should be already filled ... */
  15665. if (!error_buffer[0]) {
  15666. /* ... if not add an error message */
  15667. mg_snprintf(conn,
  15668. NULL, /* No truncation check for ebuf */
  15669. error_buffer,
  15670. error_buffer_size,
  15671. "Unexpected error");
  15672. }
  15673. return NULL;
  15674. }
  15675. if (origin != NULL) {
  15676. if (extensions != NULL) {
  15677. i = mg_printf(conn,
  15678. "GET %s HTTP/1.1\r\n"
  15679. "Host: %s\r\n"
  15680. "Upgrade: websocket\r\n"
  15681. "Connection: Upgrade\r\n"
  15682. "Sec-WebSocket-Key: %s\r\n"
  15683. "Sec-WebSocket-Version: 13\r\n"
  15684. "Sec-WebSocket-Extensions: %s\r\n"
  15685. "Origin: %s\r\n"
  15686. "\r\n",
  15687. path,
  15688. host,
  15689. magic,
  15690. extensions,
  15691. origin);
  15692. } else {
  15693. i = mg_printf(conn,
  15694. "GET %s HTTP/1.1\r\n"
  15695. "Host: %s\r\n"
  15696. "Upgrade: websocket\r\n"
  15697. "Connection: Upgrade\r\n"
  15698. "Sec-WebSocket-Key: %s\r\n"
  15699. "Sec-WebSocket-Version: 13\r\n"
  15700. "Origin: %s\r\n"
  15701. "\r\n",
  15702. path,
  15703. host,
  15704. magic,
  15705. origin);
  15706. }
  15707. } else {
  15708. if (extensions != NULL) {
  15709. i = mg_printf(conn,
  15710. "GET %s HTTP/1.1\r\n"
  15711. "Host: %s\r\n"
  15712. "Upgrade: websocket\r\n"
  15713. "Connection: Upgrade\r\n"
  15714. "Sec-WebSocket-Key: %s\r\n"
  15715. "Sec-WebSocket-Version: 13\r\n"
  15716. "Sec-WebSocket-Extensions: %s\r\n"
  15717. "\r\n",
  15718. path,
  15719. host,
  15720. magic,
  15721. extensions);
  15722. } else {
  15723. i = mg_printf(conn,
  15724. "GET %s HTTP/1.1\r\n"
  15725. "Host: %s\r\n"
  15726. "Upgrade: websocket\r\n"
  15727. "Connection: Upgrade\r\n"
  15728. "Sec-WebSocket-Key: %s\r\n"
  15729. "Sec-WebSocket-Version: 13\r\n"
  15730. "\r\n",
  15731. path,
  15732. host,
  15733. magic);
  15734. }
  15735. }
  15736. if (i <= 0) {
  15737. mg_snprintf(conn,
  15738. NULL, /* No truncation check for ebuf */
  15739. error_buffer,
  15740. error_buffer_size,
  15741. "%s",
  15742. "Error sending request");
  15743. mg_close_connection(conn);
  15744. return NULL;
  15745. }
  15746. conn->data_len = 0;
  15747. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15748. mg_close_connection(conn);
  15749. return NULL;
  15750. }
  15751. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15752. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15753. #if defined(__clang__)
  15754. #pragma clang diagnostic pop
  15755. #endif
  15756. if (conn->response_info.status_code != 101) {
  15757. /* We sent an "upgrade" request. For a correct websocket
  15758. * protocol handshake, we expect a "101 Continue" response.
  15759. * Otherwise it is a protocol violation. Maybe the HTTP
  15760. * Server does not know websockets. */
  15761. if (!*error_buffer) {
  15762. /* set an error, if not yet set */
  15763. mg_snprintf(conn,
  15764. NULL, /* No truncation check for ebuf */
  15765. error_buffer,
  15766. error_buffer_size,
  15767. "Unexpected server reply");
  15768. }
  15769. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15770. mg_close_connection(conn);
  15771. return NULL;
  15772. }
  15773. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15774. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15775. if (!thread_data) {
  15776. DEBUG_TRACE("%s\r\n", "Out of memory");
  15777. mg_close_connection(conn);
  15778. return NULL;
  15779. }
  15780. thread_data->conn = conn;
  15781. thread_data->data_handler = data_func;
  15782. thread_data->close_handler = close_func;
  15783. thread_data->callback_data = user_data;
  15784. conn->phys_ctx->worker_threadids =
  15785. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15786. if (!conn->phys_ctx->worker_threadids) {
  15787. DEBUG_TRACE("%s\r\n", "Out of memory");
  15788. mg_free(thread_data);
  15789. mg_close_connection(conn);
  15790. return NULL;
  15791. }
  15792. /* Now upgrade to ws/wss client context */
  15793. conn->phys_ctx->user_data = user_data;
  15794. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15795. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15796. /* Start a thread to read the websocket client connection
  15797. * This thread will automatically stop when mg_disconnect is
  15798. * called on the client connection */
  15799. if (mg_start_thread_with_id(websocket_client_thread,
  15800. thread_data,
  15801. conn->phys_ctx->worker_threadids)
  15802. != 0) {
  15803. conn->phys_ctx->cfg_worker_threads = 0;
  15804. mg_free(thread_data);
  15805. mg_close_connection(conn);
  15806. conn = NULL;
  15807. DEBUG_TRACE("%s",
  15808. "Websocket client connect thread could not be started\r\n");
  15809. }
  15810. #else
  15811. /* Appease "unused parameter" warnings */
  15812. (void)client_options;
  15813. (void)use_ssl;
  15814. (void)error_buffer;
  15815. (void)error_buffer_size;
  15816. (void)path;
  15817. (void)origin;
  15818. (void)extensions;
  15819. (void)user_data;
  15820. (void)data_func;
  15821. (void)close_func;
  15822. #endif
  15823. return conn;
  15824. }
  15825. struct mg_connection *
  15826. mg_connect_websocket_client(const char *host,
  15827. int port,
  15828. int use_ssl,
  15829. char *error_buffer,
  15830. size_t error_buffer_size,
  15831. const char *path,
  15832. const char *origin,
  15833. mg_websocket_data_handler data_func,
  15834. mg_websocket_close_handler close_func,
  15835. void *user_data)
  15836. {
  15837. struct mg_client_options client_options;
  15838. memset(&client_options, 0, sizeof(client_options));
  15839. client_options.host = host;
  15840. client_options.port = port;
  15841. return mg_connect_websocket_client_impl(&client_options,
  15842. use_ssl,
  15843. error_buffer,
  15844. error_buffer_size,
  15845. path,
  15846. origin,
  15847. NULL,
  15848. data_func,
  15849. close_func,
  15850. user_data);
  15851. }
  15852. struct mg_connection *
  15853. mg_connect_websocket_client_secure(
  15854. const struct mg_client_options *client_options,
  15855. char *error_buffer,
  15856. size_t error_buffer_size,
  15857. const char *path,
  15858. const char *origin,
  15859. mg_websocket_data_handler data_func,
  15860. mg_websocket_close_handler close_func,
  15861. void *user_data)
  15862. {
  15863. if (!client_options) {
  15864. return NULL;
  15865. }
  15866. return mg_connect_websocket_client_impl(client_options,
  15867. 1,
  15868. error_buffer,
  15869. error_buffer_size,
  15870. path,
  15871. origin,
  15872. NULL,
  15873. data_func,
  15874. close_func,
  15875. user_data);
  15876. }
  15877. struct mg_connection *
  15878. mg_connect_websocket_client_extensions(const char *host,
  15879. int port,
  15880. int use_ssl,
  15881. char *error_buffer,
  15882. size_t error_buffer_size,
  15883. const char *path,
  15884. const char *origin,
  15885. const char *extensions,
  15886. mg_websocket_data_handler data_func,
  15887. mg_websocket_close_handler close_func,
  15888. void *user_data)
  15889. {
  15890. struct mg_client_options client_options;
  15891. memset(&client_options, 0, sizeof(client_options));
  15892. client_options.host = host;
  15893. client_options.port = port;
  15894. return mg_connect_websocket_client_impl(&client_options,
  15895. use_ssl,
  15896. error_buffer,
  15897. error_buffer_size,
  15898. path,
  15899. origin,
  15900. extensions,
  15901. data_func,
  15902. close_func,
  15903. user_data);
  15904. }
  15905. struct mg_connection *
  15906. mg_connect_websocket_client_secure_extensions(
  15907. const struct mg_client_options *client_options,
  15908. char *error_buffer,
  15909. size_t error_buffer_size,
  15910. const char *path,
  15911. const char *origin,
  15912. const char *extensions,
  15913. mg_websocket_data_handler data_func,
  15914. mg_websocket_close_handler close_func,
  15915. void *user_data)
  15916. {
  15917. if (!client_options) {
  15918. return NULL;
  15919. }
  15920. return mg_connect_websocket_client_impl(client_options,
  15921. 1,
  15922. error_buffer,
  15923. error_buffer_size,
  15924. path,
  15925. origin,
  15926. extensions,
  15927. data_func,
  15928. close_func,
  15929. user_data);
  15930. }
  15931. /* Prepare connection data structure */
  15932. static void
  15933. init_connection(struct mg_connection *conn)
  15934. {
  15935. /* Is keep alive allowed by the server */
  15936. int keep_alive_enabled =
  15937. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15938. if (!keep_alive_enabled) {
  15939. conn->must_close = 1;
  15940. }
  15941. /* Important: on new connection, reset the receiving buffer. Credit
  15942. * goes to crule42. */
  15943. conn->data_len = 0;
  15944. conn->handled_requests = 0;
  15945. conn->connection_type = CONNECTION_TYPE_INVALID;
  15946. mg_set_user_connection_data(conn, NULL);
  15947. #if defined(USE_SERVER_STATS)
  15948. conn->conn_state = 2; /* init */
  15949. #endif
  15950. /* call the init_connection callback if assigned */
  15951. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15952. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15953. void *conn_data = NULL;
  15954. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15955. mg_set_user_connection_data(conn, conn_data);
  15956. }
  15957. }
  15958. }
  15959. /* Process a connection - may handle multiple requests
  15960. * using the same connection.
  15961. * Must be called with a valid connection (conn and
  15962. * conn->phys_ctx must be valid).
  15963. */
  15964. static void
  15965. process_new_connection(struct mg_connection *conn)
  15966. {
  15967. struct mg_request_info *ri = &conn->request_info;
  15968. int keep_alive, discard_len;
  15969. char ebuf[100];
  15970. const char *hostend;
  15971. int reqerr, uri_type;
  15972. #if defined(USE_SERVER_STATS)
  15973. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15974. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15975. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15976. #endif
  15977. DEBUG_TRACE("Start processing connection from %s",
  15978. conn->request_info.remote_addr);
  15979. /* Loop over multiple requests sent using the same connection
  15980. * (while "keep alive"). */
  15981. do {
  15982. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15983. conn->handled_requests + 1);
  15984. #if defined(USE_SERVER_STATS)
  15985. conn->conn_state = 3; /* ready */
  15986. #endif
  15987. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15988. /* The request sent by the client could not be understood by
  15989. * the server, or it was incomplete or a timeout. Send an
  15990. * error message and close the connection. */
  15991. if (reqerr > 0) {
  15992. DEBUG_ASSERT(ebuf[0] != '\0');
  15993. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15994. }
  15995. } else if (strcmp(ri->http_version, "1.0")
  15996. && strcmp(ri->http_version, "1.1")) {
  15997. /* HTTP/2 is not allowed here */
  15998. mg_snprintf(conn,
  15999. NULL, /* No truncation check for ebuf */
  16000. ebuf,
  16001. sizeof(ebuf),
  16002. "Bad HTTP version: [%s]",
  16003. ri->http_version);
  16004. mg_send_http_error(conn, 505, "%s", ebuf);
  16005. }
  16006. if (ebuf[0] == '\0') {
  16007. uri_type = get_uri_type(conn->request_info.request_uri);
  16008. switch (uri_type) {
  16009. case 1:
  16010. /* Asterisk */
  16011. conn->request_info.local_uri_raw = 0;
  16012. /* TODO: Deal with '*'. */
  16013. break;
  16014. case 2:
  16015. /* relative uri */
  16016. conn->request_info.local_uri_raw =
  16017. conn->request_info.request_uri;
  16018. break;
  16019. case 3:
  16020. case 4:
  16021. /* absolute uri (with/without port) */
  16022. hostend = get_rel_url_at_current_server(
  16023. conn->request_info.request_uri, conn);
  16024. if (hostend) {
  16025. conn->request_info.local_uri_raw = hostend;
  16026. } else {
  16027. conn->request_info.local_uri_raw = NULL;
  16028. }
  16029. break;
  16030. default:
  16031. mg_snprintf(conn,
  16032. NULL, /* No truncation check for ebuf */
  16033. ebuf,
  16034. sizeof(ebuf),
  16035. "Invalid URI");
  16036. mg_send_http_error(conn, 400, "%s", ebuf);
  16037. conn->request_info.local_uri_raw = NULL;
  16038. break;
  16039. }
  16040. conn->request_info.local_uri =
  16041. (char *)conn->request_info.local_uri_raw;
  16042. }
  16043. if (ebuf[0] != '\0') {
  16044. conn->protocol_type = -1;
  16045. } else {
  16046. /* HTTP/1 allows protocol upgrade */
  16047. conn->protocol_type = should_switch_to_protocol(conn);
  16048. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16049. /* This will occur, if a HTTP/1.1 request should be upgraded
  16050. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16051. * Since most (all?) major browsers only support HTTP/2 using
  16052. * ALPN, this is hard to test and very low priority.
  16053. * Deactivate it (at least for now).
  16054. */
  16055. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16056. }
  16057. }
  16058. DEBUG_TRACE("http: %s, error: %s",
  16059. (ri->http_version ? ri->http_version : "none"),
  16060. (ebuf[0] ? ebuf : "none"));
  16061. if (ebuf[0] == '\0') {
  16062. if (conn->request_info.local_uri) {
  16063. /* handle request to local server */
  16064. handle_request_stat_log(conn);
  16065. } else {
  16066. /* TODO: handle non-local request (PROXY) */
  16067. conn->must_close = 1;
  16068. }
  16069. } else {
  16070. conn->must_close = 1;
  16071. }
  16072. /* Response complete. Free header buffer */
  16073. free_buffered_response_header_list(conn);
  16074. if (ri->remote_user != NULL) {
  16075. mg_free((void *)ri->remote_user);
  16076. /* Important! When having connections with and without auth
  16077. * would cause double free and then crash */
  16078. ri->remote_user = NULL;
  16079. }
  16080. /* NOTE(lsm): order is important here. should_keep_alive() call
  16081. * is using parsed request, which will be invalid after
  16082. * memmove's below.
  16083. * Therefore, memorize should_keep_alive() result now for later
  16084. * use in loop exit condition. */
  16085. /* Enable it only if this request is completely discardable. */
  16086. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16087. && should_keep_alive(conn) && (conn->content_len >= 0)
  16088. && (conn->request_len > 0)
  16089. && ((conn->is_chunked == 4)
  16090. || (!conn->is_chunked
  16091. && ((conn->consumed_content == conn->content_len)
  16092. || ((conn->request_len + conn->content_len)
  16093. <= conn->data_len))))
  16094. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16095. if (keep_alive) {
  16096. /* Discard all buffered data for this request */
  16097. discard_len =
  16098. ((conn->request_len + conn->content_len) < conn->data_len)
  16099. ? (int)(conn->request_len + conn->content_len)
  16100. : conn->data_len;
  16101. conn->data_len -= discard_len;
  16102. if (conn->data_len > 0) {
  16103. DEBUG_TRACE("discard_len = %d", discard_len);
  16104. memmove(conn->buf,
  16105. conn->buf + discard_len,
  16106. (size_t)conn->data_len);
  16107. }
  16108. }
  16109. DEBUG_ASSERT(conn->data_len >= 0);
  16110. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16111. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16112. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16113. (long int)conn->data_len,
  16114. (long int)conn->buf_size);
  16115. break;
  16116. }
  16117. conn->handled_requests++;
  16118. } while (keep_alive);
  16119. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16120. conn->request_info.remote_addr,
  16121. difftime(time(NULL), conn->conn_birth_time));
  16122. close_connection(conn);
  16123. #if defined(USE_SERVER_STATS)
  16124. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16125. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16126. #endif
  16127. }
  16128. #if defined(ALTERNATIVE_QUEUE)
  16129. static void
  16130. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16131. {
  16132. unsigned int i;
  16133. while (!ctx->stop_flag) {
  16134. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16135. /* find a free worker slot and signal it */
  16136. if (ctx->client_socks[i].in_use == 2) {
  16137. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16138. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16139. ctx->client_socks[i] = *sp;
  16140. ctx->client_socks[i].in_use = 1;
  16141. /* socket has been moved to the consumer */
  16142. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16143. (void)event_signal(ctx->client_wait_events[i]);
  16144. return;
  16145. }
  16146. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16147. }
  16148. }
  16149. /* queue is full */
  16150. mg_sleep(1);
  16151. }
  16152. /* must consume */
  16153. set_blocking_mode(sp->sock);
  16154. closesocket(sp->sock);
  16155. }
  16156. static int
  16157. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16158. {
  16159. DEBUG_TRACE("%s", "going idle");
  16160. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16161. ctx->client_socks[thread_index].in_use = 2;
  16162. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16163. event_wait(ctx->client_wait_events[thread_index]);
  16164. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16165. *sp = ctx->client_socks[thread_index];
  16166. if (ctx->stop_flag) {
  16167. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16168. if (sp->in_use == 1) {
  16169. /* must consume */
  16170. set_blocking_mode(sp->sock);
  16171. closesocket(sp->sock);
  16172. }
  16173. return 0;
  16174. }
  16175. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16176. if (sp->in_use == 1) {
  16177. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16178. return 1;
  16179. }
  16180. /* must not reach here */
  16181. DEBUG_ASSERT(0);
  16182. return 0;
  16183. }
  16184. #else /* ALTERNATIVE_QUEUE */
  16185. /* Worker threads take accepted socket from the queue */
  16186. static int
  16187. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16188. {
  16189. (void)thread_index;
  16190. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16191. DEBUG_TRACE("%s", "going idle");
  16192. /* If the queue is empty, wait. We're idle at this point. */
  16193. while ((ctx->sq_head == ctx->sq_tail)
  16194. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16195. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16196. }
  16197. /* If we're stopping, sq_head may be equal to sq_tail. */
  16198. if (ctx->sq_head > ctx->sq_tail) {
  16199. /* Copy socket from the queue and increment tail */
  16200. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16201. ctx->sq_tail++;
  16202. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16203. /* Wrap pointers if needed */
  16204. while (ctx->sq_tail > ctx->sq_size) {
  16205. ctx->sq_tail -= ctx->sq_size;
  16206. ctx->sq_head -= ctx->sq_size;
  16207. }
  16208. }
  16209. (void)pthread_cond_signal(&ctx->sq_empty);
  16210. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16211. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16212. }
  16213. /* Master thread adds accepted socket to a queue */
  16214. static void
  16215. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16216. {
  16217. int queue_filled;
  16218. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16219. queue_filled = ctx->sq_head - ctx->sq_tail;
  16220. /* If the queue is full, wait */
  16221. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16222. && (queue_filled >= ctx->sq_size)) {
  16223. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16224. #if defined(USE_SERVER_STATS)
  16225. if (queue_filled > ctx->sq_max_fill) {
  16226. ctx->sq_max_fill = queue_filled;
  16227. }
  16228. #endif
  16229. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16230. ctx->sq_blocked = 0; /* Not blocked now */
  16231. queue_filled = ctx->sq_head - ctx->sq_tail;
  16232. }
  16233. if (queue_filled < ctx->sq_size) {
  16234. /* Copy socket to the queue and increment head */
  16235. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16236. ctx->sq_head++;
  16237. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16238. }
  16239. queue_filled = ctx->sq_head - ctx->sq_tail;
  16240. #if defined(USE_SERVER_STATS)
  16241. if (queue_filled > ctx->sq_max_fill) {
  16242. ctx->sq_max_fill = queue_filled;
  16243. }
  16244. #endif
  16245. (void)pthread_cond_signal(&ctx->sq_full);
  16246. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16247. }
  16248. #endif /* ALTERNATIVE_QUEUE */
  16249. static void
  16250. worker_thread_run(struct mg_connection *conn)
  16251. {
  16252. struct mg_context *ctx = conn->phys_ctx;
  16253. int thread_index;
  16254. struct mg_workerTLS tls;
  16255. mg_set_thread_name("worker");
  16256. tls.is_master = 0;
  16257. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16258. #if defined(_WIN32)
  16259. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16260. #endif
  16261. /* Initialize thread local storage before calling any callback */
  16262. pthread_setspecific(sTlsKey, &tls);
  16263. /* Check if there is a user callback */
  16264. if (ctx->callbacks.init_thread) {
  16265. /* call init_thread for a worker thread (type 1), and store the
  16266. * return value */
  16267. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16268. } else {
  16269. /* No callback: set user pointer to NULL */
  16270. tls.user_ptr = NULL;
  16271. }
  16272. /* Connection structure has been pre-allocated */
  16273. thread_index = (int)(conn - ctx->worker_connections);
  16274. if ((thread_index < 0)
  16275. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16276. mg_cry_ctx_internal(ctx,
  16277. "Internal error: Invalid worker index %i",
  16278. thread_index);
  16279. return;
  16280. }
  16281. /* Request buffers are not pre-allocated. They are private to the
  16282. * request and do not contain any state information that might be
  16283. * of interest to anyone observing a server status. */
  16284. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16285. if (conn->buf == NULL) {
  16286. mg_cry_ctx_internal(
  16287. ctx,
  16288. "Out of memory: Cannot allocate buffer for worker %i",
  16289. thread_index);
  16290. return;
  16291. }
  16292. conn->buf_size = (int)ctx->max_request_size;
  16293. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16294. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16295. conn->request_info.user_data = ctx->user_data;
  16296. /* Allocate a mutex for this connection to allow communication both
  16297. * within the request handler and from elsewhere in the application
  16298. */
  16299. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16300. mg_free(conn->buf);
  16301. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16302. return;
  16303. }
  16304. #if defined(USE_SERVER_STATS)
  16305. conn->conn_state = 1; /* not consumed */
  16306. #endif
  16307. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16308. * signal sq_empty condvar to wake up the master waiting in
  16309. * produce_socket() */
  16310. while (consume_socket(ctx, &conn->client, thread_index)) {
  16311. /* New connections must start with new protocol negotiation */
  16312. tls.alpn_proto = NULL;
  16313. #if defined(USE_SERVER_STATS)
  16314. conn->conn_close_time = 0;
  16315. #endif
  16316. conn->conn_birth_time = time(NULL);
  16317. /* Fill in IP, port info early so even if SSL setup below fails,
  16318. * error handler would have the corresponding info.
  16319. * Thanks to Johannes Winkelmann for the patch.
  16320. */
  16321. conn->request_info.remote_port =
  16322. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16323. conn->request_info.server_port =
  16324. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16325. sockaddr_to_string(conn->request_info.remote_addr,
  16326. sizeof(conn->request_info.remote_addr),
  16327. &conn->client.rsa);
  16328. DEBUG_TRACE("Incomming %sconnection from %s",
  16329. (conn->client.is_ssl ? "SSL " : ""),
  16330. conn->request_info.remote_addr);
  16331. conn->request_info.is_ssl = conn->client.is_ssl;
  16332. if (conn->client.is_ssl) {
  16333. #if defined(USE_MBEDTLS)
  16334. /* HTTPS connection */
  16335. if (mbed_ssl_accept(&(conn->ssl),
  16336. conn->dom_ctx->ssl_ctx,
  16337. (int *)&(conn->client.sock),
  16338. conn->phys_ctx)
  16339. == 0) {
  16340. /* conn->dom_ctx is set in get_request */
  16341. /* process HTTPS connection */
  16342. init_connection(conn);
  16343. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16344. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16345. process_new_connection(conn);
  16346. } else {
  16347. /* make sure the connection is cleaned up on SSL failure */
  16348. close_connection(conn);
  16349. }
  16350. #elif !defined(NO_SSL)
  16351. /* HTTPS connection */
  16352. if (sslize(conn, SSL_accept, NULL)) {
  16353. /* conn->dom_ctx is set in get_request */
  16354. /* Get SSL client certificate information (if set) */
  16355. struct mg_client_cert client_cert;
  16356. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16357. conn->request_info.client_cert = &client_cert;
  16358. }
  16359. /* process HTTPS connection */
  16360. #if defined(USE_HTTP2)
  16361. if ((tls.alpn_proto != NULL)
  16362. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16363. /* process HTTPS/2 connection */
  16364. init_connection(conn);
  16365. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16366. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16367. conn->content_len =
  16368. -1; /* content length is not predefined */
  16369. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16370. process_new_http2_connection(conn);
  16371. } else
  16372. #endif
  16373. {
  16374. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16375. init_connection(conn);
  16376. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16377. /* Start with HTTP, WS will be an "upgrade" request later */
  16378. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16379. process_new_connection(conn);
  16380. }
  16381. /* Free client certificate info */
  16382. if (conn->request_info.client_cert) {
  16383. mg_free((void *)(conn->request_info.client_cert->subject));
  16384. mg_free((void *)(conn->request_info.client_cert->issuer));
  16385. mg_free((void *)(conn->request_info.client_cert->serial));
  16386. mg_free((void *)(conn->request_info.client_cert->finger));
  16387. /* Free certificate memory */
  16388. X509_free(
  16389. (X509 *)conn->request_info.client_cert->peer_cert);
  16390. conn->request_info.client_cert->peer_cert = 0;
  16391. conn->request_info.client_cert->subject = 0;
  16392. conn->request_info.client_cert->issuer = 0;
  16393. conn->request_info.client_cert->serial = 0;
  16394. conn->request_info.client_cert->finger = 0;
  16395. conn->request_info.client_cert = 0;
  16396. }
  16397. } else {
  16398. /* make sure the connection is cleaned up on SSL failure */
  16399. close_connection(conn);
  16400. }
  16401. #endif
  16402. } else {
  16403. /* process HTTP connection */
  16404. init_connection(conn);
  16405. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16406. /* Start with HTTP, WS will be an "upgrade" request later */
  16407. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16408. process_new_connection(conn);
  16409. }
  16410. DEBUG_TRACE("%s", "Connection closed");
  16411. #if defined(USE_SERVER_STATS)
  16412. conn->conn_close_time = time(NULL);
  16413. #endif
  16414. }
  16415. /* Call exit thread user callback */
  16416. if (ctx->callbacks.exit_thread) {
  16417. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16418. }
  16419. /* delete thread local storage objects */
  16420. pthread_setspecific(sTlsKey, NULL);
  16421. #if defined(_WIN32)
  16422. CloseHandle(tls.pthread_cond_helper_mutex);
  16423. #endif
  16424. pthread_mutex_destroy(&conn->mutex);
  16425. /* Free the request buffer. */
  16426. conn->buf_size = 0;
  16427. mg_free(conn->buf);
  16428. conn->buf = NULL;
  16429. /* Free cleaned URI (if any) */
  16430. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16431. mg_free((void *)conn->request_info.local_uri);
  16432. conn->request_info.local_uri = NULL;
  16433. }
  16434. #if defined(USE_SERVER_STATS)
  16435. conn->conn_state = 9; /* done */
  16436. #endif
  16437. DEBUG_TRACE("%s", "exiting");
  16438. }
  16439. /* Threads have different return types on Windows and Unix. */
  16440. #if defined(_WIN32)
  16441. static unsigned __stdcall worker_thread(void *thread_func_param)
  16442. {
  16443. worker_thread_run((struct mg_connection *)thread_func_param);
  16444. return 0;
  16445. }
  16446. #else
  16447. static void *
  16448. worker_thread(void *thread_func_param)
  16449. {
  16450. #if !defined(__ZEPHYR__)
  16451. struct sigaction sa;
  16452. /* Ignore SIGPIPE */
  16453. memset(&sa, 0, sizeof(sa));
  16454. sa.sa_handler = SIG_IGN;
  16455. sigaction(SIGPIPE, &sa, NULL);
  16456. #endif
  16457. worker_thread_run((struct mg_connection *)thread_func_param);
  16458. return NULL;
  16459. }
  16460. #endif /* _WIN32 */
  16461. /* This is an internal function, thus all arguments are expected to be
  16462. * valid - a NULL check is not required. */
  16463. static void
  16464. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16465. {
  16466. struct socket so;
  16467. char src_addr[IP_ADDR_STR_LEN];
  16468. socklen_t len = sizeof(so.rsa);
  16469. #if !defined(__ZEPHYR__)
  16470. int on = 1;
  16471. #endif
  16472. memset(&so, 0, sizeof(so));
  16473. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16474. == INVALID_SOCKET) {
  16475. } else if (check_acl(ctx, &so.rsa) != 1) {
  16476. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16477. mg_cry_ctx_internal(ctx,
  16478. "%s: %s is not allowed to connect",
  16479. __func__,
  16480. src_addr);
  16481. closesocket(so.sock);
  16482. } else {
  16483. /* Put so socket structure into the queue */
  16484. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16485. set_close_on_exec(so.sock, NULL, ctx);
  16486. so.is_ssl = listener->is_ssl;
  16487. so.ssl_redir = listener->ssl_redir;
  16488. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16489. mg_cry_ctx_internal(ctx,
  16490. "%s: getsockname() failed: %s",
  16491. __func__,
  16492. strerror(ERRNO));
  16493. }
  16494. #if !defined(__ZEPHYR__)
  16495. if ((so.lsa.sa.sa_family == AF_INET)
  16496. || (so.lsa.sa.sa_family == AF_INET6)) {
  16497. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16498. * This is needed because if HTTP-level keep-alive
  16499. * is enabled, and client resets the connection, server won't get
  16500. * TCP FIN or RST and will keep the connection open forever. With
  16501. * TCP keep-alive, next keep-alive handshake will figure out that
  16502. * the client is down and will close the server end.
  16503. * Thanks to Igor Klopov who suggested the patch. */
  16504. if (setsockopt(so.sock,
  16505. SOL_SOCKET,
  16506. SO_KEEPALIVE,
  16507. (SOCK_OPT_TYPE)&on,
  16508. sizeof(on))
  16509. != 0) {
  16510. mg_cry_ctx_internal(
  16511. ctx,
  16512. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16513. __func__,
  16514. strerror(ERRNO));
  16515. }
  16516. }
  16517. #endif
  16518. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16519. * to effectively fill up the underlying IP packet payload and
  16520. * reduce the overhead of sending lots of small buffers. However
  16521. * this hurts the server's throughput (ie. operations per second)
  16522. * when HTTP 1.1 persistent connections are used and the responses
  16523. * are relatively small (eg. less than 1400 bytes).
  16524. */
  16525. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16526. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16527. if (set_tcp_nodelay(&so, 1) != 0) {
  16528. mg_cry_ctx_internal(
  16529. ctx,
  16530. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16531. __func__,
  16532. strerror(ERRNO));
  16533. }
  16534. }
  16535. /* The "non blocking" property should already be
  16536. * inherited from the parent socket. Set it for
  16537. * non-compliant socket implementations. */
  16538. set_non_blocking_mode(so.sock);
  16539. so.in_use = 0;
  16540. produce_socket(ctx, &so);
  16541. }
  16542. }
  16543. static void
  16544. master_thread_run(struct mg_context *ctx)
  16545. {
  16546. struct mg_workerTLS tls;
  16547. struct mg_pollfd *pfd;
  16548. unsigned int i;
  16549. unsigned int workerthreadcount;
  16550. if (!ctx) {
  16551. return;
  16552. }
  16553. mg_set_thread_name("master");
  16554. /* Increase priority of the master thread */
  16555. #if defined(_WIN32)
  16556. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16557. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16558. int min_prio = sched_get_priority_min(SCHED_RR);
  16559. int max_prio = sched_get_priority_max(SCHED_RR);
  16560. if ((min_prio >= 0) && (max_prio >= 0)
  16561. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16562. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16563. struct sched_param sched_param = {0};
  16564. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16565. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16566. }
  16567. #endif
  16568. /* Initialize thread local storage */
  16569. #if defined(_WIN32)
  16570. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16571. #endif
  16572. tls.is_master = 1;
  16573. pthread_setspecific(sTlsKey, &tls);
  16574. if (ctx->callbacks.init_thread) {
  16575. /* Callback for the master thread (type 0) */
  16576. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16577. } else {
  16578. tls.user_ptr = NULL;
  16579. }
  16580. /* Lua background script "start" event */
  16581. #if defined(USE_LUA)
  16582. if (ctx->lua_background_state) {
  16583. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16584. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16585. /* call "start()" in Lua */
  16586. lua_getglobal(lstate, "start");
  16587. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16588. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16589. if (ret != 0) {
  16590. struct mg_connection fc;
  16591. lua_cry(fake_connection(&fc, ctx),
  16592. ret,
  16593. lstate,
  16594. "lua_background_script",
  16595. "start");
  16596. }
  16597. } else {
  16598. lua_pop(lstate, 1);
  16599. }
  16600. /* determine if there is a "log()" function in Lua background script */
  16601. lua_getglobal(lstate, "log");
  16602. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16603. ctx->lua_bg_log_available = 1;
  16604. }
  16605. lua_pop(lstate, 1);
  16606. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16607. }
  16608. #endif
  16609. /* Server starts *now* */
  16610. ctx->start_time = time(NULL);
  16611. /* Server accept loop */
  16612. pfd = ctx->listening_socket_fds;
  16613. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16614. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16615. pfd[i].fd = ctx->listening_sockets[i].sock;
  16616. pfd[i].events = POLLIN;
  16617. }
  16618. if (mg_poll(pfd,
  16619. ctx->num_listening_sockets,
  16620. SOCKET_TIMEOUT_QUANTUM,
  16621. &(ctx->stop_flag))
  16622. > 0) {
  16623. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16624. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16625. * successful poll, and POLLIN is defined as
  16626. * (POLLRDNORM | POLLRDBAND)
  16627. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16628. * pfd[i].revents == POLLIN. */
  16629. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16630. && (pfd[i].revents & POLLIN)) {
  16631. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16632. }
  16633. }
  16634. }
  16635. }
  16636. /* Here stop_flag is 1 - Initiate shutdown. */
  16637. DEBUG_TRACE("%s", "stopping workers");
  16638. /* Stop signal received: somebody called mg_stop. Quit. */
  16639. close_all_listening_sockets(ctx);
  16640. /* Wakeup workers that are waiting for connections to handle. */
  16641. #if defined(ALTERNATIVE_QUEUE)
  16642. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16643. event_signal(ctx->client_wait_events[i]);
  16644. }
  16645. #else
  16646. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16647. pthread_cond_broadcast(&ctx->sq_full);
  16648. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16649. #endif
  16650. /* Join all worker threads to avoid leaking threads. */
  16651. workerthreadcount = ctx->cfg_worker_threads;
  16652. for (i = 0; i < workerthreadcount; i++) {
  16653. if (ctx->worker_threadids[i] != 0) {
  16654. mg_join_thread(ctx->worker_threadids[i]);
  16655. }
  16656. }
  16657. #if defined(USE_LUA)
  16658. /* Free Lua state of lua background task */
  16659. if (ctx->lua_background_state) {
  16660. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16661. ctx->lua_bg_log_available = 0;
  16662. /* call "stop()" in Lua */
  16663. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16664. lua_getglobal(lstate, "stop");
  16665. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16666. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16667. if (ret != 0) {
  16668. struct mg_connection fc;
  16669. lua_cry(fake_connection(&fc, ctx),
  16670. ret,
  16671. lstate,
  16672. "lua_background_script",
  16673. "stop");
  16674. }
  16675. }
  16676. lua_close(lstate);
  16677. ctx->lua_background_state = 0;
  16678. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16679. }
  16680. #endif
  16681. DEBUG_TRACE("%s", "exiting");
  16682. /* call exit thread callback */
  16683. if (ctx->callbacks.exit_thread) {
  16684. /* Callback for the master thread (type 0) */
  16685. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16686. }
  16687. #if defined(_WIN32)
  16688. CloseHandle(tls.pthread_cond_helper_mutex);
  16689. #endif
  16690. pthread_setspecific(sTlsKey, NULL);
  16691. /* Signal mg_stop() that we're done.
  16692. * WARNING: This must be the very last thing this
  16693. * thread does, as ctx becomes invalid after this line. */
  16694. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16695. }
  16696. /* Threads have different return types on Windows and Unix. */
  16697. #if defined(_WIN32)
  16698. static unsigned __stdcall master_thread(void *thread_func_param)
  16699. {
  16700. master_thread_run((struct mg_context *)thread_func_param);
  16701. return 0;
  16702. }
  16703. #else
  16704. static void *
  16705. master_thread(void *thread_func_param)
  16706. {
  16707. #if !defined(__ZEPHYR__)
  16708. struct sigaction sa;
  16709. /* Ignore SIGPIPE */
  16710. memset(&sa, 0, sizeof(sa));
  16711. sa.sa_handler = SIG_IGN;
  16712. sigaction(SIGPIPE, &sa, NULL);
  16713. #endif
  16714. master_thread_run((struct mg_context *)thread_func_param);
  16715. return NULL;
  16716. }
  16717. #endif /* _WIN32 */
  16718. static void
  16719. free_context(struct mg_context *ctx)
  16720. {
  16721. int i;
  16722. struct mg_handler_info *tmp_rh;
  16723. if (ctx == NULL) {
  16724. return;
  16725. }
  16726. /* Call user callback */
  16727. if (ctx->callbacks.exit_context) {
  16728. ctx->callbacks.exit_context(ctx);
  16729. }
  16730. /* All threads exited, no sync is needed. Destroy thread mutex and
  16731. * condvars
  16732. */
  16733. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16734. #if defined(ALTERNATIVE_QUEUE)
  16735. mg_free(ctx->client_socks);
  16736. if (ctx->client_wait_events != NULL) {
  16737. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16738. event_destroy(ctx->client_wait_events[i]);
  16739. }
  16740. mg_free(ctx->client_wait_events);
  16741. }
  16742. #else
  16743. (void)pthread_cond_destroy(&ctx->sq_empty);
  16744. (void)pthread_cond_destroy(&ctx->sq_full);
  16745. mg_free(ctx->squeue);
  16746. #endif
  16747. /* Destroy other context global data structures mutex */
  16748. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16749. #if defined(USE_LUA)
  16750. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  16751. #endif
  16752. /* Deallocate config parameters */
  16753. for (i = 0; i < NUM_OPTIONS; i++) {
  16754. if (ctx->dd.config[i] != NULL) {
  16755. #if defined(_MSC_VER)
  16756. #pragma warning(suppress : 6001)
  16757. #endif
  16758. mg_free(ctx->dd.config[i]);
  16759. }
  16760. }
  16761. /* Deallocate request handlers */
  16762. while (ctx->dd.handlers) {
  16763. tmp_rh = ctx->dd.handlers;
  16764. ctx->dd.handlers = tmp_rh->next;
  16765. mg_free(tmp_rh->uri);
  16766. mg_free(tmp_rh);
  16767. }
  16768. #if defined(USE_MBEDTLS)
  16769. if (ctx->dd.ssl_ctx != NULL) {
  16770. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16771. mg_free(ctx->dd.ssl_ctx);
  16772. ctx->dd.ssl_ctx = NULL;
  16773. }
  16774. #elif !defined(NO_SSL)
  16775. /* Deallocate SSL context */
  16776. if (ctx->dd.ssl_ctx != NULL) {
  16777. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16778. int callback_ret =
  16779. (ctx->callbacks.external_ssl_ctx == NULL)
  16780. ? 0
  16781. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16782. if (callback_ret == 0) {
  16783. SSL_CTX_free(ctx->dd.ssl_ctx);
  16784. }
  16785. /* else: ignore error and ommit SSL_CTX_free in case
  16786. * callback_ret is 1 */
  16787. }
  16788. #endif /* !NO_SSL */
  16789. /* Deallocate worker thread ID array */
  16790. mg_free(ctx->worker_threadids);
  16791. /* Deallocate worker thread ID array */
  16792. mg_free(ctx->worker_connections);
  16793. /* deallocate system name string */
  16794. mg_free(ctx->systemName);
  16795. /* Deallocate context itself */
  16796. mg_free(ctx);
  16797. }
  16798. void
  16799. mg_stop(struct mg_context *ctx)
  16800. {
  16801. pthread_t mt;
  16802. if (!ctx) {
  16803. return;
  16804. }
  16805. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16806. * two threads is not allowed. */
  16807. mt = ctx->masterthreadid;
  16808. if (mt == 0) {
  16809. return;
  16810. }
  16811. ctx->masterthreadid = 0;
  16812. /* Set stop flag, so all threads know they have to exit. */
  16813. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16814. /* Join timer thread */
  16815. #if defined(USE_TIMERS)
  16816. timers_exit(ctx);
  16817. #endif
  16818. /* Wait until everything has stopped. */
  16819. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16820. (void)mg_sleep(10);
  16821. }
  16822. /* Wait to stop master thread */
  16823. mg_join_thread(mt);
  16824. /* Close remaining Lua states */
  16825. #if defined(USE_LUA)
  16826. lua_ctx_exit(ctx);
  16827. #endif
  16828. /* Free memory */
  16829. free_context(ctx);
  16830. }
  16831. static void
  16832. get_system_name(char **sysName)
  16833. {
  16834. #if defined(_WIN32)
  16835. char name[128];
  16836. DWORD dwVersion = 0;
  16837. DWORD dwMajorVersion = 0;
  16838. DWORD dwMinorVersion = 0;
  16839. DWORD dwBuild = 0;
  16840. BOOL wowRet, isWoW = FALSE;
  16841. #if defined(_MSC_VER)
  16842. #pragma warning(push)
  16843. /* GetVersion was declared deprecated */
  16844. #pragma warning(disable : 4996)
  16845. #endif
  16846. dwVersion = GetVersion();
  16847. #if defined(_MSC_VER)
  16848. #pragma warning(pop)
  16849. #endif
  16850. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16851. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16852. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16853. (void)dwBuild;
  16854. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16855. sprintf(name,
  16856. "Windows %u.%u%s",
  16857. (unsigned)dwMajorVersion,
  16858. (unsigned)dwMinorVersion,
  16859. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16860. *sysName = mg_strdup(name);
  16861. #elif defined(__ZEPHYR__)
  16862. *sysName = mg_strdup("Zephyr OS");
  16863. #else
  16864. struct utsname name;
  16865. memset(&name, 0, sizeof(name));
  16866. uname(&name);
  16867. *sysName = mg_strdup(name.sysname);
  16868. #endif
  16869. }
  16870. static void
  16871. legacy_init(const char **options)
  16872. {
  16873. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16874. if (options) {
  16875. const char **run_options = options;
  16876. const char *optname = config_options[LISTENING_PORTS].name;
  16877. /* Try to find the "listening_ports" option */
  16878. while (*run_options) {
  16879. if (!strcmp(*run_options, optname)) {
  16880. ports_option = run_options[1];
  16881. }
  16882. run_options += 2;
  16883. }
  16884. }
  16885. if (is_ssl_port_used(ports_option)) {
  16886. /* Initialize with SSL support */
  16887. mg_init_library(MG_FEATURES_TLS);
  16888. } else {
  16889. /* Initialize without SSL support */
  16890. mg_init_library(MG_FEATURES_DEFAULT);
  16891. }
  16892. }
  16893. struct mg_context *
  16894. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16895. {
  16896. struct mg_context *ctx;
  16897. const char *name, *value, *default_value;
  16898. int idx, ok, workerthreadcount;
  16899. unsigned int i;
  16900. int itmp;
  16901. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16902. const char **options =
  16903. ((init != NULL) ? (init->configuration_options) : (NULL));
  16904. struct mg_workerTLS tls;
  16905. if (error != NULL) {
  16906. error->code = 0;
  16907. if (error->text_buffer_size > 0) {
  16908. *error->text = 0;
  16909. }
  16910. }
  16911. if (mg_init_library_called == 0) {
  16912. /* Legacy INIT, if mg_start is called without mg_init_library.
  16913. * Note: This will cause a memory leak when unloading the library.
  16914. */
  16915. legacy_init(options);
  16916. }
  16917. if (mg_init_library_called == 0) {
  16918. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16919. mg_snprintf(NULL,
  16920. NULL, /* No truncation check for error buffers */
  16921. error->text,
  16922. error->text_buffer_size,
  16923. "%s",
  16924. "Library uninitialized");
  16925. }
  16926. return NULL;
  16927. }
  16928. /* Allocate context and initialize reasonable general case defaults. */
  16929. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16930. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16931. mg_snprintf(NULL,
  16932. NULL, /* No truncation check for error buffers */
  16933. error->text,
  16934. error->text_buffer_size,
  16935. "%s",
  16936. "Out of memory");
  16937. }
  16938. return NULL;
  16939. }
  16940. /* Random number generator will initialize at the first call */
  16941. ctx->dd.auth_nonce_mask =
  16942. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16943. /* Save started thread index to reuse in other external API calls
  16944. * For the sake of thread synchronization all non-civetweb threads
  16945. * can be considered as single external thread */
  16946. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16947. tls.is_master = -1; /* Thread calling mg_start */
  16948. tls.thread_idx = ctx->starter_thread_idx;
  16949. #if defined(_WIN32)
  16950. tls.pthread_cond_helper_mutex = NULL;
  16951. #endif
  16952. pthread_setspecific(sTlsKey, &tls);
  16953. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16954. #if !defined(ALTERNATIVE_QUEUE)
  16955. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16956. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16957. ctx->sq_blocked = 0;
  16958. #endif
  16959. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16960. #if defined(USE_LUA)
  16961. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  16962. #endif
  16963. if (!ok) {
  16964. const char *err_msg =
  16965. "Cannot initialize thread synchronization objects";
  16966. /* Fatal error - abort start. However, this situation should never
  16967. * occur in practice. */
  16968. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16969. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16970. mg_snprintf(NULL,
  16971. NULL, /* No truncation check for error buffers */
  16972. error->text,
  16973. error->text_buffer_size,
  16974. "%s",
  16975. err_msg);
  16976. }
  16977. mg_free(ctx);
  16978. pthread_setspecific(sTlsKey, NULL);
  16979. return NULL;
  16980. }
  16981. if ((init != NULL) && (init->callbacks != NULL)) {
  16982. /* Set all callbacks except exit_context. */
  16983. ctx->callbacks = *init->callbacks;
  16984. exit_callback = init->callbacks->exit_context;
  16985. /* The exit callback is activated once the context is successfully
  16986. * created. It should not be called, if an incomplete context object
  16987. * is deleted during a failed initialization. */
  16988. ctx->callbacks.exit_context = 0;
  16989. }
  16990. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16991. ctx->dd.handlers = NULL;
  16992. ctx->dd.next = NULL;
  16993. #if defined(USE_LUA)
  16994. lua_ctx_init(ctx);
  16995. #endif
  16996. /* Store options */
  16997. while (options && (name = *options++) != NULL) {
  16998. if ((idx = get_option_index(name)) == -1) {
  16999. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17000. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17001. mg_snprintf(NULL,
  17002. NULL, /* No truncation check for error buffers */
  17003. error->text,
  17004. error->text_buffer_size,
  17005. "Invalid configuration option: %s",
  17006. name);
  17007. }
  17008. free_context(ctx);
  17009. pthread_setspecific(sTlsKey, NULL);
  17010. return NULL;
  17011. } else if ((value = *options++) == NULL) {
  17012. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17013. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17014. mg_snprintf(NULL,
  17015. NULL, /* No truncation check for error buffers */
  17016. error->text,
  17017. error->text_buffer_size,
  17018. "Invalid configuration option value: %s",
  17019. name);
  17020. }
  17021. free_context(ctx);
  17022. pthread_setspecific(sTlsKey, NULL);
  17023. return NULL;
  17024. }
  17025. if (ctx->dd.config[idx] != NULL) {
  17026. /* A duplicate configuration option is not an error - the last
  17027. * option value will be used. */
  17028. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17029. mg_free(ctx->dd.config[idx]);
  17030. }
  17031. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17032. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17033. }
  17034. /* Set default value if needed */
  17035. for (i = 0; config_options[i].name != NULL; i++) {
  17036. default_value = config_options[i].default_value;
  17037. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17038. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17039. }
  17040. }
  17041. /* Request size option */
  17042. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17043. if (itmp < 1024) {
  17044. mg_cry_ctx_internal(ctx,
  17045. "%s too small",
  17046. config_options[MAX_REQUEST_SIZE].name);
  17047. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17048. mg_snprintf(NULL,
  17049. NULL, /* No truncation check for error buffers */
  17050. error->text,
  17051. error->text_buffer_size,
  17052. "Invalid configuration option value: %s",
  17053. config_options[MAX_REQUEST_SIZE].name);
  17054. }
  17055. free_context(ctx);
  17056. pthread_setspecific(sTlsKey, NULL);
  17057. return NULL;
  17058. }
  17059. ctx->max_request_size = (unsigned)itmp;
  17060. /* Queue length */
  17061. #if !defined(ALTERNATIVE_QUEUE)
  17062. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17063. if (itmp < 1) {
  17064. mg_cry_ctx_internal(ctx,
  17065. "%s too small",
  17066. config_options[CONNECTION_QUEUE_SIZE].name);
  17067. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17068. mg_snprintf(NULL,
  17069. NULL, /* No truncation check for error buffers */
  17070. error->text,
  17071. error->text_buffer_size,
  17072. "Invalid configuration option value: %s",
  17073. config_options[CONNECTION_QUEUE_SIZE].name);
  17074. }
  17075. free_context(ctx);
  17076. pthread_setspecific(sTlsKey, NULL);
  17077. return NULL;
  17078. }
  17079. ctx->squeue =
  17080. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17081. if (ctx->squeue == NULL) {
  17082. mg_cry_ctx_internal(ctx,
  17083. "Out of memory: Cannot allocate %s",
  17084. config_options[CONNECTION_QUEUE_SIZE].name);
  17085. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17086. mg_snprintf(NULL,
  17087. NULL, /* No truncation check for error buffers */
  17088. error->text,
  17089. error->text_buffer_size,
  17090. "Out of memory: Cannot allocate %s",
  17091. config_options[CONNECTION_QUEUE_SIZE].name);
  17092. }
  17093. free_context(ctx);
  17094. pthread_setspecific(sTlsKey, NULL);
  17095. return NULL;
  17096. }
  17097. ctx->sq_size = itmp;
  17098. #endif
  17099. /* Worker thread count option */
  17100. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17101. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17102. if (workerthreadcount <= 0) {
  17103. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17104. } else {
  17105. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17106. }
  17107. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17108. mg_snprintf(NULL,
  17109. NULL, /* No truncation check for error buffers */
  17110. error->text,
  17111. error->text_buffer_size,
  17112. "Invalid configuration option value: %s",
  17113. config_options[NUM_THREADS].name);
  17114. }
  17115. free_context(ctx);
  17116. pthread_setspecific(sTlsKey, NULL);
  17117. return NULL;
  17118. }
  17119. /* Document root */
  17120. #if defined(NO_FILES)
  17121. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17122. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17123. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17124. mg_snprintf(NULL,
  17125. NULL, /* No truncation check for error buffers */
  17126. error->text,
  17127. error->text_buffer_size,
  17128. "Invalid configuration option value: %s",
  17129. config_options[DOCUMENT_ROOT].name);
  17130. }
  17131. free_context(ctx);
  17132. pthread_setspecific(sTlsKey, NULL);
  17133. return NULL;
  17134. }
  17135. #endif
  17136. get_system_name(&ctx->systemName);
  17137. #if defined(USE_LUA)
  17138. /* If a Lua background script has been configured, start it. */
  17139. ctx->lua_bg_log_available = 0;
  17140. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17141. char ebuf[256];
  17142. struct vec opt_vec;
  17143. struct vec eq_vec;
  17144. const char *sparams;
  17145. memset(ebuf, 0, sizeof(ebuf));
  17146. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17147. /* Create a Lua state, load all standard libraries and the mg table */
  17148. lua_State *state = mg_lua_context_script_prepare(
  17149. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17150. if (!state) {
  17151. mg_cry_ctx_internal(ctx,
  17152. "lua_background_script load error: %s",
  17153. ebuf);
  17154. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17155. mg_snprintf(NULL,
  17156. NULL, /* No truncation check for error buffers */
  17157. error->text,
  17158. error->text_buffer_size,
  17159. "Error in script %s: %s",
  17160. config_options[LUA_BACKGROUND_SCRIPT].name,
  17161. ebuf);
  17162. }
  17163. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17164. free_context(ctx);
  17165. pthread_setspecific(sTlsKey, NULL);
  17166. return NULL;
  17167. }
  17168. /* Add a table with parameters into mg.params */
  17169. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17170. if (sparams && sparams[0]) {
  17171. lua_getglobal(state, "mg");
  17172. lua_pushstring(state, "params");
  17173. lua_newtable(state);
  17174. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17175. != NULL) {
  17176. reg_llstring(
  17177. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17178. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17179. break;
  17180. }
  17181. lua_rawset(state, -3);
  17182. lua_pop(state, 1);
  17183. }
  17184. /* Call script */
  17185. state = mg_lua_context_script_run(state,
  17186. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17187. ctx,
  17188. ebuf,
  17189. sizeof(ebuf));
  17190. if (!state) {
  17191. mg_cry_ctx_internal(ctx,
  17192. "lua_background_script start error: %s",
  17193. ebuf);
  17194. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17195. mg_snprintf(NULL,
  17196. NULL, /* No truncation check for error buffers */
  17197. error->text,
  17198. error->text_buffer_size,
  17199. "Error in script %s: %s",
  17200. config_options[DOCUMENT_ROOT].name,
  17201. ebuf);
  17202. }
  17203. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17204. free_context(ctx);
  17205. pthread_setspecific(sTlsKey, NULL);
  17206. return NULL;
  17207. }
  17208. /* state remains valid */
  17209. ctx->lua_background_state = (void *)state;
  17210. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17211. } else {
  17212. ctx->lua_background_state = 0;
  17213. }
  17214. #endif
  17215. /* Step by step initialization of ctx - depending on build options */
  17216. #if !defined(NO_FILESYSTEMS)
  17217. if (!set_gpass_option(ctx, NULL)) {
  17218. const char *err_msg = "Invalid global password file";
  17219. /* Fatal error - abort start. */
  17220. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17221. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17222. mg_snprintf(NULL,
  17223. NULL, /* No truncation check for error buffers */
  17224. error->text,
  17225. error->text_buffer_size,
  17226. "%s",
  17227. err_msg);
  17228. }
  17229. free_context(ctx);
  17230. pthread_setspecific(sTlsKey, NULL);
  17231. return NULL;
  17232. }
  17233. #endif
  17234. #if defined(USE_MBEDTLS)
  17235. if (!mg_sslctx_init(ctx, NULL)) {
  17236. const char *err_msg = "Error initializing SSL context";
  17237. /* Fatal error - abort start. */
  17238. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17239. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17240. mg_snprintf(NULL,
  17241. NULL, /* No truncation check for error buffers */
  17242. error->text,
  17243. error->text_buffer_size,
  17244. "%s",
  17245. err_msg);
  17246. }
  17247. free_context(ctx);
  17248. pthread_setspecific(sTlsKey, NULL);
  17249. return NULL;
  17250. }
  17251. #elif !defined(NO_SSL)
  17252. if (!init_ssl_ctx(ctx, NULL)) {
  17253. const char *err_msg = "Error initializing SSL context";
  17254. /* Fatal error - abort start. */
  17255. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17256. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17257. mg_snprintf(NULL,
  17258. NULL, /* No truncation check for error buffers */
  17259. error->text,
  17260. error->text_buffer_size,
  17261. "%s",
  17262. err_msg);
  17263. }
  17264. free_context(ctx);
  17265. pthread_setspecific(sTlsKey, NULL);
  17266. return NULL;
  17267. }
  17268. #endif
  17269. if (!set_ports_option(ctx)) {
  17270. const char *err_msg = "Failed to setup server ports";
  17271. /* Fatal error - abort start. */
  17272. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17273. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17274. mg_snprintf(NULL,
  17275. NULL, /* No truncation check for error buffers */
  17276. error->text,
  17277. error->text_buffer_size,
  17278. "%s",
  17279. err_msg);
  17280. }
  17281. free_context(ctx);
  17282. pthread_setspecific(sTlsKey, NULL);
  17283. return NULL;
  17284. }
  17285. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17286. if (!set_uid_option(ctx)) {
  17287. const char *err_msg = "Failed to run as configured user";
  17288. /* Fatal error - abort start. */
  17289. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17290. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17291. mg_snprintf(NULL,
  17292. NULL, /* No truncation check for error buffers */
  17293. error->text,
  17294. error->text_buffer_size,
  17295. "%s",
  17296. err_msg);
  17297. }
  17298. free_context(ctx);
  17299. pthread_setspecific(sTlsKey, NULL);
  17300. return NULL;
  17301. }
  17302. #endif
  17303. if (!set_acl_option(ctx)) {
  17304. const char *err_msg = "Failed to setup access control list";
  17305. /* Fatal error - abort start. */
  17306. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17307. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17308. mg_snprintf(NULL,
  17309. NULL, /* No truncation check for error buffers */
  17310. error->text,
  17311. error->text_buffer_size,
  17312. "%s",
  17313. err_msg);
  17314. }
  17315. free_context(ctx);
  17316. pthread_setspecific(sTlsKey, NULL);
  17317. return NULL;
  17318. }
  17319. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17320. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17321. sizeof(pthread_t),
  17322. ctx);
  17323. if (ctx->worker_threadids == NULL) {
  17324. const char *err_msg = "Not enough memory for worker thread ID array";
  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->worker_connections =
  17339. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17340. sizeof(struct mg_connection),
  17341. ctx);
  17342. if (ctx->worker_connections == NULL) {
  17343. const char *err_msg =
  17344. "Not enough memory for worker thread connection array";
  17345. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17346. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17347. mg_snprintf(NULL,
  17348. NULL, /* No truncation check for error buffers */
  17349. error->text,
  17350. error->text_buffer_size,
  17351. "%s",
  17352. err_msg);
  17353. }
  17354. free_context(ctx);
  17355. pthread_setspecific(sTlsKey, NULL);
  17356. return NULL;
  17357. }
  17358. #if defined(ALTERNATIVE_QUEUE)
  17359. ctx->client_wait_events =
  17360. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17361. sizeof(ctx->client_wait_events[0]),
  17362. ctx);
  17363. if (ctx->client_wait_events == NULL) {
  17364. const char *err_msg = "Not enough memory for worker event array";
  17365. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17366. mg_free(ctx->worker_threadids);
  17367. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17368. mg_snprintf(NULL,
  17369. NULL, /* No truncation check for error buffers */
  17370. error->text,
  17371. error->text_buffer_size,
  17372. "%s",
  17373. err_msg);
  17374. }
  17375. free_context(ctx);
  17376. pthread_setspecific(sTlsKey, NULL);
  17377. return NULL;
  17378. }
  17379. ctx->client_socks =
  17380. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17381. sizeof(ctx->client_socks[0]),
  17382. ctx);
  17383. if (ctx->client_socks == NULL) {
  17384. const char *err_msg = "Not enough memory for worker socket array";
  17385. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17386. mg_free(ctx->client_wait_events);
  17387. mg_free(ctx->worker_threadids);
  17388. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17389. mg_snprintf(NULL,
  17390. NULL, /* No truncation check for error buffers */
  17391. error->text,
  17392. error->text_buffer_size,
  17393. "%s",
  17394. err_msg);
  17395. }
  17396. free_context(ctx);
  17397. pthread_setspecific(sTlsKey, NULL);
  17398. return NULL;
  17399. }
  17400. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17401. ctx->client_wait_events[i] = event_create();
  17402. if (ctx->client_wait_events[i] == 0) {
  17403. const char *err_msg = "Error creating worker event %i";
  17404. mg_cry_ctx_internal(ctx, err_msg, i);
  17405. while (i > 0) {
  17406. i--;
  17407. event_destroy(ctx->client_wait_events[i]);
  17408. }
  17409. mg_free(ctx->client_socks);
  17410. mg_free(ctx->client_wait_events);
  17411. mg_free(ctx->worker_threadids);
  17412. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17413. mg_snprintf(NULL,
  17414. NULL, /* No truncation check for error buffers */
  17415. error->text,
  17416. error->text_buffer_size,
  17417. err_msg,
  17418. i);
  17419. }
  17420. free_context(ctx);
  17421. pthread_setspecific(sTlsKey, NULL);
  17422. return NULL;
  17423. }
  17424. }
  17425. #endif
  17426. #if defined(USE_TIMERS)
  17427. if (timers_init(ctx) != 0) {
  17428. const char *err_msg = "Error creating timers";
  17429. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17430. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17431. mg_snprintf(NULL,
  17432. NULL, /* No truncation check for error buffers */
  17433. error->text,
  17434. error->text_buffer_size,
  17435. "%s",
  17436. err_msg);
  17437. }
  17438. free_context(ctx);
  17439. pthread_setspecific(sTlsKey, NULL);
  17440. return NULL;
  17441. }
  17442. #endif
  17443. /* Context has been created - init user libraries */
  17444. if (ctx->callbacks.init_context) {
  17445. ctx->callbacks.init_context(ctx);
  17446. }
  17447. /* From now, the context is successfully created.
  17448. * When it is destroyed, the exit callback should be called. */
  17449. ctx->callbacks.exit_context = exit_callback;
  17450. ctx->context_type = CONTEXT_SERVER; /* server context */
  17451. /* Start worker threads */
  17452. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17453. /* worker_thread sets up the other fields */
  17454. ctx->worker_connections[i].phys_ctx = ctx;
  17455. if (mg_start_thread_with_id(worker_thread,
  17456. &ctx->worker_connections[i],
  17457. &ctx->worker_threadids[i])
  17458. != 0) {
  17459. long error_no = (long)ERRNO;
  17460. /* thread was not created */
  17461. if (i > 0) {
  17462. /* If the second, third, ... thread cannot be created, set a
  17463. * warning, but keep running. */
  17464. mg_cry_ctx_internal(ctx,
  17465. "Cannot start worker thread %i: error %ld",
  17466. i + 1,
  17467. error_no);
  17468. /* If the server initialization should stop here, all
  17469. * threads that have already been created must be stopped
  17470. * first, before any free_context(ctx) call.
  17471. */
  17472. } else {
  17473. /* If the first worker thread cannot be created, stop
  17474. * initialization and free the entire server context. */
  17475. mg_cry_ctx_internal(ctx,
  17476. "Cannot create threads: error %ld",
  17477. error_no);
  17478. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17479. mg_snprintf(
  17480. NULL,
  17481. NULL, /* No truncation check for error buffers */
  17482. error->text,
  17483. error->text_buffer_size,
  17484. "Cannot create first worker thread: error %ld",
  17485. error_no);
  17486. }
  17487. free_context(ctx);
  17488. pthread_setspecific(sTlsKey, NULL);
  17489. return NULL;
  17490. }
  17491. break;
  17492. }
  17493. }
  17494. /* Start master (listening) thread */
  17495. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17496. pthread_setspecific(sTlsKey, NULL);
  17497. return ctx;
  17498. }
  17499. struct mg_context *
  17500. mg_start(const struct mg_callbacks *callbacks,
  17501. void *user_data,
  17502. const char **options)
  17503. {
  17504. struct mg_init_data init = {0};
  17505. init.callbacks = callbacks;
  17506. init.user_data = user_data;
  17507. init.configuration_options = options;
  17508. return mg_start2(&init, NULL);
  17509. }
  17510. /* Add an additional domain to an already running web server. */
  17511. int
  17512. mg_start_domain2(struct mg_context *ctx,
  17513. const char **options,
  17514. struct mg_error_data *error)
  17515. {
  17516. const char *name;
  17517. const char *value;
  17518. const char *default_value;
  17519. struct mg_domain_context *new_dom;
  17520. struct mg_domain_context *dom;
  17521. int idx, i;
  17522. if (error != NULL) {
  17523. error->code = 0;
  17524. if (error->text_buffer_size > 0) {
  17525. *error->text = 0;
  17526. }
  17527. }
  17528. if ((ctx == NULL) || (options == NULL)) {
  17529. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17530. mg_snprintf(NULL,
  17531. NULL, /* No truncation check for error buffers */
  17532. error->text,
  17533. error->text_buffer_size,
  17534. "%s",
  17535. "Invalid parameters");
  17536. }
  17537. return -1;
  17538. }
  17539. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17540. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17541. mg_snprintf(NULL,
  17542. NULL, /* No truncation check for error buffers */
  17543. error->text,
  17544. error->text_buffer_size,
  17545. "%s",
  17546. "Server already stopped");
  17547. }
  17548. return -1;
  17549. }
  17550. new_dom = (struct mg_domain_context *)
  17551. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17552. if (!new_dom) {
  17553. /* Out of memory */
  17554. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17555. mg_snprintf(NULL,
  17556. NULL, /* No truncation check for error buffers */
  17557. error->text,
  17558. error->text_buffer_size,
  17559. "%s",
  17560. "Out or memory");
  17561. }
  17562. return -6;
  17563. }
  17564. /* Store options - TODO: unite duplicate code */
  17565. while (options && (name = *options++) != NULL) {
  17566. if ((idx = get_option_index(name)) == -1) {
  17567. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17568. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17569. mg_snprintf(NULL,
  17570. NULL, /* No truncation check for error buffers */
  17571. error->text,
  17572. error->text_buffer_size,
  17573. "Invalid option: %s",
  17574. name);
  17575. }
  17576. mg_free(new_dom);
  17577. return -2;
  17578. } else if ((value = *options++) == NULL) {
  17579. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17580. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17581. mg_snprintf(NULL,
  17582. NULL, /* No truncation check for error buffers */
  17583. error->text,
  17584. error->text_buffer_size,
  17585. "Invalid option value: %s",
  17586. name);
  17587. }
  17588. mg_free(new_dom);
  17589. return -2;
  17590. }
  17591. if (new_dom->config[idx] != NULL) {
  17592. /* Duplicate option: Later values overwrite earlier ones. */
  17593. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17594. mg_free(new_dom->config[idx]);
  17595. }
  17596. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17597. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17598. }
  17599. /* Authentication domain is mandatory */
  17600. /* TODO: Maybe use a new option hostname? */
  17601. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17602. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17603. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17604. mg_snprintf(NULL,
  17605. NULL, /* No truncation check for error buffers */
  17606. error->text,
  17607. error->text_buffer_size,
  17608. "Mandatory option %s missing",
  17609. config_options[AUTHENTICATION_DOMAIN].name);
  17610. }
  17611. mg_free(new_dom);
  17612. return -4;
  17613. }
  17614. /* Set default value if needed. Take the config value from
  17615. * ctx as a default value. */
  17616. for (i = 0; config_options[i].name != NULL; i++) {
  17617. default_value = ctx->dd.config[i];
  17618. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17619. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17620. }
  17621. }
  17622. new_dom->handlers = NULL;
  17623. new_dom->next = NULL;
  17624. new_dom->nonce_count = 0;
  17625. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  17626. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17627. new_dom->shared_lua_websockets = NULL;
  17628. #endif
  17629. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  17630. if (!init_ssl_ctx(ctx, new_dom)) {
  17631. /* Init SSL failed */
  17632. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17633. mg_snprintf(NULL,
  17634. NULL, /* No truncation check for error buffers */
  17635. error->text,
  17636. error->text_buffer_size,
  17637. "%s",
  17638. "Initializing SSL context failed");
  17639. }
  17640. mg_free(new_dom);
  17641. return -3;
  17642. }
  17643. #endif
  17644. /* Add element to linked list. */
  17645. mg_lock_context(ctx);
  17646. idx = 0;
  17647. dom = &(ctx->dd);
  17648. for (;;) {
  17649. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17650. dom->config[AUTHENTICATION_DOMAIN])) {
  17651. /* Domain collision */
  17652. mg_cry_ctx_internal(ctx,
  17653. "domain %s already in use",
  17654. new_dom->config[AUTHENTICATION_DOMAIN]);
  17655. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17656. mg_snprintf(NULL,
  17657. NULL, /* No truncation check for error buffers */
  17658. error->text,
  17659. error->text_buffer_size,
  17660. "Domain %s specified by %s is already in use",
  17661. new_dom->config[AUTHENTICATION_DOMAIN],
  17662. config_options[AUTHENTICATION_DOMAIN].name);
  17663. }
  17664. mg_free(new_dom);
  17665. mg_unlock_context(ctx);
  17666. return -5;
  17667. }
  17668. /* Count number of domains */
  17669. idx++;
  17670. if (dom->next == NULL) {
  17671. dom->next = new_dom;
  17672. break;
  17673. }
  17674. dom = dom->next;
  17675. }
  17676. mg_unlock_context(ctx);
  17677. /* Return domain number */
  17678. return idx;
  17679. }
  17680. int
  17681. mg_start_domain(struct mg_context *ctx, const char **options)
  17682. {
  17683. return mg_start_domain2(ctx, options, NULL);
  17684. }
  17685. /* Feature check API function */
  17686. unsigned
  17687. mg_check_feature(unsigned feature)
  17688. {
  17689. static const unsigned feature_set = 0
  17690. /* Set bits for available features according to API documentation.
  17691. * This bit mask is created at compile time, according to the active
  17692. * preprocessor defines. It is a single const value at runtime. */
  17693. #if !defined(NO_FILES)
  17694. | MG_FEATURES_FILES
  17695. #endif
  17696. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17697. | MG_FEATURES_SSL
  17698. #endif
  17699. #if !defined(NO_CGI)
  17700. | MG_FEATURES_CGI
  17701. #endif
  17702. #if defined(USE_IPV6)
  17703. | MG_FEATURES_IPV6
  17704. #endif
  17705. #if defined(USE_WEBSOCKET)
  17706. | MG_FEATURES_WEBSOCKET
  17707. #endif
  17708. #if defined(USE_LUA)
  17709. | MG_FEATURES_LUA
  17710. #endif
  17711. #if defined(USE_DUKTAPE)
  17712. | MG_FEATURES_SSJS
  17713. #endif
  17714. #if !defined(NO_CACHING)
  17715. | MG_FEATURES_CACHE
  17716. #endif
  17717. #if defined(USE_SERVER_STATS)
  17718. | MG_FEATURES_STATS
  17719. #endif
  17720. #if defined(USE_ZLIB)
  17721. | MG_FEATURES_COMPRESSION
  17722. #endif
  17723. #if defined(USE_HTTP2)
  17724. | MG_FEATURES_HTTP2
  17725. #endif
  17726. #if defined(USE_X_DOM_SOCKET)
  17727. | MG_FEATURES_X_DOMAIN_SOCKET
  17728. #endif
  17729. /* Set some extra bits not defined in the API documentation.
  17730. * These bits may change without further notice. */
  17731. #if defined(MG_LEGACY_INTERFACE)
  17732. | 0x80000000u
  17733. #endif
  17734. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17735. | 0x40000000u
  17736. #endif
  17737. #if !defined(NO_RESPONSE_BUFFERING)
  17738. | 0x20000000u
  17739. #endif
  17740. #if defined(MEMORY_DEBUGGING)
  17741. | 0x10000000u
  17742. #endif
  17743. ;
  17744. return (feature & feature_set);
  17745. }
  17746. static size_t
  17747. mg_str_append(char **dst, char *end, const char *src)
  17748. {
  17749. size_t len = strlen(src);
  17750. if (*dst != end) {
  17751. /* Append src if enough space, or close dst. */
  17752. if ((size_t)(end - *dst) > len) {
  17753. strcpy(*dst, src);
  17754. *dst += len;
  17755. } else {
  17756. *dst = end;
  17757. }
  17758. }
  17759. return len;
  17760. }
  17761. /* Get system information. It can be printed or stored by the caller.
  17762. * Return the size of available information. */
  17763. int
  17764. mg_get_system_info(char *buffer, int buflen)
  17765. {
  17766. char *end, *append_eoobj = NULL, block[256];
  17767. size_t system_info_length = 0;
  17768. #if defined(_WIN32)
  17769. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17770. #else
  17771. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17772. #endif
  17773. if ((buffer == NULL) || (buflen < 1)) {
  17774. buflen = 0;
  17775. end = buffer;
  17776. } else {
  17777. *buffer = 0;
  17778. end = buffer + buflen;
  17779. }
  17780. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17781. /* has enough space to append eoobj */
  17782. append_eoobj = buffer;
  17783. if (end) {
  17784. end -= sizeof(eoobj) - 1;
  17785. }
  17786. }
  17787. system_info_length += mg_str_append(&buffer, end, "{");
  17788. /* Server version */
  17789. {
  17790. const char *version = mg_version();
  17791. mg_snprintf(NULL,
  17792. NULL,
  17793. block,
  17794. sizeof(block),
  17795. "%s\"version\" : \"%s\"",
  17796. eol,
  17797. version);
  17798. system_info_length += mg_str_append(&buffer, end, block);
  17799. }
  17800. /* System info */
  17801. {
  17802. #if defined(_WIN32)
  17803. DWORD dwVersion = 0;
  17804. DWORD dwMajorVersion = 0;
  17805. DWORD dwMinorVersion = 0;
  17806. SYSTEM_INFO si;
  17807. GetSystemInfo(&si);
  17808. #if defined(_MSC_VER)
  17809. #pragma warning(push)
  17810. /* GetVersion was declared deprecated */
  17811. #pragma warning(disable : 4996)
  17812. #endif
  17813. dwVersion = GetVersion();
  17814. #if defined(_MSC_VER)
  17815. #pragma warning(pop)
  17816. #endif
  17817. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17818. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17819. mg_snprintf(NULL,
  17820. NULL,
  17821. block,
  17822. sizeof(block),
  17823. ",%s\"os\" : \"Windows %u.%u\"",
  17824. eol,
  17825. (unsigned)dwMajorVersion,
  17826. (unsigned)dwMinorVersion);
  17827. system_info_length += mg_str_append(&buffer, end, block);
  17828. mg_snprintf(NULL,
  17829. NULL,
  17830. block,
  17831. sizeof(block),
  17832. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17833. eol,
  17834. (unsigned)si.wProcessorArchitecture,
  17835. (unsigned)si.dwNumberOfProcessors,
  17836. (unsigned)si.dwActiveProcessorMask);
  17837. system_info_length += mg_str_append(&buffer, end, block);
  17838. #elif defined(__ZEPHYR__)
  17839. mg_snprintf(NULL,
  17840. NULL,
  17841. block,
  17842. sizeof(block),
  17843. ",%s\"os\" : \"%s %s\"",
  17844. eol,
  17845. "Zephyr OS",
  17846. ZEPHYR_VERSION);
  17847. system_info_length += mg_str_append(&buffer, end, block);
  17848. #else
  17849. struct utsname name;
  17850. memset(&name, 0, sizeof(name));
  17851. uname(&name);
  17852. mg_snprintf(NULL,
  17853. NULL,
  17854. block,
  17855. sizeof(block),
  17856. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17857. eol,
  17858. name.sysname,
  17859. name.version,
  17860. name.release,
  17861. name.machine);
  17862. system_info_length += mg_str_append(&buffer, end, block);
  17863. #endif
  17864. }
  17865. /* Features */
  17866. {
  17867. mg_snprintf(NULL,
  17868. NULL,
  17869. block,
  17870. sizeof(block),
  17871. ",%s\"features\" : %lu"
  17872. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17873. eol,
  17874. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17875. eol,
  17876. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17877. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17878. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17879. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17880. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17881. : "",
  17882. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17883. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17884. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17885. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17886. system_info_length += mg_str_append(&buffer, end, block);
  17887. #if defined(USE_LUA)
  17888. mg_snprintf(NULL,
  17889. NULL,
  17890. block,
  17891. sizeof(block),
  17892. ",%s\"lua_version\" : \"%u (%s)\"",
  17893. eol,
  17894. (unsigned)LUA_VERSION_NUM,
  17895. LUA_RELEASE);
  17896. system_info_length += mg_str_append(&buffer, end, block);
  17897. #endif
  17898. #if defined(USE_DUKTAPE)
  17899. mg_snprintf(NULL,
  17900. NULL,
  17901. block,
  17902. sizeof(block),
  17903. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17904. eol,
  17905. (unsigned)DUK_VERSION / 10000,
  17906. ((unsigned)DUK_VERSION / 100) % 100,
  17907. (unsigned)DUK_VERSION % 100);
  17908. system_info_length += mg_str_append(&buffer, end, block);
  17909. #endif
  17910. }
  17911. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  17912. {
  17913. #if defined(BUILD_DATE)
  17914. const char *bd = BUILD_DATE;
  17915. #else
  17916. #if defined(GCC_DIAGNOSTIC)
  17917. #if GCC_VERSION >= 40900
  17918. #pragma GCC diagnostic push
  17919. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  17920. * does not work in some versions. If "BUILD_DATE" is defined to some
  17921. * string, it is used instead of __DATE__. */
  17922. #pragma GCC diagnostic ignored "-Wdate-time"
  17923. #endif
  17924. #endif
  17925. const char *bd = __DATE__;
  17926. #if defined(GCC_DIAGNOSTIC)
  17927. #if GCC_VERSION >= 40900
  17928. #pragma GCC diagnostic pop
  17929. #endif
  17930. #endif
  17931. #endif
  17932. mg_snprintf(
  17933. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17934. system_info_length += mg_str_append(&buffer, end, block);
  17935. }
  17936. /* Compiler information */
  17937. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17938. {
  17939. #if defined(_MSC_VER)
  17940. mg_snprintf(NULL,
  17941. NULL,
  17942. block,
  17943. sizeof(block),
  17944. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17945. eol,
  17946. (unsigned)_MSC_VER,
  17947. (unsigned)_MSC_FULL_VER);
  17948. system_info_length += mg_str_append(&buffer, end, block);
  17949. #elif defined(__MINGW64__)
  17950. mg_snprintf(NULL,
  17951. NULL,
  17952. block,
  17953. sizeof(block),
  17954. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17955. eol,
  17956. (unsigned)__MINGW64_VERSION_MAJOR,
  17957. (unsigned)__MINGW64_VERSION_MINOR);
  17958. system_info_length += mg_str_append(&buffer, end, block);
  17959. mg_snprintf(NULL,
  17960. NULL,
  17961. block,
  17962. sizeof(block),
  17963. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17964. eol,
  17965. (unsigned)__MINGW32_MAJOR_VERSION,
  17966. (unsigned)__MINGW32_MINOR_VERSION);
  17967. system_info_length += mg_str_append(&buffer, end, block);
  17968. #elif defined(__MINGW32__)
  17969. mg_snprintf(NULL,
  17970. NULL,
  17971. block,
  17972. sizeof(block),
  17973. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17974. eol,
  17975. (unsigned)__MINGW32_MAJOR_VERSION,
  17976. (unsigned)__MINGW32_MINOR_VERSION);
  17977. system_info_length += mg_str_append(&buffer, end, block);
  17978. #elif defined(__clang__)
  17979. mg_snprintf(NULL,
  17980. NULL,
  17981. block,
  17982. sizeof(block),
  17983. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17984. eol,
  17985. __clang_major__,
  17986. __clang_minor__,
  17987. __clang_patchlevel__,
  17988. __clang_version__);
  17989. system_info_length += mg_str_append(&buffer, end, block);
  17990. #elif defined(__GNUC__)
  17991. mg_snprintf(NULL,
  17992. NULL,
  17993. block,
  17994. sizeof(block),
  17995. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17996. eol,
  17997. (unsigned)__GNUC__,
  17998. (unsigned)__GNUC_MINOR__,
  17999. (unsigned)__GNUC_PATCHLEVEL__);
  18000. system_info_length += mg_str_append(&buffer, end, block);
  18001. #elif defined(__INTEL_COMPILER)
  18002. mg_snprintf(NULL,
  18003. NULL,
  18004. block,
  18005. sizeof(block),
  18006. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18007. eol,
  18008. (unsigned)__INTEL_COMPILER);
  18009. system_info_length += mg_str_append(&buffer, end, block);
  18010. #elif defined(__BORLANDC__)
  18011. mg_snprintf(NULL,
  18012. NULL,
  18013. block,
  18014. sizeof(block),
  18015. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18016. eol,
  18017. (unsigned)__BORLANDC__);
  18018. system_info_length += mg_str_append(&buffer, end, block);
  18019. #elif defined(__SUNPRO_C)
  18020. mg_snprintf(NULL,
  18021. NULL,
  18022. block,
  18023. sizeof(block),
  18024. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18025. eol,
  18026. (unsigned)__SUNPRO_C);
  18027. system_info_length += mg_str_append(&buffer, end, block);
  18028. #else
  18029. mg_snprintf(NULL,
  18030. NULL,
  18031. block,
  18032. sizeof(block),
  18033. ",%s\"compiler\" : \"other\"",
  18034. eol);
  18035. system_info_length += mg_str_append(&buffer, end, block);
  18036. #endif
  18037. }
  18038. /* Determine 32/64 bit data mode.
  18039. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18040. {
  18041. mg_snprintf(NULL,
  18042. NULL,
  18043. block,
  18044. sizeof(block),
  18045. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18046. "char:%u/%u, "
  18047. "ptr:%u, size:%u, time:%u\"",
  18048. eol,
  18049. (unsigned)sizeof(short),
  18050. (unsigned)sizeof(int),
  18051. (unsigned)sizeof(long),
  18052. (unsigned)sizeof(long long),
  18053. (unsigned)sizeof(float),
  18054. (unsigned)sizeof(double),
  18055. (unsigned)sizeof(long double),
  18056. (unsigned)sizeof(char),
  18057. (unsigned)sizeof(wchar_t),
  18058. (unsigned)sizeof(void *),
  18059. (unsigned)sizeof(size_t),
  18060. (unsigned)sizeof(time_t));
  18061. system_info_length += mg_str_append(&buffer, end, block);
  18062. }
  18063. /* Terminate string */
  18064. if (append_eoobj) {
  18065. strcat(append_eoobj, eoobj);
  18066. }
  18067. system_info_length += sizeof(eoobj) - 1;
  18068. return (int)system_info_length;
  18069. }
  18070. /* Get context information. It can be printed or stored by the caller.
  18071. * Return the size of available information. */
  18072. int
  18073. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18074. {
  18075. #if defined(USE_SERVER_STATS)
  18076. char *end, *append_eoobj = NULL, block[256];
  18077. size_t context_info_length = 0;
  18078. #if defined(_WIN32)
  18079. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18080. #else
  18081. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18082. #endif
  18083. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18084. if ((buffer == NULL) || (buflen < 1)) {
  18085. buflen = 0;
  18086. end = buffer;
  18087. } else {
  18088. *buffer = 0;
  18089. end = buffer + buflen;
  18090. }
  18091. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18092. /* has enough space to append eoobj */
  18093. append_eoobj = buffer;
  18094. end -= sizeof(eoobj) - 1;
  18095. }
  18096. context_info_length += mg_str_append(&buffer, end, "{");
  18097. if (ms) { /* <-- should be always true */
  18098. /* Memory information */
  18099. int blockCount = (int)ms->blockCount;
  18100. int64_t totalMemUsed = ms->totalMemUsed;
  18101. int64_t maxMemUsed = ms->maxMemUsed;
  18102. if (totalMemUsed > maxMemUsed) {
  18103. maxMemUsed = totalMemUsed;
  18104. }
  18105. mg_snprintf(NULL,
  18106. NULL,
  18107. block,
  18108. sizeof(block),
  18109. "%s\"memory\" : {%s"
  18110. "\"blocks\" : %i,%s"
  18111. "\"used\" : %" INT64_FMT ",%s"
  18112. "\"maxUsed\" : %" INT64_FMT "%s"
  18113. "}",
  18114. eol,
  18115. eol,
  18116. blockCount,
  18117. eol,
  18118. totalMemUsed,
  18119. eol,
  18120. maxMemUsed,
  18121. eol);
  18122. context_info_length += mg_str_append(&buffer, end, block);
  18123. }
  18124. if (ctx) {
  18125. /* Declare all variables at begin of the block, to comply
  18126. * with old C standards. */
  18127. char start_time_str[64] = {0};
  18128. char now_str[64] = {0};
  18129. time_t start_time = ctx->start_time;
  18130. time_t now = time(NULL);
  18131. int64_t total_data_read, total_data_written;
  18132. int active_connections = (int)ctx->active_connections;
  18133. int max_active_connections = (int)ctx->max_active_connections;
  18134. int total_connections = (int)ctx->total_connections;
  18135. if (active_connections > max_active_connections) {
  18136. max_active_connections = active_connections;
  18137. }
  18138. if (active_connections > total_connections) {
  18139. total_connections = active_connections;
  18140. }
  18141. /* Connections information */
  18142. mg_snprintf(NULL,
  18143. NULL,
  18144. block,
  18145. sizeof(block),
  18146. ",%s\"connections\" : {%s"
  18147. "\"active\" : %i,%s"
  18148. "\"maxActive\" : %i,%s"
  18149. "\"total\" : %i%s"
  18150. "}",
  18151. eol,
  18152. eol,
  18153. active_connections,
  18154. eol,
  18155. max_active_connections,
  18156. eol,
  18157. total_connections,
  18158. eol);
  18159. context_info_length += mg_str_append(&buffer, end, block);
  18160. /* Queue information */
  18161. #if !defined(ALTERNATIVE_QUEUE)
  18162. mg_snprintf(NULL,
  18163. NULL,
  18164. block,
  18165. sizeof(block),
  18166. ",%s\"queue\" : {%s"
  18167. "\"length\" : %i,%s"
  18168. "\"filled\" : %i,%s"
  18169. "\"maxFilled\" : %i,%s"
  18170. "\"full\" : %s%s"
  18171. "}",
  18172. eol,
  18173. eol,
  18174. ctx->sq_size,
  18175. eol,
  18176. ctx->sq_head - ctx->sq_tail,
  18177. eol,
  18178. ctx->sq_max_fill,
  18179. eol,
  18180. (ctx->sq_blocked ? "true" : "false"),
  18181. eol);
  18182. context_info_length += mg_str_append(&buffer, end, block);
  18183. #endif
  18184. /* Requests information */
  18185. mg_snprintf(NULL,
  18186. NULL,
  18187. block,
  18188. sizeof(block),
  18189. ",%s\"requests\" : {%s"
  18190. "\"total\" : %lu%s"
  18191. "}",
  18192. eol,
  18193. eol,
  18194. (unsigned long)ctx->total_requests,
  18195. eol);
  18196. context_info_length += mg_str_append(&buffer, end, block);
  18197. /* Data information */
  18198. total_data_read =
  18199. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18200. total_data_written =
  18201. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18202. mg_snprintf(NULL,
  18203. NULL,
  18204. block,
  18205. sizeof(block),
  18206. ",%s\"data\" : {%s"
  18207. "\"read\" : %" INT64_FMT ",%s"
  18208. "\"written\" : %" INT64_FMT "%s"
  18209. "}",
  18210. eol,
  18211. eol,
  18212. total_data_read,
  18213. eol,
  18214. total_data_written,
  18215. eol);
  18216. context_info_length += mg_str_append(&buffer, end, block);
  18217. /* Execution time information */
  18218. gmt_time_string(start_time_str,
  18219. sizeof(start_time_str) - 1,
  18220. &start_time);
  18221. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18222. mg_snprintf(NULL,
  18223. NULL,
  18224. block,
  18225. sizeof(block),
  18226. ",%s\"time\" : {%s"
  18227. "\"uptime\" : %.0f,%s"
  18228. "\"start\" : \"%s\",%s"
  18229. "\"now\" : \"%s\"%s"
  18230. "}",
  18231. eol,
  18232. eol,
  18233. difftime(now, start_time),
  18234. eol,
  18235. start_time_str,
  18236. eol,
  18237. now_str,
  18238. eol);
  18239. context_info_length += mg_str_append(&buffer, end, block);
  18240. }
  18241. /* Terminate string */
  18242. if (append_eoobj) {
  18243. strcat(append_eoobj, eoobj);
  18244. }
  18245. context_info_length += sizeof(eoobj) - 1;
  18246. return (int)context_info_length;
  18247. #else
  18248. (void)ctx;
  18249. if ((buffer != NULL) && (buflen > 0)) {
  18250. *buffer = 0;
  18251. }
  18252. return 0;
  18253. #endif
  18254. }
  18255. void
  18256. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18257. {
  18258. /* https://github.com/civetweb/civetweb/issues/727 */
  18259. if (conn != NULL) {
  18260. conn->must_close = 1;
  18261. }
  18262. }
  18263. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18264. /* Get connection information. It can be printed or stored by the caller.
  18265. * Return the size of available information. */
  18266. int
  18267. mg_get_connection_info(const struct mg_context *ctx,
  18268. int idx,
  18269. char *buffer,
  18270. int buflen)
  18271. {
  18272. const struct mg_connection *conn;
  18273. const struct mg_request_info *ri;
  18274. char *end, *append_eoobj = NULL, block[256];
  18275. size_t connection_info_length = 0;
  18276. int state = 0;
  18277. const char *state_str = "unknown";
  18278. #if defined(_WIN32)
  18279. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18280. #else
  18281. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18282. #endif
  18283. if ((buffer == NULL) || (buflen < 1)) {
  18284. buflen = 0;
  18285. end = buffer;
  18286. } else {
  18287. *buffer = 0;
  18288. end = buffer + buflen;
  18289. }
  18290. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18291. /* has enough space to append eoobj */
  18292. append_eoobj = buffer;
  18293. end -= sizeof(eoobj) - 1;
  18294. }
  18295. if ((ctx == NULL) || (idx < 0)) {
  18296. /* Parameter error */
  18297. return 0;
  18298. }
  18299. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18300. /* Out of range */
  18301. return 0;
  18302. }
  18303. /* Take connection [idx]. This connection is not locked in
  18304. * any way, so some other thread might use it. */
  18305. conn = (ctx->worker_connections) + idx;
  18306. /* Initialize output string */
  18307. connection_info_length += mg_str_append(&buffer, end, "{");
  18308. /* Init variables */
  18309. ri = &(conn->request_info);
  18310. #if defined(USE_SERVER_STATS)
  18311. state = conn->conn_state;
  18312. /* State as string */
  18313. switch (state) {
  18314. case 0:
  18315. state_str = "undefined";
  18316. break;
  18317. case 1:
  18318. state_str = "not used";
  18319. break;
  18320. case 2:
  18321. state_str = "init";
  18322. break;
  18323. case 3:
  18324. state_str = "ready";
  18325. break;
  18326. case 4:
  18327. state_str = "processing";
  18328. break;
  18329. case 5:
  18330. state_str = "processed";
  18331. break;
  18332. case 6:
  18333. state_str = "to close";
  18334. break;
  18335. case 7:
  18336. state_str = "closing";
  18337. break;
  18338. case 8:
  18339. state_str = "closed";
  18340. break;
  18341. case 9:
  18342. state_str = "done";
  18343. break;
  18344. }
  18345. #endif
  18346. /* Connection info */
  18347. if ((state >= 3) && (state < 9)) {
  18348. mg_snprintf(NULL,
  18349. NULL,
  18350. block,
  18351. sizeof(block),
  18352. "%s\"connection\" : {%s"
  18353. "\"remote\" : {%s"
  18354. "\"protocol\" : \"%s\",%s"
  18355. "\"addr\" : \"%s\",%s"
  18356. "\"port\" : %u%s"
  18357. "},%s"
  18358. "\"handled_requests\" : %u%s"
  18359. "}",
  18360. eol,
  18361. eol,
  18362. eol,
  18363. get_proto_name(conn),
  18364. eol,
  18365. ri->remote_addr,
  18366. eol,
  18367. ri->remote_port,
  18368. eol,
  18369. eol,
  18370. conn->handled_requests,
  18371. eol);
  18372. connection_info_length += mg_str_append(&buffer, end, block);
  18373. }
  18374. /* Request info */
  18375. if ((state >= 4) && (state < 6)) {
  18376. mg_snprintf(NULL,
  18377. NULL,
  18378. block,
  18379. sizeof(block),
  18380. "%s%s\"request_info\" : {%s"
  18381. "\"method\" : \"%s\",%s"
  18382. "\"uri\" : \"%s\",%s"
  18383. "\"query\" : %s%s%s%s"
  18384. "}",
  18385. (connection_info_length > 1 ? "," : ""),
  18386. eol,
  18387. eol,
  18388. ri->request_method,
  18389. eol,
  18390. ri->request_uri,
  18391. eol,
  18392. ri->query_string ? "\"" : "",
  18393. ri->query_string ? ri->query_string : "null",
  18394. ri->query_string ? "\"" : "",
  18395. eol);
  18396. connection_info_length += mg_str_append(&buffer, end, block);
  18397. }
  18398. /* Execution time information */
  18399. if ((state >= 2) && (state < 9)) {
  18400. char start_time_str[64] = {0};
  18401. char close_time_str[64] = {0};
  18402. time_t start_time = conn->conn_birth_time;
  18403. time_t close_time = 0;
  18404. double time_diff;
  18405. gmt_time_string(start_time_str,
  18406. sizeof(start_time_str) - 1,
  18407. &start_time);
  18408. #if defined(USE_SERVER_STATS)
  18409. close_time = conn->conn_close_time;
  18410. #endif
  18411. if (close_time != 0) {
  18412. time_diff = difftime(close_time, start_time);
  18413. gmt_time_string(close_time_str,
  18414. sizeof(close_time_str) - 1,
  18415. &close_time);
  18416. } else {
  18417. time_t now = time(NULL);
  18418. time_diff = difftime(now, start_time);
  18419. close_time_str[0] = 0; /* or use "now" ? */
  18420. }
  18421. mg_snprintf(NULL,
  18422. NULL,
  18423. block,
  18424. sizeof(block),
  18425. "%s%s\"time\" : {%s"
  18426. "\"uptime\" : %.0f,%s"
  18427. "\"start\" : \"%s\",%s"
  18428. "\"closed\" : \"%s\"%s"
  18429. "}",
  18430. (connection_info_length > 1 ? "," : ""),
  18431. eol,
  18432. eol,
  18433. time_diff,
  18434. eol,
  18435. start_time_str,
  18436. eol,
  18437. close_time_str,
  18438. eol);
  18439. connection_info_length += mg_str_append(&buffer, end, block);
  18440. }
  18441. /* Remote user name */
  18442. if ((ri->remote_user) && (state < 9)) {
  18443. mg_snprintf(NULL,
  18444. NULL,
  18445. block,
  18446. sizeof(block),
  18447. "%s%s\"user\" : {%s"
  18448. "\"name\" : \"%s\",%s"
  18449. "}",
  18450. (connection_info_length > 1 ? "," : ""),
  18451. eol,
  18452. eol,
  18453. ri->remote_user,
  18454. eol);
  18455. connection_info_length += mg_str_append(&buffer, end, block);
  18456. }
  18457. /* Data block */
  18458. if (state >= 3) {
  18459. mg_snprintf(NULL,
  18460. NULL,
  18461. block,
  18462. sizeof(block),
  18463. "%s%s\"data\" : {%s"
  18464. "\"read\" : %" INT64_FMT ",%s"
  18465. "\"written\" : %" INT64_FMT "%s"
  18466. "}",
  18467. (connection_info_length > 1 ? "," : ""),
  18468. eol,
  18469. eol,
  18470. conn->consumed_content,
  18471. eol,
  18472. conn->num_bytes_sent,
  18473. eol);
  18474. connection_info_length += mg_str_append(&buffer, end, block);
  18475. }
  18476. /* State */
  18477. mg_snprintf(NULL,
  18478. NULL,
  18479. block,
  18480. sizeof(block),
  18481. "%s%s\"state\" : \"%s\"",
  18482. (connection_info_length > 1 ? "," : ""),
  18483. eol,
  18484. state_str);
  18485. connection_info_length += mg_str_append(&buffer, end, block);
  18486. /* Terminate string */
  18487. if (append_eoobj) {
  18488. strcat(append_eoobj, eoobj);
  18489. }
  18490. connection_info_length += sizeof(eoobj) - 1;
  18491. return (int)connection_info_length;
  18492. }
  18493. #endif
  18494. /* Initialize this library. This function does not need to be thread safe.
  18495. */
  18496. unsigned
  18497. mg_init_library(unsigned features)
  18498. {
  18499. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18500. unsigned features_inited = features_to_init;
  18501. if (mg_init_library_called <= 0) {
  18502. /* Not initialized yet */
  18503. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18504. return 0;
  18505. }
  18506. }
  18507. mg_global_lock();
  18508. if (mg_init_library_called <= 0) {
  18509. #if defined(_WIN32)
  18510. int file_mutex_init = 1;
  18511. int wsa = 1;
  18512. #else
  18513. int mutexattr_init = 1;
  18514. #endif
  18515. int failed = 1;
  18516. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18517. if (key_create == 0) {
  18518. #if defined(_WIN32)
  18519. file_mutex_init =
  18520. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18521. if (file_mutex_init == 0) {
  18522. /* Start WinSock */
  18523. WSADATA data;
  18524. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18525. }
  18526. #else
  18527. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18528. if (mutexattr_init == 0) {
  18529. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18530. PTHREAD_MUTEX_RECURSIVE);
  18531. }
  18532. #endif
  18533. }
  18534. if (failed) {
  18535. #if defined(_WIN32)
  18536. if (wsa == 0) {
  18537. (void)WSACleanup();
  18538. }
  18539. if (file_mutex_init == 0) {
  18540. (void)pthread_mutex_destroy(&global_log_file_lock);
  18541. }
  18542. #else
  18543. if (mutexattr_init == 0) {
  18544. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18545. }
  18546. #endif
  18547. if (key_create == 0) {
  18548. (void)pthread_key_delete(sTlsKey);
  18549. }
  18550. mg_global_unlock();
  18551. (void)pthread_mutex_destroy(&global_lock_mutex);
  18552. return 0;
  18553. }
  18554. #if defined(USE_LUA)
  18555. lua_init_optional_libraries();
  18556. #endif
  18557. }
  18558. mg_global_unlock();
  18559. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  18560. || defined(OPENSSL_API_3_0)) \
  18561. && !defined(NO_SSL)
  18562. if (features_to_init & MG_FEATURES_SSL) {
  18563. if (!mg_openssl_initialized) {
  18564. char ebuf[128];
  18565. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  18566. mg_openssl_initialized = 1;
  18567. } else {
  18568. (void)ebuf;
  18569. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18570. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18571. }
  18572. } else {
  18573. /* ssl already initialized */
  18574. }
  18575. }
  18576. #endif
  18577. mg_global_lock();
  18578. if (mg_init_library_called <= 0) {
  18579. mg_init_library_called = 1;
  18580. } else {
  18581. mg_init_library_called++;
  18582. }
  18583. mg_global_unlock();
  18584. return features_inited;
  18585. }
  18586. /* Un-initialize this library. */
  18587. unsigned
  18588. mg_exit_library(void)
  18589. {
  18590. if (mg_init_library_called <= 0) {
  18591. return 0;
  18592. }
  18593. mg_global_lock();
  18594. mg_init_library_called--;
  18595. if (mg_init_library_called == 0) {
  18596. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  18597. if (mg_openssl_initialized) {
  18598. uninitialize_openssl();
  18599. mg_openssl_initialized = 0;
  18600. }
  18601. #endif
  18602. #if defined(_WIN32)
  18603. (void)WSACleanup();
  18604. (void)pthread_mutex_destroy(&global_log_file_lock);
  18605. #else
  18606. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18607. #endif
  18608. (void)pthread_key_delete(sTlsKey);
  18609. #if defined(USE_LUA)
  18610. lua_exit_optional_libraries();
  18611. #endif
  18612. mg_global_unlock();
  18613. (void)pthread_mutex_destroy(&global_lock_mutex);
  18614. return 1;
  18615. }
  18616. mg_global_unlock();
  18617. return 1;
  18618. }
  18619. /* End of civetweb.c */