civetweb.c 613 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969
  1. /* Copyright (c) 2013-2024 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. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__ZEPHYR__)
  170. #include <ctype.h>
  171. #include <fcntl.h>
  172. #include <netdb.h>
  173. #include <poll.h>
  174. #include <pthread.h>
  175. #include <stdio.h>
  176. #include <stdlib.h>
  177. #include <string.h>
  178. #include <sys/socket.h>
  179. #include <time.h>
  180. #include <zephyr/kernel.h>
  181. /* Max worker threads is the max of pthreads minus the main application thread
  182. * and minus the main civetweb thread, thus -2
  183. */
  184. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  186. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  187. #else
  188. #define ZEPHYR_STACK_SIZE (1024 * 16)
  189. #endif
  190. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  191. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  192. MAX_WORKER_THREADS,
  193. ZEPHYR_STACK_SIZE);
  194. static int zephyr_worker_stack_index;
  195. #endif
  196. #if !defined(CIVETWEB_HEADER_INCLUDED)
  197. /* Include the header file here, so the CivetWeb interface is defined for the
  198. * entire implementation, including the following forward definitions. */
  199. #include "civetweb.h"
  200. #endif
  201. #if !defined(DEBUG_TRACE)
  202. #if defined(DEBUG)
  203. static void DEBUG_TRACE_FUNC(const char *func,
  204. unsigned line,
  205. PRINTF_FORMAT_STRING(const char *fmt),
  206. ...) PRINTF_ARGS(3, 4);
  207. #define DEBUG_TRACE(fmt, ...) \
  208. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  209. #define NEED_DEBUG_TRACE_FUNC
  210. #if !defined(DEBUG_TRACE_STREAM)
  211. #define DEBUG_TRACE_STREAM stdout
  212. #endif
  213. #else
  214. #define DEBUG_TRACE(fmt, ...) \
  215. do { \
  216. } while (0)
  217. #endif /* DEBUG */
  218. #endif /* DEBUG_TRACE */
  219. #if !defined(DEBUG_ASSERT)
  220. #if defined(DEBUG)
  221. #include <stdlib.h>
  222. #define DEBUG_ASSERT(cond) \
  223. do { \
  224. if (!(cond)) { \
  225. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  226. exit(2); /* Exit with error */ \
  227. } \
  228. } while (0)
  229. #else
  230. #define DEBUG_ASSERT(cond)
  231. #endif /* DEBUG */
  232. #endif
  233. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  234. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  237. __attribute__((no_instrument_function));
  238. void
  239. __cyg_profile_func_enter(void *this_fn, void *call_site)
  240. {
  241. if ((void *)this_fn != (void *)printf) {
  242. printf("E %p %p\n", this_fn, call_site);
  243. }
  244. }
  245. void
  246. __cyg_profile_func_exit(void *this_fn, void *call_site)
  247. {
  248. if ((void *)this_fn != (void *)printf) {
  249. printf("X %p %p\n", this_fn, call_site);
  250. }
  251. }
  252. #endif
  253. #if !defined(IGNORE_UNUSED_RESULT)
  254. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  255. #endif
  256. #if defined(__GNUC__) || defined(__MINGW32__)
  257. /* GCC unused function attribute seems fundamentally broken.
  258. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  259. * OR UNUSED" for individual functions failed.
  260. * Either the compiler creates an "unused-function" warning if a
  261. * function is not marked with __attribute__((unused)).
  262. * On the other hand, if the function is marked with this attribute,
  263. * but is used, the compiler raises a completely idiotic
  264. * "used-but-marked-unused" warning - and
  265. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  266. * raises error: unknown option after "#pragma GCC diagnostic".
  267. * Disable this warning completely, until the GCC guys sober up
  268. * again.
  269. */
  270. #pragma GCC diagnostic ignored "-Wunused-function"
  271. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  272. #else
  273. #define FUNCTION_MAY_BE_UNUSED
  274. #endif
  275. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  276. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  277. #include <errno.h>
  278. #include <fcntl.h>
  279. #include <signal.h>
  280. #include <stdlib.h>
  281. #include <sys/stat.h>
  282. #include <sys/types.h>
  283. #endif /* !_WIN32_WCE */
  284. #if defined(__clang__)
  285. /* When using -Weverything, clang does not accept it's own headers
  286. * in a release build configuration. Disable what is too much in
  287. * -Weverything. */
  288. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  289. #endif
  290. #if defined(__GNUC__) || defined(__MINGW32__)
  291. /* Who on earth came to the conclusion, using __DATE__ should rise
  292. * an "expansion of date or time macro is not reproducible"
  293. * warning. That's exactly what was intended by using this macro.
  294. * Just disable this nonsense warning. */
  295. /* And disabling them does not work either:
  296. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  297. * #pragma clang diagnostic ignored "-Wdate-time"
  298. * So we just have to disable ALL warnings for some lines
  299. * of code.
  300. * This seems to be a known GCC bug, not resolved since 2012:
  301. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  302. */
  303. #endif
  304. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if defined(_WIN32)
  376. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  377. #else
  378. /* Unix might return different error codes indicating to try again.
  379. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  380. * decades ago, but better check both and let the compiler optimize it. */
  381. #define ERROR_TRY_AGAIN(err) \
  382. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  383. #endif
  384. #if defined(USE_ZLIB)
  385. #include "zconf.h"
  386. #include "zlib.h"
  387. #endif
  388. /********************************************************************/
  389. /* CivetWeb configuration defines */
  390. /********************************************************************/
  391. /* Maximum number of threads that can be configured.
  392. * The number of threads actually created depends on the "num_threads"
  393. * configuration parameter, but this is the upper limit. */
  394. #if !defined(MAX_WORKER_THREADS)
  395. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  396. #endif
  397. /* Timeout interval for select/poll calls.
  398. * The timeouts depend on "*_timeout_ms" configuration values, but long
  399. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  400. * This reduces the time required to stop the server. */
  401. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  402. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  403. #endif
  404. /* Do not try to compress files smaller than this limit. */
  405. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  406. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  407. #endif
  408. #if !defined(PASSWORDS_FILE_NAME)
  409. #define PASSWORDS_FILE_NAME ".htpasswd"
  410. #endif
  411. /* Initial buffer size for all CGI environment variables. In case there is
  412. * not enough space, another block is allocated. */
  413. #if !defined(CGI_ENVIRONMENT_SIZE)
  414. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  415. #endif
  416. /* Maximum number of environment variables. */
  417. #if !defined(MAX_CGI_ENVIR_VARS)
  418. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  419. #endif
  420. /* General purpose buffer size. */
  421. #if !defined(MG_BUF_LEN) /* in bytes */
  422. #define MG_BUF_LEN (1024 * 8)
  423. #endif
  424. /********************************************************************/
  425. /* Helper macros */
  426. #if !defined(ARRAY_SIZE)
  427. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  428. #endif
  429. #include <stdint.h>
  430. /* Standard defines */
  431. #if !defined(INT64_MAX)
  432. #define INT64_MAX (9223372036854775807)
  433. #endif
  434. #define SHUTDOWN_RD (0)
  435. #define SHUTDOWN_WR (1)
  436. #define SHUTDOWN_BOTH (2)
  437. mg_static_assert(MAX_WORKER_THREADS >= 1,
  438. "worker threads must be a positive number");
  439. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  440. "size_t data type size check");
  441. #if defined(_WIN32) /* WINDOWS include block */
  442. #include <malloc.h> /* *alloc( */
  443. #include <stdlib.h> /* *alloc( */
  444. #include <time.h> /* struct timespec */
  445. #include <windows.h>
  446. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  447. #include <ws2tcpip.h>
  448. typedef const char *SOCK_OPT_TYPE;
  449. /* For a detailed description of these *_PATH_MAX defines, see
  450. * https://github.com/civetweb/civetweb/issues/937. */
  451. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  452. * null termination, rounded up to the next 4 bytes boundary */
  453. #define UTF8_PATH_MAX (3 * 260)
  454. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  455. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  456. #define UTF16_PATH_MAX (260)
  457. #if !defined(_IN_PORT_T)
  458. #if !defined(in_port_t)
  459. #define in_port_t u_short
  460. #endif
  461. #endif
  462. #if defined(_WIN32_WCE)
  463. #error "WinCE support has ended"
  464. #endif
  465. #include <direct.h>
  466. #include <io.h>
  467. #include <process.h>
  468. #define MAKEUQUAD(lo, hi) \
  469. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  470. #define RATE_DIFF (10000000) /* 100 nsecs */
  471. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  472. #define SYS2UNIX_TIME(lo, hi) \
  473. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  474. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  475. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  476. * Also use _strtoui64 on modern M$ compilers */
  477. #if defined(_MSC_VER)
  478. #if (_MSC_VER < 1300)
  479. #define STRX(x) #x
  480. #define STR(x) STRX(x)
  481. #define __func__ __FILE__ ":" STR(__LINE__)
  482. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  483. #define strtoll(x, y, z) (_atoi64(x))
  484. #else
  485. #define __func__ __FUNCTION__
  486. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  487. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  488. #endif
  489. #endif /* _MSC_VER */
  490. #define ERRNO ((int)(GetLastError()))
  491. #define NO_SOCKLEN_T
  492. #if defined(_WIN64) || defined(__MINGW64__)
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_3_0)
  495. #define SSL_LIB "libssl-3-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  497. #endif
  498. #if defined(OPENSSL_API_1_1)
  499. #define SSL_LIB "libssl-1_1-x64.dll"
  500. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  501. #endif /* OPENSSL_API_1_1 */
  502. #if defined(OPENSSL_API_1_0)
  503. #define SSL_LIB "ssleay64.dll"
  504. #define CRYPTO_LIB "libeay64.dll"
  505. #endif /* OPENSSL_API_1_0 */
  506. #endif
  507. #else /* defined(_WIN64) || defined(__MINGW64__) */
  508. #if !defined(SSL_LIB)
  509. #if defined(OPENSSL_API_3_0)
  510. #define SSL_LIB "libssl-3.dll"
  511. #define CRYPTO_LIB "libcrypto-3.dll"
  512. #endif
  513. #if defined(OPENSSL_API_1_1)
  514. #define SSL_LIB "libssl-1_1.dll"
  515. #define CRYPTO_LIB "libcrypto-1_1.dll"
  516. #endif /* OPENSSL_API_1_1 */
  517. #if defined(OPENSSL_API_1_0)
  518. #define SSL_LIB "ssleay32.dll"
  519. #define CRYPTO_LIB "libeay32.dll"
  520. #endif /* OPENSSL_API_1_0 */
  521. #endif /* SSL_LIB */
  522. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  523. #define O_NONBLOCK (0)
  524. #if !defined(W_OK)
  525. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  526. #endif
  527. #define _POSIX_
  528. #define INT64_FMT "I64d"
  529. #define UINT64_FMT "I64u"
  530. #define WINCDECL __cdecl
  531. #define vsnprintf_impl _vsnprintf
  532. #define access _access
  533. #define mg_sleep(x) (Sleep(x))
  534. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  535. #if !defined(popen)
  536. #define popen(x, y) (_popen(x, y))
  537. #endif
  538. #if !defined(pclose)
  539. #define pclose(x) (_pclose(x))
  540. #endif
  541. #define close(x) (_close(x))
  542. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  543. #define RTLD_LAZY (0)
  544. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  545. #define fdopen(x, y) (_fdopen((x), (y)))
  546. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  547. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  548. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  549. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  550. #define sleep(x) (Sleep((x)*1000))
  551. #define rmdir(x) (_rmdir(x))
  552. #if defined(_WIN64) || !defined(__MINGW32__)
  553. /* Only MinGW 32 bit is missing this function */
  554. #define timegm(x) (_mkgmtime(x))
  555. #else
  556. time_t timegm(struct tm *tm);
  557. #define NEED_TIMEGM
  558. #endif
  559. #if !defined(fileno)
  560. #define fileno(x) (_fileno(x))
  561. #endif /* !fileno MINGW #defines fileno */
  562. typedef struct {
  563. CRITICAL_SECTION sec; /* Immovable */
  564. } pthread_mutex_t;
  565. typedef DWORD pthread_key_t;
  566. typedef HANDLE pthread_t;
  567. typedef struct {
  568. pthread_mutex_t threadIdSec;
  569. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  570. } pthread_cond_t;
  571. #if !defined(__clockid_t_defined)
  572. typedef DWORD clockid_t;
  573. #endif
  574. #if !defined(CLOCK_MONOTONIC)
  575. #define CLOCK_MONOTONIC (1)
  576. #endif
  577. #if !defined(CLOCK_REALTIME)
  578. #define CLOCK_REALTIME (2)
  579. #endif
  580. #if !defined(CLOCK_THREAD)
  581. #define CLOCK_THREAD (3)
  582. #endif
  583. #if !defined(CLOCK_PROCESS)
  584. #define CLOCK_PROCESS (4)
  585. #endif
  586. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  587. #define _TIMESPEC_DEFINED
  588. #endif
  589. #if !defined(_TIMESPEC_DEFINED)
  590. struct timespec {
  591. time_t tv_sec; /* seconds */
  592. long tv_nsec; /* nanoseconds */
  593. };
  594. #endif
  595. #if !defined(WIN_PTHREADS_TIME_H)
  596. #define MUST_IMPLEMENT_CLOCK_GETTIME
  597. #endif
  598. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  599. #define clock_gettime mg_clock_gettime
  600. static int
  601. clock_gettime(clockid_t clk_id, struct timespec *tp)
  602. {
  603. FILETIME ft;
  604. ULARGE_INTEGER li, li2;
  605. BOOL ok = FALSE;
  606. double d;
  607. static double perfcnt_per_sec = 0.0;
  608. static BOOL initialized = FALSE;
  609. if (!initialized) {
  610. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  611. perfcnt_per_sec = 1.0 / li.QuadPart;
  612. initialized = TRUE;
  613. }
  614. if (tp) {
  615. memset(tp, 0, sizeof(*tp));
  616. if (clk_id == CLOCK_REALTIME) {
  617. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  618. GetSystemTimeAsFileTime(&ft);
  619. li.LowPart = ft.dwLowDateTime;
  620. li.HighPart = ft.dwHighDateTime;
  621. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  622. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  623. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  624. ok = TRUE;
  625. /* END: CLOCK_REALTIME */
  626. } else if (clk_id == CLOCK_MONOTONIC) {
  627. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  628. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  629. d = li.QuadPart * perfcnt_per_sec;
  630. tp->tv_sec = (time_t)d;
  631. d -= (double)tp->tv_sec;
  632. tp->tv_nsec = (long)(d * 1.0E9);
  633. ok = TRUE;
  634. /* END: CLOCK_MONOTONIC */
  635. } else if (clk_id == CLOCK_THREAD) {
  636. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  637. FILETIME t_create, t_exit, t_kernel, t_user;
  638. if (GetThreadTimes(GetCurrentThread(),
  639. &t_create,
  640. &t_exit,
  641. &t_kernel,
  642. &t_user)) {
  643. li.LowPart = t_user.dwLowDateTime;
  644. li.HighPart = t_user.dwHighDateTime;
  645. li2.LowPart = t_kernel.dwLowDateTime;
  646. li2.HighPart = t_kernel.dwHighDateTime;
  647. li.QuadPart += li2.QuadPart;
  648. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  649. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  650. ok = TRUE;
  651. }
  652. /* END: CLOCK_THREAD */
  653. } else if (clk_id == CLOCK_PROCESS) {
  654. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  655. FILETIME t_create, t_exit, t_kernel, t_user;
  656. if (GetProcessTimes(GetCurrentProcess(),
  657. &t_create,
  658. &t_exit,
  659. &t_kernel,
  660. &t_user)) {
  661. li.LowPart = t_user.dwLowDateTime;
  662. li.HighPart = t_user.dwHighDateTime;
  663. li2.LowPart = t_kernel.dwLowDateTime;
  664. li2.HighPart = t_kernel.dwHighDateTime;
  665. li.QuadPart += li2.QuadPart;
  666. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  667. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  668. ok = TRUE;
  669. }
  670. /* END: CLOCK_PROCESS */
  671. } else {
  672. /* BEGIN: unknown clock */
  673. /* ok = FALSE; already set by init */
  674. /* END: unknown clock */
  675. }
  676. }
  677. return ok ? 0 : -1;
  678. }
  679. #endif
  680. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  681. static int pthread_mutex_lock(pthread_mutex_t *);
  682. static int pthread_mutex_unlock(pthread_mutex_t *);
  683. static void path_to_unicode(const struct mg_connection *conn,
  684. const char *path,
  685. wchar_t *wbuf,
  686. size_t wbuf_len);
  687. /* All file operations need to be rewritten to solve #246. */
  688. struct mg_file;
  689. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  690. /* POSIX dirent interface */
  691. struct dirent {
  692. char d_name[UTF8_PATH_MAX];
  693. };
  694. typedef struct DIR {
  695. HANDLE handle;
  696. WIN32_FIND_DATAW info;
  697. struct dirent result;
  698. } DIR;
  699. #if defined(HAVE_POLL)
  700. #define mg_pollfd pollfd
  701. #else
  702. struct mg_pollfd {
  703. SOCKET fd;
  704. short events;
  705. short revents;
  706. };
  707. #endif
  708. /* Mark required libraries */
  709. #if defined(_MSC_VER)
  710. #pragma comment(lib, "Ws2_32.lib")
  711. #endif
  712. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  713. #include <inttypes.h>
  714. /* Linux & co. internally use UTF8 */
  715. #define UTF8_PATH_MAX (PATH_MAX)
  716. typedef const void *SOCK_OPT_TYPE;
  717. #if defined(ANDROID)
  718. typedef unsigned short int in_port_t;
  719. #endif
  720. #if !defined(__ZEPHYR__)
  721. #include <arpa/inet.h>
  722. #include <ctype.h>
  723. #include <dirent.h>
  724. #include <grp.h>
  725. #include <limits.h>
  726. #include <netdb.h>
  727. #include <netinet/in.h>
  728. #include <netinet/tcp.h>
  729. #include <poll.h>
  730. #include <pthread.h>
  731. #include <pwd.h>
  732. #include <stdarg.h>
  733. #include <stddef.h>
  734. #include <stdio.h>
  735. #include <stdlib.h>
  736. #include <string.h>
  737. #include <sys/socket.h>
  738. #include <sys/time.h>
  739. #include <sys/utsname.h>
  740. #include <sys/wait.h>
  741. #include <time.h>
  742. #include <unistd.h>
  743. #if defined(USE_X_DOM_SOCKET)
  744. #include <sys/un.h>
  745. #endif
  746. #endif
  747. #define vsnprintf_impl vsnprintf
  748. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  749. #include <dlfcn.h>
  750. #endif
  751. #if defined(__MACH__) && defined(__APPLE__)
  752. #define SSL_LIB "libssl.dylib"
  753. #define CRYPTO_LIB "libcrypto.dylib"
  754. #else
  755. #if !defined(SSL_LIB)
  756. #define SSL_LIB "libssl.so"
  757. #endif
  758. #if !defined(CRYPTO_LIB)
  759. #define CRYPTO_LIB "libcrypto.so"
  760. #endif
  761. #endif
  762. #if !defined(O_BINARY)
  763. #define O_BINARY (0)
  764. #endif /* O_BINARY */
  765. #define closesocket(a) (close(a))
  766. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  767. #define mg_remove(conn, x) (remove(x))
  768. #define mg_sleep(x) (usleep((x)*1000))
  769. #define mg_opendir(conn, x) (opendir(x))
  770. #define mg_closedir(x) (closedir(x))
  771. #define mg_readdir(x) (readdir(x))
  772. #define ERRNO (errno)
  773. #define INVALID_SOCKET (-1)
  774. #define INT64_FMT PRId64
  775. #define UINT64_FMT PRIu64
  776. typedef int SOCKET;
  777. #define WINCDECL
  778. #if defined(__hpux)
  779. /* HPUX 11 does not have monotonic, fall back to realtime */
  780. #if !defined(CLOCK_MONOTONIC)
  781. #define CLOCK_MONOTONIC CLOCK_REALTIME
  782. #endif
  783. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  784. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  785. * the prototypes use int* rather than socklen_t* which matches the
  786. * actual library expectation. When called with the wrong size arg
  787. * accept() returns a zero client inet addr and check_acl() always
  788. * fails. Since socklen_t is widely used below, just force replace
  789. * their typedef with int. - DTL
  790. */
  791. #define socklen_t int
  792. #endif /* hpux */
  793. #define mg_pollfd pollfd
  794. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  795. /* In case our C library is missing "timegm", provide an implementation */
  796. #if defined(NEED_TIMEGM)
  797. static inline int
  798. is_leap(int y)
  799. {
  800. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  801. }
  802. static inline int
  803. count_leap(int y)
  804. {
  805. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  806. }
  807. time_t
  808. timegm(struct tm *tm)
  809. {
  810. static const unsigned short ydays[] = {
  811. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  812. int year = tm->tm_year + 1900;
  813. int mon = tm->tm_mon;
  814. int mday = tm->tm_mday - 1;
  815. int hour = tm->tm_hour;
  816. int min = tm->tm_min;
  817. int sec = tm->tm_sec;
  818. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  819. || (mday >= ydays[mon + 1] - ydays[mon]
  820. + (mon == 1 && is_leap(year) ? 1 : 0))
  821. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  822. return -1;
  823. time_t res = year - 1970;
  824. res *= 365;
  825. res += mday;
  826. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  827. res += count_leap(year);
  828. res *= 24;
  829. res += hour;
  830. res *= 60;
  831. res += min;
  832. res *= 60;
  833. res += sec;
  834. return res;
  835. }
  836. #endif /* NEED_TIMEGM */
  837. /* va_copy should always be a macro, C99 and C++11 - DTL */
  838. #if !defined(va_copy)
  839. #define va_copy(x, y) ((x) = (y))
  840. #endif
  841. #if defined(_WIN32)
  842. /* Create substitutes for POSIX functions in Win32. */
  843. #if defined(GCC_DIAGNOSTIC)
  844. /* Show no warning in case system functions are not used. */
  845. #pragma GCC diagnostic push
  846. #pragma GCC diagnostic ignored "-Wunused-function"
  847. #endif
  848. static pthread_mutex_t global_log_file_lock;
  849. FUNCTION_MAY_BE_UNUSED
  850. static DWORD
  851. pthread_self(void)
  852. {
  853. return GetCurrentThreadId();
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_create(
  858. pthread_key_t *key,
  859. void (*_ignored)(void *) /* destructor not supported for Windows */
  860. )
  861. {
  862. (void)_ignored;
  863. if ((key != 0)) {
  864. *key = TlsAlloc();
  865. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  866. }
  867. return -2;
  868. }
  869. FUNCTION_MAY_BE_UNUSED
  870. static int
  871. pthread_key_delete(pthread_key_t key)
  872. {
  873. return TlsFree(key) ? 0 : 1;
  874. }
  875. FUNCTION_MAY_BE_UNUSED
  876. static int
  877. pthread_setspecific(pthread_key_t key, void *value)
  878. {
  879. return TlsSetValue(key, value) ? 0 : 1;
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static void *
  883. pthread_getspecific(pthread_key_t key)
  884. {
  885. return TlsGetValue(key);
  886. }
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Enable unused function warning again */
  889. #pragma GCC diagnostic pop
  890. #endif
  891. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  892. #else
  893. static pthread_mutexattr_t pthread_mutex_attr;
  894. #endif /* _WIN32 */
  895. #if defined(GCC_DIAGNOSTIC)
  896. /* Show no warning in case system functions are not used. */
  897. #pragma GCC diagnostic push
  898. #pragma GCC diagnostic ignored "-Wunused-function"
  899. #endif /* defined(GCC_DIAGNOSTIC) */
  900. #if defined(__clang__)
  901. /* Show no warning in case system functions are not used. */
  902. #pragma clang diagnostic push
  903. #pragma clang diagnostic ignored "-Wunused-function"
  904. #endif
  905. static pthread_mutex_t global_lock_mutex;
  906. FUNCTION_MAY_BE_UNUSED
  907. static void
  908. mg_global_lock(void)
  909. {
  910. (void)pthread_mutex_lock(&global_lock_mutex);
  911. }
  912. FUNCTION_MAY_BE_UNUSED
  913. static void
  914. mg_global_unlock(void)
  915. {
  916. (void)pthread_mutex_unlock(&global_lock_mutex);
  917. }
  918. #if defined(_WIN64)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  920. #elif defined(_WIN32)
  921. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  922. #endif
  923. /* Atomic functions working on ptrdiff_t ("signed size_t").
  924. * Operations: Increment, Decrement, Add, Maximum.
  925. * Up to size_t, they do not an atomic "load" operation.
  926. */
  927. FUNCTION_MAY_BE_UNUSED
  928. static ptrdiff_t
  929. mg_atomic_inc(volatile ptrdiff_t *addr)
  930. {
  931. ptrdiff_t ret;
  932. #if defined(_WIN64) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement64(addr);
  934. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  935. #ifdef __cplusplus
  936. /* For C++ the Microsoft Visual Studio compiler can not decide what
  937. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  938. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  939. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  940. ret = InterlockedIncrement((LONG *)addr);
  941. #else
  942. ret = InterlockedIncrement(addr);
  943. #endif
  944. #elif defined(__GNUC__) \
  945. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  946. && !defined(NO_ATOMICS)
  947. ret = __sync_add_and_fetch(addr, 1);
  948. #else
  949. mg_global_lock();
  950. ret = (++(*addr));
  951. mg_global_unlock();
  952. #endif
  953. return ret;
  954. }
  955. FUNCTION_MAY_BE_UNUSED
  956. static ptrdiff_t
  957. mg_atomic_dec(volatile ptrdiff_t *addr)
  958. {
  959. ptrdiff_t ret;
  960. #if defined(_WIN64) && !defined(NO_ATOMICS)
  961. ret = InterlockedDecrement64(addr);
  962. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  963. #ifdef __cplusplus
  964. /* see mg_atomic_inc */
  965. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  966. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  967. ret = InterlockedDecrement((LONG *)addr);
  968. #else
  969. ret = InterlockedDecrement(addr);
  970. #endif
  971. #elif defined(__GNUC__) \
  972. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  973. && !defined(NO_ATOMICS)
  974. ret = __sync_sub_and_fetch(addr, 1);
  975. #else
  976. mg_global_lock();
  977. ret = (--(*addr));
  978. mg_global_unlock();
  979. #endif
  980. return ret;
  981. }
  982. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  983. static ptrdiff_t
  984. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedAdd64(addr, value);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedExchangeAdd(addr, value) + value;
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_add_and_fetch(addr, value);
  995. #else
  996. mg_global_lock();
  997. *addr += value;
  998. ret = (*addr);
  999. mg_global_unlock();
  1000. #endif
  1001. return ret;
  1002. }
  1003. FUNCTION_MAY_BE_UNUSED
  1004. static ptrdiff_t
  1005. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1006. ptrdiff_t oldval,
  1007. ptrdiff_t newval)
  1008. {
  1009. ptrdiff_t ret;
  1010. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1011. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1012. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1013. ret = InterlockedCompareExchange(addr, newval, oldval);
  1014. #elif defined(__GNUC__) \
  1015. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1016. && !defined(NO_ATOMICS)
  1017. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1018. #else
  1019. mg_global_lock();
  1020. ret = *addr;
  1021. if ((ret != newval) && (ret == oldval)) {
  1022. *addr = newval;
  1023. }
  1024. mg_global_unlock();
  1025. #endif
  1026. return ret;
  1027. }
  1028. static void
  1029. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1030. {
  1031. register ptrdiff_t tmp = *addr;
  1032. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1033. while (tmp < value) {
  1034. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1035. }
  1036. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1037. while (tmp < value) {
  1038. tmp = InterlockedCompareExchange(addr, value, tmp);
  1039. }
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. while (tmp < value) {
  1044. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1045. }
  1046. #else
  1047. mg_global_lock();
  1048. if (*addr < value) {
  1049. *addr = value;
  1050. }
  1051. mg_global_unlock();
  1052. #endif
  1053. }
  1054. static int64_t
  1055. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1061. ret = InterlockedExchangeAdd64(addr, value) + value;
  1062. #elif defined(__GNUC__) \
  1063. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1064. && !defined(NO_ATOMICS)
  1065. ret = __sync_add_and_fetch(addr, value);
  1066. #else
  1067. mg_global_lock();
  1068. *addr += value;
  1069. ret = (*addr);
  1070. mg_global_unlock();
  1071. #endif
  1072. return ret;
  1073. }
  1074. #endif
  1075. #if defined(GCC_DIAGNOSTIC)
  1076. /* Show no warning in case system functions are not used. */
  1077. #pragma GCC diagnostic pop
  1078. #endif /* defined(GCC_DIAGNOSTIC) */
  1079. #if defined(__clang__)
  1080. /* Show no warning in case system functions are not used. */
  1081. #pragma clang diagnostic pop
  1082. #endif
  1083. #if defined(USE_SERVER_STATS)
  1084. struct mg_memory_stat {
  1085. volatile ptrdiff_t totalMemUsed;
  1086. volatile ptrdiff_t maxMemUsed;
  1087. volatile ptrdiff_t blockCount;
  1088. };
  1089. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1090. static void *
  1091. mg_malloc_ex(size_t size,
  1092. struct mg_context *ctx,
  1093. const char *file,
  1094. unsigned line)
  1095. {
  1096. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1097. void *memory = 0;
  1098. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1099. #if defined(MEMORY_DEBUGGING)
  1100. char mallocStr[256];
  1101. #else
  1102. (void)file;
  1103. (void)line;
  1104. #endif
  1105. if (data) {
  1106. uintptr_t *tmp = (uintptr_t *)data;
  1107. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1108. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1109. mg_atomic_inc(&mstat->blockCount);
  1110. tmp[0] = size;
  1111. tmp[1] = (uintptr_t)mstat;
  1112. memory = (void *)&tmp[2];
  1113. }
  1114. #if defined(MEMORY_DEBUGGING)
  1115. sprintf(mallocStr,
  1116. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1117. memory,
  1118. (unsigned long)size,
  1119. (unsigned long)mstat->totalMemUsed,
  1120. (unsigned long)mstat->blockCount,
  1121. file,
  1122. line);
  1123. DEBUG_TRACE("%s", mallocStr);
  1124. #endif
  1125. return memory;
  1126. }
  1127. static void *
  1128. mg_calloc_ex(size_t count,
  1129. size_t size,
  1130. struct mg_context *ctx,
  1131. const char *file,
  1132. unsigned line)
  1133. {
  1134. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1135. if (data) {
  1136. memset(data, 0, size * count);
  1137. }
  1138. return data;
  1139. }
  1140. static void
  1141. mg_free_ex(void *memory, const char *file, unsigned line)
  1142. {
  1143. #if defined(MEMORY_DEBUGGING)
  1144. char mallocStr[256];
  1145. #else
  1146. (void)file;
  1147. (void)line;
  1148. #endif
  1149. if (memory) {
  1150. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1151. uintptr_t size = ((uintptr_t *)data)[0];
  1152. struct mg_memory_stat *mstat =
  1153. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1154. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1155. mg_atomic_dec(&mstat->blockCount);
  1156. #if defined(MEMORY_DEBUGGING)
  1157. sprintf(mallocStr,
  1158. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1159. memory,
  1160. (unsigned long)size,
  1161. (unsigned long)mstat->totalMemUsed,
  1162. (unsigned long)mstat->blockCount,
  1163. file,
  1164. line);
  1165. DEBUG_TRACE("%s", mallocStr);
  1166. #endif
  1167. free(data);
  1168. }
  1169. }
  1170. static void *
  1171. mg_realloc_ex(void *memory,
  1172. size_t newsize,
  1173. struct mg_context *ctx,
  1174. const char *file,
  1175. unsigned line)
  1176. {
  1177. void *data;
  1178. void *_realloc;
  1179. uintptr_t oldsize;
  1180. #if defined(MEMORY_DEBUGGING)
  1181. char mallocStr[256];
  1182. #else
  1183. (void)file;
  1184. (void)line;
  1185. #endif
  1186. if (newsize) {
  1187. if (memory) {
  1188. /* Reallocate existing block */
  1189. struct mg_memory_stat *mstat;
  1190. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1191. oldsize = ((uintptr_t *)data)[0];
  1192. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1193. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1194. if (_realloc) {
  1195. data = _realloc;
  1196. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1197. #if defined(MEMORY_DEBUGGING)
  1198. sprintf(mallocStr,
  1199. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1200. memory,
  1201. (unsigned long)oldsize,
  1202. (unsigned long)mstat->totalMemUsed,
  1203. (unsigned long)mstat->blockCount,
  1204. file,
  1205. line);
  1206. DEBUG_TRACE("%s", mallocStr);
  1207. #endif
  1208. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1209. #if defined(MEMORY_DEBUGGING)
  1210. sprintf(mallocStr,
  1211. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1212. memory,
  1213. (unsigned long)newsize,
  1214. (unsigned long)mstat->totalMemUsed,
  1215. (unsigned long)mstat->blockCount,
  1216. file,
  1217. line);
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. *(uintptr_t *)data = newsize;
  1221. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1222. } else {
  1223. #if defined(MEMORY_DEBUGGING)
  1224. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1225. #endif
  1226. return _realloc;
  1227. }
  1228. } else {
  1229. /* Allocate new block */
  1230. data = mg_malloc_ex(newsize, ctx, file, line);
  1231. }
  1232. } else {
  1233. /* Free existing block */
  1234. data = 0;
  1235. mg_free_ex(memory, file, line);
  1236. }
  1237. return data;
  1238. }
  1239. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1240. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1241. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1242. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1243. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1246. #else /* USE_SERVER_STATS */
  1247. static __inline void *
  1248. mg_malloc(size_t a)
  1249. {
  1250. return malloc(a);
  1251. }
  1252. static __inline void *
  1253. mg_calloc(size_t a, size_t b)
  1254. {
  1255. return calloc(a, b);
  1256. }
  1257. static __inline void *
  1258. mg_realloc(void *a, size_t b)
  1259. {
  1260. return realloc(a, b);
  1261. }
  1262. static __inline void
  1263. mg_free(void *a)
  1264. {
  1265. free(a);
  1266. }
  1267. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1268. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1269. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1270. #define mg_free_ctx(a, c) mg_free(a)
  1271. #endif /* USE_SERVER_STATS */
  1272. static void mg_vsnprintf(const struct mg_connection *conn,
  1273. int *truncated,
  1274. char *buf,
  1275. size_t buflen,
  1276. const char *fmt,
  1277. va_list ap);
  1278. static void mg_snprintf(const struct mg_connection *conn,
  1279. int *truncated,
  1280. char *buf,
  1281. size_t buflen,
  1282. PRINTF_FORMAT_STRING(const char *fmt),
  1283. ...) PRINTF_ARGS(5, 6);
  1284. /* This following lines are just meant as a reminder to use the mg-functions
  1285. * for memory management */
  1286. #if defined(malloc)
  1287. #undef malloc
  1288. #endif
  1289. #if defined(calloc)
  1290. #undef calloc
  1291. #endif
  1292. #if defined(realloc)
  1293. #undef realloc
  1294. #endif
  1295. #if defined(free)
  1296. #undef free
  1297. #endif
  1298. #if defined(snprintf)
  1299. #undef snprintf
  1300. #endif
  1301. #if defined(vsnprintf)
  1302. #undef vsnprintf
  1303. #endif
  1304. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1305. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1306. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1307. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1308. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1309. #if defined(_WIN32)
  1310. /* vsnprintf must not be used in any system,
  1311. * but this define only works well for Windows. */
  1312. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1313. #endif
  1314. /* mg_init_library counter */
  1315. static int mg_init_library_called = 0;
  1316. #if !defined(NO_SSL)
  1317. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1318. || defined(OPENSSL_API_3_0)
  1319. static int mg_openssl_initialized = 0;
  1320. #endif
  1321. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1322. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1323. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1324. #endif
  1325. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1326. #error "Multiple OPENSSL_API versions defined"
  1327. #endif
  1328. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1329. #error "Multiple OPENSSL_API versions defined"
  1330. #endif
  1331. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1332. #error "Multiple OPENSSL_API versions defined"
  1333. #endif
  1334. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)) \
  1336. && defined(USE_MBEDTLS)
  1337. #error "Multiple SSL libraries defined"
  1338. #endif
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static volatile ptrdiff_t thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. const char *alpn_proto;
  1354. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1355. char txtbuf[4];
  1356. #endif
  1357. };
  1358. #if defined(GCC_DIAGNOSTIC)
  1359. /* Show no warning in case system functions are not used. */
  1360. #pragma GCC diagnostic push
  1361. #pragma GCC diagnostic ignored "-Wunused-function"
  1362. #endif /* defined(GCC_DIAGNOSTIC) */
  1363. #if defined(__clang__)
  1364. /* Show no warning in case system functions are not used. */
  1365. #pragma clang diagnostic push
  1366. #pragma clang diagnostic ignored "-Wunused-function"
  1367. #endif
  1368. /* Get a unique thread ID as unsigned long, independent from the data type
  1369. * of thread IDs defined by the operating system API.
  1370. * If two calls to mg_current_thread_id return the same value, they calls
  1371. * are done from the same thread. If they return different values, they are
  1372. * done from different threads. (Provided this function is used in the same
  1373. * process context and threads are not repeatedly created and deleted, but
  1374. * CivetWeb does not do that).
  1375. * This function must match the signature required for SSL id callbacks:
  1376. * CRYPTO_set_id_callback
  1377. */
  1378. FUNCTION_MAY_BE_UNUSED
  1379. static unsigned long
  1380. mg_current_thread_id(void)
  1381. {
  1382. #if defined(_WIN32)
  1383. return GetCurrentThreadId();
  1384. #else
  1385. #if defined(__clang__)
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunreachable-code"
  1388. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1389. * or not, so one of the two conditions will be unreachable by construction.
  1390. * Unfortunately the C standard does not define a way to check this at
  1391. * compile time, since the #if preprocessor conditions can not use the
  1392. * sizeof operator as an argument. */
  1393. #endif
  1394. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1395. /* This is the problematic case for CRYPTO_set_id_callback:
  1396. * The OS pthread_t can not be cast to unsigned long. */
  1397. struct mg_workerTLS *tls =
  1398. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1399. if (tls == NULL) {
  1400. /* SSL called from an unknown thread: Create some thread index.
  1401. */
  1402. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1403. tls->is_master = -2; /* -2 means "3rd party thread" */
  1404. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1405. pthread_setspecific(sTlsKey, tls);
  1406. }
  1407. return tls->thread_idx;
  1408. } else {
  1409. /* pthread_t may be any data type, so a simple cast to unsigned long
  1410. * can rise a warning/error, depending on the platform.
  1411. * Here memcpy is used as an anything-to-anything cast. */
  1412. unsigned long ret = 0;
  1413. pthread_t t = pthread_self();
  1414. memcpy(&ret, &t, sizeof(pthread_t));
  1415. return ret;
  1416. }
  1417. #if defined(__clang__)
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #endif
  1421. }
  1422. FUNCTION_MAY_BE_UNUSED
  1423. static uint64_t
  1424. mg_get_current_time_ns(void)
  1425. {
  1426. struct timespec tsnow;
  1427. clock_gettime(CLOCK_REALTIME, &tsnow);
  1428. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1429. }
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic pop
  1433. #endif /* defined(GCC_DIAGNOSTIC) */
  1434. #if defined(__clang__)
  1435. /* Show no warning in case system functions are not used. */
  1436. #pragma clang diagnostic pop
  1437. #endif
  1438. #if defined(NEED_DEBUG_TRACE_FUNC)
  1439. static void
  1440. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1441. {
  1442. va_list args;
  1443. struct timespec tsnow;
  1444. /* Get some operating system independent thread id */
  1445. unsigned long thread_id = mg_current_thread_id();
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. flockfile(DEBUG_TRACE_STREAM);
  1448. fprintf(DEBUG_TRACE_STREAM,
  1449. "*** %lu.%09lu %lu %s:%u: ",
  1450. (unsigned long)tsnow.tv_sec,
  1451. (unsigned long)tsnow.tv_nsec,
  1452. thread_id,
  1453. func,
  1454. line);
  1455. va_start(args, fmt);
  1456. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1457. va_end(args);
  1458. putc('\n', DEBUG_TRACE_STREAM);
  1459. fflush(DEBUG_TRACE_STREAM);
  1460. funlockfile(DEBUG_TRACE_STREAM);
  1461. }
  1462. #endif /* NEED_DEBUG_TRACE_FUNC */
  1463. #define MD5_STATIC static
  1464. #include "md5.inl"
  1465. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1466. #if defined(NO_SOCKLEN_T)
  1467. typedef int socklen_t;
  1468. #endif /* NO_SOCKLEN_T */
  1469. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1470. #if !defined(MSG_NOSIGNAL)
  1471. #define MSG_NOSIGNAL (0)
  1472. #endif
  1473. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1474. #if defined(USE_MBEDTLS)
  1475. /* mbedTLS */
  1476. #include "mod_mbedtls.inl"
  1477. #elif defined(NO_SSL)
  1478. /* no SSL */
  1479. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1480. typedef struct SSL_CTX SSL_CTX;
  1481. #elif defined(NO_SSL_DL)
  1482. /* OpenSSL without dynamic loading */
  1483. #include <openssl/bn.h>
  1484. #include <openssl/conf.h>
  1485. #include <openssl/crypto.h>
  1486. #include <openssl/dh.h>
  1487. #include <openssl/engine.h>
  1488. #include <openssl/err.h>
  1489. #include <openssl/opensslv.h>
  1490. #include <openssl/pem.h>
  1491. #include <openssl/ssl.h>
  1492. #include <openssl/tls1.h>
  1493. #include <openssl/x509.h>
  1494. #if defined(WOLFSSL_VERSION)
  1495. /* Additional defines for WolfSSL, see
  1496. * https://github.com/civetweb/civetweb/issues/583 */
  1497. #include "wolfssl_extras.inl"
  1498. #endif
  1499. #if defined(OPENSSL_IS_BORINGSSL)
  1500. /* From boringssl/src/include/openssl/mem.h:
  1501. *
  1502. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1503. * However, that was written in a time before Valgrind and ASAN. Since we now
  1504. * have those tools, the OpenSSL allocation functions are simply macros around
  1505. * the standard memory functions.
  1506. *
  1507. * #define OPENSSL_free free */
  1508. #define free free
  1509. // disable for boringssl
  1510. #define CONF_modules_unload(a) ((void)0)
  1511. #define ENGINE_cleanup() ((void)0)
  1512. #endif
  1513. /* If OpenSSL headers are included, automatically select the API version */
  1514. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1515. #if !defined(OPENSSL_API_3_0)
  1516. #define OPENSSL_API_3_0
  1517. #endif
  1518. #define OPENSSL_REMOVE_THREAD_STATE()
  1519. #else
  1520. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1521. #if !defined(OPENSSL_API_1_1)
  1522. #define OPENSSL_API_1_1
  1523. #endif
  1524. #define OPENSSL_REMOVE_THREAD_STATE()
  1525. #else
  1526. #if !defined(OPENSSL_API_1_0)
  1527. #define OPENSSL_API_1_0
  1528. #endif
  1529. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1530. #endif
  1531. #endif
  1532. #else
  1533. /* SSL loaded dynamically from DLL / shared object */
  1534. /* Add all prototypes here, to be independent from OpenSSL source
  1535. * installation. */
  1536. #include "openssl_dl.inl"
  1537. #endif /* Various SSL bindings */
  1538. #if !defined(NO_CACHING)
  1539. static const char month_names[][4] = {"Jan",
  1540. "Feb",
  1541. "Mar",
  1542. "Apr",
  1543. "May",
  1544. "Jun",
  1545. "Jul",
  1546. "Aug",
  1547. "Sep",
  1548. "Oct",
  1549. "Nov",
  1550. "Dec"};
  1551. #endif /* !NO_CACHING */
  1552. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1553. * the union u. */
  1554. union usa {
  1555. struct sockaddr sa;
  1556. struct sockaddr_in sin;
  1557. #if defined(USE_IPV6)
  1558. struct sockaddr_in6 sin6;
  1559. #endif
  1560. #if defined(USE_X_DOM_SOCKET)
  1561. struct sockaddr_un sun;
  1562. #endif
  1563. };
  1564. #if defined(USE_X_DOM_SOCKET)
  1565. static unsigned short
  1566. USA_IN_PORT_UNSAFE(union usa *s)
  1567. {
  1568. if (s->sa.sa_family == AF_INET)
  1569. return s->sin.sin_port;
  1570. #if defined(USE_IPV6)
  1571. if (s->sa.sa_family == AF_INET6)
  1572. return s->sin6.sin6_port;
  1573. #endif
  1574. return 0;
  1575. }
  1576. #endif
  1577. #if defined(USE_IPV6)
  1578. #define USA_IN_PORT_UNSAFE(s) \
  1579. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1580. #else
  1581. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1582. #endif
  1583. /* Describes a string (chunk of memory). */
  1584. struct vec {
  1585. const char *ptr;
  1586. size_t len;
  1587. };
  1588. struct mg_file_stat {
  1589. /* File properties filled by mg_stat: */
  1590. uint64_t size;
  1591. time_t last_modified;
  1592. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1593. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1594. * case we need a "Content-Eencoding: gzip" header */
  1595. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1596. };
  1597. struct mg_file_access {
  1598. /* File properties filled by mg_fopen: */
  1599. FILE *fp;
  1600. };
  1601. struct mg_file {
  1602. struct mg_file_stat stat;
  1603. struct mg_file_access access;
  1604. };
  1605. #define STRUCT_FILE_INITIALIZER \
  1606. { \
  1607. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1608. { \
  1609. (FILE *)NULL \
  1610. } \
  1611. }
  1612. /* Describes listening socket, or socket which was accept()-ed by the master
  1613. * thread and queued for future handling by the worker thread. */
  1614. struct socket {
  1615. SOCKET sock; /* Listening socket */
  1616. union usa lsa; /* Local socket address */
  1617. union usa rsa; /* Remote socket address */
  1618. unsigned char is_ssl; /* Is port SSL-ed */
  1619. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1620. * port */
  1621. unsigned char
  1622. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1623. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1624. };
  1625. /* Enum const for all options must be in sync with
  1626. * static struct mg_option config_options[]
  1627. * This is tested in the unit test (test/private.c)
  1628. * "Private Config Options"
  1629. */
  1630. enum {
  1631. /* Once for each server */
  1632. LISTENING_PORTS,
  1633. NUM_THREADS,
  1634. PRESPAWN_THREADS,
  1635. RUN_AS_USER,
  1636. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1637. * socket option typedef TCP_NODELAY. */
  1638. MAX_REQUEST_SIZE,
  1639. LINGER_TIMEOUT,
  1640. CONNECTION_QUEUE_SIZE,
  1641. LISTEN_BACKLOG_SIZE,
  1642. #if defined(__linux__)
  1643. ALLOW_SENDFILE_CALL,
  1644. #endif
  1645. #if defined(_WIN32)
  1646. CASE_SENSITIVE_FILES,
  1647. #endif
  1648. THROTTLE,
  1649. ENABLE_KEEP_ALIVE,
  1650. REQUEST_TIMEOUT,
  1651. KEEP_ALIVE_TIMEOUT,
  1652. #if defined(USE_WEBSOCKET)
  1653. WEBSOCKET_TIMEOUT,
  1654. ENABLE_WEBSOCKET_PING_PONG,
  1655. #endif
  1656. DECODE_URL,
  1657. DECODE_QUERY_STRING,
  1658. #if defined(USE_LUA)
  1659. LUA_BACKGROUND_SCRIPT,
  1660. LUA_BACKGROUND_SCRIPT_PARAMS,
  1661. #endif
  1662. #if defined(USE_HTTP2)
  1663. ENABLE_HTTP2,
  1664. #endif
  1665. /* Once for each domain */
  1666. DOCUMENT_ROOT,
  1667. FALLBACK_DOCUMENT_ROOT,
  1668. ACCESS_LOG_FILE,
  1669. ERROR_LOG_FILE,
  1670. CGI_EXTENSIONS,
  1671. CGI_ENVIRONMENT,
  1672. CGI_INTERPRETER,
  1673. CGI_INTERPRETER_ARGS,
  1674. #if defined(USE_TIMERS)
  1675. CGI_TIMEOUT,
  1676. #endif
  1677. CGI_BUFFERING,
  1678. CGI2_EXTENSIONS,
  1679. CGI2_ENVIRONMENT,
  1680. CGI2_INTERPRETER,
  1681. CGI2_INTERPRETER_ARGS,
  1682. #if defined(USE_TIMERS)
  1683. CGI2_TIMEOUT,
  1684. #endif
  1685. CGI2_BUFFERING,
  1686. #if defined(USE_4_CGI)
  1687. CGI3_EXTENSIONS,
  1688. CGI3_ENVIRONMENT,
  1689. CGI3_INTERPRETER,
  1690. CGI3_INTERPRETER_ARGS,
  1691. #if defined(USE_TIMERS)
  1692. CGI3_TIMEOUT,
  1693. #endif
  1694. CGI3_BUFFERING,
  1695. CGI4_EXTENSIONS,
  1696. CGI4_ENVIRONMENT,
  1697. CGI4_INTERPRETER,
  1698. CGI4_INTERPRETER_ARGS,
  1699. #if defined(USE_TIMERS)
  1700. CGI4_TIMEOUT,
  1701. #endif
  1702. CGI4_BUFFERING,
  1703. #endif
  1704. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1705. PROTECT_URI,
  1706. AUTHENTICATION_DOMAIN,
  1707. ENABLE_AUTH_DOMAIN_CHECK,
  1708. SSI_EXTENSIONS,
  1709. ENABLE_DIRECTORY_LISTING,
  1710. ENABLE_WEBDAV,
  1711. GLOBAL_PASSWORDS_FILE,
  1712. INDEX_FILES,
  1713. ACCESS_CONTROL_LIST,
  1714. EXTRA_MIME_TYPES,
  1715. SSL_CERTIFICATE,
  1716. SSL_CERTIFICATE_CHAIN,
  1717. URL_REWRITE_PATTERN,
  1718. HIDE_FILES,
  1719. SSL_DO_VERIFY_PEER,
  1720. SSL_CACHE_TIMEOUT,
  1721. SSL_CA_PATH,
  1722. SSL_CA_FILE,
  1723. SSL_VERIFY_DEPTH,
  1724. SSL_DEFAULT_VERIFY_PATHS,
  1725. SSL_CIPHER_LIST,
  1726. SSL_PROTOCOL_VERSION,
  1727. SSL_SHORT_TRUST,
  1728. #if defined(USE_LUA)
  1729. LUA_PRELOAD_FILE,
  1730. LUA_SCRIPT_EXTENSIONS,
  1731. LUA_SERVER_PAGE_EXTENSIONS,
  1732. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1733. LUA_DEBUG_PARAMS,
  1734. #endif
  1735. #endif
  1736. #if defined(USE_DUKTAPE)
  1737. DUKTAPE_SCRIPT_EXTENSIONS,
  1738. #endif
  1739. #if defined(USE_WEBSOCKET)
  1740. WEBSOCKET_ROOT,
  1741. FALLBACK_WEBSOCKET_ROOT,
  1742. #endif
  1743. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1744. LUA_WEBSOCKET_EXTENSIONS,
  1745. #endif
  1746. ACCESS_CONTROL_ALLOW_ORIGIN,
  1747. ACCESS_CONTROL_ALLOW_METHODS,
  1748. ACCESS_CONTROL_ALLOW_HEADERS,
  1749. ACCESS_CONTROL_EXPOSE_HEADERS,
  1750. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1751. ERROR_PAGES,
  1752. #if !defined(NO_CACHING)
  1753. STATIC_FILE_MAX_AGE,
  1754. STATIC_FILE_CACHE_CONTROL,
  1755. #endif
  1756. #if !defined(NO_SSL)
  1757. STRICT_HTTPS_MAX_AGE,
  1758. #endif
  1759. ADDITIONAL_HEADER,
  1760. ALLOW_INDEX_SCRIPT_SUB_RES,
  1761. NUM_OPTIONS
  1762. };
  1763. /* Config option name, config types, default value.
  1764. * Must be in the same order as the enum const above.
  1765. */
  1766. static const struct mg_option config_options[] = {
  1767. /* Once for each server */
  1768. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1769. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1770. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1771. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1772. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1773. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1774. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1775. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1776. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1777. #if defined(__linux__)
  1778. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1779. #endif
  1780. #if defined(_WIN32)
  1781. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1782. #endif
  1783. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1784. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1785. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1786. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1787. #if defined(USE_WEBSOCKET)
  1788. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1789. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1790. #endif
  1791. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1792. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1793. #if defined(USE_LUA)
  1794. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1795. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1796. #endif
  1797. #if defined(USE_HTTP2)
  1798. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1799. #endif
  1800. /* Once for each domain */
  1801. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1802. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1803. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1804. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1805. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1806. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1808. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1809. #if defined(USE_TIMERS)
  1810. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1811. #endif
  1812. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1813. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1814. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1815. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1816. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1817. #if defined(USE_TIMERS)
  1818. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1819. #endif
  1820. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1821. #if defined(USE_4_CGI)
  1822. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1823. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1824. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1825. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1826. #if defined(USE_TIMERS)
  1827. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1828. #endif
  1829. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1830. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1831. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1832. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1834. #if defined(USE_TIMERS)
  1835. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1836. #endif
  1837. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1838. #endif
  1839. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1841. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1842. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1843. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1844. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1845. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1846. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1847. {"index_files",
  1848. MG_CONFIG_TYPE_STRING_LIST,
  1849. #if defined(USE_LUA)
  1850. "index.xhtml,index.html,index.htm,"
  1851. "index.lp,index.lsp,index.lua,index.cgi,"
  1852. "index.shtml,index.php"},
  1853. #else
  1854. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1855. #endif
  1856. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1858. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1859. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1860. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1861. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1862. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1863. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1864. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1865. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1866. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1867. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1868. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1869. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1870. * as a minimum in 2020 */
  1871. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1872. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1873. #if defined(USE_LUA)
  1874. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1875. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1876. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1877. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1878. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1879. #endif
  1880. #endif
  1881. #if defined(USE_DUKTAPE)
  1882. /* The support for duktape is still in alpha version state.
  1883. * The name of this config option might change. */
  1884. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1885. #endif
  1886. #if defined(USE_WEBSOCKET)
  1887. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1888. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. #endif
  1890. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1891. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1892. #endif
  1893. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1894. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1895. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1896. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1897. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1898. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1899. #if !defined(NO_CACHING)
  1900. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1901. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1902. #endif
  1903. #if !defined(NO_SSL)
  1904. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1905. #endif
  1906. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1907. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1908. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1909. /* Check if the config_options and the corresponding enum have compatible
  1910. * sizes. */
  1911. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1912. == (NUM_OPTIONS + 1),
  1913. "config_options and enum not sync");
  1914. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1915. struct mg_handler_info {
  1916. /* Name/Pattern of the URI. */
  1917. char *uri;
  1918. size_t uri_len;
  1919. /* handler type */
  1920. int handler_type;
  1921. /* Handler for http/https or requests. */
  1922. mg_request_handler handler;
  1923. unsigned int refcount;
  1924. int removing;
  1925. /* Handler for ws/wss (websocket) requests. */
  1926. mg_websocket_connect_handler connect_handler;
  1927. mg_websocket_ready_handler ready_handler;
  1928. mg_websocket_data_handler data_handler;
  1929. mg_websocket_close_handler close_handler;
  1930. /* accepted subprotocols for ws/wss requests. */
  1931. struct mg_websocket_subprotocols *subprotocols;
  1932. /* Handler for authorization requests */
  1933. mg_authorization_handler auth_handler;
  1934. /* User supplied argument for the handler function. */
  1935. void *cbdata;
  1936. /* next handler in a linked list */
  1937. struct mg_handler_info *next;
  1938. };
  1939. enum {
  1940. CONTEXT_INVALID,
  1941. CONTEXT_SERVER,
  1942. CONTEXT_HTTP_CLIENT,
  1943. CONTEXT_WS_CLIENT
  1944. };
  1945. struct mg_domain_context {
  1946. SSL_CTX *ssl_ctx; /* SSL context */
  1947. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1948. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1949. int64_t ssl_cert_last_mtime;
  1950. /* Server nonce */
  1951. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1952. unsigned long nonce_count; /* Used nonces, used for authentication */
  1953. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1954. /* linked list of shared lua websockets */
  1955. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1956. #endif
  1957. /* Linked list of domains */
  1958. struct mg_domain_context *next;
  1959. };
  1960. /* Stop flag can be "volatile" or require a lock.
  1961. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1962. * states a read operation for int is always atomic. */
  1963. #if defined(STOP_FLAG_NEEDS_LOCK)
  1964. typedef ptrdiff_t volatile stop_flag_t;
  1965. static int
  1966. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1967. {
  1968. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1969. return (sf == 0);
  1970. }
  1971. static int
  1972. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1973. {
  1974. stop_flag_t sf = mg_atomic_add(f, 0);
  1975. return (sf == 2);
  1976. }
  1977. static void
  1978. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1979. {
  1980. stop_flag_t sf = 0;
  1981. do {
  1982. sf = mg_atomic_compare_and_swap(f, *f, v);
  1983. } while (sf != v);
  1984. }
  1985. #else /* STOP_FLAG_NEEDS_LOCK */
  1986. typedef int volatile stop_flag_t;
  1987. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1988. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1989. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1990. #endif /* STOP_FLAG_NEEDS_LOCK */
  1991. #if !defined(NUM_WEBDAV_LOCKS)
  1992. #define NUM_WEBDAV_LOCKS 10
  1993. #endif
  1994. #if !defined(LOCK_DURATION_S)
  1995. #define LOCK_DURATION_S 60
  1996. #endif
  1997. struct twebdav_lock {
  1998. uint64_t locktime;
  1999. char token[33];
  2000. char path[UTF8_PATH_MAX * 2];
  2001. char user[UTF8_PATH_MAX * 2];
  2002. };
  2003. struct mg_context {
  2004. /* Part 1 - Physical context:
  2005. * This holds threads, ports, timeouts, ...
  2006. * set for the entire server, independent from the
  2007. * addressed hostname.
  2008. */
  2009. /* Connection related */
  2010. int context_type; /* See CONTEXT_* above */
  2011. struct socket *listening_sockets;
  2012. struct mg_pollfd *listening_socket_fds;
  2013. unsigned int num_listening_sockets;
  2014. struct mg_connection *worker_connections; /* The connection struct, pre-
  2015. * allocated for each worker */
  2016. #if defined(USE_SERVER_STATS)
  2017. volatile ptrdiff_t active_connections;
  2018. volatile ptrdiff_t max_active_connections;
  2019. volatile ptrdiff_t total_connections;
  2020. volatile ptrdiff_t total_requests;
  2021. volatile int64_t total_data_read;
  2022. volatile int64_t total_data_written;
  2023. #endif
  2024. /* Thread related */
  2025. stop_flag_t stop_flag; /* Should we stop event loop */
  2026. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2027. pthread_t masterthreadid; /* The master thread ID */
  2028. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2029. allowed to create, total */
  2030. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2031. exist (modified by master thread) */
  2032. unsigned int
  2033. idle_worker_thread_count; /* How many worker-threads are currently
  2034. sitting around with nothing to do */
  2035. /* Access to this value MUST be synchronized by thread_mutex */
  2036. pthread_t *worker_threadids; /* The worker thread IDs */
  2037. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2038. /* Connection to thread dispatching */
  2039. #if defined(ALTERNATIVE_QUEUE)
  2040. struct socket *client_socks;
  2041. void **client_wait_events;
  2042. #else
  2043. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2044. worker thread */
  2045. volatile int sq_head; /* Head of the socket queue */
  2046. volatile int sq_tail; /* Tail of the socket queue */
  2047. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2048. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2049. volatile int sq_blocked; /* Status information: sq is full */
  2050. int sq_size; /* No of elements in socket queue */
  2051. #if defined(USE_SERVER_STATS)
  2052. int sq_max_fill;
  2053. #endif /* USE_SERVER_STATS */
  2054. #endif /* ALTERNATIVE_QUEUE */
  2055. /* Memory related */
  2056. unsigned int max_request_size; /* The max request size */
  2057. #if defined(USE_SERVER_STATS)
  2058. struct mg_memory_stat ctx_memory;
  2059. #endif
  2060. /* WebDAV lock structures */
  2061. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2062. /* Operating system related */
  2063. char *systemName; /* What operating system is running */
  2064. time_t start_time; /* Server start time, used for authentication
  2065. * and for diagnstics. */
  2066. #if defined(USE_TIMERS)
  2067. struct ttimers *timers;
  2068. #endif
  2069. /* Lua specific: Background operations and shared websockets */
  2070. #if defined(USE_LUA)
  2071. void *lua_background_state; /* lua_State (here as void *) */
  2072. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2073. int lua_bg_log_available; /* Use Lua background state for access log */
  2074. #endif
  2075. int user_shutdown_notification_socket; /* mg_stop() will close this
  2076. socket... */
  2077. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2078. to return immediately */
  2079. /* Server nonce */
  2080. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2081. * ssl_cert_last_mtime, nonce_count, and
  2082. * next (linked list) */
  2083. /* Server callbacks */
  2084. struct mg_callbacks callbacks; /* User-defined callback function */
  2085. void *user_data; /* User-defined data */
  2086. /* Part 2 - Logical domain:
  2087. * This holds hostname, TLS certificate, document root, ...
  2088. * set for a domain hosted at the server.
  2089. * There may be multiple domains hosted at one physical server.
  2090. * The default domain "dd" is the first element of a list of
  2091. * domains.
  2092. */
  2093. struct mg_domain_context dd; /* default domain */
  2094. };
  2095. #if defined(USE_SERVER_STATS)
  2096. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2097. static struct mg_memory_stat *
  2098. get_memory_stat(struct mg_context *ctx)
  2099. {
  2100. if (ctx) {
  2101. return &(ctx->ctx_memory);
  2102. }
  2103. return &mg_common_memory;
  2104. }
  2105. #endif
  2106. enum {
  2107. CONNECTION_TYPE_INVALID = 0,
  2108. CONNECTION_TYPE_REQUEST = 1,
  2109. CONNECTION_TYPE_RESPONSE = 2
  2110. };
  2111. enum {
  2112. PROTOCOL_TYPE_HTTP1 = 0,
  2113. PROTOCOL_TYPE_WEBSOCKET = 1,
  2114. PROTOCOL_TYPE_HTTP2 = 2
  2115. };
  2116. #if defined(USE_HTTP2)
  2117. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2118. #define HTTP2_DYN_TABLE_SIZE (256)
  2119. #endif
  2120. struct mg_http2_connection {
  2121. uint32_t stream_id;
  2122. uint32_t dyn_table_size;
  2123. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2124. };
  2125. #endif
  2126. struct mg_connection {
  2127. int connection_type; /* see CONNECTION_TYPE_* above */
  2128. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2129. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2130. fully sent */
  2131. #if defined(USE_HTTP2)
  2132. struct mg_http2_connection http2;
  2133. #endif
  2134. struct mg_request_info request_info;
  2135. struct mg_response_info response_info;
  2136. struct mg_context *phys_ctx;
  2137. struct mg_domain_context *dom_ctx;
  2138. #if defined(USE_SERVER_STATS)
  2139. int conn_state; /* 0 = undef, numerical value may change in different
  2140. * versions. For the current definition, see
  2141. * mg_get_connection_info_impl */
  2142. #endif
  2143. SSL *ssl; /* SSL descriptor */
  2144. struct socket client; /* Connected client */
  2145. time_t conn_birth_time; /* Time (wall clock) when connection was
  2146. * established */
  2147. #if defined(USE_SERVER_STATS)
  2148. time_t conn_close_time; /* Time (wall clock) when connection was
  2149. * closed (or 0 if still open) */
  2150. double processing_time; /* Processing time for one request. */
  2151. #endif
  2152. struct timespec req_time; /* Time (since system start) when the request
  2153. * was received */
  2154. int64_t num_bytes_sent; /* Total bytes sent to client */
  2155. int64_t content_len; /* How many bytes of content can be read
  2156. * !is_chunked: Content-Length header value
  2157. * or -1 (until connection closed,
  2158. * not allowed for a request)
  2159. * is_chunked: >= 0, appended gradually
  2160. */
  2161. int64_t consumed_content; /* How many bytes of content have been read */
  2162. int is_chunked; /* Transfer-Encoding is chunked:
  2163. * 0 = not chunked,
  2164. * 1 = chunked, not yet, or some data read,
  2165. * 2 = chunked, has error,
  2166. * 3 = chunked, all data read except trailer,
  2167. * 4 = chunked, all data read
  2168. */
  2169. char *buf; /* Buffer for received data */
  2170. char *path_info; /* PATH_INFO part of the URL */
  2171. int must_close; /* 1 if connection must be closed */
  2172. int accept_gzip; /* 1 if gzip encoding is accepted */
  2173. int in_error_handler; /* 1 if in handler for user defined error
  2174. * pages */
  2175. #if defined(USE_WEBSOCKET)
  2176. int in_websocket_handling; /* 1 if in read_websocket */
  2177. #endif
  2178. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2179. && defined(MG_EXPERIMENTAL_INTERFACES)
  2180. /* Parameters for websocket data compression according to rfc7692 */
  2181. int websocket_deflate_server_max_windows_bits;
  2182. int websocket_deflate_client_max_windows_bits;
  2183. int websocket_deflate_server_no_context_takeover;
  2184. int websocket_deflate_client_no_context_takeover;
  2185. int websocket_deflate_initialized;
  2186. int websocket_deflate_flush;
  2187. z_stream websocket_deflate_state;
  2188. z_stream websocket_inflate_state;
  2189. #endif
  2190. int handled_requests; /* Number of requests handled by this connection
  2191. */
  2192. int buf_size; /* Buffer size */
  2193. int request_len; /* Size of the request + headers in a buffer */
  2194. int data_len; /* Total size of data in a buffer */
  2195. int status_code; /* HTTP reply status code, e.g. 200 */
  2196. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2197. * throttle */
  2198. time_t last_throttle_time; /* Last time throttled data was sent */
  2199. int last_throttle_bytes; /* Bytes sent this second */
  2200. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2201. * atomic transmissions for websockets */
  2202. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2203. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2204. #endif
  2205. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2206. * for quick access */
  2207. };
  2208. /* Directory entry */
  2209. struct de {
  2210. char *file_name;
  2211. struct mg_file_stat file;
  2212. };
  2213. #define mg_cry_internal(conn, fmt, ...) \
  2214. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2215. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2216. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2217. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2218. struct mg_context *ctx,
  2219. const char *func,
  2220. unsigned line,
  2221. const char *fmt,
  2222. ...) PRINTF_ARGS(5, 6);
  2223. #if !defined(NO_THREAD_NAME)
  2224. #if defined(_WIN32) && defined(_MSC_VER)
  2225. /* Set the thread name for debugging purposes in Visual Studio
  2226. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2227. */
  2228. #pragma pack(push, 8)
  2229. typedef struct tagTHREADNAME_INFO {
  2230. DWORD dwType; /* Must be 0x1000. */
  2231. LPCSTR szName; /* Pointer to name (in user addr space). */
  2232. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2233. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2234. } THREADNAME_INFO;
  2235. #pragma pack(pop)
  2236. #elif defined(__linux__)
  2237. #include <sys/prctl.h>
  2238. #include <sys/sendfile.h>
  2239. #if defined(ALTERNATIVE_QUEUE)
  2240. #include <sys/eventfd.h>
  2241. #endif /* ALTERNATIVE_QUEUE */
  2242. #if defined(ALTERNATIVE_QUEUE)
  2243. static void *
  2244. event_create(void)
  2245. {
  2246. int evhdl = eventfd(0, EFD_CLOEXEC);
  2247. int *ret;
  2248. if (evhdl == -1) {
  2249. /* Linux uses -1 on error, Windows NULL. */
  2250. /* However, Linux does not return 0 on success either. */
  2251. return 0;
  2252. }
  2253. ret = (int *)mg_malloc(sizeof(int));
  2254. if (ret) {
  2255. *ret = evhdl;
  2256. } else {
  2257. (void)close(evhdl);
  2258. }
  2259. return (void *)ret;
  2260. }
  2261. static int
  2262. event_wait(void *eventhdl)
  2263. {
  2264. uint64_t u;
  2265. int evhdl, s;
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return 0;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. s = (int)read(evhdl, &u, sizeof(u));
  2272. if (s != sizeof(u)) {
  2273. /* error */
  2274. return 0;
  2275. }
  2276. (void)u; /* the value is not required */
  2277. return 1;
  2278. }
  2279. static int
  2280. event_signal(void *eventhdl)
  2281. {
  2282. uint64_t u = 1;
  2283. int evhdl, s;
  2284. if (!eventhdl) {
  2285. /* error */
  2286. return 0;
  2287. }
  2288. evhdl = *(int *)eventhdl;
  2289. s = (int)write(evhdl, &u, sizeof(u));
  2290. if (s != sizeof(u)) {
  2291. /* error */
  2292. return 0;
  2293. }
  2294. return 1;
  2295. }
  2296. static void
  2297. event_destroy(void *eventhdl)
  2298. {
  2299. int evhdl;
  2300. if (!eventhdl) {
  2301. /* error */
  2302. return;
  2303. }
  2304. evhdl = *(int *)eventhdl;
  2305. close(evhdl);
  2306. mg_free(eventhdl);
  2307. }
  2308. #endif
  2309. #endif
  2310. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2311. struct posix_event {
  2312. pthread_mutex_t mutex;
  2313. pthread_cond_t cond;
  2314. int signaled;
  2315. };
  2316. static void *
  2317. event_create(void)
  2318. {
  2319. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2320. if (ret == 0) {
  2321. /* out of memory */
  2322. return 0;
  2323. }
  2324. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2325. /* pthread mutex not available */
  2326. mg_free(ret);
  2327. return 0;
  2328. }
  2329. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2330. /* pthread cond not available */
  2331. pthread_mutex_destroy(&(ret->mutex));
  2332. mg_free(ret);
  2333. return 0;
  2334. }
  2335. ret->signaled = 0;
  2336. return (void *)ret;
  2337. }
  2338. static int
  2339. event_wait(void *eventhdl)
  2340. {
  2341. struct posix_event *ev = (struct posix_event *)eventhdl;
  2342. pthread_mutex_lock(&(ev->mutex));
  2343. while (!ev->signaled) {
  2344. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2345. }
  2346. ev->signaled = 0;
  2347. pthread_mutex_unlock(&(ev->mutex));
  2348. return 1;
  2349. }
  2350. static int
  2351. event_signal(void *eventhdl)
  2352. {
  2353. struct posix_event *ev = (struct posix_event *)eventhdl;
  2354. pthread_mutex_lock(&(ev->mutex));
  2355. pthread_cond_signal(&(ev->cond));
  2356. ev->signaled = 1;
  2357. pthread_mutex_unlock(&(ev->mutex));
  2358. return 1;
  2359. }
  2360. static void
  2361. event_destroy(void *eventhdl)
  2362. {
  2363. struct posix_event *ev = (struct posix_event *)eventhdl;
  2364. pthread_cond_destroy(&(ev->cond));
  2365. pthread_mutex_destroy(&(ev->mutex));
  2366. mg_free(ev);
  2367. }
  2368. #endif
  2369. static void
  2370. mg_set_thread_name(const char *name)
  2371. {
  2372. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2373. mg_snprintf(
  2374. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2375. #if defined(_WIN32)
  2376. #if defined(_MSC_VER)
  2377. /* Windows and Visual Studio Compiler */
  2378. __try {
  2379. THREADNAME_INFO info;
  2380. info.dwType = 0x1000;
  2381. info.szName = threadName;
  2382. info.dwThreadID = ~0U;
  2383. info.dwFlags = 0;
  2384. RaiseException(0x406D1388,
  2385. 0,
  2386. sizeof(info) / sizeof(ULONG_PTR),
  2387. (ULONG_PTR *)&info);
  2388. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2389. }
  2390. #elif defined(__MINGW32__)
  2391. /* No option known to set thread name for MinGW known */
  2392. #endif
  2393. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2394. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2395. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2396. #if defined(__MACH__) && defined(__APPLE__)
  2397. /* OS X only current thread name can be changed */
  2398. (void)pthread_setname_np(threadName);
  2399. #else
  2400. (void)pthread_setname_np(pthread_self(), threadName);
  2401. #endif
  2402. #elif defined(__linux__)
  2403. /* On Linux we can use the prctl function.
  2404. * When building for Linux Standard Base (LSB) use
  2405. * NO_THREAD_NAME. However, thread names are a big
  2406. * help for debugging, so the stadard is to set them.
  2407. */
  2408. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2409. #endif
  2410. }
  2411. #else /* !defined(NO_THREAD_NAME) */
  2412. static void
  2413. mg_set_thread_name(const char *threadName)
  2414. {
  2415. }
  2416. #endif
  2417. CIVETWEB_API const struct mg_option *
  2418. mg_get_valid_options(void)
  2419. {
  2420. return config_options;
  2421. }
  2422. /* Do not open file (unused) */
  2423. #define MG_FOPEN_MODE_NONE (0)
  2424. /* Open file for read only access */
  2425. #define MG_FOPEN_MODE_READ (1)
  2426. /* Open file for writing, create and overwrite */
  2427. #define MG_FOPEN_MODE_WRITE (2)
  2428. /* Open file for writing, create and append */
  2429. #define MG_FOPEN_MODE_APPEND (4)
  2430. static int
  2431. is_file_opened(const struct mg_file_access *fileacc)
  2432. {
  2433. if (!fileacc) {
  2434. return 0;
  2435. }
  2436. return (fileacc->fp != NULL);
  2437. }
  2438. #if !defined(NO_FILESYSTEMS)
  2439. static int mg_stat(const struct mg_connection *conn,
  2440. const char *path,
  2441. struct mg_file_stat *filep);
  2442. /* Reject files with special characters (for Windows) */
  2443. static int
  2444. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2445. {
  2446. const uint8_t *c = (const uint8_t *)path;
  2447. (void)conn; /* not used */
  2448. if ((c == NULL) || (c[0] == 0)) {
  2449. /* Null pointer or empty path --> suspicious */
  2450. return 1;
  2451. }
  2452. #if defined(_WIN32)
  2453. while (*c) {
  2454. if (*c < 32) {
  2455. /* Control character */
  2456. return 1;
  2457. }
  2458. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2459. /* stdin/stdout redirection character */
  2460. return 1;
  2461. }
  2462. if ((*c == '*') || (*c == '?')) {
  2463. /* Wildcard character */
  2464. return 1;
  2465. }
  2466. if (*c == '"') {
  2467. /* Windows quotation */
  2468. return 1;
  2469. }
  2470. c++;
  2471. }
  2472. #endif
  2473. /* Nothing suspicious found */
  2474. return 0;
  2475. }
  2476. /* mg_fopen will open a file either in memory or on the disk.
  2477. * The input parameter path is a string in UTF-8 encoding.
  2478. * The input parameter mode is MG_FOPEN_MODE_*
  2479. * On success, fp will be set in the output struct mg_file.
  2480. * All status members will also be set.
  2481. * The function returns 1 on success, 0 on error. */
  2482. static int
  2483. mg_fopen(const struct mg_connection *conn,
  2484. const char *path,
  2485. int mode,
  2486. struct mg_file *filep)
  2487. {
  2488. int found;
  2489. if (!filep) {
  2490. return 0;
  2491. }
  2492. filep->access.fp = NULL;
  2493. if (mg_path_suspicious(conn, path)) {
  2494. return 0;
  2495. }
  2496. /* filep is initialized in mg_stat: all fields with memset to,
  2497. * some fields like size and modification date with values */
  2498. found = mg_stat(conn, path, &(filep->stat));
  2499. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2500. /* file does not exist and will not be created */
  2501. return 0;
  2502. }
  2503. #if defined(_WIN32)
  2504. {
  2505. wchar_t wbuf[UTF16_PATH_MAX];
  2506. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2507. switch (mode) {
  2508. case MG_FOPEN_MODE_READ:
  2509. filep->access.fp = _wfopen(wbuf, L"rb");
  2510. break;
  2511. case MG_FOPEN_MODE_WRITE:
  2512. filep->access.fp = _wfopen(wbuf, L"wb");
  2513. break;
  2514. case MG_FOPEN_MODE_APPEND:
  2515. filep->access.fp = _wfopen(wbuf, L"ab");
  2516. break;
  2517. }
  2518. }
  2519. #else
  2520. /* Linux et al already use unicode. No need to convert. */
  2521. switch (mode) {
  2522. case MG_FOPEN_MODE_READ:
  2523. filep->access.fp = fopen(path, "r");
  2524. break;
  2525. case MG_FOPEN_MODE_WRITE:
  2526. filep->access.fp = fopen(path, "w");
  2527. break;
  2528. case MG_FOPEN_MODE_APPEND:
  2529. filep->access.fp = fopen(path, "a");
  2530. break;
  2531. }
  2532. #endif
  2533. if (!found) {
  2534. /* File did not exist before fopen was called.
  2535. * Maybe it has been created now. Get stat info
  2536. * like creation time now. */
  2537. found = mg_stat(conn, path, &(filep->stat));
  2538. (void)found;
  2539. }
  2540. /* return OK if file is opened */
  2541. return (filep->access.fp != NULL);
  2542. }
  2543. /* return 0 on success, just like fclose */
  2544. static int
  2545. mg_fclose(struct mg_file_access *fileacc)
  2546. {
  2547. int ret = -1;
  2548. if (fileacc != NULL) {
  2549. if (fileacc->fp != NULL) {
  2550. ret = fclose(fileacc->fp);
  2551. }
  2552. /* reset all members of fileacc */
  2553. memset(fileacc, 0, sizeof(*fileacc));
  2554. }
  2555. return ret;
  2556. }
  2557. #endif /* NO_FILESYSTEMS */
  2558. static void
  2559. mg_strlcpy(char *dst, const char *src, size_t n)
  2560. {
  2561. for (; *src != '\0' && n > 1; n--) {
  2562. *dst++ = *src++;
  2563. }
  2564. *dst = '\0';
  2565. }
  2566. static int
  2567. lowercase(const char *s)
  2568. {
  2569. return tolower((unsigned char)*s);
  2570. }
  2571. CIVETWEB_API int
  2572. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2573. {
  2574. int diff = 0;
  2575. if (len > 0) {
  2576. do {
  2577. diff = lowercase(s1++) - lowercase(s2++);
  2578. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2579. }
  2580. return diff;
  2581. }
  2582. CIVETWEB_API int
  2583. mg_strcasecmp(const char *s1, const char *s2)
  2584. {
  2585. int diff;
  2586. do {
  2587. diff = lowercase(s1++) - lowercase(s2++);
  2588. } while (diff == 0 && s1[-1] != '\0');
  2589. return diff;
  2590. }
  2591. static char *
  2592. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2593. {
  2594. char *p;
  2595. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2596. * defined */
  2597. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2598. mg_strlcpy(p, ptr, len + 1);
  2599. }
  2600. return p;
  2601. }
  2602. static char *
  2603. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2604. {
  2605. return mg_strndup_ctx(str, strlen(str), ctx);
  2606. }
  2607. static char *
  2608. mg_strdup(const char *str)
  2609. {
  2610. return mg_strndup_ctx(str, strlen(str), NULL);
  2611. }
  2612. static const char *
  2613. mg_strcasestr(const char *big_str, const char *small_str)
  2614. {
  2615. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2616. if (big_len >= small_len) {
  2617. for (i = 0; i <= (big_len - small_len); i++) {
  2618. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2619. return big_str + i;
  2620. }
  2621. }
  2622. }
  2623. return NULL;
  2624. }
  2625. /* Return null terminated string of given maximum length.
  2626. * Report errors if length is exceeded. */
  2627. static void
  2628. mg_vsnprintf(const struct mg_connection *conn,
  2629. int *truncated,
  2630. char *buf,
  2631. size_t buflen,
  2632. const char *fmt,
  2633. va_list ap)
  2634. {
  2635. int n, ok;
  2636. if (buflen == 0) {
  2637. if (truncated) {
  2638. *truncated = 1;
  2639. }
  2640. return;
  2641. }
  2642. #if defined(__clang__)
  2643. #pragma clang diagnostic push
  2644. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2645. /* Using fmt as a non-literal is intended here, since it is mostly called
  2646. * indirectly by mg_snprintf */
  2647. #endif
  2648. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2649. ok = (n >= 0) && ((size_t)n < buflen);
  2650. #if defined(__clang__)
  2651. #pragma clang diagnostic pop
  2652. #endif
  2653. if (ok) {
  2654. if (truncated) {
  2655. *truncated = 0;
  2656. }
  2657. } else {
  2658. if (truncated) {
  2659. *truncated = 1;
  2660. }
  2661. mg_cry_internal(conn,
  2662. "truncating vsnprintf buffer: [%.*s]",
  2663. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2664. buf);
  2665. n = (int)buflen - 1;
  2666. }
  2667. buf[n] = '\0';
  2668. }
  2669. static void
  2670. mg_snprintf(const struct mg_connection *conn,
  2671. int *truncated,
  2672. char *buf,
  2673. size_t buflen,
  2674. const char *fmt,
  2675. ...)
  2676. {
  2677. va_list ap;
  2678. va_start(ap, fmt);
  2679. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2680. va_end(ap);
  2681. }
  2682. static int
  2683. get_option_index(const char *name)
  2684. {
  2685. int i;
  2686. for (i = 0; config_options[i].name != NULL; i++) {
  2687. if (strcmp(config_options[i].name, name) == 0) {
  2688. return i;
  2689. }
  2690. }
  2691. return -1;
  2692. }
  2693. CIVETWEB_API const char *
  2694. mg_get_option(const struct mg_context *ctx, const char *name)
  2695. {
  2696. int i;
  2697. if ((i = get_option_index(name)) == -1) {
  2698. return NULL;
  2699. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2700. return "";
  2701. } else {
  2702. return ctx->dd.config[i];
  2703. }
  2704. }
  2705. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2706. CIVETWEB_API struct mg_context *
  2707. mg_get_context(const struct mg_connection *conn)
  2708. {
  2709. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2710. }
  2711. CIVETWEB_API void *
  2712. mg_get_user_data(const struct mg_context *ctx)
  2713. {
  2714. return (ctx == NULL) ? NULL : ctx->user_data;
  2715. }
  2716. CIVETWEB_API void *
  2717. mg_get_user_context_data(const struct mg_connection *conn)
  2718. {
  2719. return mg_get_user_data(mg_get_context(conn));
  2720. }
  2721. CIVETWEB_API void *
  2722. mg_get_thread_pointer(const struct mg_connection *conn)
  2723. {
  2724. /* both methods should return the same pointer */
  2725. if (conn) {
  2726. /* quick access, in case conn is known */
  2727. return conn->tls_user_ptr;
  2728. } else {
  2729. /* otherwise get pointer from thread local storage (TLS) */
  2730. struct mg_workerTLS *tls =
  2731. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2732. return tls->user_ptr;
  2733. }
  2734. }
  2735. CIVETWEB_API void
  2736. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2737. {
  2738. if (const_conn != NULL) {
  2739. /* Const cast, since "const struct mg_connection *" does not mean
  2740. * the connection object is not modified. Here "const" is used,
  2741. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2742. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2743. conn->request_info.conn_data = data;
  2744. }
  2745. }
  2746. CIVETWEB_API void *
  2747. mg_get_user_connection_data(const struct mg_connection *conn)
  2748. {
  2749. if (conn != NULL) {
  2750. return conn->request_info.conn_data;
  2751. }
  2752. return NULL;
  2753. }
  2754. CIVETWEB_API int
  2755. mg_get_server_ports(const struct mg_context *ctx,
  2756. int size,
  2757. struct mg_server_port *ports)
  2758. {
  2759. int i, cnt = 0;
  2760. if (size <= 0) {
  2761. return -1;
  2762. }
  2763. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2764. if (!ctx) {
  2765. return -1;
  2766. }
  2767. if (!ctx->listening_sockets) {
  2768. return -1;
  2769. }
  2770. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2771. ports[cnt].port =
  2772. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2773. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2774. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2775. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2776. /* IPv4 */
  2777. ports[cnt].protocol = 1;
  2778. cnt++;
  2779. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2780. /* IPv6 */
  2781. ports[cnt].protocol = 3;
  2782. cnt++;
  2783. }
  2784. }
  2785. return cnt;
  2786. }
  2787. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2788. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2789. #endif
  2790. static void
  2791. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2792. {
  2793. buf[0] = '\0';
  2794. if (!usa) {
  2795. return;
  2796. }
  2797. if (usa->sa.sa_family == AF_INET) {
  2798. getnameinfo(&usa->sa,
  2799. sizeof(usa->sin),
  2800. buf,
  2801. (unsigned)len,
  2802. NULL,
  2803. 0,
  2804. NI_NUMERICHOST);
  2805. }
  2806. #if defined(USE_IPV6)
  2807. else if (usa->sa.sa_family == AF_INET6) {
  2808. getnameinfo(&usa->sa,
  2809. sizeof(usa->sin6),
  2810. buf,
  2811. (unsigned)len,
  2812. NULL,
  2813. 0,
  2814. NI_NUMERICHOST);
  2815. }
  2816. #endif
  2817. #if defined(USE_X_DOM_SOCKET)
  2818. else if (usa->sa.sa_family == AF_UNIX) {
  2819. /* TODO: Define a remote address for unix domain sockets.
  2820. * This code will always return "localhost", identical to http+tcp:
  2821. getnameinfo(&usa->sa,
  2822. sizeof(usa->sun),
  2823. buf,
  2824. (unsigned)len,
  2825. NULL,
  2826. 0,
  2827. NI_NUMERICHOST);
  2828. */
  2829. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2830. }
  2831. #endif
  2832. }
  2833. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2834. * included in all responses other than 100, 101, 5xx. */
  2835. static void
  2836. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2837. {
  2838. #if !defined(REENTRANT_TIME)
  2839. struct tm *tm;
  2840. tm = ((t != NULL) ? gmtime(t) : NULL);
  2841. if (tm != NULL) {
  2842. #else
  2843. struct tm _tm;
  2844. struct tm *tm = &_tm;
  2845. if (t != NULL) {
  2846. gmtime_r(t, tm);
  2847. #endif
  2848. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2849. } else {
  2850. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2851. }
  2852. }
  2853. /* difftime for struct timespec. Return value is in seconds. */
  2854. static double
  2855. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2856. {
  2857. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2858. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2859. }
  2860. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2861. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2862. const char *func,
  2863. unsigned line,
  2864. const char *fmt,
  2865. va_list ap);
  2866. #include "external_mg_cry_internal_impl.inl"
  2867. #elif !defined(NO_FILESYSTEMS)
  2868. /* Print error message to the opened error log stream. */
  2869. static void
  2870. mg_cry_internal_impl(const struct mg_connection *conn,
  2871. const char *func,
  2872. unsigned line,
  2873. const char *fmt,
  2874. va_list ap)
  2875. {
  2876. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2877. struct mg_file fi;
  2878. time_t timestamp;
  2879. /* Unused, in the RELEASE build */
  2880. (void)func;
  2881. (void)line;
  2882. #if defined(GCC_DIAGNOSTIC)
  2883. #pragma GCC diagnostic push
  2884. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2885. #endif
  2886. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2887. #if defined(GCC_DIAGNOSTIC)
  2888. #pragma GCC diagnostic pop
  2889. #endif
  2890. buf[sizeof(buf) - 1] = 0;
  2891. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2892. if (!conn) {
  2893. puts(buf);
  2894. return;
  2895. }
  2896. /* Do not lock when getting the callback value, here and below.
  2897. * I suppose this is fine, since function cannot disappear in the
  2898. * same way string option can. */
  2899. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2900. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2901. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2902. if (mg_fopen(conn,
  2903. conn->dom_ctx->config[ERROR_LOG_FILE],
  2904. MG_FOPEN_MODE_APPEND,
  2905. &fi)
  2906. == 0) {
  2907. fi.access.fp = NULL;
  2908. }
  2909. } else {
  2910. fi.access.fp = NULL;
  2911. }
  2912. if (fi.access.fp != NULL) {
  2913. flockfile(fi.access.fp);
  2914. timestamp = time(NULL);
  2915. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2916. fprintf(fi.access.fp,
  2917. "[%010lu] [error] [client %s] ",
  2918. (unsigned long)timestamp,
  2919. src_addr);
  2920. if (conn->request_info.request_method != NULL) {
  2921. fprintf(fi.access.fp,
  2922. "%s %s: ",
  2923. conn->request_info.request_method,
  2924. conn->request_info.request_uri
  2925. ? conn->request_info.request_uri
  2926. : "");
  2927. }
  2928. fprintf(fi.access.fp, "%s", buf);
  2929. fputc('\n', fi.access.fp);
  2930. fflush(fi.access.fp);
  2931. funlockfile(fi.access.fp);
  2932. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2933. * mg_cry here anyway ;-) */
  2934. }
  2935. }
  2936. }
  2937. #else
  2938. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2939. #endif /* Externally provided function */
  2940. /* Construct fake connection structure. Used for logging, if connection
  2941. * is not applicable at the moment of logging. */
  2942. static struct mg_connection *
  2943. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2944. {
  2945. static const struct mg_connection conn_zero = {0};
  2946. *fc = conn_zero;
  2947. fc->phys_ctx = ctx;
  2948. fc->dom_ctx = &(ctx->dd);
  2949. return fc;
  2950. }
  2951. static void
  2952. mg_cry_internal_wrap(const struct mg_connection *conn,
  2953. struct mg_context *ctx,
  2954. const char *func,
  2955. unsigned line,
  2956. const char *fmt,
  2957. ...)
  2958. {
  2959. va_list ap;
  2960. va_start(ap, fmt);
  2961. if (!conn && ctx) {
  2962. struct mg_connection fc;
  2963. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2964. } else {
  2965. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2966. }
  2967. va_end(ap);
  2968. }
  2969. CIVETWEB_API void
  2970. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2971. {
  2972. va_list ap;
  2973. va_start(ap, fmt);
  2974. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2975. va_end(ap);
  2976. }
  2977. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2978. CIVETWEB_API const char *
  2979. mg_version(void)
  2980. {
  2981. return CIVETWEB_VERSION;
  2982. }
  2983. CIVETWEB_API const struct mg_request_info *
  2984. mg_get_request_info(const struct mg_connection *conn)
  2985. {
  2986. if (!conn) {
  2987. return NULL;
  2988. }
  2989. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2990. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2991. char txt[16];
  2992. struct mg_workerTLS *tls =
  2993. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2994. sprintf(txt, "%03i", conn->response_info.status_code);
  2995. if (strlen(txt) == 3) {
  2996. memcpy(tls->txtbuf, txt, 4);
  2997. } else {
  2998. strcpy(tls->txtbuf, "ERR");
  2999. }
  3000. ((struct mg_connection *)conn)->request_info.local_uri =
  3001. tls->txtbuf; /* use thread safe buffer */
  3002. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3003. tls->txtbuf; /* use the same thread safe buffer */
  3004. ((struct mg_connection *)conn)->request_info.request_uri =
  3005. tls->txtbuf; /* use the same thread safe buffer */
  3006. ((struct mg_connection *)conn)->request_info.num_headers =
  3007. conn->response_info.num_headers;
  3008. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3009. conn->response_info.http_headers,
  3010. sizeof(conn->response_info.http_headers));
  3011. } else
  3012. #endif
  3013. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3014. return NULL;
  3015. }
  3016. return &conn->request_info;
  3017. }
  3018. CIVETWEB_API const struct mg_response_info *
  3019. mg_get_response_info(const struct mg_connection *conn)
  3020. {
  3021. if (!conn) {
  3022. return NULL;
  3023. }
  3024. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3025. return NULL;
  3026. }
  3027. return &conn->response_info;
  3028. }
  3029. static const char *
  3030. get_proto_name(const struct mg_connection *conn)
  3031. {
  3032. #if defined(__clang__)
  3033. #pragma clang diagnostic push
  3034. #pragma clang diagnostic ignored "-Wunreachable-code"
  3035. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3036. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3037. * unreachable, but splitting into four different #ifdef clauses here is
  3038. * more complicated.
  3039. */
  3040. #endif
  3041. const struct mg_request_info *ri = &conn->request_info;
  3042. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3043. ? (ri->is_ssl ? "wss" : "ws")
  3044. : (ri->is_ssl ? "https" : "http"));
  3045. return proto;
  3046. #if defined(__clang__)
  3047. #pragma clang diagnostic pop
  3048. #endif
  3049. }
  3050. static int
  3051. mg_construct_local_link(const struct mg_connection *conn,
  3052. char *buf,
  3053. size_t buflen,
  3054. const char *define_proto,
  3055. int define_port,
  3056. const char *define_uri)
  3057. {
  3058. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3059. return -1;
  3060. } else {
  3061. int i, j;
  3062. int truncated = 0;
  3063. const struct mg_request_info *ri = &conn->request_info;
  3064. const char *proto =
  3065. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3066. const char *uri =
  3067. (define_uri != NULL)
  3068. ? define_uri
  3069. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3070. int port = (define_port > 0) ? define_port : ri->server_port;
  3071. int default_port = 80;
  3072. char *uri_encoded;
  3073. size_t uri_encoded_len;
  3074. if (uri == NULL) {
  3075. return -1;
  3076. }
  3077. uri_encoded_len = strlen(uri) * 3 + 1;
  3078. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3079. if (uri_encoded == NULL) {
  3080. return -1;
  3081. }
  3082. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3083. /* Directory separator should be preserved. */
  3084. for (i = j = 0; uri_encoded[i]; j++) {
  3085. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3086. uri_encoded[j] = '/';
  3087. i += 3;
  3088. } else {
  3089. uri_encoded[j] = uri_encoded[i++];
  3090. }
  3091. }
  3092. uri_encoded[j] = '\0';
  3093. #if defined(USE_X_DOM_SOCKET)
  3094. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3095. /* TODO: Define and document a link for UNIX domain sockets. */
  3096. /* There seems to be no official standard for this.
  3097. * Common uses seem to be "httpunix://", "http.unix://" or
  3098. * "http+unix://" as a protocol definition string, followed by
  3099. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3100. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3101. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3102. * "" (completely skipping the server name part). In any case, the
  3103. * last part is the server local path. */
  3104. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3105. mg_snprintf(conn,
  3106. &truncated,
  3107. buf,
  3108. buflen,
  3109. "%s.unix://%s%s",
  3110. proto,
  3111. server_name,
  3112. ri->local_uri);
  3113. default_port = 0;
  3114. mg_free(uri_encoded);
  3115. return 0;
  3116. }
  3117. #endif
  3118. if (define_proto) {
  3119. /* If we got a protocol name, use the default port accordingly. */
  3120. if ((0 == strcmp(define_proto, "https"))
  3121. || (0 == strcmp(define_proto, "wss"))) {
  3122. default_port = 443;
  3123. }
  3124. } else if (ri->is_ssl) {
  3125. /* If we did not get a protocol name, use TLS as default if it is
  3126. * already used. */
  3127. default_port = 443;
  3128. }
  3129. {
  3130. #if defined(USE_IPV6)
  3131. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3132. #endif
  3133. int auth_domain_check_enabled =
  3134. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3135. && (!mg_strcasecmp(
  3136. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3137. const char *server_domain =
  3138. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3139. char portstr[16];
  3140. char server_ip[48];
  3141. if (port != default_port) {
  3142. sprintf(portstr, ":%u", (unsigned)port);
  3143. } else {
  3144. portstr[0] = 0;
  3145. }
  3146. if (!auth_domain_check_enabled || !server_domain) {
  3147. sockaddr_to_string(server_ip,
  3148. sizeof(server_ip),
  3149. &conn->client.lsa);
  3150. server_domain = server_ip;
  3151. }
  3152. mg_snprintf(conn,
  3153. &truncated,
  3154. buf,
  3155. buflen,
  3156. #if defined(USE_IPV6)
  3157. "%s://%s%s%s%s%s",
  3158. proto,
  3159. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3160. server_domain,
  3161. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3162. #else
  3163. "%s://%s%s%s",
  3164. proto,
  3165. server_domain,
  3166. #endif
  3167. portstr,
  3168. uri_encoded);
  3169. mg_free(uri_encoded);
  3170. if (truncated) {
  3171. return -1;
  3172. }
  3173. return 0;
  3174. }
  3175. }
  3176. }
  3177. CIVETWEB_API int
  3178. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3179. {
  3180. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3181. }
  3182. /* Skip the characters until one of the delimiters characters found.
  3183. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3184. * Advance pointer to buffer to the next word. Return found 0-terminated
  3185. * word.
  3186. * Delimiters can be quoted with quotechar. */
  3187. static char *
  3188. skip_quoted(char **buf,
  3189. const char *delimiters,
  3190. const char *whitespace,
  3191. char quotechar)
  3192. {
  3193. char *p, *begin_word, *end_word, *end_whitespace;
  3194. begin_word = *buf;
  3195. end_word = begin_word + strcspn(begin_word, delimiters);
  3196. /* Check for quotechar */
  3197. if (end_word > begin_word) {
  3198. p = end_word - 1;
  3199. while (*p == quotechar) {
  3200. /* While the delimiter is quoted, look for the next delimiter. */
  3201. /* This happens, e.g., in calls from parse_auth_header,
  3202. * if the user name contains a " character. */
  3203. /* If there is anything beyond end_word, copy it. */
  3204. if (*end_word != '\0') {
  3205. size_t end_off = strcspn(end_word + 1, delimiters);
  3206. memmove(p, end_word, end_off + 1);
  3207. p += end_off; /* p must correspond to end_word - 1 */
  3208. end_word += end_off + 1;
  3209. } else {
  3210. *p = '\0';
  3211. break;
  3212. }
  3213. }
  3214. for (p++; p < end_word; p++) {
  3215. *p = '\0';
  3216. }
  3217. }
  3218. if (*end_word == '\0') {
  3219. *buf = end_word;
  3220. } else {
  3221. #if defined(GCC_DIAGNOSTIC)
  3222. /* Disable spurious conversion warning for GCC */
  3223. #pragma GCC diagnostic push
  3224. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3225. #endif /* defined(GCC_DIAGNOSTIC) */
  3226. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3227. #if defined(GCC_DIAGNOSTIC)
  3228. #pragma GCC diagnostic pop
  3229. #endif /* defined(GCC_DIAGNOSTIC) */
  3230. for (p = end_word; p < end_whitespace; p++) {
  3231. *p = '\0';
  3232. }
  3233. *buf = end_whitespace;
  3234. }
  3235. return begin_word;
  3236. }
  3237. /* Return HTTP header value, or NULL if not found. */
  3238. static const char *
  3239. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3240. {
  3241. int i;
  3242. for (i = 0; i < num_hdr; i++) {
  3243. if (!mg_strcasecmp(name, hdr[i].name)) {
  3244. return hdr[i].value;
  3245. }
  3246. }
  3247. return NULL;
  3248. }
  3249. /* Retrieve requested HTTP header multiple values, and return the number of
  3250. * found occurrences */
  3251. static int
  3252. get_req_headers(const struct mg_request_info *ri,
  3253. const char *name,
  3254. const char **output,
  3255. int output_max_size)
  3256. {
  3257. int i;
  3258. int cnt = 0;
  3259. if (ri) {
  3260. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3261. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3262. output[cnt++] = ri->http_headers[i].value;
  3263. }
  3264. }
  3265. }
  3266. return cnt;
  3267. }
  3268. CIVETWEB_API const char *
  3269. mg_get_header(const struct mg_connection *conn, const char *name)
  3270. {
  3271. if (!conn) {
  3272. return NULL;
  3273. }
  3274. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3275. return get_header(conn->request_info.http_headers,
  3276. conn->request_info.num_headers,
  3277. name);
  3278. }
  3279. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3280. return get_header(conn->response_info.http_headers,
  3281. conn->response_info.num_headers,
  3282. name);
  3283. }
  3284. return NULL;
  3285. }
  3286. static const char *
  3287. get_http_version(const struct mg_connection *conn)
  3288. {
  3289. if (!conn) {
  3290. return NULL;
  3291. }
  3292. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3293. return conn->request_info.http_version;
  3294. }
  3295. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3296. return conn->response_info.http_version;
  3297. }
  3298. return NULL;
  3299. }
  3300. /* A helper function for traversing a comma separated list of values.
  3301. * It returns a list pointer shifted to the next value, or NULL if the end
  3302. * of the list found.
  3303. * Value is stored in val vector. If value has form "x=y", then eq_val
  3304. * vector is initialized to point to the "y" part, and val vector length
  3305. * is adjusted to point only to "x". */
  3306. static const char *
  3307. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3308. {
  3309. int end;
  3310. reparse:
  3311. if (val == NULL || list == NULL || *list == '\0') {
  3312. /* End of the list */
  3313. return NULL;
  3314. }
  3315. /* Skip over leading LWS */
  3316. while (*list == ' ' || *list == '\t')
  3317. list++;
  3318. val->ptr = list;
  3319. if ((list = strchr(val->ptr, ',')) != NULL) {
  3320. /* Comma found. Store length and shift the list ptr */
  3321. val->len = ((size_t)(list - val->ptr));
  3322. list++;
  3323. } else {
  3324. /* This value is the last one */
  3325. list = val->ptr + strlen(val->ptr);
  3326. val->len = ((size_t)(list - val->ptr));
  3327. }
  3328. /* Adjust length for trailing LWS */
  3329. end = (int)val->len - 1;
  3330. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3331. end--;
  3332. val->len = (size_t)(end) + (size_t)(1);
  3333. if (val->len == 0) {
  3334. /* Ignore any empty entries. */
  3335. goto reparse;
  3336. }
  3337. if (eq_val != NULL) {
  3338. /* Value has form "x=y", adjust pointers and lengths
  3339. * so that val points to "x", and eq_val points to "y". */
  3340. eq_val->len = 0;
  3341. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3342. if (eq_val->ptr != NULL) {
  3343. eq_val->ptr++; /* Skip over '=' character */
  3344. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3345. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3346. }
  3347. }
  3348. return list;
  3349. }
  3350. /* A helper function for checking if a comma separated list of values
  3351. * contains
  3352. * the given option (case insensitvely).
  3353. * 'header' can be NULL, in which case false is returned. */
  3354. static int
  3355. header_has_option(const char *header, const char *option)
  3356. {
  3357. struct vec opt_vec;
  3358. struct vec eq_vec;
  3359. DEBUG_ASSERT(option != NULL);
  3360. DEBUG_ASSERT(option[0] != '\0');
  3361. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3362. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3363. return 1;
  3364. }
  3365. return 0;
  3366. }
  3367. /* Sorting function implemented in a separate file */
  3368. #include "sort.inl"
  3369. /* Pattern matching has been reimplemented in a new file */
  3370. #include "match.inl"
  3371. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3372. * This function must tolerate situations when connection info is not
  3373. * set up, for example if request parsing failed. */
  3374. static int
  3375. should_keep_alive(const struct mg_connection *conn)
  3376. {
  3377. const char *http_version;
  3378. const char *header;
  3379. /* First satisfy needs of the server */
  3380. if ((conn == NULL) || conn->must_close) {
  3381. /* Close, if civetweb framework needs to close */
  3382. return 0;
  3383. }
  3384. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3385. /* Close, if keep alive is not enabled */
  3386. return 0;
  3387. }
  3388. /* Check explicit wish of the client */
  3389. header = mg_get_header(conn, "Connection");
  3390. if (header) {
  3391. /* If there is a connection header from the client, obey */
  3392. if (header_has_option(header, "keep-alive")) {
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Use default of the standard */
  3398. http_version = get_http_version(conn);
  3399. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3400. /* HTTP 1.1 default is keep alive */
  3401. return 1;
  3402. }
  3403. /* HTTP 1.0 (and earlier) default is to close the connection */
  3404. return 0;
  3405. }
  3406. static int
  3407. should_decode_url(const struct mg_connection *conn)
  3408. {
  3409. if (!conn || !conn->dom_ctx) {
  3410. return 0;
  3411. }
  3412. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3413. }
  3414. static int
  3415. should_decode_query_string(const struct mg_connection *conn)
  3416. {
  3417. if (!conn || !conn->dom_ctx) {
  3418. return 0;
  3419. }
  3420. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3421. == 0);
  3422. }
  3423. static const char *
  3424. suggest_connection_header(const struct mg_connection *conn)
  3425. {
  3426. return should_keep_alive(conn) ? "keep-alive" : "close";
  3427. }
  3428. #include "response.inl"
  3429. static void
  3430. send_no_cache_header(struct mg_connection *conn)
  3431. {
  3432. /* Send all current and obsolete cache opt-out directives. */
  3433. mg_response_header_add(conn,
  3434. "Cache-Control",
  3435. "no-cache, no-store, "
  3436. "must-revalidate, private, max-age=0",
  3437. -1);
  3438. mg_response_header_add(conn, "Expires", "0", -1);
  3439. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3440. /* Obsolete, but still send it for HTTP/1.0 */
  3441. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3442. }
  3443. }
  3444. static void
  3445. send_static_cache_header(struct mg_connection *conn)
  3446. {
  3447. #if !defined(NO_CACHING)
  3448. int max_age;
  3449. char val[64];
  3450. const char *cache_control =
  3451. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3452. /* If there is a full cache-control option configured,0 use it */
  3453. if (cache_control != NULL) {
  3454. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3455. return;
  3456. }
  3457. /* Read the server config to check how long a file may be cached.
  3458. * The configuration is in seconds. */
  3459. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3460. if (max_age <= 0) {
  3461. /* 0 means "do not cache". All values <0 are reserved
  3462. * and may be used differently in the future. */
  3463. /* If a file should not be cached, do not only send
  3464. * max-age=0, but also pragmas and Expires headers. */
  3465. send_no_cache_header(conn);
  3466. return;
  3467. }
  3468. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3469. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3470. /* See also https://www.mnot.net/cache_docs/ */
  3471. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3472. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3473. * leap
  3474. * year to 31622400 seconds. For the moment, we just send whatever has
  3475. * been configured, still the behavior for >1 year should be considered
  3476. * as undefined. */
  3477. mg_snprintf(
  3478. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3479. mg_response_header_add(conn, "Cache-Control", val, -1);
  3480. #else /* NO_CACHING */
  3481. send_no_cache_header(conn);
  3482. #endif /* !NO_CACHING */
  3483. }
  3484. static void
  3485. send_additional_header(struct mg_connection *conn)
  3486. {
  3487. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3488. #if !defined(NO_SSL)
  3489. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3490. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3491. if (max_age >= 0) {
  3492. char val[64];
  3493. mg_snprintf(conn,
  3494. NULL,
  3495. val,
  3496. sizeof(val),
  3497. "max-age=%lu",
  3498. (unsigned long)max_age);
  3499. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3500. }
  3501. }
  3502. #endif
  3503. // Content-Security-Policy
  3504. if (header && header[0]) {
  3505. mg_response_header_add_lines(conn, header);
  3506. }
  3507. }
  3508. static void
  3509. send_cors_header(struct mg_connection *conn)
  3510. {
  3511. const char *origin_hdr = mg_get_header(conn, "Origin");
  3512. const char *cors_orig_cfg =
  3513. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3514. const char *cors_cred_cfg =
  3515. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3516. const char *cors_hdr_cfg =
  3517. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3518. const char *cors_exphdr_cfg =
  3519. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3520. const char *cors_meth_cfg =
  3521. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3522. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3523. /* Cross-origin resource sharing (CORS), see
  3524. * http://www.html5rocks.com/en/tutorials/cors/,
  3525. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3526. * CORS preflight is not supported for files. */
  3527. mg_response_header_add(conn,
  3528. "Access-Control-Allow-Origin",
  3529. cors_orig_cfg,
  3530. -1);
  3531. }
  3532. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3533. /* Cross-origin resource sharing (CORS), see
  3534. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3535. */
  3536. mg_response_header_add(conn,
  3537. "Access-Control-Allow-Credentials",
  3538. cors_cred_cfg,
  3539. -1);
  3540. }
  3541. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3542. mg_response_header_add(conn,
  3543. "Access-Control-Allow-Headers",
  3544. cors_hdr_cfg,
  3545. -1);
  3546. }
  3547. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3548. mg_response_header_add(conn,
  3549. "Access-Control-Expose-Headers",
  3550. cors_exphdr_cfg,
  3551. -1);
  3552. }
  3553. if (cors_meth_cfg && *cors_meth_cfg) {
  3554. mg_response_header_add(conn,
  3555. "Access-Control-Allow-Methods",
  3556. cors_meth_cfg,
  3557. -1);
  3558. }
  3559. }
  3560. #if !defined(NO_FILESYSTEMS)
  3561. static void handle_file_based_request(struct mg_connection *conn,
  3562. const char *path,
  3563. struct mg_file *filep);
  3564. #endif /* NO_FILESYSTEMS */
  3565. CIVETWEB_API const char *
  3566. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3567. {
  3568. /* See IANA HTTP status code assignment:
  3569. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3570. */
  3571. switch (response_code) {
  3572. /* RFC2616 Section 10.1 - Informational 1xx */
  3573. case 100:
  3574. return "Continue"; /* RFC2616 Section 10.1.1 */
  3575. case 101:
  3576. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3577. case 102:
  3578. return "Processing"; /* RFC2518 Section 10.1 */
  3579. /* RFC2616 Section 10.2 - Successful 2xx */
  3580. case 200:
  3581. return "OK"; /* RFC2616 Section 10.2.1 */
  3582. case 201:
  3583. return "Created"; /* RFC2616 Section 10.2.2 */
  3584. case 202:
  3585. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3586. case 203:
  3587. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3588. case 204:
  3589. return "No Content"; /* RFC2616 Section 10.2.5 */
  3590. case 205:
  3591. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3592. case 206:
  3593. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3594. case 207:
  3595. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3596. */
  3597. case 208:
  3598. return "Already Reported"; /* RFC5842 Section 7.1 */
  3599. case 226:
  3600. return "IM used"; /* RFC3229 Section 10.4.1 */
  3601. /* RFC2616 Section 10.3 - Redirection 3xx */
  3602. case 300:
  3603. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3604. case 301:
  3605. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3606. case 302:
  3607. return "Found"; /* RFC2616 Section 10.3.3 */
  3608. case 303:
  3609. return "See Other"; /* RFC2616 Section 10.3.4 */
  3610. case 304:
  3611. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3612. case 305:
  3613. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3614. case 307:
  3615. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3616. case 308:
  3617. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3618. /* RFC2616 Section 10.4 - Client Error 4xx */
  3619. case 400:
  3620. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3621. case 401:
  3622. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3623. case 402:
  3624. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3625. case 403:
  3626. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3627. case 404:
  3628. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3629. case 405:
  3630. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3631. case 406:
  3632. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3633. case 407:
  3634. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3635. case 408:
  3636. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3637. case 409:
  3638. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3639. case 410:
  3640. return "Gone"; /* RFC2616 Section 10.4.11 */
  3641. case 411:
  3642. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3643. case 412:
  3644. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3645. case 413:
  3646. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3647. case 414:
  3648. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3649. case 415:
  3650. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3651. case 416:
  3652. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3653. */
  3654. case 417:
  3655. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3656. case 421:
  3657. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3658. case 422:
  3659. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3660. * Section 11.2 */
  3661. case 423:
  3662. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3663. case 424:
  3664. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3665. * Section 11.4 */
  3666. case 426:
  3667. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3668. case 428:
  3669. return "Precondition Required"; /* RFC 6585, Section 3 */
  3670. case 429:
  3671. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3672. case 431:
  3673. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3674. case 451:
  3675. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3676. * Section 3 */
  3677. /* RFC2616 Section 10.5 - Server Error 5xx */
  3678. case 500:
  3679. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3680. case 501:
  3681. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3682. case 502:
  3683. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3684. case 503:
  3685. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3686. case 504:
  3687. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3688. case 505:
  3689. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3690. case 506:
  3691. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3692. case 507:
  3693. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3694. * Section 11.5 */
  3695. case 508:
  3696. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3697. case 510:
  3698. return "Not Extended"; /* RFC 2774, Section 7 */
  3699. case 511:
  3700. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3701. /* Other status codes, not shown in the IANA HTTP status code
  3702. * assignment.
  3703. * E.g., "de facto" standards due to common use, ... */
  3704. case 418:
  3705. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3706. case 419:
  3707. return "Authentication Timeout"; /* common use */
  3708. case 420:
  3709. return "Enhance Your Calm"; /* common use */
  3710. case 440:
  3711. return "Login Timeout"; /* common use */
  3712. case 509:
  3713. return "Bandwidth Limit Exceeded"; /* common use */
  3714. default:
  3715. /* This error code is unknown. This should not happen. */
  3716. if (conn) {
  3717. mg_cry_internal(conn,
  3718. "Unknown HTTP response code: %u",
  3719. response_code);
  3720. }
  3721. /* Return at least a category according to RFC 2616 Section 10. */
  3722. if (response_code >= 100 && response_code < 200) {
  3723. /* Unknown informational status code */
  3724. return "Information";
  3725. }
  3726. if (response_code >= 200 && response_code < 300) {
  3727. /* Unknown success code */
  3728. return "Success";
  3729. }
  3730. if (response_code >= 300 && response_code < 400) {
  3731. /* Unknown redirection code */
  3732. return "Redirection";
  3733. }
  3734. if (response_code >= 400 && response_code < 500) {
  3735. /* Unknown request error code */
  3736. return "Client Error";
  3737. }
  3738. if (response_code >= 500 && response_code < 600) {
  3739. /* Unknown server error code */
  3740. return "Server Error";
  3741. }
  3742. /* Response code not even within reasonable range */
  3743. return "";
  3744. }
  3745. }
  3746. static int
  3747. mg_send_http_error_impl(struct mg_connection *conn,
  3748. int status,
  3749. const char *fmt,
  3750. va_list args)
  3751. {
  3752. char errmsg_buf[MG_BUF_LEN];
  3753. va_list ap;
  3754. int has_body;
  3755. #if !defined(NO_FILESYSTEMS)
  3756. char path_buf[UTF8_PATH_MAX];
  3757. int len, i, page_handler_found, scope, truncated;
  3758. const char *error_handler = NULL;
  3759. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3760. const char *error_page_file_ext, *tstr;
  3761. #endif /* NO_FILESYSTEMS */
  3762. int handled_by_callback = 0;
  3763. if ((conn == NULL) || (fmt == NULL)) {
  3764. return -2;
  3765. }
  3766. /* Set status (for log) */
  3767. conn->status_code = status;
  3768. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3769. has_body = ((status > 199) && (status != 204) && (status != 304));
  3770. /* Prepare message in buf, if required */
  3771. if (has_body
  3772. || (!conn->in_error_handler
  3773. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3774. /* Store error message in errmsg_buf */
  3775. va_copy(ap, args);
  3776. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3777. va_end(ap);
  3778. /* In a debug build, print all html errors */
  3779. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3780. }
  3781. /* If there is a http_error callback, call it.
  3782. * But don't do it recursively, if callback calls mg_send_http_error again.
  3783. */
  3784. if (!conn->in_error_handler
  3785. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3786. /* Mark in_error_handler to avoid recursion and call user callback. */
  3787. conn->in_error_handler = 1;
  3788. handled_by_callback =
  3789. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3790. == 0);
  3791. conn->in_error_handler = 0;
  3792. }
  3793. if (!handled_by_callback) {
  3794. /* Check for recursion */
  3795. if (conn->in_error_handler) {
  3796. DEBUG_TRACE(
  3797. "Recursion when handling error %u - fall back to default",
  3798. status);
  3799. #if !defined(NO_FILESYSTEMS)
  3800. } else {
  3801. /* Send user defined error pages, if defined */
  3802. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3803. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3804. page_handler_found = 0;
  3805. if (error_handler != NULL) {
  3806. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3807. switch (scope) {
  3808. case 1: /* Handler for specific error, e.g. 404 error */
  3809. mg_snprintf(conn,
  3810. &truncated,
  3811. path_buf,
  3812. sizeof(path_buf) - 32,
  3813. "%serror%03u.",
  3814. error_handler,
  3815. status);
  3816. break;
  3817. case 2: /* Handler for error group, e.g., 5xx error
  3818. * handler
  3819. * for all server errors (500-599) */
  3820. mg_snprintf(conn,
  3821. &truncated,
  3822. path_buf,
  3823. sizeof(path_buf) - 32,
  3824. "%serror%01uxx.",
  3825. error_handler,
  3826. status / 100);
  3827. break;
  3828. default: /* Handler for all errors */
  3829. mg_snprintf(conn,
  3830. &truncated,
  3831. path_buf,
  3832. sizeof(path_buf) - 32,
  3833. "%serror.",
  3834. error_handler);
  3835. break;
  3836. }
  3837. /* String truncation in buf may only occur if
  3838. * error_handler is too long. This string is
  3839. * from the config, not from a client. */
  3840. (void)truncated;
  3841. /* The following code is redundant, but it should avoid
  3842. * false positives in static source code analyzers and
  3843. * vulnerability scanners.
  3844. */
  3845. path_buf[sizeof(path_buf) - 32] = 0;
  3846. len = (int)strlen(path_buf);
  3847. if (len > (int)sizeof(path_buf) - 32) {
  3848. len = (int)sizeof(path_buf) - 32;
  3849. }
  3850. /* Start with the file extension from the configuration. */
  3851. tstr = strchr(error_page_file_ext, '.');
  3852. while (tstr) {
  3853. for (i = 1;
  3854. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3855. i++) {
  3856. /* buffer overrun is not possible here, since
  3857. * (i < 32) && (len < sizeof(path_buf) - 32)
  3858. * ==> (i + len) < sizeof(path_buf) */
  3859. path_buf[len + i - 1] = tstr[i];
  3860. }
  3861. /* buffer overrun is not possible here, since
  3862. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3863. * ==> (i + len) <= sizeof(path_buf) */
  3864. path_buf[len + i - 1] = 0;
  3865. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3866. DEBUG_TRACE("Check error page %s - found",
  3867. path_buf);
  3868. page_handler_found = 1;
  3869. break;
  3870. }
  3871. DEBUG_TRACE("Check error page %s - not found",
  3872. path_buf);
  3873. /* Continue with the next file extension from the
  3874. * configuration (if there is a next one). */
  3875. tstr = strchr(tstr + i, '.');
  3876. }
  3877. }
  3878. }
  3879. if (page_handler_found) {
  3880. conn->in_error_handler = 1;
  3881. handle_file_based_request(conn, path_buf, &error_page_file);
  3882. conn->in_error_handler = 0;
  3883. return 0;
  3884. }
  3885. #endif /* NO_FILESYSTEMS */
  3886. }
  3887. /* No custom error page. Send default error page. */
  3888. conn->must_close = 1;
  3889. mg_response_header_start(conn, status);
  3890. send_no_cache_header(conn);
  3891. send_additional_header(conn);
  3892. send_cors_header(conn);
  3893. if (has_body) {
  3894. mg_response_header_add(conn,
  3895. "Content-Type",
  3896. "text/plain; charset=utf-8",
  3897. -1);
  3898. }
  3899. mg_response_header_send(conn);
  3900. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3901. if (has_body) {
  3902. /* For other errors, send a generic error message. */
  3903. const char *status_text = mg_get_response_code_text(conn, status);
  3904. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3905. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3906. } else {
  3907. /* No body allowed. Close the connection. */
  3908. DEBUG_TRACE("Error %i", status);
  3909. }
  3910. }
  3911. return 0;
  3912. }
  3913. CIVETWEB_API int
  3914. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3915. {
  3916. va_list ap;
  3917. int ret;
  3918. va_start(ap, fmt);
  3919. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3920. va_end(ap);
  3921. return ret;
  3922. }
  3923. CIVETWEB_API int
  3924. mg_send_http_ok(struct mg_connection *conn,
  3925. const char *mime_type,
  3926. long long content_length)
  3927. {
  3928. if ((mime_type == NULL) || (*mime_type == 0)) {
  3929. /* No content type defined: default to text/html */
  3930. mime_type = "text/html";
  3931. }
  3932. mg_response_header_start(conn, 200);
  3933. send_no_cache_header(conn);
  3934. send_additional_header(conn);
  3935. send_cors_header(conn);
  3936. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3937. if (content_length < 0) {
  3938. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3939. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3940. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3941. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3942. }
  3943. } else {
  3944. char len[32];
  3945. int trunc = 0;
  3946. mg_snprintf(conn,
  3947. &trunc,
  3948. len,
  3949. sizeof(len),
  3950. "%" UINT64_FMT,
  3951. (uint64_t)content_length);
  3952. if (!trunc) {
  3953. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3954. * !trunc is always true */
  3955. mg_response_header_add(conn, "Content-Length", len, -1);
  3956. }
  3957. }
  3958. mg_response_header_send(conn);
  3959. return 0;
  3960. }
  3961. CIVETWEB_API int
  3962. mg_send_http_redirect(struct mg_connection *conn,
  3963. const char *target_url,
  3964. int redirect_code)
  3965. {
  3966. /* Send a 30x redirect response.
  3967. *
  3968. * Redirect types (status codes):
  3969. *
  3970. * Status | Perm/Temp | Method | Version
  3971. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3972. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3973. * 303 | temporary | always use GET | HTTP/1.1
  3974. * 307 | temporary | always keep method | HTTP/1.1
  3975. * 308 | permanent | always keep method | HTTP/1.1
  3976. */
  3977. #if defined(MG_SEND_REDIRECT_BODY)
  3978. char redirect_body[MG_BUF_LEN];
  3979. size_t content_len = 0;
  3980. char content_len_text[32];
  3981. #endif
  3982. /* In case redirect_code=0, use 307. */
  3983. if (redirect_code == 0) {
  3984. redirect_code = 307;
  3985. }
  3986. /* In case redirect_code is none of the above, return error. */
  3987. if ((redirect_code != 301) && (redirect_code != 302)
  3988. && (redirect_code != 303) && (redirect_code != 307)
  3989. && (redirect_code != 308)) {
  3990. /* Parameter error */
  3991. return -2;
  3992. }
  3993. /* If target_url is not defined, redirect to "/". */
  3994. if ((target_url == NULL) || (*target_url == 0)) {
  3995. target_url = "/";
  3996. }
  3997. #if defined(MG_SEND_REDIRECT_BODY)
  3998. /* TODO: condition name? */
  3999. /* Prepare a response body with a hyperlink.
  4000. *
  4001. * According to RFC2616 (and RFC1945 before):
  4002. * Unless the request method was HEAD, the entity of the
  4003. * response SHOULD contain a short hypertext note with a hyperlink to
  4004. * the new URI(s).
  4005. *
  4006. * However, this response body is not useful in M2M communication.
  4007. * Probably the original reason in the RFC was, clients not supporting
  4008. * a 30x HTTP redirect could still show the HTML page and let the user
  4009. * press the link. Since current browsers support 30x HTTP, the additional
  4010. * HTML body does not seem to make sense anymore.
  4011. *
  4012. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4013. * but it only notes:
  4014. * The server's response payload usually contains a short
  4015. * hypertext note with a hyperlink to the new URI(s).
  4016. *
  4017. * Deactivated by default. If you need the 30x body, set the define.
  4018. */
  4019. mg_snprintf(
  4020. conn,
  4021. NULL /* ignore truncation */,
  4022. redirect_body,
  4023. sizeof(redirect_body),
  4024. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4025. redirect_text,
  4026. target_url,
  4027. target_url);
  4028. content_len = strlen(reply);
  4029. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4030. #endif
  4031. /* Send all required headers */
  4032. mg_response_header_start(conn, redirect_code);
  4033. mg_response_header_add(conn, "Location", target_url, -1);
  4034. if ((redirect_code == 301) || (redirect_code == 308)) {
  4035. /* Permanent redirect */
  4036. send_static_cache_header(conn);
  4037. } else {
  4038. /* Temporary redirect */
  4039. send_no_cache_header(conn);
  4040. }
  4041. send_additional_header(conn);
  4042. send_cors_header(conn);
  4043. #if defined(MG_SEND_REDIRECT_BODY)
  4044. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4045. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4046. #else
  4047. mg_response_header_add(conn, "Content-Length", "0", 1);
  4048. #endif
  4049. mg_response_header_send(conn);
  4050. #if defined(MG_SEND_REDIRECT_BODY)
  4051. /* Send response body */
  4052. /* ... unless it is a HEAD request */
  4053. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4054. ret = mg_write(conn, redirect_body, content_len);
  4055. }
  4056. #endif
  4057. return 1;
  4058. }
  4059. #if defined(_WIN32)
  4060. /* Create substitutes for POSIX functions in Win32. */
  4061. #if defined(GCC_DIAGNOSTIC)
  4062. /* Show no warning in case system functions are not used. */
  4063. #pragma GCC diagnostic push
  4064. #pragma GCC diagnostic ignored "-Wunused-function"
  4065. #endif
  4066. static int
  4067. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4068. {
  4069. (void)unused;
  4070. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4071. InitializeCriticalSection(&mutex->sec);
  4072. return 0;
  4073. }
  4074. static int
  4075. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4076. {
  4077. DeleteCriticalSection(&mutex->sec);
  4078. return 0;
  4079. }
  4080. static int
  4081. pthread_mutex_lock(pthread_mutex_t *mutex)
  4082. {
  4083. EnterCriticalSection(&mutex->sec);
  4084. return 0;
  4085. }
  4086. static int
  4087. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4088. {
  4089. LeaveCriticalSection(&mutex->sec);
  4090. return 0;
  4091. }
  4092. FUNCTION_MAY_BE_UNUSED
  4093. static int
  4094. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4095. {
  4096. (void)unused;
  4097. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4098. cv->waiting_thread = NULL;
  4099. return 0;
  4100. }
  4101. FUNCTION_MAY_BE_UNUSED
  4102. static int
  4103. pthread_cond_timedwait(pthread_cond_t *cv,
  4104. pthread_mutex_t *mutex,
  4105. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4106. {
  4107. struct mg_workerTLS **ptls,
  4108. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4109. int ok;
  4110. uint64_t nsnow, nswaitabs;
  4111. int64_t nswaitrel;
  4112. DWORD mswaitrel;
  4113. pthread_mutex_lock(&cv->threadIdSec);
  4114. /* Add this thread to cv's waiting list */
  4115. ptls = &cv->waiting_thread;
  4116. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4117. ;
  4118. tls->next_waiting_thread = NULL;
  4119. *ptls = tls;
  4120. pthread_mutex_unlock(&cv->threadIdSec);
  4121. if (abstime) {
  4122. nsnow = mg_get_current_time_ns();
  4123. nswaitabs =
  4124. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4125. nswaitrel = nswaitabs - nsnow;
  4126. if (nswaitrel < 0) {
  4127. nswaitrel = 0;
  4128. }
  4129. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4130. } else {
  4131. mswaitrel = (DWORD)INFINITE;
  4132. }
  4133. pthread_mutex_unlock(mutex);
  4134. ok = (WAIT_OBJECT_0
  4135. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4136. if (!ok) {
  4137. ok = 1;
  4138. pthread_mutex_lock(&cv->threadIdSec);
  4139. ptls = &cv->waiting_thread;
  4140. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4141. if (*ptls == tls) {
  4142. *ptls = tls->next_waiting_thread;
  4143. ok = 0;
  4144. break;
  4145. }
  4146. }
  4147. pthread_mutex_unlock(&cv->threadIdSec);
  4148. if (ok) {
  4149. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4150. (DWORD)INFINITE);
  4151. }
  4152. }
  4153. /* This thread has been removed from cv's waiting list */
  4154. pthread_mutex_lock(mutex);
  4155. return ok ? 0 : -1;
  4156. }
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static int
  4159. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4160. {
  4161. return pthread_cond_timedwait(cv, mutex, NULL);
  4162. }
  4163. FUNCTION_MAY_BE_UNUSED
  4164. static int
  4165. pthread_cond_signal(pthread_cond_t *cv)
  4166. {
  4167. HANDLE wkup = NULL;
  4168. BOOL ok = FALSE;
  4169. pthread_mutex_lock(&cv->threadIdSec);
  4170. if (cv->waiting_thread) {
  4171. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4172. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4173. ok = SetEvent(wkup);
  4174. DEBUG_ASSERT(ok);
  4175. }
  4176. pthread_mutex_unlock(&cv->threadIdSec);
  4177. return ok ? 0 : 1;
  4178. }
  4179. FUNCTION_MAY_BE_UNUSED
  4180. static int
  4181. pthread_cond_broadcast(pthread_cond_t *cv)
  4182. {
  4183. pthread_mutex_lock(&cv->threadIdSec);
  4184. while (cv->waiting_thread) {
  4185. pthread_cond_signal(cv);
  4186. }
  4187. pthread_mutex_unlock(&cv->threadIdSec);
  4188. return 0;
  4189. }
  4190. FUNCTION_MAY_BE_UNUSED
  4191. static int
  4192. pthread_cond_destroy(pthread_cond_t *cv)
  4193. {
  4194. pthread_mutex_lock(&cv->threadIdSec);
  4195. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4196. pthread_mutex_unlock(&cv->threadIdSec);
  4197. pthread_mutex_destroy(&cv->threadIdSec);
  4198. return 0;
  4199. }
  4200. #if defined(ALTERNATIVE_QUEUE)
  4201. FUNCTION_MAY_BE_UNUSED
  4202. static void *
  4203. event_create(void)
  4204. {
  4205. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4206. }
  4207. FUNCTION_MAY_BE_UNUSED
  4208. static int
  4209. event_wait(void *eventhdl)
  4210. {
  4211. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4212. return (res == WAIT_OBJECT_0);
  4213. }
  4214. FUNCTION_MAY_BE_UNUSED
  4215. static int
  4216. event_signal(void *eventhdl)
  4217. {
  4218. return (int)SetEvent((HANDLE)eventhdl);
  4219. }
  4220. FUNCTION_MAY_BE_UNUSED
  4221. static void
  4222. event_destroy(void *eventhdl)
  4223. {
  4224. CloseHandle((HANDLE)eventhdl);
  4225. }
  4226. #endif
  4227. #if defined(GCC_DIAGNOSTIC)
  4228. /* Enable unused function warning again */
  4229. #pragma GCC diagnostic pop
  4230. #endif
  4231. /* For Windows, change all slashes to backslashes in path names. */
  4232. static void
  4233. change_slashes_to_backslashes(char *path)
  4234. {
  4235. int i;
  4236. for (i = 0; path[i] != '\0'; i++) {
  4237. if (path[i] == '/') {
  4238. path[i] = '\\';
  4239. }
  4240. /* remove double backslash (check i > 0 to preserve UNC paths,
  4241. * like \\server\file.txt) */
  4242. if ((i > 0) && (path[i] == '\\')) {
  4243. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4244. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4245. }
  4246. }
  4247. }
  4248. }
  4249. static int
  4250. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4251. {
  4252. int diff;
  4253. do {
  4254. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4255. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4256. s1++;
  4257. s2++;
  4258. } while ((diff == 0) && (s1[-1] != L'\0'));
  4259. return diff;
  4260. }
  4261. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4262. * wbuf and wbuf_len is a target buffer and its length. */
  4263. static void
  4264. path_to_unicode(const struct mg_connection *conn,
  4265. const char *path,
  4266. wchar_t *wbuf,
  4267. size_t wbuf_len)
  4268. {
  4269. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4270. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4271. DWORD long_len, err;
  4272. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4273. mg_strlcpy(buf, path, sizeof(buf));
  4274. change_slashes_to_backslashes(buf);
  4275. /* Convert to Unicode and back. If doubly-converted string does not
  4276. * match the original, something is fishy, reject. */
  4277. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4278. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4279. WideCharToMultiByte(
  4280. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4281. if (strcmp(buf, buf2) != 0) {
  4282. wbuf[0] = L'\0';
  4283. }
  4284. /* Windows file systems are not case sensitive, but you can still use
  4285. * uppercase and lowercase letters (on all modern file systems).
  4286. * The server can check if the URI uses the same upper/lowercase
  4287. * letters an the file system, effectively making Windows servers
  4288. * case sensitive (like Linux servers are). It is still not possible
  4289. * to use two files with the same name in different cases on Windows
  4290. * (like /a and /A) - this would be possible in Linux.
  4291. * As a default, Windows is not case sensitive, but the case sensitive
  4292. * file name check can be activated by an additional configuration. */
  4293. if (conn) {
  4294. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4295. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4296. "yes")) {
  4297. /* Use case sensitive compare function */
  4298. fcompare = wcscmp;
  4299. }
  4300. }
  4301. (void)conn; /* conn is currently unused */
  4302. /* Only accept a full file path, not a Windows short (8.3) path. */
  4303. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4304. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4305. if (long_len == 0) {
  4306. err = GetLastError();
  4307. if (err == ERROR_FILE_NOT_FOUND) {
  4308. /* File does not exist. This is not always a problem here. */
  4309. return;
  4310. }
  4311. }
  4312. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4313. /* Short name is used. */
  4314. wbuf[0] = L'\0';
  4315. }
  4316. }
  4317. #if !defined(NO_FILESYSTEMS)
  4318. /* Get file information, return 1 if file exists, 0 if not */
  4319. static int
  4320. mg_stat(const struct mg_connection *conn,
  4321. const char *path,
  4322. struct mg_file_stat *filep)
  4323. {
  4324. wchar_t wbuf[UTF16_PATH_MAX];
  4325. WIN32_FILE_ATTRIBUTE_DATA info;
  4326. time_t creation_time;
  4327. size_t len;
  4328. if (!filep) {
  4329. return 0;
  4330. }
  4331. memset(filep, 0, sizeof(*filep));
  4332. if (mg_path_suspicious(conn, path)) {
  4333. return 0;
  4334. }
  4335. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4336. /* Windows happily opens files with some garbage at the end of file name.
  4337. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4338. * "a.cgi", despite one would expect an error back. */
  4339. len = strlen(path);
  4340. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4341. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4342. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4343. filep->last_modified =
  4344. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4345. info.ftLastWriteTime.dwHighDateTime);
  4346. /* On Windows, the file creation time can be higher than the
  4347. * modification time, e.g. when a file is copied.
  4348. * Since the Last-Modified timestamp is used for caching
  4349. * it should be based on the most recent timestamp. */
  4350. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4351. info.ftCreationTime.dwHighDateTime);
  4352. if (creation_time > filep->last_modified) {
  4353. filep->last_modified = creation_time;
  4354. }
  4355. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4356. return 1;
  4357. }
  4358. return 0;
  4359. }
  4360. #endif
  4361. static int
  4362. mg_remove(const struct mg_connection *conn, const char *path)
  4363. {
  4364. wchar_t wbuf[UTF16_PATH_MAX];
  4365. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4366. return DeleteFileW(wbuf) ? 0 : -1;
  4367. }
  4368. static int
  4369. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4370. {
  4371. wchar_t wbuf[UTF16_PATH_MAX];
  4372. (void)mode;
  4373. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4374. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4375. }
  4376. /* Create substitutes for POSIX functions in Win32. */
  4377. #if defined(GCC_DIAGNOSTIC)
  4378. /* Show no warning in case system functions are not used. */
  4379. #pragma GCC diagnostic push
  4380. #pragma GCC diagnostic ignored "-Wunused-function"
  4381. #endif
  4382. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4383. FUNCTION_MAY_BE_UNUSED
  4384. static DIR *
  4385. mg_opendir(const struct mg_connection *conn, const char *name)
  4386. {
  4387. DIR *dir = NULL;
  4388. wchar_t wpath[UTF16_PATH_MAX];
  4389. DWORD attrs;
  4390. if (name == NULL) {
  4391. SetLastError(ERROR_BAD_ARGUMENTS);
  4392. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4393. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4394. } else {
  4395. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4396. attrs = GetFileAttributesW(wpath);
  4397. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4398. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4399. (void)wcscat(wpath, L"\\*");
  4400. dir->handle = FindFirstFileW(wpath, &dir->info);
  4401. dir->result.d_name[0] = '\0';
  4402. } else {
  4403. mg_free(dir);
  4404. dir = NULL;
  4405. }
  4406. }
  4407. return dir;
  4408. }
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static int
  4411. mg_closedir(DIR *dir)
  4412. {
  4413. int result = 0;
  4414. if (dir != NULL) {
  4415. if (dir->handle != INVALID_HANDLE_VALUE)
  4416. result = FindClose(dir->handle) ? 0 : -1;
  4417. mg_free(dir);
  4418. } else {
  4419. result = -1;
  4420. SetLastError(ERROR_BAD_ARGUMENTS);
  4421. }
  4422. return result;
  4423. }
  4424. FUNCTION_MAY_BE_UNUSED
  4425. static struct dirent *
  4426. mg_readdir(DIR *dir)
  4427. {
  4428. struct dirent *result = 0;
  4429. if (dir) {
  4430. if (dir->handle != INVALID_HANDLE_VALUE) {
  4431. result = &dir->result;
  4432. (void)WideCharToMultiByte(CP_UTF8,
  4433. 0,
  4434. dir->info.cFileName,
  4435. -1,
  4436. result->d_name,
  4437. sizeof(result->d_name),
  4438. NULL,
  4439. NULL);
  4440. if (!FindNextFileW(dir->handle, &dir->info)) {
  4441. (void)FindClose(dir->handle);
  4442. dir->handle = INVALID_HANDLE_VALUE;
  4443. }
  4444. } else {
  4445. SetLastError(ERROR_FILE_NOT_FOUND);
  4446. }
  4447. } else {
  4448. SetLastError(ERROR_BAD_ARGUMENTS);
  4449. }
  4450. return result;
  4451. }
  4452. #if !defined(HAVE_POLL)
  4453. #undef POLLIN
  4454. #undef POLLPRI
  4455. #undef POLLOUT
  4456. #undef POLLERR
  4457. #define POLLIN (1) /* Data ready - read will not block. */
  4458. #define POLLPRI (2) /* Priority data ready. */
  4459. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4460. #define POLLERR (8) /* Error event */
  4461. FUNCTION_MAY_BE_UNUSED
  4462. static int
  4463. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4464. {
  4465. struct timeval tv;
  4466. fd_set rset;
  4467. fd_set wset;
  4468. fd_set eset;
  4469. unsigned int i;
  4470. int result;
  4471. SOCKET maxfd = 0;
  4472. memset(&tv, 0, sizeof(tv));
  4473. tv.tv_sec = milliseconds / 1000;
  4474. tv.tv_usec = (milliseconds % 1000) * 1000;
  4475. FD_ZERO(&rset);
  4476. FD_ZERO(&wset);
  4477. FD_ZERO(&eset);
  4478. for (i = 0; i < n; i++) {
  4479. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4480. if (pfd[i].events & POLLIN) {
  4481. FD_SET(pfd[i].fd, &rset);
  4482. }
  4483. if (pfd[i].events & POLLOUT) {
  4484. FD_SET(pfd[i].fd, &wset);
  4485. }
  4486. /* Check for errors for any FD in the set */
  4487. FD_SET(pfd[i].fd, &eset);
  4488. }
  4489. pfd[i].revents = 0;
  4490. if (pfd[i].fd > maxfd) {
  4491. maxfd = pfd[i].fd;
  4492. }
  4493. }
  4494. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4495. for (i = 0; i < n; i++) {
  4496. if (FD_ISSET(pfd[i].fd, &rset)) {
  4497. pfd[i].revents |= POLLIN;
  4498. }
  4499. if (FD_ISSET(pfd[i].fd, &wset)) {
  4500. pfd[i].revents |= POLLOUT;
  4501. }
  4502. if (FD_ISSET(pfd[i].fd, &eset)) {
  4503. pfd[i].revents |= POLLERR;
  4504. }
  4505. }
  4506. }
  4507. /* We should subtract the time used in select from remaining
  4508. * "milliseconds", in particular if called from mg_poll with a
  4509. * timeout quantum.
  4510. * Unfortunately, the remaining time is not stored in "tv" in all
  4511. * implementations, so the result in "tv" must be considered undefined.
  4512. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4513. return result;
  4514. }
  4515. #endif /* HAVE_POLL */
  4516. #if defined(GCC_DIAGNOSTIC)
  4517. /* Enable unused function warning again */
  4518. #pragma GCC diagnostic pop
  4519. #endif
  4520. static void
  4521. set_close_on_exec(SOCKET sock,
  4522. const struct mg_connection *conn /* may be null */,
  4523. struct mg_context *ctx /* may be null */)
  4524. {
  4525. (void)conn; /* Unused. */
  4526. (void)ctx;
  4527. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4528. }
  4529. CIVETWEB_API int
  4530. mg_start_thread(mg_thread_func_t f, void *p)
  4531. {
  4532. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4533. /* Compile-time option to control stack size, e.g.
  4534. * -DUSE_STACK_SIZE=16384
  4535. */
  4536. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4537. == ((uintptr_t)(-1L)))
  4538. ? -1
  4539. : 0);
  4540. #else
  4541. return (
  4542. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4543. ? -1
  4544. : 0);
  4545. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4546. }
  4547. /* Start a thread storing the thread context. */
  4548. static int
  4549. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4550. void *p,
  4551. pthread_t *threadidptr)
  4552. {
  4553. uintptr_t uip;
  4554. HANDLE threadhandle;
  4555. int result = -1;
  4556. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4557. threadhandle = (HANDLE)uip;
  4558. if ((uip != 0) && (threadidptr != NULL)) {
  4559. *threadidptr = threadhandle;
  4560. result = 0;
  4561. }
  4562. return result;
  4563. }
  4564. /* Wait for a thread to finish. */
  4565. static int
  4566. mg_join_thread(pthread_t threadid)
  4567. {
  4568. int result;
  4569. DWORD dwevent;
  4570. result = -1;
  4571. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4572. if (dwevent == WAIT_FAILED) {
  4573. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4574. } else {
  4575. if (dwevent == WAIT_OBJECT_0) {
  4576. CloseHandle(threadid);
  4577. result = 0;
  4578. }
  4579. }
  4580. return result;
  4581. }
  4582. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4583. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4584. /* Create substitutes for POSIX functions in Win32. */
  4585. #if defined(GCC_DIAGNOSTIC)
  4586. /* Show no warning in case system functions are not used. */
  4587. #pragma GCC diagnostic push
  4588. #pragma GCC diagnostic ignored "-Wunused-function"
  4589. #endif
  4590. FUNCTION_MAY_BE_UNUSED
  4591. static HANDLE
  4592. dlopen(const char *dll_name, int flags)
  4593. {
  4594. wchar_t wbuf[UTF16_PATH_MAX];
  4595. (void)flags;
  4596. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4597. return LoadLibraryW(wbuf);
  4598. }
  4599. FUNCTION_MAY_BE_UNUSED
  4600. static int
  4601. dlclose(void *handle)
  4602. {
  4603. int result;
  4604. if (FreeLibrary((HMODULE)handle) != 0) {
  4605. result = 0;
  4606. } else {
  4607. result = -1;
  4608. }
  4609. return result;
  4610. }
  4611. #if defined(GCC_DIAGNOSTIC)
  4612. /* Enable unused function warning again */
  4613. #pragma GCC diagnostic pop
  4614. #endif
  4615. #endif
  4616. #if !defined(NO_CGI)
  4617. #define SIGKILL (0)
  4618. static int
  4619. kill(pid_t pid, int sig_num)
  4620. {
  4621. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4622. (void)CloseHandle((HANDLE)pid);
  4623. return 0;
  4624. }
  4625. #if !defined(WNOHANG)
  4626. #define WNOHANG (1)
  4627. #endif
  4628. static pid_t
  4629. waitpid(pid_t pid, int *status, int flags)
  4630. {
  4631. DWORD timeout = INFINITE;
  4632. DWORD waitres;
  4633. (void)status; /* Currently not used by any client here */
  4634. if ((flags | WNOHANG) == WNOHANG) {
  4635. timeout = 0;
  4636. }
  4637. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4638. if (waitres == WAIT_OBJECT_0) {
  4639. return pid;
  4640. }
  4641. if (waitres == WAIT_TIMEOUT) {
  4642. return 0;
  4643. }
  4644. return (pid_t)-1;
  4645. }
  4646. static void
  4647. trim_trailing_whitespaces(char *s)
  4648. {
  4649. char *e = s + strlen(s);
  4650. while ((e > s) && isspace((unsigned char)e[-1])) {
  4651. *(--e) = '\0';
  4652. }
  4653. }
  4654. static pid_t
  4655. spawn_process(struct mg_connection *conn,
  4656. const char *prog,
  4657. char *envblk,
  4658. char *envp[],
  4659. int fdin[2],
  4660. int fdout[2],
  4661. int fderr[2],
  4662. const char *dir,
  4663. int cgi_config_idx)
  4664. {
  4665. HANDLE me;
  4666. char *interp;
  4667. char *interp_arg = 0;
  4668. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4669. int truncated;
  4670. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4671. STARTUPINFOA si;
  4672. PROCESS_INFORMATION pi = {0};
  4673. (void)envp;
  4674. memset(&si, 0, sizeof(si));
  4675. si.cb = sizeof(si);
  4676. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4677. si.wShowWindow = SW_HIDE;
  4678. me = GetCurrentProcess();
  4679. DuplicateHandle(me,
  4680. (HANDLE)_get_osfhandle(fdin[0]),
  4681. me,
  4682. &si.hStdInput,
  4683. 0,
  4684. TRUE,
  4685. DUPLICATE_SAME_ACCESS);
  4686. DuplicateHandle(me,
  4687. (HANDLE)_get_osfhandle(fdout[1]),
  4688. me,
  4689. &si.hStdOutput,
  4690. 0,
  4691. TRUE,
  4692. DUPLICATE_SAME_ACCESS);
  4693. DuplicateHandle(me,
  4694. (HANDLE)_get_osfhandle(fderr[1]),
  4695. me,
  4696. &si.hStdError,
  4697. 0,
  4698. TRUE,
  4699. DUPLICATE_SAME_ACCESS);
  4700. /* Mark handles that should not be inherited. See
  4701. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4702. */
  4703. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4704. HANDLE_FLAG_INHERIT,
  4705. 0);
  4706. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4707. HANDLE_FLAG_INHERIT,
  4708. 0);
  4709. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4710. HANDLE_FLAG_INHERIT,
  4711. 0);
  4712. /* First check, if there is a CGI interpreter configured for all CGI
  4713. * scripts. */
  4714. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4715. if (interp != NULL) {
  4716. /* If there is a configured interpreter, check for additional arguments
  4717. */
  4718. interp_arg =
  4719. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4720. } else {
  4721. /* Otherwise, the interpreter must be stated in the first line of the
  4722. * CGI script file, after a #! (shebang) mark. */
  4723. buf[0] = buf[1] = '\0';
  4724. /* Get the full script path */
  4725. mg_snprintf(
  4726. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4727. if (truncated) {
  4728. pi.hProcess = (pid_t)-1;
  4729. goto spawn_cleanup;
  4730. }
  4731. /* Open the script file, to read the first line */
  4732. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4733. /* Read the first line of the script into the buffer */
  4734. mg_fgets(buf, sizeof(buf), &file);
  4735. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4736. buf[sizeof(buf) - 1] = '\0';
  4737. }
  4738. if ((buf[0] == '#') && (buf[1] == '!')) {
  4739. trim_trailing_whitespaces(buf + 2);
  4740. } else {
  4741. buf[2] = '\0';
  4742. }
  4743. interp = buf + 2;
  4744. }
  4745. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4746. if (interp[0] != '\0') {
  4747. /* This is an interpreted script file. We must call the interpreter. */
  4748. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4749. mg_snprintf(conn,
  4750. &truncated,
  4751. cmdline,
  4752. sizeof(cmdline),
  4753. "\"%s\" %s \"%s\\%s\"",
  4754. interp,
  4755. interp_arg,
  4756. full_dir,
  4757. prog);
  4758. } else {
  4759. mg_snprintf(conn,
  4760. &truncated,
  4761. cmdline,
  4762. sizeof(cmdline),
  4763. "\"%s\" \"%s\\%s\"",
  4764. interp,
  4765. full_dir,
  4766. prog);
  4767. }
  4768. } else {
  4769. /* This is (probably) a compiled program. We call it directly. */
  4770. mg_snprintf(conn,
  4771. &truncated,
  4772. cmdline,
  4773. sizeof(cmdline),
  4774. "\"%s\\%s\"",
  4775. full_dir,
  4776. prog);
  4777. }
  4778. if (truncated) {
  4779. pi.hProcess = (pid_t)-1;
  4780. goto spawn_cleanup;
  4781. }
  4782. DEBUG_TRACE("Running [%s]", cmdline);
  4783. if (CreateProcessA(NULL,
  4784. cmdline,
  4785. NULL,
  4786. NULL,
  4787. TRUE,
  4788. CREATE_NEW_PROCESS_GROUP,
  4789. envblk,
  4790. NULL,
  4791. &si,
  4792. &pi)
  4793. == 0) {
  4794. mg_cry_internal(
  4795. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4796. pi.hProcess = (pid_t)-1;
  4797. /* goto spawn_cleanup; */
  4798. }
  4799. spawn_cleanup:
  4800. (void)CloseHandle(si.hStdOutput);
  4801. (void)CloseHandle(si.hStdError);
  4802. (void)CloseHandle(si.hStdInput);
  4803. if (pi.hThread != NULL) {
  4804. (void)CloseHandle(pi.hThread);
  4805. }
  4806. return (pid_t)pi.hProcess;
  4807. }
  4808. #endif /* !NO_CGI */
  4809. static int
  4810. set_blocking_mode(SOCKET sock)
  4811. {
  4812. unsigned long non_blocking = 0;
  4813. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4814. }
  4815. static int
  4816. set_non_blocking_mode(SOCKET sock)
  4817. {
  4818. unsigned long non_blocking = 1;
  4819. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4820. }
  4821. #else
  4822. #if !defined(NO_FILESYSTEMS)
  4823. static int
  4824. mg_stat(const struct mg_connection *conn,
  4825. const char *path,
  4826. struct mg_file_stat *filep)
  4827. {
  4828. struct stat st;
  4829. if (!filep) {
  4830. return 0;
  4831. }
  4832. memset(filep, 0, sizeof(*filep));
  4833. if (mg_path_suspicious(conn, path)) {
  4834. return 0;
  4835. }
  4836. if (0 == stat(path, &st)) {
  4837. filep->size = (uint64_t)(st.st_size);
  4838. filep->last_modified = st.st_mtime;
  4839. filep->is_directory = S_ISDIR(st.st_mode);
  4840. return 1;
  4841. }
  4842. return 0;
  4843. }
  4844. #endif /* NO_FILESYSTEMS */
  4845. static void
  4846. set_close_on_exec(int fd,
  4847. const struct mg_connection *conn /* may be null */,
  4848. struct mg_context *ctx /* may be null */)
  4849. {
  4850. #if defined(__ZEPHYR__)
  4851. (void)fd;
  4852. (void)conn;
  4853. (void)ctx;
  4854. #else
  4855. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4856. if (conn || ctx) {
  4857. struct mg_connection fc;
  4858. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4859. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4860. __func__,
  4861. strerror(ERRNO));
  4862. }
  4863. }
  4864. #endif
  4865. }
  4866. CIVETWEB_API int
  4867. mg_start_thread(mg_thread_func_t func, void *param)
  4868. {
  4869. pthread_t thread_id;
  4870. pthread_attr_t attr;
  4871. int result;
  4872. (void)pthread_attr_init(&attr);
  4873. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4874. #if defined(__ZEPHYR__)
  4875. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4876. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4877. /* Compile-time option to control stack size,
  4878. * e.g. -DUSE_STACK_SIZE=16384 */
  4879. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4880. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4881. result = pthread_create(&thread_id, &attr, func, param);
  4882. pthread_attr_destroy(&attr);
  4883. return result;
  4884. }
  4885. /* Start a thread storing the thread context. */
  4886. static int
  4887. mg_start_thread_with_id(mg_thread_func_t func,
  4888. void *param,
  4889. pthread_t *threadidptr)
  4890. {
  4891. pthread_t thread_id;
  4892. pthread_attr_t attr;
  4893. int result;
  4894. (void)pthread_attr_init(&attr);
  4895. #if defined(__ZEPHYR__)
  4896. pthread_attr_setstack(&attr,
  4897. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4898. ZEPHYR_STACK_SIZE);
  4899. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4900. /* Compile-time option to control stack size,
  4901. * e.g. -DUSE_STACK_SIZE=16384 */
  4902. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4903. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4904. result = pthread_create(&thread_id, &attr, func, param);
  4905. pthread_attr_destroy(&attr);
  4906. if ((result == 0) && (threadidptr != NULL)) {
  4907. *threadidptr = thread_id;
  4908. }
  4909. return result;
  4910. }
  4911. /* Wait for a thread to finish. */
  4912. static int
  4913. mg_join_thread(pthread_t threadid)
  4914. {
  4915. int result;
  4916. result = pthread_join(threadid, NULL);
  4917. return result;
  4918. }
  4919. #if !defined(NO_CGI)
  4920. static pid_t
  4921. spawn_process(struct mg_connection *conn,
  4922. const char *prog,
  4923. char *envblk,
  4924. char *envp[],
  4925. int fdin[2],
  4926. int fdout[2],
  4927. int fderr[2],
  4928. const char *dir,
  4929. int cgi_config_idx)
  4930. {
  4931. pid_t pid;
  4932. const char *interp;
  4933. (void)envblk;
  4934. if ((pid = fork()) == -1) {
  4935. /* Parent */
  4936. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4937. } else if (pid != 0) {
  4938. /* Make sure children close parent-side descriptors.
  4939. * The caller will close the child-side immediately. */
  4940. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4941. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4942. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4943. } else {
  4944. /* Child */
  4945. if (chdir(dir) != 0) {
  4946. mg_cry_internal(
  4947. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4948. } else if (dup2(fdin[0], 0) == -1) {
  4949. mg_cry_internal(conn,
  4950. "%s: dup2(%d, 0): %s",
  4951. __func__,
  4952. fdin[0],
  4953. strerror(ERRNO));
  4954. } else if (dup2(fdout[1], 1) == -1) {
  4955. mg_cry_internal(conn,
  4956. "%s: dup2(%d, 1): %s",
  4957. __func__,
  4958. fdout[1],
  4959. strerror(ERRNO));
  4960. } else if (dup2(fderr[1], 2) == -1) {
  4961. mg_cry_internal(conn,
  4962. "%s: dup2(%d, 2): %s",
  4963. __func__,
  4964. fderr[1],
  4965. strerror(ERRNO));
  4966. } else {
  4967. struct sigaction sa;
  4968. /* Keep stderr and stdout in two different pipes.
  4969. * Stdout will be sent back to the client,
  4970. * stderr should go into a server error log. */
  4971. (void)close(fdin[0]);
  4972. (void)close(fdout[1]);
  4973. (void)close(fderr[1]);
  4974. /* Close write end fdin and read end fdout and fderr */
  4975. (void)close(fdin[1]);
  4976. (void)close(fdout[0]);
  4977. (void)close(fderr[0]);
  4978. /* After exec, all signal handlers are restored to their default
  4979. * values, with one exception of SIGCHLD. According to
  4980. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4981. * will leave unchanged after exec if it was set to be ignored.
  4982. * Restore it to default action. */
  4983. memset(&sa, 0, sizeof(sa));
  4984. sa.sa_handler = SIG_DFL;
  4985. sigaction(SIGCHLD, &sa, NULL);
  4986. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4987. if (interp == NULL) {
  4988. /* no interpreter configured, call the program directly */
  4989. (void)execle(prog, prog, NULL, envp);
  4990. mg_cry_internal(conn,
  4991. "%s: execle(%s): %s",
  4992. __func__,
  4993. prog,
  4994. strerror(ERRNO));
  4995. } else {
  4996. /* call the configured interpreter */
  4997. const char *interp_args =
  4998. conn->dom_ctx
  4999. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5000. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5001. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5002. } else {
  5003. (void)execle(interp, interp, prog, NULL, envp);
  5004. }
  5005. mg_cry_internal(conn,
  5006. "%s: execle(%s %s): %s",
  5007. __func__,
  5008. interp,
  5009. prog,
  5010. strerror(ERRNO));
  5011. }
  5012. }
  5013. exit(EXIT_FAILURE);
  5014. }
  5015. return pid;
  5016. }
  5017. #endif /* !NO_CGI */
  5018. static int
  5019. set_non_blocking_mode(SOCKET sock)
  5020. {
  5021. int flags = fcntl(sock, F_GETFL, 0);
  5022. if (flags < 0) {
  5023. return -1;
  5024. }
  5025. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5026. return -1;
  5027. }
  5028. return 0;
  5029. }
  5030. static int
  5031. set_blocking_mode(SOCKET sock)
  5032. {
  5033. int flags = fcntl(sock, F_GETFL, 0);
  5034. if (flags < 0) {
  5035. return -1;
  5036. }
  5037. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5038. return -1;
  5039. }
  5040. return 0;
  5041. }
  5042. #endif /* _WIN32 / else */
  5043. /* End of initial operating system specific define block. */
  5044. /* Get a random number (independent of C rand function) */
  5045. static uint64_t
  5046. get_random(void)
  5047. {
  5048. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5049. static uint64_t lcg = 0; /* Linear congruential generator */
  5050. uint64_t now = mg_get_current_time_ns();
  5051. if (lfsr == 0) {
  5052. /* lfsr will be only 0 if has not been initialized,
  5053. * so this code is called only once. */
  5054. lfsr = mg_get_current_time_ns();
  5055. lcg = mg_get_current_time_ns();
  5056. } else {
  5057. /* Get the next step of both random number generators. */
  5058. lfsr = (lfsr >> 1)
  5059. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5060. << 63);
  5061. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5062. }
  5063. /* Combining two pseudo-random number generators and a high resolution
  5064. * part
  5065. * of the current server time will make it hard (impossible?) to guess
  5066. * the
  5067. * next number. */
  5068. return (lfsr ^ lcg ^ now);
  5069. }
  5070. static int
  5071. mg_poll(struct mg_pollfd *pfd,
  5072. unsigned int n,
  5073. int milliseconds,
  5074. const stop_flag_t *stop_flag)
  5075. {
  5076. /* Call poll, but only for a maximum time of a few seconds.
  5077. * This will allow to stop the server after some seconds, instead
  5078. * of having to wait for a long socket timeout. */
  5079. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5080. int check_pollerr = 0;
  5081. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5082. /* If we wait for only one file descriptor, wait on error as well */
  5083. pfd[0].events |= POLLERR;
  5084. check_pollerr = 1;
  5085. }
  5086. do {
  5087. int result;
  5088. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5089. /* Shut down signal */
  5090. return -2;
  5091. }
  5092. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5093. ms_now = milliseconds;
  5094. }
  5095. result = poll(pfd, n, ms_now);
  5096. if (result != 0) {
  5097. int err = ERRNO;
  5098. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5099. /* Poll returned either success (1) or error (-1).
  5100. * Forward both to the caller. */
  5101. if ((check_pollerr)
  5102. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5103. == POLLERR)) {
  5104. /* One and only file descriptor returned error */
  5105. return -1;
  5106. }
  5107. return result;
  5108. }
  5109. }
  5110. /* Poll returned timeout (0). */
  5111. if (milliseconds > 0) {
  5112. milliseconds -= ms_now;
  5113. }
  5114. } while (milliseconds > 0);
  5115. /* timeout: return 0 */
  5116. return 0;
  5117. }
  5118. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5119. * descriptor.
  5120. * Return value:
  5121. * >=0 .. number of bytes successfully written
  5122. * -1 .. timeout
  5123. * -2 .. error
  5124. */
  5125. static int
  5126. push_inner(struct mg_context *ctx,
  5127. FILE *fp,
  5128. SOCKET sock,
  5129. SSL *ssl,
  5130. const char *buf,
  5131. int len,
  5132. double timeout)
  5133. {
  5134. uint64_t start = 0, now = 0, timeout_ns = 0;
  5135. int n, err;
  5136. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5137. #if defined(_WIN32)
  5138. typedef int len_t;
  5139. #else
  5140. typedef size_t len_t;
  5141. #endif
  5142. if (timeout > 0) {
  5143. now = mg_get_current_time_ns();
  5144. start = now;
  5145. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5146. }
  5147. if (ctx == NULL) {
  5148. return -2;
  5149. }
  5150. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5151. if (ssl) {
  5152. return -2;
  5153. }
  5154. #endif
  5155. /* Try to read until it succeeds, fails, times out, or the server
  5156. * shuts down. */
  5157. for (;;) {
  5158. #if defined(USE_MBEDTLS)
  5159. if (ssl != NULL) {
  5160. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5161. if (n <= 0) {
  5162. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5163. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5164. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5165. n = 0;
  5166. } else {
  5167. fprintf(stderr, "SSL write failed, error %d\n", n);
  5168. return -2;
  5169. }
  5170. } else {
  5171. err = 0;
  5172. }
  5173. } else
  5174. #elif !defined(NO_SSL)
  5175. if (ssl != NULL) {
  5176. ERR_clear_error();
  5177. n = SSL_write(ssl, buf, len);
  5178. if (n <= 0) {
  5179. err = SSL_get_error(ssl, n);
  5180. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5181. err = ERRNO;
  5182. } else if ((err == SSL_ERROR_WANT_READ)
  5183. || (err == SSL_ERROR_WANT_WRITE)) {
  5184. n = 0;
  5185. } else {
  5186. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5187. ERR_clear_error();
  5188. return -2;
  5189. }
  5190. ERR_clear_error();
  5191. } else {
  5192. err = 0;
  5193. }
  5194. } else
  5195. #endif
  5196. if (fp != NULL) {
  5197. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5198. if (ferror(fp)) {
  5199. n = -1;
  5200. err = ERRNO;
  5201. } else {
  5202. err = 0;
  5203. }
  5204. } else {
  5205. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5206. err = (n < 0) ? ERRNO : 0;
  5207. if (ERROR_TRY_AGAIN(err)) {
  5208. err = 0;
  5209. n = 0;
  5210. }
  5211. if (n < 0) {
  5212. /* shutdown of the socket at client side */
  5213. return -2;
  5214. }
  5215. }
  5216. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5217. return -2;
  5218. }
  5219. if ((n > 0) || ((n == 0) && (len == 0))) {
  5220. /* some data has been read, or no data was requested */
  5221. return n;
  5222. }
  5223. if (n < 0) {
  5224. /* socket error - check errno */
  5225. DEBUG_TRACE("send() failed, error %d", err);
  5226. /* TODO (mid): error handling depending on the error code.
  5227. * These codes are different between Windows and Linux.
  5228. * Currently there is no problem with failing send calls,
  5229. * if there is a reproducible situation, it should be
  5230. * investigated in detail.
  5231. */
  5232. return -2;
  5233. }
  5234. /* Only in case n=0 (timeout), repeat calling the write function */
  5235. /* If send failed, wait before retry */
  5236. if (fp != NULL) {
  5237. /* For files, just wait a fixed time.
  5238. * Maybe it helps, maybe not. */
  5239. mg_sleep(5);
  5240. } else {
  5241. /* For sockets, wait for the socket using poll */
  5242. struct mg_pollfd pfd[2];
  5243. int pollres;
  5244. pfd[0].fd = sock;
  5245. pfd[0].events = POLLOUT;
  5246. pfd[1].fd = ctx->thread_shutdown_notification_socket;
  5247. pfd[1].events = POLLIN;
  5248. pollres = mg_poll(pfd, 2, (int)(ms_wait), &(ctx->stop_flag));
  5249. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5250. return -2;
  5251. }
  5252. if (pollres > 0) {
  5253. continue;
  5254. }
  5255. }
  5256. if (timeout > 0) {
  5257. now = mg_get_current_time_ns();
  5258. if ((now - start) > timeout_ns) {
  5259. /* Timeout */
  5260. break;
  5261. }
  5262. }
  5263. }
  5264. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5265. used */
  5266. return -1;
  5267. }
  5268. static int
  5269. push_all(struct mg_context *ctx,
  5270. FILE *fp,
  5271. SOCKET sock,
  5272. SSL *ssl,
  5273. const char *buf,
  5274. int len)
  5275. {
  5276. double timeout = -1.0;
  5277. int n, nwritten = 0;
  5278. if (ctx == NULL) {
  5279. return -1;
  5280. }
  5281. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5282. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5283. }
  5284. if (timeout <= 0.0) {
  5285. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5286. / 1000.0;
  5287. }
  5288. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5289. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5290. if (n < 0) {
  5291. if (nwritten == 0) {
  5292. nwritten = -1; /* Propagate the error */
  5293. }
  5294. break;
  5295. } else if (n == 0) {
  5296. break; /* No more data to write */
  5297. } else {
  5298. nwritten += n;
  5299. len -= n;
  5300. }
  5301. }
  5302. return nwritten;
  5303. }
  5304. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5305. * Return value:
  5306. * >=0 .. number of bytes successfully read
  5307. * -1 .. timeout
  5308. * -2 .. error
  5309. */
  5310. static int
  5311. pull_inner(FILE *fp,
  5312. struct mg_connection *conn,
  5313. char *buf,
  5314. int len,
  5315. double timeout)
  5316. {
  5317. int nread, err = 0;
  5318. #if defined(_WIN32)
  5319. typedef int len_t;
  5320. #else
  5321. typedef size_t len_t;
  5322. #endif
  5323. /* We need an additional wait loop around this, because in some cases
  5324. * with TLSwe may get data from the socket but not from SSL_read.
  5325. * In this case we need to repeat at least once.
  5326. */
  5327. if (fp != NULL) {
  5328. /* Use read() instead of fread(), because if we're reading from the
  5329. * CGI pipe, fread() may block until IO buffer is filled up. We
  5330. * cannot afford to block and must pass all read bytes immediately
  5331. * to the client. */
  5332. nread = (int)read(fileno(fp), buf, (size_t)len);
  5333. err = (nread < 0) ? ERRNO : 0;
  5334. if ((nread == 0) && (len > 0)) {
  5335. /* Should get data, but got EOL */
  5336. return -2;
  5337. }
  5338. #if defined(USE_MBEDTLS)
  5339. } else if (conn->ssl != NULL) {
  5340. struct mg_pollfd pfd[2];
  5341. int to_read;
  5342. int pollres;
  5343. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5344. if (to_read > 0) {
  5345. /* We already know there is no more data buffered in conn->buf
  5346. * but there is more available in the SSL layer. So don't poll
  5347. * conn->client.sock yet. */
  5348. pollres = 1;
  5349. if (to_read > len)
  5350. to_read = len;
  5351. } else {
  5352. pfd[0].fd = conn->client.sock;
  5353. pfd[0].events = POLLIN;
  5354. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5355. pfd[1].events = POLLIN;
  5356. to_read = len;
  5357. pollres = mg_poll(pfd,
  5358. 2,
  5359. (int)(timeout * 1000.0),
  5360. &(conn->phys_ctx->stop_flag));
  5361. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5362. return -2;
  5363. }
  5364. }
  5365. if (pollres > 0) {
  5366. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5367. if (nread <= 0) {
  5368. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5369. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5370. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5371. nread = 0;
  5372. } else {
  5373. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5374. return -2;
  5375. }
  5376. } else {
  5377. err = 0;
  5378. }
  5379. } else if (pollres < 0) {
  5380. /* Error */
  5381. return -2;
  5382. } else {
  5383. /* pollres = 0 means timeout */
  5384. nread = 0;
  5385. }
  5386. #elif !defined(NO_SSL)
  5387. } else if (conn->ssl != NULL) {
  5388. int ssl_pending;
  5389. struct mg_pollfd pfd[2];
  5390. int pollres;
  5391. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5392. /* We already know there is no more data buffered in conn->buf
  5393. * but there is more available in the SSL layer. So don't poll
  5394. * conn->client.sock yet. */
  5395. if (ssl_pending > len) {
  5396. ssl_pending = len;
  5397. }
  5398. pollres = 1;
  5399. } else {
  5400. pfd[0].fd = conn->client.sock;
  5401. pfd[0].events = POLLIN;
  5402. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5403. pfd[1].events = POLLIN;
  5404. pollres = mg_poll(pfd,
  5405. 2,
  5406. (int)(timeout * 1000.0),
  5407. &(conn->phys_ctx->stop_flag));
  5408. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5409. return -2;
  5410. }
  5411. }
  5412. if (pollres > 0) {
  5413. ERR_clear_error();
  5414. nread =
  5415. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5416. if (nread <= 0) {
  5417. err = SSL_get_error(conn->ssl, nread);
  5418. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5419. err = ERRNO;
  5420. } else if ((err == SSL_ERROR_WANT_READ)
  5421. || (err == SSL_ERROR_WANT_WRITE)) {
  5422. nread = 0;
  5423. } else {
  5424. /* All errors should return -2 */
  5425. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5426. ERR_clear_error();
  5427. return -2;
  5428. }
  5429. ERR_clear_error();
  5430. } else {
  5431. err = 0;
  5432. }
  5433. } else if (pollres < 0) {
  5434. /* Error */
  5435. return -2;
  5436. } else {
  5437. /* pollres = 0 means timeout */
  5438. nread = 0;
  5439. }
  5440. #endif
  5441. } else {
  5442. struct mg_pollfd pfd[2];
  5443. int pollres;
  5444. pfd[0].fd = conn->client.sock;
  5445. pfd[0].events = POLLIN;
  5446. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5447. pfd[1].events = POLLIN;
  5448. pollres = mg_poll(pfd,
  5449. 2,
  5450. (int)(timeout * 1000.0),
  5451. &(conn->phys_ctx->stop_flag));
  5452. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5453. return -2;
  5454. }
  5455. if (pollres > 0) {
  5456. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5457. err = (nread < 0) ? ERRNO : 0;
  5458. if (nread <= 0) {
  5459. /* shutdown of the socket at client side */
  5460. return -2;
  5461. }
  5462. } else if (pollres < 0) {
  5463. /* error calling poll */
  5464. return -2;
  5465. } else {
  5466. /* pollres = 0 means timeout */
  5467. nread = 0;
  5468. }
  5469. }
  5470. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5471. return -2;
  5472. }
  5473. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5474. /* some data has been read, or no data was requested */
  5475. return nread;
  5476. }
  5477. if (nread < 0) {
  5478. /* socket error - check errno */
  5479. #if defined(_WIN32)
  5480. if (err == WSAEWOULDBLOCK) {
  5481. /* TODO (low): check if this is still required */
  5482. /* standard case if called from close_socket_gracefully */
  5483. return -2;
  5484. } else if (err == WSAETIMEDOUT) {
  5485. /* TODO (low): check if this is still required */
  5486. /* timeout is handled by the while loop */
  5487. return 0;
  5488. } else if (err == WSAECONNABORTED) {
  5489. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5490. return -2;
  5491. } else {
  5492. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5493. return -2;
  5494. }
  5495. #else
  5496. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5497. * if the timeout is reached and if the socket was set to non-
  5498. * blocking in close_socket_gracefully, so we can not distinguish
  5499. * here. We have to wait for the timeout in both cases for now.
  5500. */
  5501. if (ERROR_TRY_AGAIN(err)) {
  5502. /* TODO (low): check if this is still required */
  5503. /* EAGAIN/EWOULDBLOCK:
  5504. * standard case if called from close_socket_gracefully
  5505. * => should return -1 */
  5506. /* or timeout occurred
  5507. * => the code must stay in the while loop */
  5508. /* EINTR can be generated on a socket with a timeout set even
  5509. * when SA_RESTART is effective for all relevant signals
  5510. * (see signal(7)).
  5511. * => stay in the while loop */
  5512. } else {
  5513. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5514. return -2;
  5515. }
  5516. #endif
  5517. }
  5518. /* Timeout occurred, but no data available. */
  5519. return -1;
  5520. }
  5521. static int
  5522. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5523. {
  5524. int n, nread = 0;
  5525. double timeout = -1.0;
  5526. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5527. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5528. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5529. }
  5530. if (timeout <= 0.0) {
  5531. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5532. / 1000.0;
  5533. }
  5534. start_time = mg_get_current_time_ns();
  5535. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5536. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5537. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5538. if (n == -2) {
  5539. if (nread == 0) {
  5540. nread = -1; /* Propagate the error */
  5541. }
  5542. break;
  5543. } else if (n == -1) {
  5544. /* timeout */
  5545. if (timeout >= 0.0) {
  5546. now = mg_get_current_time_ns();
  5547. if ((now - start_time) <= timeout_ns) {
  5548. continue;
  5549. }
  5550. }
  5551. break;
  5552. } else if (n == 0) {
  5553. break; /* No more data to read */
  5554. } else {
  5555. nread += n;
  5556. len -= n;
  5557. }
  5558. }
  5559. return nread;
  5560. }
  5561. static void
  5562. discard_unread_request_data(struct mg_connection *conn)
  5563. {
  5564. char buf[MG_BUF_LEN];
  5565. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5566. ;
  5567. }
  5568. static int
  5569. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5570. {
  5571. int64_t content_len, n, buffered_len, nread;
  5572. int64_t len64 =
  5573. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5574. * int, we may not read more
  5575. * bytes */
  5576. const char *body;
  5577. if (conn == NULL) {
  5578. return 0;
  5579. }
  5580. /* If Content-Length is not set for a response with body data,
  5581. * we do not know in advance how much data should be read. */
  5582. content_len = conn->content_len;
  5583. if (content_len < 0) {
  5584. /* The body data is completed when the connection is closed. */
  5585. content_len = INT64_MAX;
  5586. }
  5587. nread = 0;
  5588. if (conn->consumed_content < content_len) {
  5589. /* Adjust number of bytes to read. */
  5590. int64_t left_to_read = content_len - conn->consumed_content;
  5591. if (left_to_read < len64) {
  5592. /* Do not read more than the total content length of the
  5593. * request.
  5594. */
  5595. len64 = left_to_read;
  5596. }
  5597. /* Return buffered data */
  5598. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5599. - conn->consumed_content;
  5600. if (buffered_len > 0) {
  5601. if (len64 < buffered_len) {
  5602. buffered_len = len64;
  5603. }
  5604. body = conn->buf + conn->request_len + conn->consumed_content;
  5605. memcpy(buf, body, (size_t)buffered_len);
  5606. len64 -= buffered_len;
  5607. conn->consumed_content += buffered_len;
  5608. nread += buffered_len;
  5609. buf = (char *)buf + buffered_len;
  5610. }
  5611. /* We have returned all buffered data. Read new data from the remote
  5612. * socket.
  5613. */
  5614. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5615. conn->consumed_content += n;
  5616. nread += n;
  5617. } else {
  5618. nread = ((nread > 0) ? nread : n);
  5619. }
  5620. }
  5621. return (int)nread;
  5622. }
  5623. /* Forward declarations */
  5624. static void handle_request(struct mg_connection *);
  5625. static void log_access(const struct mg_connection *);
  5626. /* Handle request, update statistics and call access log */
  5627. static void
  5628. handle_request_stat_log(struct mg_connection *conn)
  5629. {
  5630. #if defined(USE_SERVER_STATS)
  5631. struct timespec tnow;
  5632. conn->conn_state = 4; /* processing */
  5633. #endif
  5634. handle_request(conn);
  5635. #if defined(USE_SERVER_STATS)
  5636. conn->conn_state = 5; /* processed */
  5637. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5638. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5639. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5640. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5641. conn->num_bytes_sent);
  5642. #endif
  5643. DEBUG_TRACE("%s", "handle_request done");
  5644. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5645. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5646. DEBUG_TRACE("%s", "end_request callback done");
  5647. }
  5648. log_access(conn);
  5649. }
  5650. #if defined(USE_HTTP2)
  5651. #if defined(NO_SSL)
  5652. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5653. #endif
  5654. #define USE_ALPN
  5655. #include "http2.inl"
  5656. /* Not supported with HTTP/2 */
  5657. #define HTTP1_only \
  5658. { \
  5659. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5660. http2_must_use_http1(conn); \
  5661. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5662. return; \
  5663. } \
  5664. }
  5665. #else
  5666. #define HTTP1_only
  5667. #endif
  5668. CIVETWEB_API int
  5669. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5670. {
  5671. if (len > INT_MAX) {
  5672. len = INT_MAX;
  5673. }
  5674. if (conn == NULL) {
  5675. return 0;
  5676. }
  5677. if (conn->is_chunked) {
  5678. size_t all_read = 0;
  5679. while (len > 0) {
  5680. if (conn->is_chunked >= 3) {
  5681. /* No more data left to read */
  5682. return 0;
  5683. }
  5684. if (conn->is_chunked != 1) {
  5685. /* Has error */
  5686. return -1;
  5687. }
  5688. if (conn->consumed_content != conn->content_len) {
  5689. /* copy from the current chunk */
  5690. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5691. if (read_ret < 1) {
  5692. /* read error */
  5693. conn->is_chunked = 2;
  5694. return -1;
  5695. }
  5696. all_read += (size_t)read_ret;
  5697. len -= (size_t)read_ret;
  5698. if (conn->consumed_content == conn->content_len) {
  5699. /* Add data bytes in the current chunk have been read,
  5700. * so we are expecting \r\n now. */
  5701. char x[2];
  5702. conn->content_len += 2;
  5703. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5704. || (x[1] != '\n')) {
  5705. /* Protocol violation */
  5706. conn->is_chunked = 2;
  5707. return -1;
  5708. }
  5709. }
  5710. } else {
  5711. /* fetch a new chunk */
  5712. size_t i;
  5713. char lenbuf[64];
  5714. char *end = NULL;
  5715. unsigned long chunkSize = 0;
  5716. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5717. conn->content_len++;
  5718. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5719. lenbuf[i] = 0;
  5720. }
  5721. if ((i > 0) && (lenbuf[i] == ';')) {
  5722. // chunk extension --> skip chars until next CR
  5723. //
  5724. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5725. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5726. //
  5727. // chunk = chunk-size [ chunk-extension ] CRLF
  5728. // chunk-data CRLF
  5729. // ...
  5730. // chunk-extension= *( ";" chunk-ext-name [ "="
  5731. // chunk-ext-val ] )
  5732. do
  5733. ++conn->content_len;
  5734. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5735. && lenbuf[i] != '\r');
  5736. }
  5737. if ((i > 0) && (lenbuf[i] == '\r')
  5738. && (lenbuf[i - 1] != '\r')) {
  5739. continue;
  5740. }
  5741. if ((i > 1) && (lenbuf[i] == '\n')
  5742. && (lenbuf[i - 1] == '\r')) {
  5743. lenbuf[i + 1] = 0;
  5744. chunkSize = strtoul(lenbuf, &end, 16);
  5745. if (chunkSize == 0) {
  5746. /* regular end of content */
  5747. conn->is_chunked = 3;
  5748. }
  5749. break;
  5750. }
  5751. if (!isxdigit((unsigned char)lenbuf[i])) {
  5752. /* illegal character for chunk length */
  5753. conn->is_chunked = 2;
  5754. return -1;
  5755. }
  5756. }
  5757. if ((end == NULL) || (*end != '\r')) {
  5758. /* chunksize not set correctly */
  5759. conn->is_chunked = 2;
  5760. return -1;
  5761. }
  5762. if (conn->is_chunked == 3) {
  5763. /* try discarding trailer for keep-alive */
  5764. // We found the last chunk (length 0) including the
  5765. // CRLF that terminates that chunk. Now follows a possibly
  5766. // empty trailer and a final CRLF.
  5767. //
  5768. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5769. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5770. //
  5771. // Chunked-Body = *chunk
  5772. // last-chunk
  5773. // trailer
  5774. // CRLF
  5775. // ...
  5776. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5777. // ...
  5778. // trailer = *(entity-header CRLF)
  5779. int crlf_count = 2; // one CRLF already determined
  5780. while (crlf_count < 4 && conn->is_chunked == 3) {
  5781. ++conn->content_len;
  5782. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5783. if ((crlf_count == 0 || crlf_count == 2)) {
  5784. if (lenbuf[0] == '\r')
  5785. ++crlf_count;
  5786. else
  5787. crlf_count = 0;
  5788. } else {
  5789. // previous character was a CR
  5790. // --> next character must be LF
  5791. if (lenbuf[0] == '\n')
  5792. ++crlf_count;
  5793. else
  5794. conn->is_chunked = 2;
  5795. }
  5796. } else
  5797. // premature end of trailer
  5798. conn->is_chunked = 2;
  5799. }
  5800. if (conn->is_chunked == 2)
  5801. return -1;
  5802. else
  5803. conn->is_chunked = 4;
  5804. break;
  5805. }
  5806. /* append a new chunk */
  5807. conn->content_len += (int64_t)chunkSize;
  5808. }
  5809. }
  5810. return (int)all_read;
  5811. }
  5812. return mg_read_inner(conn, buf, len);
  5813. }
  5814. CIVETWEB_API int
  5815. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5816. {
  5817. time_t now;
  5818. int n, total, allowed;
  5819. if (conn == NULL) {
  5820. return 0;
  5821. }
  5822. if (len > INT_MAX) {
  5823. return -1;
  5824. }
  5825. /* Mark connection as "data sent" */
  5826. conn->request_state = 10;
  5827. #if defined(USE_HTTP2)
  5828. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5829. http2_data_frame_head(conn, len, 0);
  5830. }
  5831. #endif
  5832. if (conn->throttle > 0) {
  5833. if ((now = time(NULL)) != conn->last_throttle_time) {
  5834. conn->last_throttle_time = now;
  5835. conn->last_throttle_bytes = 0;
  5836. }
  5837. allowed = conn->throttle - conn->last_throttle_bytes;
  5838. if (allowed > (int)len) {
  5839. allowed = (int)len;
  5840. }
  5841. total = push_all(conn->phys_ctx,
  5842. NULL,
  5843. conn->client.sock,
  5844. conn->ssl,
  5845. (const char *)buf,
  5846. allowed);
  5847. if (total == allowed) {
  5848. buf = (const char *)buf + total;
  5849. conn->last_throttle_bytes += total;
  5850. while ((total < (int)len)
  5851. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5852. allowed = (conn->throttle > ((int)len - total))
  5853. ? (int)len - total
  5854. : conn->throttle;
  5855. n = push_all(conn->phys_ctx,
  5856. NULL,
  5857. conn->client.sock,
  5858. conn->ssl,
  5859. (const char *)buf,
  5860. allowed);
  5861. if (n != allowed) {
  5862. break;
  5863. }
  5864. sleep(1);
  5865. conn->last_throttle_bytes = allowed;
  5866. conn->last_throttle_time = time(NULL);
  5867. buf = (const char *)buf + n;
  5868. total += n;
  5869. }
  5870. }
  5871. } else {
  5872. total = push_all(conn->phys_ctx,
  5873. NULL,
  5874. conn->client.sock,
  5875. conn->ssl,
  5876. (const char *)buf,
  5877. (int)len);
  5878. }
  5879. if (total > 0) {
  5880. conn->num_bytes_sent += total;
  5881. }
  5882. return total;
  5883. }
  5884. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5885. CIVETWEB_API int
  5886. mg_send_chunk(struct mg_connection *conn,
  5887. const char *chunk,
  5888. unsigned int chunk_len)
  5889. {
  5890. char lenbuf[16];
  5891. size_t lenbuf_len;
  5892. int ret;
  5893. int t;
  5894. /* First store the length information in a text buffer. */
  5895. sprintf(lenbuf, "%x\r\n", chunk_len);
  5896. lenbuf_len = strlen(lenbuf);
  5897. /* Then send length information, chunk and terminating \r\n. */
  5898. ret = mg_write(conn, lenbuf, lenbuf_len);
  5899. if (ret != (int)lenbuf_len) {
  5900. return -1;
  5901. }
  5902. t = ret;
  5903. ret = mg_write(conn, chunk, chunk_len);
  5904. if (ret != (int)chunk_len) {
  5905. return -1;
  5906. }
  5907. t += ret;
  5908. ret = mg_write(conn, "\r\n", 2);
  5909. if (ret != 2) {
  5910. return -1;
  5911. }
  5912. t += ret;
  5913. return t;
  5914. }
  5915. #if defined(GCC_DIAGNOSTIC)
  5916. /* This block forwards format strings to printf implementations,
  5917. * so we need to disable the format-nonliteral warning. */
  5918. #pragma GCC diagnostic push
  5919. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5920. #endif
  5921. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5922. static int
  5923. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5924. {
  5925. va_list ap_copy;
  5926. size_t size = MG_BUF_LEN / 4;
  5927. int len = -1;
  5928. *buf = NULL;
  5929. while (len < 0) {
  5930. if (*buf) {
  5931. mg_free(*buf);
  5932. }
  5933. size *= 4;
  5934. *buf = (char *)mg_malloc(size);
  5935. if (!*buf) {
  5936. break;
  5937. }
  5938. va_copy(ap_copy, ap);
  5939. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5940. va_end(ap_copy);
  5941. (*buf)[size - 1] = 0;
  5942. }
  5943. return len;
  5944. }
  5945. /* Print message to buffer. If buffer is large enough to hold the message,
  5946. * return buffer. If buffer is to small, allocate large enough buffer on
  5947. * heap,
  5948. * and return allocated buffer. */
  5949. static int
  5950. alloc_vprintf(char **out_buf,
  5951. char *prealloc_buf,
  5952. size_t prealloc_size,
  5953. const char *fmt,
  5954. va_list ap)
  5955. {
  5956. va_list ap_copy;
  5957. int len;
  5958. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5959. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5960. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5961. * Therefore, we make two passes: on first pass, get required message
  5962. * length.
  5963. * On second pass, actually print the message. */
  5964. va_copy(ap_copy, ap);
  5965. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5966. va_end(ap_copy);
  5967. if (len < 0) {
  5968. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5969. * Switch to alternative code path that uses incremental
  5970. * allocations.
  5971. */
  5972. va_copy(ap_copy, ap);
  5973. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5974. va_end(ap_copy);
  5975. } else if ((size_t)(len) >= prealloc_size) {
  5976. /* The pre-allocated buffer not large enough. */
  5977. /* Allocate a new buffer. */
  5978. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5979. if (!*out_buf) {
  5980. /* Allocation failed. Return -1 as "out of memory" error. */
  5981. return -1;
  5982. }
  5983. /* Buffer allocation successful. Store the string there. */
  5984. va_copy(ap_copy, ap);
  5985. IGNORE_UNUSED_RESULT(
  5986. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5987. va_end(ap_copy);
  5988. } else {
  5989. /* The pre-allocated buffer is large enough.
  5990. * Use it to store the string and return the address. */
  5991. va_copy(ap_copy, ap);
  5992. IGNORE_UNUSED_RESULT(
  5993. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5994. va_end(ap_copy);
  5995. *out_buf = prealloc_buf;
  5996. }
  5997. return len;
  5998. }
  5999. static int
  6000. alloc_printf(char **out_buf, const char *fmt, ...)
  6001. {
  6002. va_list ap;
  6003. int result;
  6004. va_start(ap, fmt);
  6005. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6006. va_end(ap);
  6007. return result;
  6008. }
  6009. #if defined(GCC_DIAGNOSTIC)
  6010. /* Enable format-nonliteral warning again. */
  6011. #pragma GCC diagnostic pop
  6012. #endif
  6013. static int
  6014. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6015. {
  6016. char mem[MG_BUF_LEN];
  6017. char *buf = NULL;
  6018. int len;
  6019. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6020. len = mg_write(conn, buf, (size_t)len);
  6021. }
  6022. if (buf != mem) {
  6023. mg_free(buf);
  6024. }
  6025. return len;
  6026. }
  6027. CIVETWEB_API int
  6028. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6029. {
  6030. va_list ap;
  6031. int result;
  6032. va_start(ap, fmt);
  6033. result = mg_vprintf(conn, fmt, ap);
  6034. va_end(ap);
  6035. return result;
  6036. }
  6037. CIVETWEB_API int
  6038. mg_url_decode(const char *src,
  6039. int src_len,
  6040. char *dst,
  6041. int dst_len,
  6042. int is_form_url_encoded)
  6043. {
  6044. int i, j, a, b;
  6045. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6046. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6047. if ((i < src_len - 2) && (src[i] == '%')
  6048. && isxdigit((unsigned char)src[i + 1])
  6049. && isxdigit((unsigned char)src[i + 2])) {
  6050. a = tolower((unsigned char)src[i + 1]);
  6051. b = tolower((unsigned char)src[i + 2]);
  6052. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6053. i += 2;
  6054. } else if (is_form_url_encoded && (src[i] == '+')) {
  6055. dst[j] = ' ';
  6056. } else {
  6057. dst[j] = src[i];
  6058. }
  6059. }
  6060. dst[j] = '\0'; /* Null-terminate the destination */
  6061. return (i >= src_len) ? j : -1;
  6062. }
  6063. /* form url decoding of an entire string */
  6064. static void
  6065. url_decode_in_place(char *buf)
  6066. {
  6067. int len = (int)strlen(buf);
  6068. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6069. }
  6070. CIVETWEB_API int
  6071. mg_get_var(const char *data,
  6072. size_t data_len,
  6073. const char *name,
  6074. char *dst,
  6075. size_t dst_len)
  6076. {
  6077. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6078. }
  6079. CIVETWEB_API int
  6080. mg_get_var2(const char *data,
  6081. size_t data_len,
  6082. const char *name,
  6083. char *dst,
  6084. size_t dst_len,
  6085. size_t occurrence)
  6086. {
  6087. const char *p, *e, *s;
  6088. size_t name_len;
  6089. int len;
  6090. if ((dst == NULL) || (dst_len == 0)) {
  6091. len = -2;
  6092. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6093. len = -1;
  6094. dst[0] = '\0';
  6095. } else {
  6096. name_len = strlen(name);
  6097. e = data + data_len;
  6098. len = -1;
  6099. dst[0] = '\0';
  6100. /* data is "var1=val1&var2=val2...". Find variable first */
  6101. for (p = data; p + name_len < e; p++) {
  6102. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6103. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6104. /* Point p to variable value */
  6105. p += name_len + 1;
  6106. /* Point s to the end of the value */
  6107. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6108. if (s == NULL) {
  6109. s = e;
  6110. }
  6111. DEBUG_ASSERT(s >= p);
  6112. if (s < p) {
  6113. return -3;
  6114. }
  6115. /* Decode variable into destination buffer */
  6116. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6117. /* Redirect error code from -1 to -2 (destination buffer too
  6118. * small). */
  6119. if (len == -1) {
  6120. len = -2;
  6121. }
  6122. break;
  6123. }
  6124. }
  6125. }
  6126. return len;
  6127. }
  6128. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6129. CIVETWEB_API int
  6130. mg_split_form_urlencoded(char *data,
  6131. struct mg_header *form_fields,
  6132. unsigned num_form_fields)
  6133. {
  6134. char *b;
  6135. int i;
  6136. int num = 0;
  6137. if (data == NULL) {
  6138. /* parameter error */
  6139. return -1;
  6140. }
  6141. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6142. /* determine the number of expected fields */
  6143. if (data[0] == 0) {
  6144. return 0;
  6145. }
  6146. /* count number of & to return the number of key-value-pairs */
  6147. num = 1;
  6148. while (*data) {
  6149. if (*data == '&') {
  6150. num++;
  6151. }
  6152. data++;
  6153. }
  6154. return num;
  6155. }
  6156. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6157. /* parameter error */
  6158. return -1;
  6159. }
  6160. for (i = 0; i < (int)num_form_fields; i++) {
  6161. /* extract key-value pairs from input data */
  6162. while ((*data == ' ') || (*data == '\t')) {
  6163. /* skip initial spaces */
  6164. data++;
  6165. }
  6166. if (*data == 0) {
  6167. /* end of string reached */
  6168. break;
  6169. }
  6170. form_fields[num].name = data;
  6171. /* find & or = */
  6172. b = data;
  6173. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6174. b++;
  6175. }
  6176. if (*b == 0) {
  6177. /* last key without value */
  6178. form_fields[num].value = NULL;
  6179. } else if (*b == '&') {
  6180. /* mid key without value */
  6181. form_fields[num].value = NULL;
  6182. } else {
  6183. /* terminate string */
  6184. *b = 0;
  6185. /* value starts after '=' */
  6186. data = b + 1;
  6187. form_fields[num].value = data;
  6188. }
  6189. /* new field is stored */
  6190. num++;
  6191. /* find a next key */
  6192. b = strchr(data, '&');
  6193. if (b == 0) {
  6194. /* no more data */
  6195. break;
  6196. } else {
  6197. /* terminate value of last field at '&' */
  6198. *b = 0;
  6199. /* next key-value-pairs starts after '&' */
  6200. data = b + 1;
  6201. }
  6202. }
  6203. /* Decode all values */
  6204. for (i = 0; i < num; i++) {
  6205. if (form_fields[i].name) {
  6206. url_decode_in_place((char *)form_fields[i].name);
  6207. }
  6208. if (form_fields[i].value) {
  6209. url_decode_in_place((char *)form_fields[i].value);
  6210. }
  6211. }
  6212. /* return number of fields found */
  6213. return num;
  6214. }
  6215. /* HCP24: some changes to compare whole var_name */
  6216. CIVETWEB_API int
  6217. mg_get_cookie(const char *cookie_header,
  6218. const char *var_name,
  6219. char *dst,
  6220. size_t dst_size)
  6221. {
  6222. const char *s, *p, *end;
  6223. int name_len, len = -1;
  6224. if ((dst == NULL) || (dst_size == 0)) {
  6225. return -2;
  6226. }
  6227. dst[0] = '\0';
  6228. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6229. return -1;
  6230. }
  6231. name_len = (int)strlen(var_name);
  6232. end = s + strlen(s);
  6233. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6234. if (s[name_len] == '=') {
  6235. /* HCP24: now check is it a substring or a full cookie name */
  6236. if ((s == cookie_header) || (s[-1] == ' ')) {
  6237. s += name_len + 1;
  6238. if ((p = strchr(s, ' ')) == NULL) {
  6239. p = end;
  6240. }
  6241. if (p[-1] == ';') {
  6242. p--;
  6243. }
  6244. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6245. s++;
  6246. p--;
  6247. }
  6248. if ((size_t)(p - s) < dst_size) {
  6249. len = (int)(p - s);
  6250. mg_strlcpy(dst, s, (size_t)len + 1);
  6251. } else {
  6252. len = -3;
  6253. }
  6254. break;
  6255. }
  6256. }
  6257. }
  6258. return len;
  6259. }
  6260. CIVETWEB_API int
  6261. mg_base64_encode(const unsigned char *src,
  6262. size_t src_len,
  6263. char *dst,
  6264. size_t *dst_len)
  6265. {
  6266. static const char *b64 =
  6267. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6268. size_t i, j;
  6269. int a, b, c;
  6270. if (dst_len != NULL) {
  6271. /* Expected length including 0 termination: */
  6272. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6273. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6274. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6275. if (*dst_len < expected_len) {
  6276. if (*dst_len > 0) {
  6277. dst[0] = '\0';
  6278. }
  6279. *dst_len = expected_len;
  6280. return 0;
  6281. }
  6282. }
  6283. for (i = j = 0; i < src_len; i += 3) {
  6284. a = src[i];
  6285. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6286. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6287. dst[j++] = b64[a >> 2];
  6288. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6289. if (i + 1 < src_len) {
  6290. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6291. }
  6292. if (i + 2 < src_len) {
  6293. dst[j++] = b64[c & 63];
  6294. }
  6295. }
  6296. while (j % 4 != 0) {
  6297. dst[j++] = '=';
  6298. }
  6299. dst[j++] = '\0';
  6300. if (dst_len != NULL) {
  6301. *dst_len = (size_t)j;
  6302. }
  6303. /* Return -1 for "OK" */
  6304. return -1;
  6305. }
  6306. static unsigned char
  6307. b64reverse(char letter)
  6308. {
  6309. if ((letter >= 'A') && (letter <= 'Z')) {
  6310. return (unsigned char)(letter - 'A');
  6311. }
  6312. if ((letter >= 'a') && (letter <= 'z')) {
  6313. return (unsigned char)(letter - 'a' + 26);
  6314. }
  6315. if ((letter >= '0') && (letter <= '9')) {
  6316. return (unsigned char)(letter - '0' + 52);
  6317. }
  6318. if (letter == '+') {
  6319. return 62;
  6320. }
  6321. if (letter == '/') {
  6322. return 63;
  6323. }
  6324. if (letter == '=') {
  6325. return 255; /* normal end */
  6326. }
  6327. return 254; /* error */
  6328. }
  6329. CIVETWEB_API int
  6330. mg_base64_decode(const char *src,
  6331. size_t src_len,
  6332. unsigned char *dst,
  6333. size_t *dst_len)
  6334. {
  6335. size_t i;
  6336. unsigned char a, b, c, d;
  6337. size_t dst_len_limit = (size_t)-1;
  6338. size_t dst_len_used = 0;
  6339. if (dst_len != NULL) {
  6340. dst_len_limit = *dst_len;
  6341. *dst_len = 0;
  6342. }
  6343. for (i = 0; i < src_len; i += 4) {
  6344. /* Read 4 characters from BASE64 string */
  6345. a = b64reverse(src[i]);
  6346. if (a >= 254) {
  6347. return (int)i;
  6348. }
  6349. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6350. if (b >= 254) {
  6351. return (int)i + 1;
  6352. }
  6353. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6354. if (c == 254) {
  6355. return (int)i + 2;
  6356. }
  6357. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6358. if (d == 254) {
  6359. return (int)i + 3;
  6360. }
  6361. /* Add first (of 3) decoded character */
  6362. if (dst_len_used < dst_len_limit) {
  6363. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6364. + (unsigned char)(b >> 4));
  6365. }
  6366. dst_len_used++;
  6367. if (c != 255) {
  6368. if (dst_len_used < dst_len_limit) {
  6369. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6370. + (unsigned char)(c >> 2));
  6371. }
  6372. dst_len_used++;
  6373. if (d != 255) {
  6374. if (dst_len_used < dst_len_limit) {
  6375. dst[dst_len_used] =
  6376. (unsigned char)((unsigned char)(c << 6) + d);
  6377. }
  6378. dst_len_used++;
  6379. }
  6380. }
  6381. }
  6382. /* Add terminating zero */
  6383. if (dst_len_used < dst_len_limit) {
  6384. dst[dst_len_used] = '\0';
  6385. }
  6386. dst_len_used++;
  6387. if (dst_len != NULL) {
  6388. *dst_len = dst_len_used;
  6389. }
  6390. if (dst_len_used > dst_len_limit) {
  6391. /* Out of memory */
  6392. return 0;
  6393. }
  6394. /* Return -1 for "OK" */
  6395. return -1;
  6396. }
  6397. static int
  6398. is_put_or_delete_method(const struct mg_connection *conn)
  6399. {
  6400. if (conn) {
  6401. const char *s = conn->request_info.request_method;
  6402. if (s != NULL) {
  6403. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6404. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6405. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6406. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6407. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6408. || !strcmp(s, "COPY"));
  6409. }
  6410. }
  6411. return 0;
  6412. }
  6413. static int
  6414. is_civetweb_webdav_method(const struct mg_connection *conn)
  6415. {
  6416. /* Note: Here we only have to identify the WebDav methods that need special
  6417. * handling in the CivetWeb code - not all methods used in WebDav. In
  6418. * particular, methods used on directories (when using Windows Explorer as
  6419. * WebDav client).
  6420. */
  6421. if (conn) {
  6422. const char *s = conn->request_info.request_method;
  6423. if (s != NULL) {
  6424. /* These are the civetweb builtin DAV methods */
  6425. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6426. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6427. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6428. }
  6429. }
  6430. return 0;
  6431. }
  6432. #if !defined(NO_FILES)
  6433. static int
  6434. extention_matches_script(
  6435. struct mg_connection *conn, /* in: request (must be valid) */
  6436. const char *filename /* in: filename (must be valid) */
  6437. )
  6438. {
  6439. #if !defined(NO_CGI)
  6440. int cgi_config_idx, inc, max;
  6441. #endif
  6442. #if defined(USE_LUA)
  6443. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6444. filename)
  6445. > 0) {
  6446. return 1;
  6447. }
  6448. #endif
  6449. #if defined(USE_DUKTAPE)
  6450. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6451. filename)
  6452. > 0) {
  6453. return 1;
  6454. }
  6455. #endif
  6456. #if !defined(NO_CGI)
  6457. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6458. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6459. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6460. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6461. && (match_prefix_strlen(
  6462. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6463. filename)
  6464. > 0)) {
  6465. return 1;
  6466. }
  6467. }
  6468. #endif
  6469. /* filename and conn could be unused, if all preocessor conditions
  6470. * are false (no script language supported). */
  6471. (void)filename;
  6472. (void)conn;
  6473. return 0;
  6474. }
  6475. static int
  6476. extention_matches_template_text(
  6477. struct mg_connection *conn, /* in: request (must be valid) */
  6478. const char *filename /* in: filename (must be valid) */
  6479. )
  6480. {
  6481. #if defined(USE_LUA)
  6482. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6483. filename)
  6484. > 0) {
  6485. return 1;
  6486. }
  6487. #endif
  6488. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6489. > 0) {
  6490. return 1;
  6491. }
  6492. return 0;
  6493. }
  6494. /* For given directory path, substitute it to valid index file.
  6495. * Return 1 if index file has been found, 0 if not found.
  6496. * If the file is found, it's stats is returned in stp. */
  6497. static int
  6498. substitute_index_file_aux(struct mg_connection *conn,
  6499. char *path,
  6500. size_t path_len,
  6501. struct mg_file_stat *filestat)
  6502. {
  6503. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6504. struct vec filename_vec;
  6505. size_t n = strlen(path);
  6506. int found = 0;
  6507. /* The 'path' given to us points to the directory. Remove all trailing
  6508. * directory separator characters from the end of the path, and
  6509. * then append single directory separator character. */
  6510. while ((n > 0) && (path[n - 1] == '/')) {
  6511. n--;
  6512. }
  6513. path[n] = '/';
  6514. /* Traverse index files list. For each entry, append it to the given
  6515. * path and see if the file exists. If it exists, break the loop */
  6516. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6517. /* Ignore too long entries that may overflow path buffer */
  6518. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6519. continue;
  6520. }
  6521. /* Prepare full path to the index file */
  6522. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6523. /* Does it exist? */
  6524. if (mg_stat(conn, path, filestat)) {
  6525. /* Yes it does, break the loop */
  6526. found = 1;
  6527. break;
  6528. }
  6529. }
  6530. /* If no index file exists, restore directory path */
  6531. if (!found) {
  6532. path[n] = '\0';
  6533. }
  6534. return found;
  6535. }
  6536. /* Same as above, except if the first try fails and a fallback-root is
  6537. * configured, we'll try there also */
  6538. static int
  6539. substitute_index_file(struct mg_connection *conn,
  6540. char *path,
  6541. size_t path_len,
  6542. struct mg_file_stat *filestat)
  6543. {
  6544. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6545. if (ret == 0) {
  6546. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6547. const char *fallback_root_prefix =
  6548. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6549. if ((root_prefix) && (fallback_root_prefix)) {
  6550. const size_t root_prefix_len = strlen(root_prefix);
  6551. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6552. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6553. side effects if we fail */
  6554. size_t sub_path_len;
  6555. const size_t fallback_root_prefix_len =
  6556. strlen(fallback_root_prefix);
  6557. const char *sub_path = path + root_prefix_len;
  6558. while (*sub_path == '/') {
  6559. sub_path++;
  6560. }
  6561. sub_path_len = strlen(sub_path);
  6562. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6563. < sizeof(scratch_path))) {
  6564. /* The concatenations below are all safe because we
  6565. * pre-verified string lengths above */
  6566. char *nul;
  6567. strcpy(scratch_path, fallback_root_prefix);
  6568. nul = strchr(scratch_path, '\0');
  6569. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6570. *nul++ = '/';
  6571. *nul = '\0';
  6572. }
  6573. strcat(scratch_path, sub_path);
  6574. if (substitute_index_file_aux(conn,
  6575. scratch_path,
  6576. sizeof(scratch_path),
  6577. filestat)) {
  6578. mg_strlcpy(path, scratch_path, path_len);
  6579. return 1;
  6580. }
  6581. }
  6582. }
  6583. }
  6584. }
  6585. return ret;
  6586. }
  6587. #endif
  6588. static void
  6589. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6590. char *filename, /* out: filename */
  6591. size_t filename_buf_len, /* in: size of filename buffer */
  6592. struct mg_file_stat *filestat, /* out: file status structure */
  6593. int *is_found, /* out: file found (directly) */
  6594. int *is_script_resource, /* out: handled by a script? */
  6595. int *is_websocket_request, /* out: websocket connection? */
  6596. int *is_put_or_delete_request, /* out: put/delete a file? */
  6597. int *is_webdav_request, /* out: webdav request? */
  6598. int *is_template_text /* out: SSI file or LSP file? */
  6599. )
  6600. {
  6601. char const *accept_encoding;
  6602. #if !defined(NO_FILES)
  6603. const char *uri = conn->request_info.local_uri;
  6604. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6605. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6606. NULL};
  6607. int fileExists = 0;
  6608. const char *rewrite;
  6609. struct vec a, b;
  6610. ptrdiff_t match_len;
  6611. char gz_path[UTF8_PATH_MAX];
  6612. int truncated;
  6613. int i;
  6614. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6615. char *tmp_str;
  6616. size_t tmp_str_len, sep_pos;
  6617. int allow_substitute_script_subresources;
  6618. #endif
  6619. #else
  6620. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6621. #endif
  6622. /* Step 1: Set all initially unknown outputs to zero */
  6623. memset(filestat, 0, sizeof(*filestat));
  6624. *filename = 0;
  6625. *is_found = 0;
  6626. *is_script_resource = 0;
  6627. *is_template_text = 0;
  6628. /* Step 2: Classify the request method */
  6629. /* Step 2a: Check if the request attempts to modify the file system */
  6630. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6631. /* Step 2b: Check if the request uses WebDav method that requires special
  6632. * handling */
  6633. *is_webdav_request = is_civetweb_webdav_method(conn);
  6634. /* Step 3: Check if it is a websocket request, and modify the document
  6635. * root if required */
  6636. #if defined(USE_WEBSOCKET)
  6637. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6638. #if !defined(NO_FILES)
  6639. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6640. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6641. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6642. }
  6643. #endif /* !NO_FILES */
  6644. #else /* USE_WEBSOCKET */
  6645. *is_websocket_request = 0;
  6646. #endif /* USE_WEBSOCKET */
  6647. /* Step 4: Check if gzip encoded response is allowed */
  6648. conn->accept_gzip = 0;
  6649. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6650. if (strstr(accept_encoding, "gzip") != NULL) {
  6651. conn->accept_gzip = 1;
  6652. }
  6653. }
  6654. #if !defined(NO_FILES)
  6655. /* Step 5: If there is no root directory, don't look for files. */
  6656. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6657. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6658. * config is not required. */
  6659. if (roots[0] == NULL) {
  6660. /* all file related outputs have already been set to 0, just return
  6661. */
  6662. return;
  6663. }
  6664. for (i = 0; roots[i] != NULL; i++) {
  6665. /* Step 6: Determine the local file path from the root path and the
  6666. * request uri. */
  6667. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6668. * part of the path one byte on the right. */
  6669. truncated = 0;
  6670. mg_snprintf(conn,
  6671. &truncated,
  6672. filename,
  6673. filename_buf_len - 1,
  6674. "%s%s",
  6675. roots[i],
  6676. uri);
  6677. if (truncated) {
  6678. goto interpret_cleanup;
  6679. }
  6680. /* Step 7: URI rewriting */
  6681. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6682. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6683. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6684. mg_snprintf(conn,
  6685. &truncated,
  6686. filename,
  6687. filename_buf_len - 1,
  6688. "%.*s%s",
  6689. (int)b.len,
  6690. b.ptr,
  6691. uri + match_len);
  6692. break;
  6693. }
  6694. }
  6695. if (truncated) {
  6696. goto interpret_cleanup;
  6697. }
  6698. /* Step 8: Check if the file exists at the server */
  6699. /* Local file path and name, corresponding to requested URI
  6700. * is now stored in "filename" variable. */
  6701. if (mg_stat(conn, filename, filestat)) {
  6702. fileExists = 1;
  6703. break;
  6704. }
  6705. }
  6706. if (fileExists) {
  6707. int uri_len = (int)strlen(uri);
  6708. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6709. /* 8.1: File exists. */
  6710. *is_found = 1;
  6711. /* 8.2: Check if it is a script type. */
  6712. if (extention_matches_script(conn, filename)) {
  6713. /* The request addresses a CGI resource, Lua script or
  6714. * server-side javascript.
  6715. * The URI corresponds to the script itself (like
  6716. * /path/script.cgi), and there is no additional resource
  6717. * path (like /path/script.cgi/something).
  6718. * Requests that modify (replace or delete) a resource, like
  6719. * PUT and DELETE requests, should replace/delete the script
  6720. * file.
  6721. * Requests that read or write from/to a resource, like GET and
  6722. * POST requests, should call the script and return the
  6723. * generated response. */
  6724. *is_script_resource = (!*is_put_or_delete_request);
  6725. }
  6726. /* 8.3: Check for SSI and LSP files */
  6727. if (extention_matches_template_text(conn, filename)) {
  6728. /* Same as above, but for *.lsp and *.shtml files. */
  6729. /* A "template text" is a file delivered directly to the client,
  6730. * but with some text tags replaced by dynamic content.
  6731. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6732. * (LP, LSP) file. */
  6733. *is_template_text = (!*is_put_or_delete_request);
  6734. }
  6735. /* 8.4: If the request target is a directory, there could be
  6736. * a substitute file (index.html, index.cgi, ...). */
  6737. /* But do not substitute a directory for a WebDav request */
  6738. if (filestat->is_directory && is_uri_end_slash
  6739. && (!*is_webdav_request)) {
  6740. /* Use a local copy here, since substitute_index_file will
  6741. * change the content of the file status */
  6742. struct mg_file_stat tmp_filestat;
  6743. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6744. if (substitute_index_file(
  6745. conn, filename, filename_buf_len, &tmp_filestat)) {
  6746. /* Substitute file found. Copy stat to the output, then
  6747. * check if the file is a script file */
  6748. *filestat = tmp_filestat;
  6749. if (extention_matches_script(conn, filename)) {
  6750. /* Substitute file is a script file */
  6751. *is_script_resource = 1;
  6752. } else if (extention_matches_template_text(conn, filename)) {
  6753. /* Substitute file is a LSP or SSI file */
  6754. *is_template_text = 1;
  6755. } else {
  6756. /* Substitute file is a regular file */
  6757. *is_script_resource = 0;
  6758. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6759. }
  6760. }
  6761. /* If there is no substitute file, the server could return
  6762. * a directory listing in a later step */
  6763. }
  6764. return;
  6765. }
  6766. /* Step 9: Check for zipped files: */
  6767. /* If we can't find the actual file, look for the file
  6768. * with the same name but a .gz extension. If we find it,
  6769. * use that and set the gzipped flag in the file struct
  6770. * to indicate that the response need to have the content-
  6771. * encoding: gzip header.
  6772. * We can only do this if the browser declares support. */
  6773. if (conn->accept_gzip) {
  6774. mg_snprintf(
  6775. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6776. if (truncated) {
  6777. goto interpret_cleanup;
  6778. }
  6779. if (mg_stat(conn, gz_path, filestat)) {
  6780. if (filestat) {
  6781. filestat->is_gzipped = 1;
  6782. *is_found = 1;
  6783. }
  6784. /* Currently gz files can not be scripts. */
  6785. return;
  6786. }
  6787. }
  6788. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6789. /* Step 10: Script resources may handle sub-resources */
  6790. /* Support PATH_INFO for CGI scripts. */
  6791. tmp_str_len = strlen(filename);
  6792. tmp_str =
  6793. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6794. if (!tmp_str) {
  6795. /* Out of memory */
  6796. goto interpret_cleanup;
  6797. }
  6798. memcpy(tmp_str, filename, tmp_str_len + 1);
  6799. /* Check config, if index scripts may have sub-resources */
  6800. allow_substitute_script_subresources =
  6801. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6802. "yes");
  6803. if (*is_webdav_request) {
  6804. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6805. * PROPFIND for their subresources? */
  6806. /* allow_substitute_script_subresources = 0; */
  6807. }
  6808. sep_pos = tmp_str_len;
  6809. while (sep_pos > 0) {
  6810. sep_pos--;
  6811. if (tmp_str[sep_pos] == '/') {
  6812. int is_script = 0, does_exist = 0;
  6813. tmp_str[sep_pos] = 0;
  6814. if (tmp_str[0]) {
  6815. is_script = extention_matches_script(conn, tmp_str);
  6816. does_exist = mg_stat(conn, tmp_str, filestat);
  6817. }
  6818. if (does_exist && is_script) {
  6819. filename[sep_pos] = 0;
  6820. memmove(filename + sep_pos + 2,
  6821. filename + sep_pos + 1,
  6822. strlen(filename + sep_pos + 1) + 1);
  6823. conn->path_info = filename + sep_pos + 1;
  6824. filename[sep_pos + 1] = '/';
  6825. *is_script_resource = 1;
  6826. *is_found = 1;
  6827. break;
  6828. }
  6829. if (allow_substitute_script_subresources) {
  6830. if (substitute_index_file(
  6831. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6832. /* some intermediate directory has an index file */
  6833. if (extention_matches_script(conn, tmp_str)) {
  6834. size_t script_name_len = strlen(tmp_str);
  6835. /* subres_name read before this memory locatio will be
  6836. overwritten */
  6837. char *subres_name = filename + sep_pos;
  6838. size_t subres_name_len = strlen(subres_name);
  6839. DEBUG_TRACE("Substitute script %s serving path %s",
  6840. tmp_str,
  6841. filename);
  6842. /* this index file is a script */
  6843. if ((script_name_len + subres_name_len + 2)
  6844. >= filename_buf_len) {
  6845. mg_free(tmp_str);
  6846. goto interpret_cleanup;
  6847. }
  6848. conn->path_info =
  6849. filename + script_name_len + 1; /* new target */
  6850. memmove(conn->path_info, subres_name, subres_name_len);
  6851. conn->path_info[subres_name_len] = 0;
  6852. memcpy(filename, tmp_str, script_name_len + 1);
  6853. *is_script_resource = 1;
  6854. *is_found = 1;
  6855. break;
  6856. } else {
  6857. DEBUG_TRACE("Substitute file %s serving path %s",
  6858. tmp_str,
  6859. filename);
  6860. /* non-script files will not have sub-resources */
  6861. filename[sep_pos] = 0;
  6862. conn->path_info = 0;
  6863. *is_script_resource = 0;
  6864. *is_found = 0;
  6865. break;
  6866. }
  6867. }
  6868. }
  6869. tmp_str[sep_pos] = '/';
  6870. }
  6871. }
  6872. mg_free(tmp_str);
  6873. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6874. #endif /* !defined(NO_FILES) */
  6875. return;
  6876. #if !defined(NO_FILES)
  6877. /* Reset all outputs */
  6878. interpret_cleanup:
  6879. memset(filestat, 0, sizeof(*filestat));
  6880. *filename = 0;
  6881. *is_found = 0;
  6882. *is_script_resource = 0;
  6883. *is_websocket_request = 0;
  6884. *is_put_or_delete_request = 0;
  6885. #endif /* !defined(NO_FILES) */
  6886. }
  6887. /* Check whether full request is buffered. Return:
  6888. * -1 if request or response is malformed
  6889. * 0 if request or response is not yet fully buffered
  6890. * >0 actual request length, including last \r\n\r\n */
  6891. static int
  6892. get_http_header_len(const char *buf, int buflen)
  6893. {
  6894. int i;
  6895. for (i = 0; i < buflen; i++) {
  6896. /* Do an unsigned comparison in some conditions below */
  6897. const unsigned char c = (unsigned char)buf[i];
  6898. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6899. && !isprint(c)) {
  6900. /* abort scan as soon as one malformed character is found */
  6901. return -1;
  6902. }
  6903. if (i < buflen - 1) {
  6904. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6905. /* Two newline, no carriage return - not standard compliant,
  6906. * but it should be accepted */
  6907. return i + 2;
  6908. }
  6909. }
  6910. if (i < buflen - 3) {
  6911. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6912. && (buf[i + 3] == '\n')) {
  6913. /* Two \r\n - standard compliant */
  6914. return i + 4;
  6915. }
  6916. }
  6917. }
  6918. return 0;
  6919. }
  6920. #if !defined(NO_CACHING)
  6921. /* Convert month to the month number. Return -1 on error, or month number */
  6922. static int
  6923. get_month_index(const char *s)
  6924. {
  6925. size_t i;
  6926. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6927. if (!strcmp(s, month_names[i])) {
  6928. return (int)i;
  6929. }
  6930. }
  6931. return -1;
  6932. }
  6933. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6934. static time_t
  6935. parse_date_string(const char *datetime)
  6936. {
  6937. char month_str[32] = {0};
  6938. int second, minute, hour, day, month, year;
  6939. time_t result = (time_t)0;
  6940. struct tm tm;
  6941. if ((sscanf(datetime,
  6942. "%d/%3s/%d %d:%d:%d",
  6943. &day,
  6944. month_str,
  6945. &year,
  6946. &hour,
  6947. &minute,
  6948. &second)
  6949. == 6)
  6950. || (sscanf(datetime,
  6951. "%d %3s %d %d:%d:%d",
  6952. &day,
  6953. month_str,
  6954. &year,
  6955. &hour,
  6956. &minute,
  6957. &second)
  6958. == 6)
  6959. || (sscanf(datetime,
  6960. "%*3s, %d %3s %d %d:%d:%d",
  6961. &day,
  6962. month_str,
  6963. &year,
  6964. &hour,
  6965. &minute,
  6966. &second)
  6967. == 6)
  6968. || (sscanf(datetime,
  6969. "%d-%3s-%d %d:%d:%d",
  6970. &day,
  6971. month_str,
  6972. &year,
  6973. &hour,
  6974. &minute,
  6975. &second)
  6976. == 6)) {
  6977. month = get_month_index(month_str);
  6978. if ((month >= 0) && (year >= 1970)) {
  6979. memset(&tm, 0, sizeof(tm));
  6980. tm.tm_year = year - 1900;
  6981. tm.tm_mon = month;
  6982. tm.tm_mday = day;
  6983. tm.tm_hour = hour;
  6984. tm.tm_min = minute;
  6985. tm.tm_sec = second;
  6986. result = timegm(&tm);
  6987. }
  6988. }
  6989. return result;
  6990. }
  6991. #endif /* !NO_CACHING */
  6992. /* Pre-process URIs according to RFC + protect against directory disclosure
  6993. * attacks by removing '..', excessive '/' and '\' characters */
  6994. static void
  6995. remove_dot_segments(char *inout)
  6996. {
  6997. /* Windows backend protection
  6998. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6999. * in URI by slash */
  7000. char *out_end = inout;
  7001. char *in = inout;
  7002. if (!in) {
  7003. /* Param error. */
  7004. return;
  7005. }
  7006. while (*in) {
  7007. if (*in == '\\') {
  7008. *in = '/';
  7009. }
  7010. in++;
  7011. }
  7012. /* Algorithm "remove_dot_segments" from
  7013. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7014. /* Step 1:
  7015. * The input buffer is initialized.
  7016. * The output buffer is initialized to the empty string.
  7017. */
  7018. in = inout;
  7019. /* Step 2:
  7020. * While the input buffer is not empty, loop as follows:
  7021. */
  7022. /* Less than out_end of the inout buffer is used as output, so keep
  7023. * condition: out_end <= in */
  7024. while (*in) {
  7025. /* Step 2a:
  7026. * If the input buffer begins with a prefix of "../" or "./",
  7027. * then remove that prefix from the input buffer;
  7028. */
  7029. if (!strncmp(in, "../", 3)) {
  7030. in += 3;
  7031. } else if (!strncmp(in, "./", 2)) {
  7032. in += 2;
  7033. }
  7034. /* otherwise */
  7035. /* Step 2b:
  7036. * if the input buffer begins with a prefix of "/./" or "/.",
  7037. * where "." is a complete path segment, then replace that
  7038. * prefix with "/" in the input buffer;
  7039. */
  7040. else if (!strncmp(in, "/./", 3)) {
  7041. in += 2;
  7042. } else if (!strcmp(in, "/.")) {
  7043. in[1] = 0;
  7044. }
  7045. /* otherwise */
  7046. /* Step 2c:
  7047. * if the input buffer begins with a prefix of "/../" or "/..",
  7048. * where ".." is a complete path segment, then replace that
  7049. * prefix with "/" in the input buffer and remove the last
  7050. * segment and its preceding "/" (if any) from the output
  7051. * buffer;
  7052. */
  7053. else if (!strncmp(in, "/../", 4)) {
  7054. in += 3;
  7055. if (inout != out_end) {
  7056. /* remove last segment */
  7057. do {
  7058. out_end--;
  7059. } while ((inout != out_end) && (*out_end != '/'));
  7060. }
  7061. } else if (!strcmp(in, "/..")) {
  7062. in[1] = 0;
  7063. if (inout != out_end) {
  7064. /* remove last segment */
  7065. do {
  7066. out_end--;
  7067. } while ((inout != out_end) && (*out_end != '/'));
  7068. }
  7069. }
  7070. /* otherwise */
  7071. /* Step 2d:
  7072. * if the input buffer consists only of "." or "..", then remove
  7073. * that from the input buffer;
  7074. */
  7075. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7076. *in = 0;
  7077. }
  7078. /* otherwise */
  7079. /* Step 2e:
  7080. * move the first path segment in the input buffer to the end of
  7081. * the output buffer, including the initial "/" character (if
  7082. * any) and any subsequent characters up to, but not including,
  7083. * the next "/" character or the end of the input buffer.
  7084. */
  7085. else {
  7086. do {
  7087. *out_end = *in;
  7088. out_end++;
  7089. in++;
  7090. } while ((*in != 0) && (*in != '/'));
  7091. }
  7092. }
  7093. /* Step 3:
  7094. * Finally, the output buffer is returned as the result of
  7095. * remove_dot_segments.
  7096. */
  7097. /* Terminate output */
  7098. *out_end = 0;
  7099. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7100. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7101. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7102. * or "//" anymore.
  7103. */
  7104. out_end = in = inout;
  7105. while (*in) {
  7106. if (*in == '.') {
  7107. /* remove . at the end or preceding of / */
  7108. char *in_ahead = in;
  7109. do {
  7110. in_ahead++;
  7111. } while (*in_ahead == '.');
  7112. if (*in_ahead == '/') {
  7113. in = in_ahead;
  7114. if ((out_end != inout) && (out_end[-1] == '/')) {
  7115. /* remove generated // */
  7116. out_end--;
  7117. }
  7118. } else if (*in_ahead == 0) {
  7119. in = in_ahead;
  7120. } else {
  7121. do {
  7122. *out_end++ = '.';
  7123. in++;
  7124. } while (in != in_ahead);
  7125. }
  7126. } else if (*in == '/') {
  7127. /* replace // by / */
  7128. *out_end++ = '/';
  7129. do {
  7130. in++;
  7131. } while (*in == '/');
  7132. } else {
  7133. *out_end++ = *in;
  7134. in++;
  7135. }
  7136. }
  7137. *out_end = 0;
  7138. }
  7139. static const struct {
  7140. const char *extension;
  7141. size_t ext_len;
  7142. const char *mime_type;
  7143. } builtin_mime_types[] = {
  7144. /* IANA registered MIME types
  7145. * (http://www.iana.org/assignments/media-types)
  7146. * application types */
  7147. {".bin", 4, "application/octet-stream"},
  7148. {".deb", 4, "application/octet-stream"},
  7149. {".dmg", 4, "application/octet-stream"},
  7150. {".dll", 4, "application/octet-stream"},
  7151. {".doc", 4, "application/msword"},
  7152. {".eps", 4, "application/postscript"},
  7153. {".exe", 4, "application/octet-stream"},
  7154. {".iso", 4, "application/octet-stream"},
  7155. {".js", 3, "application/javascript"},
  7156. {".json", 5, "application/json"},
  7157. {".mjs", 4, "application/javascript"},
  7158. {".msi", 4, "application/octet-stream"},
  7159. {".pdf", 4, "application/pdf"},
  7160. {".ps", 3, "application/postscript"},
  7161. {".rtf", 4, "application/rtf"},
  7162. {".wasm", 5, "application/wasm"},
  7163. {".xhtml", 6, "application/xhtml+xml"},
  7164. {".xsl", 4, "application/xml"},
  7165. {".xslt", 5, "application/xml"},
  7166. /* fonts */
  7167. {".ttf", 4, "application/font-sfnt"},
  7168. {".cff", 4, "application/font-sfnt"},
  7169. {".otf", 4, "application/font-sfnt"},
  7170. {".aat", 4, "application/font-sfnt"},
  7171. {".sil", 4, "application/font-sfnt"},
  7172. {".pfr", 4, "application/font-tdpfr"},
  7173. {".woff", 5, "application/font-woff"},
  7174. {".woff2", 6, "application/font-woff2"},
  7175. /* audio */
  7176. {".mp3", 4, "audio/mpeg"},
  7177. {".oga", 4, "audio/ogg"},
  7178. {".ogg", 4, "audio/ogg"},
  7179. /* image */
  7180. {".gif", 4, "image/gif"},
  7181. {".ief", 4, "image/ief"},
  7182. {".jpeg", 5, "image/jpeg"},
  7183. {".jpg", 4, "image/jpeg"},
  7184. {".jpm", 4, "image/jpm"},
  7185. {".jpx", 4, "image/jpx"},
  7186. {".png", 4, "image/png"},
  7187. {".svg", 4, "image/svg+xml"},
  7188. {".tif", 4, "image/tiff"},
  7189. {".tiff", 5, "image/tiff"},
  7190. /* model */
  7191. {".wrl", 4, "model/vrml"},
  7192. /* text */
  7193. {".css", 4, "text/css"},
  7194. {".csv", 4, "text/csv"},
  7195. {".htm", 4, "text/html"},
  7196. {".html", 5, "text/html"},
  7197. {".sgm", 4, "text/sgml"},
  7198. {".shtm", 5, "text/html"},
  7199. {".shtml", 6, "text/html"},
  7200. {".txt", 4, "text/plain"},
  7201. {".xml", 4, "text/xml"},
  7202. /* video */
  7203. {".mov", 4, "video/quicktime"},
  7204. {".mp4", 4, "video/mp4"},
  7205. {".mpeg", 5, "video/mpeg"},
  7206. {".mpg", 4, "video/mpeg"},
  7207. {".ogv", 4, "video/ogg"},
  7208. {".qt", 3, "video/quicktime"},
  7209. /* not registered types
  7210. * (http://reference.sitepoint.com/html/mime-types-full,
  7211. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7212. {".arj", 4, "application/x-arj-compressed"},
  7213. {".gz", 3, "application/x-gunzip"},
  7214. {".rar", 4, "application/x-arj-compressed"},
  7215. {".swf", 4, "application/x-shockwave-flash"},
  7216. {".tar", 4, "application/x-tar"},
  7217. {".tgz", 4, "application/x-tar-gz"},
  7218. {".torrent", 8, "application/x-bittorrent"},
  7219. {".ppt", 4, "application/x-mspowerpoint"},
  7220. {".xls", 4, "application/x-msexcel"},
  7221. {".zip", 4, "application/x-zip-compressed"},
  7222. {".aac",
  7223. 4,
  7224. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7225. {".flac", 5, "audio/flac"},
  7226. {".aif", 4, "audio/x-aif"},
  7227. {".m3u", 4, "audio/x-mpegurl"},
  7228. {".mid", 4, "audio/x-midi"},
  7229. {".ra", 3, "audio/x-pn-realaudio"},
  7230. {".ram", 4, "audio/x-pn-realaudio"},
  7231. {".wav", 4, "audio/x-wav"},
  7232. {".bmp", 4, "image/bmp"},
  7233. {".ico", 4, "image/x-icon"},
  7234. {".pct", 4, "image/x-pct"},
  7235. {".pict", 5, "image/pict"},
  7236. {".rgb", 4, "image/x-rgb"},
  7237. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7238. {".asf", 4, "video/x-ms-asf"},
  7239. {".avi", 4, "video/x-msvideo"},
  7240. {".m4v", 4, "video/x-m4v"},
  7241. {NULL, 0, NULL}};
  7242. CIVETWEB_API const char *
  7243. mg_get_builtin_mime_type(const char *path)
  7244. {
  7245. const char *ext;
  7246. size_t i, path_len;
  7247. path_len = strlen(path);
  7248. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7249. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7250. if ((path_len > builtin_mime_types[i].ext_len)
  7251. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7252. return builtin_mime_types[i].mime_type;
  7253. }
  7254. }
  7255. return "text/plain";
  7256. }
  7257. /* Look at the "path" extension and figure what mime type it has.
  7258. * Store mime type in the vector. */
  7259. static void
  7260. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7261. {
  7262. struct vec ext_vec, mime_vec;
  7263. const char *list, *ext;
  7264. size_t path_len;
  7265. path_len = strlen(path);
  7266. if ((conn == NULL) || (vec == NULL)) {
  7267. if (vec != NULL) {
  7268. memset(vec, '\0', sizeof(struct vec));
  7269. }
  7270. return;
  7271. }
  7272. /* Scan user-defined mime types first, in case user wants to
  7273. * override default mime types. */
  7274. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7275. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7276. /* ext now points to the path suffix */
  7277. ext = path + path_len - ext_vec.len;
  7278. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7279. *vec = mime_vec;
  7280. return;
  7281. }
  7282. }
  7283. vec->ptr = mg_get_builtin_mime_type(path);
  7284. vec->len = strlen(vec->ptr);
  7285. }
  7286. /* Stringify binary data. Output buffer must be twice as big as input,
  7287. * because each byte takes 2 bytes in string representation */
  7288. static void
  7289. bin2str(char *to, const unsigned char *p, size_t len)
  7290. {
  7291. static const char *hex = "0123456789abcdef";
  7292. for (; len--; p++) {
  7293. *to++ = hex[p[0] >> 4];
  7294. *to++ = hex[p[0] & 0x0f];
  7295. }
  7296. *to = '\0';
  7297. }
  7298. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7299. */
  7300. CIVETWEB_API char *
  7301. mg_md5(char buf[33], ...)
  7302. {
  7303. md5_byte_t hash[16];
  7304. const char *p;
  7305. va_list ap;
  7306. md5_state_t ctx;
  7307. md5_init(&ctx);
  7308. va_start(ap, buf);
  7309. while ((p = va_arg(ap, const char *)) != NULL) {
  7310. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7311. }
  7312. va_end(ap);
  7313. md5_finish(&ctx, hash);
  7314. bin2str(buf, hash, sizeof(hash));
  7315. return buf;
  7316. }
  7317. /* Check the user's password, return 1 if OK */
  7318. static int
  7319. check_password_digest(const char *method,
  7320. const char *ha1,
  7321. const char *uri,
  7322. const char *nonce,
  7323. const char *nc,
  7324. const char *cnonce,
  7325. const char *qop,
  7326. const char *response)
  7327. {
  7328. char ha2[32 + 1], expected_response[32 + 1];
  7329. /* Some of the parameters may be NULL */
  7330. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7331. || (qop == NULL) || (response == NULL)) {
  7332. return 0;
  7333. }
  7334. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7335. if (strlen(response) != 32) {
  7336. return 0;
  7337. }
  7338. mg_md5(ha2, method, ":", uri, NULL);
  7339. mg_md5(expected_response,
  7340. ha1,
  7341. ":",
  7342. nonce,
  7343. ":",
  7344. nc,
  7345. ":",
  7346. cnonce,
  7347. ":",
  7348. qop,
  7349. ":",
  7350. ha2,
  7351. NULL);
  7352. return mg_strcasecmp(response, expected_response) == 0;
  7353. }
  7354. #if !defined(NO_FILESYSTEMS)
  7355. /* Use the global passwords file, if specified by auth_gpass option,
  7356. * or search for .htpasswd in the requested directory. */
  7357. static void
  7358. open_auth_file(struct mg_connection *conn,
  7359. const char *path,
  7360. struct mg_file *filep)
  7361. {
  7362. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7363. char name[UTF8_PATH_MAX];
  7364. const char *p, *e,
  7365. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7366. int truncated;
  7367. if (gpass != NULL) {
  7368. /* Use global passwords file */
  7369. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7370. #if defined(DEBUG)
  7371. /* Use mg_cry_internal here, since gpass has been
  7372. * configured. */
  7373. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7374. #endif
  7375. }
  7376. /* Important: using local struct mg_file to test path for
  7377. * is_directory flag. If filep is used, mg_stat() makes it
  7378. * appear as if auth file was opened.
  7379. * TODO(mid): Check if this is still required after rewriting
  7380. * mg_stat */
  7381. } else if (mg_stat(conn, path, &filep->stat)
  7382. && filep->stat.is_directory) {
  7383. mg_snprintf(conn,
  7384. &truncated,
  7385. name,
  7386. sizeof(name),
  7387. "%s/%s",
  7388. path,
  7389. PASSWORDS_FILE_NAME);
  7390. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7391. #if defined(DEBUG)
  7392. /* Don't use mg_cry_internal here, but only a trace, since
  7393. * this is a typical case. It will occur for every directory
  7394. * without a password file. */
  7395. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7396. #endif
  7397. }
  7398. } else {
  7399. /* Try to find .htpasswd in requested directory. */
  7400. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7401. if (e[0] == '/') {
  7402. break;
  7403. }
  7404. }
  7405. mg_snprintf(conn,
  7406. &truncated,
  7407. name,
  7408. sizeof(name),
  7409. "%.*s/%s",
  7410. (int)(e - p),
  7411. p,
  7412. PASSWORDS_FILE_NAME);
  7413. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7414. #if defined(DEBUG)
  7415. /* Don't use mg_cry_internal here, but only a trace, since
  7416. * this is a typical case. It will occur for every directory
  7417. * without a password file. */
  7418. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7419. #endif
  7420. }
  7421. }
  7422. }
  7423. }
  7424. #endif /* NO_FILESYSTEMS */
  7425. /* Parsed Authorization header */
  7426. struct ah {
  7427. char *user;
  7428. int type; /* 1 = basic, 2 = digest */
  7429. char *plain_password; /* Basic only */
  7430. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7431. };
  7432. /* Return 1 on success. Always initializes the ah structure. */
  7433. static int
  7434. parse_auth_header(struct mg_connection *conn,
  7435. char *buf,
  7436. size_t buf_size,
  7437. struct ah *ah)
  7438. {
  7439. char *name, *value, *s;
  7440. const char *auth_header;
  7441. uint64_t nonce;
  7442. if (!ah || !conn) {
  7443. return 0;
  7444. }
  7445. (void)memset(ah, 0, sizeof(*ah));
  7446. auth_header = mg_get_header(conn, "Authorization");
  7447. if (auth_header == NULL) {
  7448. /* No Authorization header at all */
  7449. return 0;
  7450. }
  7451. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7452. /* Basic Auth (we never asked for this, but some client may send it) */
  7453. char *split;
  7454. const char *userpw_b64 = auth_header + 6;
  7455. size_t userpw_b64_len = strlen(userpw_b64);
  7456. size_t buf_len_r = buf_size;
  7457. if (mg_base64_decode(
  7458. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7459. != -1) {
  7460. return 0; /* decode error */
  7461. }
  7462. split = strchr(buf, ':');
  7463. if (!split) {
  7464. return 0; /* Format error */
  7465. }
  7466. /* Separate string at ':' */
  7467. *split = 0;
  7468. /* User name is before ':', Password is after ':' */
  7469. ah->user = buf;
  7470. ah->type = 1;
  7471. ah->plain_password = split + 1;
  7472. return 1;
  7473. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7474. /* Digest Auth ... implemented below */
  7475. ah->type = 2;
  7476. } else {
  7477. /* Unknown or invalid Auth method */
  7478. return 0;
  7479. }
  7480. /* Make modifiable copy of the auth header */
  7481. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7482. s = buf;
  7483. /* Parse authorization header */
  7484. for (;;) {
  7485. /* Gobble initial spaces */
  7486. while (isspace((unsigned char)*s)) {
  7487. s++;
  7488. }
  7489. name = skip_quoted(&s, "=", " ", 0);
  7490. /* Value is either quote-delimited, or ends at first comma or space.
  7491. */
  7492. if (s[0] == '\"') {
  7493. s++;
  7494. value = skip_quoted(&s, "\"", " ", '\\');
  7495. if (s[0] == ',') {
  7496. s++;
  7497. }
  7498. } else {
  7499. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7500. * uses spaces */
  7501. }
  7502. if (*name == '\0') {
  7503. break;
  7504. }
  7505. if (!strcmp(name, "username")) {
  7506. ah->user = value;
  7507. } else if (!strcmp(name, "cnonce")) {
  7508. ah->cnonce = value;
  7509. } else if (!strcmp(name, "response")) {
  7510. ah->response = value;
  7511. } else if (!strcmp(name, "uri")) {
  7512. ah->uri = value;
  7513. } else if (!strcmp(name, "qop")) {
  7514. ah->qop = value;
  7515. } else if (!strcmp(name, "nc")) {
  7516. ah->nc = value;
  7517. } else if (!strcmp(name, "nonce")) {
  7518. ah->nonce = value;
  7519. }
  7520. }
  7521. #if !defined(NO_NONCE_CHECK)
  7522. /* Read the nonce from the response. */
  7523. if (ah->nonce == NULL) {
  7524. return 0;
  7525. }
  7526. s = NULL;
  7527. nonce = strtoull(ah->nonce, &s, 10);
  7528. if ((s == NULL) || (*s != 0)) {
  7529. return 0;
  7530. }
  7531. /* Convert the nonce from the client to a number. */
  7532. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7533. /* The converted number corresponds to the time the nounce has been
  7534. * created. This should not be earlier than the server start. */
  7535. /* Server side nonce check is valuable in all situations but one:
  7536. * if the server restarts frequently, but the client should not see
  7537. * that, so the server should accept nonces from previous starts. */
  7538. /* However, the reasonable default is to not accept a nonce from a
  7539. * previous start, so if anyone changed the access rights between
  7540. * two restarts, a new login is required. */
  7541. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7542. /* nonce is from a previous start of the server and no longer valid
  7543. * (replay attack?) */
  7544. return 0;
  7545. }
  7546. /* Check if the nonce is too high, so it has not (yet) been used by the
  7547. * server. */
  7548. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7549. + conn->dom_ctx->nonce_count)) {
  7550. return 0;
  7551. }
  7552. #else
  7553. (void)nonce;
  7554. #endif
  7555. return (ah->user != NULL);
  7556. }
  7557. static const char *
  7558. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7559. {
  7560. if (!filep) {
  7561. return NULL;
  7562. }
  7563. if (filep->access.fp != NULL) {
  7564. return fgets(buf, (int)size, filep->access.fp);
  7565. } else {
  7566. return NULL;
  7567. }
  7568. }
  7569. /* Define the initial recursion depth for procesesing htpasswd files that
  7570. * include other htpasswd
  7571. * (or even the same) files. It is not difficult to provide a file or files
  7572. * s.t. they force civetweb
  7573. * to infinitely recurse and then crash.
  7574. */
  7575. #define INITIAL_DEPTH 9
  7576. #if INITIAL_DEPTH <= 0
  7577. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7578. #endif
  7579. #if !defined(NO_FILESYSTEMS)
  7580. struct read_auth_file_struct {
  7581. struct mg_connection *conn;
  7582. struct ah ah;
  7583. const char *domain;
  7584. char buf[256 + 256 + 40];
  7585. const char *f_user;
  7586. const char *f_domain;
  7587. const char *f_ha1;
  7588. };
  7589. static int
  7590. read_auth_file(struct mg_file *filep,
  7591. struct read_auth_file_struct *workdata,
  7592. int depth)
  7593. {
  7594. int is_authorized = 0;
  7595. struct mg_file fp;
  7596. size_t l;
  7597. if (!filep || !workdata || (0 == depth)) {
  7598. return 0;
  7599. }
  7600. /* Loop over passwords file */
  7601. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7602. l = strlen(workdata->buf);
  7603. while (l > 0) {
  7604. if (isspace((unsigned char)workdata->buf[l - 1])
  7605. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7606. l--;
  7607. workdata->buf[l] = 0;
  7608. } else
  7609. break;
  7610. }
  7611. if (l < 1) {
  7612. continue;
  7613. }
  7614. workdata->f_user = workdata->buf;
  7615. if (workdata->f_user[0] == ':') {
  7616. /* user names may not contain a ':' and may not be empty,
  7617. * so lines starting with ':' may be used for a special purpose
  7618. */
  7619. if (workdata->f_user[1] == '#') {
  7620. /* :# is a comment */
  7621. continue;
  7622. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7623. if (mg_fopen(workdata->conn,
  7624. workdata->f_user + 9,
  7625. MG_FOPEN_MODE_READ,
  7626. &fp)) {
  7627. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7628. (void)mg_fclose(
  7629. &fp.access); /* ignore error on read only file */
  7630. /* No need to continue processing files once we have a
  7631. * match, since nothing will reset it back
  7632. * to 0.
  7633. */
  7634. if (is_authorized) {
  7635. return is_authorized;
  7636. }
  7637. } else {
  7638. mg_cry_internal(workdata->conn,
  7639. "%s: cannot open authorization file: %s",
  7640. __func__,
  7641. workdata->buf);
  7642. }
  7643. continue;
  7644. }
  7645. /* everything is invalid for the moment (might change in the
  7646. * future) */
  7647. mg_cry_internal(workdata->conn,
  7648. "%s: syntax error in authorization file: %s",
  7649. __func__,
  7650. workdata->buf);
  7651. continue;
  7652. }
  7653. workdata->f_domain = strchr(workdata->f_user, ':');
  7654. if (workdata->f_domain == NULL) {
  7655. mg_cry_internal(workdata->conn,
  7656. "%s: syntax error in authorization file: %s",
  7657. __func__,
  7658. workdata->buf);
  7659. continue;
  7660. }
  7661. *(char *)(workdata->f_domain) = 0;
  7662. (workdata->f_domain)++;
  7663. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7664. if (workdata->f_ha1 == NULL) {
  7665. mg_cry_internal(workdata->conn,
  7666. "%s: syntax error in authorization file: %s",
  7667. __func__,
  7668. workdata->buf);
  7669. continue;
  7670. }
  7671. *(char *)(workdata->f_ha1) = 0;
  7672. (workdata->f_ha1)++;
  7673. if (!strcmp(workdata->ah.user, workdata->f_user)
  7674. && !strcmp(workdata->domain, workdata->f_domain)) {
  7675. switch (workdata->ah.type) {
  7676. case 1: /* Basic */
  7677. {
  7678. char md5[33];
  7679. mg_md5(md5,
  7680. workdata->f_user,
  7681. ":",
  7682. workdata->domain,
  7683. ":",
  7684. workdata->ah.plain_password,
  7685. NULL);
  7686. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7687. }
  7688. case 2: /* Digest */
  7689. return check_password_digest(
  7690. workdata->conn->request_info.request_method,
  7691. workdata->f_ha1,
  7692. workdata->ah.uri,
  7693. workdata->ah.nonce,
  7694. workdata->ah.nc,
  7695. workdata->ah.cnonce,
  7696. workdata->ah.qop,
  7697. workdata->ah.response);
  7698. default: /* None/Other/Unknown */
  7699. return 0;
  7700. }
  7701. }
  7702. }
  7703. return is_authorized;
  7704. }
  7705. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7706. static int
  7707. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7708. {
  7709. struct read_auth_file_struct workdata;
  7710. char buf[MG_BUF_LEN];
  7711. if (!conn || !conn->dom_ctx) {
  7712. return 0;
  7713. }
  7714. memset(&workdata, 0, sizeof(workdata));
  7715. workdata.conn = conn;
  7716. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7717. return 0;
  7718. }
  7719. /* CGI needs it as REMOTE_USER */
  7720. conn->request_info.remote_user =
  7721. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7722. if (realm) {
  7723. workdata.domain = realm;
  7724. } else {
  7725. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7726. }
  7727. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7728. }
  7729. /* Public function to check http digest authentication header */
  7730. CIVETWEB_API int
  7731. mg_check_digest_access_authentication(struct mg_connection *conn,
  7732. const char *realm,
  7733. const char *filename)
  7734. {
  7735. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7736. int auth;
  7737. if (!conn || !filename) {
  7738. return -1;
  7739. }
  7740. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7741. return -2;
  7742. }
  7743. auth = authorize(conn, &file, realm);
  7744. mg_fclose(&file.access);
  7745. return auth;
  7746. }
  7747. #endif /* NO_FILESYSTEMS */
  7748. /* Return 1 if request is authorised, 0 otherwise. */
  7749. static int
  7750. check_authorization(struct mg_connection *conn, const char *path)
  7751. {
  7752. #if !defined(NO_FILESYSTEMS)
  7753. char fname[UTF8_PATH_MAX];
  7754. struct vec uri_vec, filename_vec;
  7755. const char *list;
  7756. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7757. int authorized = 1, truncated;
  7758. if (!conn || !conn->dom_ctx) {
  7759. return 0;
  7760. }
  7761. list = conn->dom_ctx->config[PROTECT_URI];
  7762. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7763. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7764. mg_snprintf(conn,
  7765. &truncated,
  7766. fname,
  7767. sizeof(fname),
  7768. "%.*s",
  7769. (int)filename_vec.len,
  7770. filename_vec.ptr);
  7771. if (truncated
  7772. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7773. mg_cry_internal(conn,
  7774. "%s: cannot open %s: %s",
  7775. __func__,
  7776. fname,
  7777. strerror(errno));
  7778. }
  7779. break;
  7780. }
  7781. }
  7782. if (!is_file_opened(&file.access)) {
  7783. open_auth_file(conn, path, &file);
  7784. }
  7785. if (is_file_opened(&file.access)) {
  7786. authorized = authorize(conn, &file, NULL);
  7787. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7788. }
  7789. return authorized;
  7790. #else
  7791. (void)conn;
  7792. (void)path;
  7793. return 1;
  7794. #endif /* NO_FILESYSTEMS */
  7795. }
  7796. /* Internal function. Assumes conn is valid */
  7797. static void
  7798. send_authorization_request(struct mg_connection *conn, const char *realm)
  7799. {
  7800. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7801. int trunc = 0;
  7802. char buf[128];
  7803. if (!realm) {
  7804. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7805. }
  7806. mg_lock_context(conn->phys_ctx);
  7807. nonce += conn->dom_ctx->nonce_count;
  7808. ++conn->dom_ctx->nonce_count;
  7809. mg_unlock_context(conn->phys_ctx);
  7810. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7811. conn->must_close = 1;
  7812. /* Create 401 response */
  7813. mg_response_header_start(conn, 401);
  7814. send_no_cache_header(conn);
  7815. send_additional_header(conn);
  7816. mg_response_header_add(conn, "Content-Length", "0", -1);
  7817. /* Content for "WWW-Authenticate" header */
  7818. mg_snprintf(conn,
  7819. &trunc,
  7820. buf,
  7821. sizeof(buf),
  7822. "Digest qop=\"auth\", realm=\"%s\", "
  7823. "nonce=\"%" UINT64_FMT "\"",
  7824. realm,
  7825. nonce);
  7826. if (!trunc) {
  7827. /* !trunc should always be true */
  7828. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7829. }
  7830. /* Send all headers */
  7831. mg_response_header_send(conn);
  7832. }
  7833. /* Interface function. Parameters are provided by the user, so do
  7834. * at least some basic checks.
  7835. */
  7836. CIVETWEB_API int
  7837. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7838. const char *realm)
  7839. {
  7840. if (conn && conn->dom_ctx) {
  7841. send_authorization_request(conn, realm);
  7842. return 0;
  7843. }
  7844. return -1;
  7845. }
  7846. #if !defined(NO_FILES)
  7847. static int
  7848. is_authorized_for_put(struct mg_connection *conn)
  7849. {
  7850. int ret = 0;
  7851. if (conn) {
  7852. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7853. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7854. if (passfile != NULL
  7855. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7856. ret = authorize(conn, &file, NULL);
  7857. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7858. }
  7859. }
  7860. DEBUG_TRACE("file write authorization: %i", ret);
  7861. return ret;
  7862. }
  7863. #endif
  7864. CIVETWEB_API int
  7865. mg_modify_passwords_file_ha1(const char *fname,
  7866. const char *domain,
  7867. const char *user,
  7868. const char *ha1)
  7869. {
  7870. int found = 0, i, result = 1;
  7871. char line[512], u[256], d[256], h[256];
  7872. struct stat st = {0};
  7873. FILE *fp = NULL;
  7874. char *temp_file = NULL;
  7875. int temp_file_offs = 0;
  7876. /* Regard empty password as no password - remove user record. */
  7877. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7878. ha1 = NULL;
  7879. }
  7880. /* Other arguments must not be empty */
  7881. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7882. return 0;
  7883. }
  7884. /* Using the given file format, user name and domain must not contain
  7885. * the ':' character */
  7886. if (strchr(user, ':') != NULL) {
  7887. return 0;
  7888. }
  7889. if (strchr(domain, ':') != NULL) {
  7890. return 0;
  7891. }
  7892. /* Do not allow control characters like newline in user name and domain.
  7893. * Do not allow excessively long names either. */
  7894. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7895. if (iscntrl((unsigned char)user[i])) {
  7896. return 0;
  7897. }
  7898. }
  7899. if (user[i]) {
  7900. return 0; /* user name too long */
  7901. }
  7902. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7903. if (iscntrl((unsigned char)domain[i])) {
  7904. return 0;
  7905. }
  7906. }
  7907. if (domain[i]) {
  7908. return 0; /* domain name too long */
  7909. }
  7910. /* The maximum length of the path to the password file is limited */
  7911. if (strlen(fname) >= UTF8_PATH_MAX) {
  7912. return 0;
  7913. }
  7914. /* Check if the file exists, and get file size */
  7915. if (0 == stat(fname, &st)) {
  7916. int temp_buf_len;
  7917. if (st.st_size > 10485760) {
  7918. /* Some funster provided a >10 MB text file */
  7919. return 0;
  7920. }
  7921. /* Add enough space for one more line */
  7922. temp_buf_len = (int)st.st_size + 1024;
  7923. /* Allocate memory (instead of using a temporary file) */
  7924. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  7925. if (!temp_file) {
  7926. /* Out of memory */
  7927. return 0;
  7928. }
  7929. /* File exists. Read it into a memory buffer. */
  7930. fp = fopen(fname, "r");
  7931. if (fp == NULL) {
  7932. /* Cannot read file. No permission? */
  7933. mg_free(temp_file);
  7934. return 0;
  7935. }
  7936. /* Read content and store in memory */
  7937. while ((fgets(line, sizeof(line), fp) != NULL)
  7938. && ((temp_file_offs + 600) < temp_buf_len)) {
  7939. /* file format is "user:domain:hash\n" */
  7940. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7941. continue;
  7942. }
  7943. u[255] = 0;
  7944. d[255] = 0;
  7945. h[255] = 0;
  7946. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7947. /* Found the user: change the password hash or drop the user
  7948. */
  7949. if ((ha1 != NULL) && (!found)) {
  7950. i = sprintf(temp_file + temp_file_offs,
  7951. "%s:%s:%s\n",
  7952. user,
  7953. domain,
  7954. ha1);
  7955. if (i < 1) {
  7956. fclose(fp);
  7957. mg_free(temp_file);
  7958. return 0;
  7959. }
  7960. temp_file_offs += i;
  7961. }
  7962. found = 1;
  7963. } else {
  7964. /* Copy existing user, including password hash */
  7965. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7966. if (i < 1) {
  7967. fclose(fp);
  7968. mg_free(temp_file);
  7969. return 0;
  7970. }
  7971. temp_file_offs += i;
  7972. }
  7973. }
  7974. fclose(fp);
  7975. }
  7976. /* Create new file */
  7977. fp = fopen(fname, "w");
  7978. if (!fp) {
  7979. mg_free(temp_file);
  7980. return 0;
  7981. }
  7982. #if !defined(_WIN32)
  7983. /* On Linux & co., restrict file read/write permissions to the owner */
  7984. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7985. result = 0;
  7986. }
  7987. #endif
  7988. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7989. /* Store buffered content of old file */
  7990. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  7991. != (size_t)temp_file_offs) {
  7992. result = 0;
  7993. }
  7994. }
  7995. /* If new user, just add it */
  7996. if ((ha1 != NULL) && (!found)) {
  7997. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7998. result = 0;
  7999. }
  8000. }
  8001. /* All data written */
  8002. if (fclose(fp) != 0) {
  8003. result = 0;
  8004. }
  8005. mg_free(temp_file);
  8006. return result;
  8007. }
  8008. CIVETWEB_API int
  8009. mg_modify_passwords_file(const char *fname,
  8010. const char *domain,
  8011. const char *user,
  8012. const char *pass)
  8013. {
  8014. char ha1buf[33];
  8015. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8016. return 0;
  8017. }
  8018. if ((pass == NULL) || (pass[0] == 0)) {
  8019. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8020. }
  8021. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8022. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8023. }
  8024. static int
  8025. is_valid_port(unsigned long port)
  8026. {
  8027. return (port <= 0xffff);
  8028. }
  8029. static int
  8030. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8031. {
  8032. struct addrinfo hints, *res, *ressave;
  8033. int func_ret = 0;
  8034. int gai_ret;
  8035. memset(&hints, 0, sizeof(struct addrinfo));
  8036. hints.ai_family = af;
  8037. if (!resolve_src) {
  8038. hints.ai_flags = AI_NUMERICHOST;
  8039. }
  8040. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8041. if (gai_ret != 0) {
  8042. /* gai_strerror could be used to convert gai_ret to a string */
  8043. /* POSIX return values: see
  8044. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8045. */
  8046. /* Windows return values: see
  8047. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8048. */
  8049. return 0;
  8050. }
  8051. ressave = res;
  8052. while (res) {
  8053. if ((dstlen >= (size_t)res->ai_addrlen)
  8054. && (res->ai_addr->sa_family == af)) {
  8055. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8056. func_ret = 1;
  8057. }
  8058. res = res->ai_next;
  8059. }
  8060. freeaddrinfo(ressave);
  8061. return func_ret;
  8062. }
  8063. static int
  8064. connect_socket(
  8065. struct mg_context *ctx /* may be NULL */,
  8066. const char *host,
  8067. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8068. int use_ssl, /* 0 or 1 */
  8069. struct mg_error_data *error,
  8070. SOCKET *sock /* output: socket, must not be NULL */,
  8071. union usa *sa /* output: socket address, must not be NULL */
  8072. )
  8073. {
  8074. int ip_ver = 0;
  8075. int conn_ret = -1;
  8076. int sockerr = 0;
  8077. *sock = INVALID_SOCKET;
  8078. memset(sa, 0, sizeof(*sa));
  8079. if (host == NULL) {
  8080. if (error != NULL) {
  8081. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8082. mg_snprintf(NULL,
  8083. NULL, /* No truncation check for ebuf */
  8084. error->text,
  8085. error->text_buffer_size,
  8086. "%s",
  8087. "NULL host");
  8088. }
  8089. return 0;
  8090. }
  8091. #if defined(USE_X_DOM_SOCKET)
  8092. if (port == -99) {
  8093. /* Unix domain socket */
  8094. size_t hostlen = strlen(host);
  8095. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8096. if (error != NULL) {
  8097. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8098. mg_snprintf(NULL,
  8099. NULL, /* No truncation check for ebuf */
  8100. error->text,
  8101. error->text_buffer_size,
  8102. "%s",
  8103. "host length exceeds limit");
  8104. }
  8105. return 0;
  8106. }
  8107. } else
  8108. #endif
  8109. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8110. if (error != NULL) {
  8111. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8112. mg_snprintf(NULL,
  8113. NULL, /* No truncation check for ebuf */
  8114. error->text,
  8115. error->text_buffer_size,
  8116. "%s",
  8117. "invalid port");
  8118. }
  8119. return 0;
  8120. }
  8121. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8122. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8123. if (use_ssl && (TLS_client_method == NULL)) {
  8124. if (error != NULL) {
  8125. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8126. mg_snprintf(NULL,
  8127. NULL, /* No truncation check for ebuf */
  8128. error->text,
  8129. error->text_buffer_size,
  8130. "%s",
  8131. "SSL is not initialized");
  8132. }
  8133. return 0;
  8134. }
  8135. #else
  8136. if (use_ssl && (SSLv23_client_method == NULL)) {
  8137. if (error != 0) {
  8138. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8139. mg_snprintf(NULL,
  8140. NULL, /* No truncation check for ebuf */
  8141. error->text,
  8142. error->text_buffer_size,
  8143. "%s",
  8144. "SSL is not initialized");
  8145. }
  8146. return 0;
  8147. }
  8148. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8149. #else
  8150. (void)use_ssl;
  8151. #endif /* NO SSL */
  8152. #if defined(USE_X_DOM_SOCKET)
  8153. if (port == -99) {
  8154. size_t hostlen = strlen(host);
  8155. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8156. ip_ver = -99;
  8157. sa->sun.sun_family = AF_UNIX;
  8158. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8159. memcpy(sa->sun.sun_path, host, hostlen);
  8160. } else
  8161. #endif
  8162. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8163. sa->sin.sin_port = htons((uint16_t)port);
  8164. ip_ver = 4;
  8165. #if defined(USE_IPV6)
  8166. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8167. sa->sin6.sin6_port = htons((uint16_t)port);
  8168. ip_ver = 6;
  8169. } else if (host[0] == '[') {
  8170. /* While getaddrinfo on Windows will work with [::1],
  8171. * getaddrinfo on Linux only works with ::1 (without []). */
  8172. size_t l = strlen(host + 1);
  8173. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8174. if (h) {
  8175. h[l - 1] = 0;
  8176. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8177. sa->sin6.sin6_port = htons((uint16_t)port);
  8178. ip_ver = 6;
  8179. }
  8180. mg_free(h);
  8181. }
  8182. #endif
  8183. }
  8184. if (ip_ver == 0) {
  8185. if (error != NULL) {
  8186. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8187. mg_snprintf(NULL,
  8188. NULL, /* No truncation check for ebuf */
  8189. error->text,
  8190. error->text_buffer_size,
  8191. "%s",
  8192. "host not found");
  8193. }
  8194. return 0;
  8195. }
  8196. if (ip_ver == 4) {
  8197. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8198. }
  8199. #if defined(USE_IPV6)
  8200. else if (ip_ver == 6) {
  8201. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8202. }
  8203. #endif
  8204. #if defined(USE_X_DOM_SOCKET)
  8205. else if (ip_ver == -99) {
  8206. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8207. }
  8208. #endif
  8209. if (*sock == INVALID_SOCKET) {
  8210. if (error != NULL) {
  8211. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8212. error->code_sub = (unsigned)ERRNO;
  8213. mg_snprintf(NULL,
  8214. NULL, /* No truncation check for ebuf */
  8215. error->text,
  8216. error->text_buffer_size,
  8217. "socket(): %s",
  8218. strerror(ERRNO));
  8219. }
  8220. return 0;
  8221. }
  8222. if (0 != set_non_blocking_mode(*sock)) {
  8223. if (error != NULL) {
  8224. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8225. error->code_sub = (unsigned)ERRNO;
  8226. mg_snprintf(NULL,
  8227. NULL, /* No truncation check for ebuf */
  8228. error->text,
  8229. error->text_buffer_size,
  8230. "Cannot set socket to non-blocking: %s",
  8231. strerror(ERRNO));
  8232. }
  8233. closesocket(*sock);
  8234. *sock = INVALID_SOCKET;
  8235. return 0;
  8236. }
  8237. set_close_on_exec(*sock, NULL, ctx);
  8238. if (ip_ver == 4) {
  8239. /* connected with IPv4 */
  8240. conn_ret = connect(*sock,
  8241. (struct sockaddr *)((void *)&sa->sin),
  8242. sizeof(sa->sin));
  8243. }
  8244. #if defined(USE_IPV6)
  8245. else if (ip_ver == 6) {
  8246. /* connected with IPv6 */
  8247. conn_ret = connect(*sock,
  8248. (struct sockaddr *)((void *)&sa->sin6),
  8249. sizeof(sa->sin6));
  8250. }
  8251. #endif
  8252. #if defined(USE_X_DOM_SOCKET)
  8253. else if (ip_ver == -99) {
  8254. /* connected to domain socket */
  8255. conn_ret = connect(*sock,
  8256. (struct sockaddr *)((void *)&sa->sun),
  8257. sizeof(sa->sun));
  8258. }
  8259. #endif
  8260. if (conn_ret != 0) {
  8261. sockerr = ERRNO;
  8262. }
  8263. #if defined(_WIN32)
  8264. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8265. #else
  8266. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8267. #endif
  8268. /* Data for getsockopt */
  8269. void *psockerr = &sockerr;
  8270. int ret;
  8271. #if defined(_WIN32)
  8272. int len = (int)sizeof(sockerr);
  8273. #else
  8274. socklen_t len = (socklen_t)sizeof(sockerr);
  8275. #endif
  8276. /* Data for poll */
  8277. struct mg_pollfd pfd[2];
  8278. int pollres;
  8279. int ms_wait = 10000; /* 10 second timeout */
  8280. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8281. unsigned int num_sock = 1; /* use one or two sockets */
  8282. /* For a non-blocking socket, the connect sequence is:
  8283. * 1) call connect (will not block)
  8284. * 2) wait until the socket is ready for writing (select or poll)
  8285. * 3) check connection state with getsockopt
  8286. */
  8287. pfd[0].fd = *sock;
  8288. pfd[0].events = POLLOUT;
  8289. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8290. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8291. pfd[num_sock].events = POLLIN;
  8292. num_sock++;
  8293. }
  8294. pollres =
  8295. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8296. if (pollres != 1) {
  8297. /* Not connected */
  8298. if (error != NULL) {
  8299. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8300. mg_snprintf(NULL,
  8301. NULL, /* No truncation check for ebuf */
  8302. error->text,
  8303. error->text_buffer_size,
  8304. "connect(%s:%d): timeout",
  8305. host,
  8306. port);
  8307. }
  8308. closesocket(*sock);
  8309. *sock = INVALID_SOCKET;
  8310. return 0;
  8311. }
  8312. #if defined(_WIN32)
  8313. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8314. #else
  8315. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8316. #endif
  8317. if ((ret == 0) && (sockerr == 0)) {
  8318. conn_ret = 0;
  8319. }
  8320. }
  8321. if (conn_ret != 0) {
  8322. /* Not connected */
  8323. if (error != NULL) {
  8324. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8325. error->code_sub = (unsigned)ERRNO;
  8326. mg_snprintf(NULL,
  8327. NULL, /* No truncation check for ebuf */
  8328. error->text,
  8329. error->text_buffer_size,
  8330. "connect(%s:%d): error %s",
  8331. host,
  8332. port,
  8333. strerror(sockerr));
  8334. }
  8335. closesocket(*sock);
  8336. *sock = INVALID_SOCKET;
  8337. return 0;
  8338. }
  8339. return 1;
  8340. }
  8341. CIVETWEB_API int
  8342. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8343. {
  8344. static const char *dont_escape = "._-$,;~()";
  8345. static const char *hex = "0123456789abcdef";
  8346. char *pos = dst;
  8347. const char *end = dst + dst_len - 1;
  8348. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8349. if (isalnum((unsigned char)*src)
  8350. || (strchr(dont_escape, *src) != NULL)) {
  8351. *pos = *src;
  8352. } else if (pos + 2 < end) {
  8353. pos[0] = '%';
  8354. pos[1] = hex[(unsigned char)*src >> 4];
  8355. pos[2] = hex[(unsigned char)*src & 0xf];
  8356. pos += 2;
  8357. } else {
  8358. break;
  8359. }
  8360. }
  8361. *pos = '\0';
  8362. return (*src == '\0') ? (int)(pos - dst) : -1;
  8363. }
  8364. /* Return 0 on success, non-zero if an error occurs. */
  8365. static int
  8366. print_dir_entry(struct mg_connection *conn, struct de *de)
  8367. {
  8368. size_t namesize, escsize, i;
  8369. char *href, *esc, *p;
  8370. char size[64], mod[64];
  8371. #if defined(REENTRANT_TIME)
  8372. struct tm _tm;
  8373. struct tm *tm = &_tm;
  8374. #else
  8375. struct tm *tm;
  8376. #endif
  8377. /* Estimate worst case size for encoding and escaping */
  8378. namesize = strlen(de->file_name) + 1;
  8379. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8380. href = (char *)mg_malloc(namesize * 3 + escsize);
  8381. if (href == NULL) {
  8382. return -1;
  8383. }
  8384. mg_url_encode(de->file_name, href, namesize * 3);
  8385. esc = NULL;
  8386. if (escsize > 0) {
  8387. /* HTML escaping needed */
  8388. esc = href + namesize * 3;
  8389. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8390. mg_strlcpy(p, de->file_name + i, 2);
  8391. if (*p == '&') {
  8392. strcpy(p, "&amp;");
  8393. } else if (*p == '<') {
  8394. strcpy(p, "&lt;");
  8395. } else if (*p == '>') {
  8396. strcpy(p, "&gt;");
  8397. }
  8398. }
  8399. }
  8400. if (de->file.is_directory) {
  8401. mg_snprintf(conn,
  8402. NULL, /* Buffer is big enough */
  8403. size,
  8404. sizeof(size),
  8405. "%s",
  8406. "[DIRECTORY]");
  8407. } else {
  8408. /* We use (signed) cast below because MSVC 6 compiler cannot
  8409. * convert unsigned __int64 to double. Sigh. */
  8410. if (de->file.size < 1024) {
  8411. mg_snprintf(conn,
  8412. NULL, /* Buffer is big enough */
  8413. size,
  8414. sizeof(size),
  8415. "%d",
  8416. (int)de->file.size);
  8417. } else if (de->file.size < 0x100000) {
  8418. mg_snprintf(conn,
  8419. NULL, /* Buffer is big enough */
  8420. size,
  8421. sizeof(size),
  8422. "%.1fk",
  8423. (double)de->file.size / 1024.0);
  8424. } else if (de->file.size < 0x40000000) {
  8425. mg_snprintf(conn,
  8426. NULL, /* Buffer is big enough */
  8427. size,
  8428. sizeof(size),
  8429. "%.1fM",
  8430. (double)de->file.size / 1048576);
  8431. } else {
  8432. mg_snprintf(conn,
  8433. NULL, /* Buffer is big enough */
  8434. size,
  8435. sizeof(size),
  8436. "%.1fG",
  8437. (double)de->file.size / 1073741824);
  8438. }
  8439. }
  8440. /* Note: mg_snprintf will not cause a buffer overflow above.
  8441. * So, string truncation checks are not required here. */
  8442. #if defined(REENTRANT_TIME)
  8443. localtime_r(&de->file.last_modified, tm);
  8444. #else
  8445. tm = localtime(&de->file.last_modified);
  8446. #endif
  8447. if (tm != NULL) {
  8448. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8449. } else {
  8450. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8451. }
  8452. mg_printf(conn,
  8453. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8454. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8455. href,
  8456. de->file.is_directory ? "/" : "",
  8457. esc ? esc : de->file_name,
  8458. de->file.is_directory ? "/" : "",
  8459. mod,
  8460. size);
  8461. mg_free(href);
  8462. return 0;
  8463. }
  8464. /* This function is called from send_directory() and used for
  8465. * sorting directory entries by size, name, or modification time. */
  8466. static int
  8467. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8468. {
  8469. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8470. if (p1 && p2) {
  8471. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8472. int cmp_result = 0;
  8473. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8474. query_string = "n";
  8475. }
  8476. /* Sort Directories vs Files */
  8477. if (a->file.is_directory && !b->file.is_directory) {
  8478. return -1; /* Always put directories on top */
  8479. } else if (!a->file.is_directory && b->file.is_directory) {
  8480. return 1; /* Always put directories on top */
  8481. }
  8482. /* Sort by size or date */
  8483. if (*query_string == 's') {
  8484. cmp_result = (a->file.size == b->file.size)
  8485. ? 0
  8486. : ((a->file.size > b->file.size) ? 1 : -1);
  8487. } else if (*query_string == 'd') {
  8488. cmp_result =
  8489. (a->file.last_modified == b->file.last_modified)
  8490. ? 0
  8491. : ((a->file.last_modified > b->file.last_modified) ? 1
  8492. : -1);
  8493. }
  8494. /* Sort by name:
  8495. * if (*query_string == 'n') ...
  8496. * but also sort files of same size/date by name as secondary criterion.
  8497. */
  8498. if (cmp_result == 0) {
  8499. cmp_result = strcmp(a->file_name, b->file_name);
  8500. }
  8501. /* For descending order, invert result */
  8502. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8503. }
  8504. return 0;
  8505. }
  8506. static int
  8507. must_hide_file(struct mg_connection *conn, const char *path)
  8508. {
  8509. if (conn && conn->dom_ctx) {
  8510. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8511. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8512. return (match_prefix_strlen(pw_pattern, path) > 0)
  8513. || (match_prefix_strlen(pattern, path) > 0);
  8514. }
  8515. return 0;
  8516. }
  8517. #if !defined(NO_FILESYSTEMS)
  8518. static int
  8519. scan_directory(struct mg_connection *conn,
  8520. const char *dir,
  8521. void *data,
  8522. int (*cb)(struct de *, void *))
  8523. {
  8524. char path[UTF8_PATH_MAX];
  8525. struct dirent *dp;
  8526. DIR *dirp;
  8527. struct de de;
  8528. int truncated;
  8529. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8530. return 0;
  8531. } else {
  8532. while ((dp = mg_readdir(dirp)) != NULL) {
  8533. /* Do not show current dir and hidden files */
  8534. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8535. || must_hide_file(conn, dp->d_name)) {
  8536. continue;
  8537. }
  8538. mg_snprintf(
  8539. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8540. /* If we don't memset stat structure to zero, mtime will have
  8541. * garbage and strftime() will segfault later on in
  8542. * print_dir_entry(). memset is required only if mg_stat()
  8543. * fails. For more details, see
  8544. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8545. memset(&de.file, 0, sizeof(de.file));
  8546. if (truncated) {
  8547. /* If the path is not complete, skip processing. */
  8548. continue;
  8549. }
  8550. if (!mg_stat(conn, path, &de.file)) {
  8551. mg_cry_internal(conn,
  8552. "%s: mg_stat(%s) failed: %s",
  8553. __func__,
  8554. path,
  8555. strerror(ERRNO));
  8556. }
  8557. de.file_name = dp->d_name;
  8558. if (cb(&de, data)) {
  8559. /* stopped */
  8560. break;
  8561. }
  8562. }
  8563. (void)mg_closedir(dirp);
  8564. }
  8565. return 1;
  8566. }
  8567. #endif /* NO_FILESYSTEMS */
  8568. #if !defined(NO_FILES)
  8569. static int
  8570. remove_directory(struct mg_connection *conn, const char *dir)
  8571. {
  8572. char path[UTF8_PATH_MAX];
  8573. struct dirent *dp;
  8574. DIR *dirp;
  8575. struct de de;
  8576. int truncated;
  8577. int ok = 1;
  8578. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8579. return 0;
  8580. } else {
  8581. while ((dp = mg_readdir(dirp)) != NULL) {
  8582. /* Do not show current dir (but show hidden files as they will
  8583. * also be removed) */
  8584. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8585. continue;
  8586. }
  8587. mg_snprintf(
  8588. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8589. /* If we don't memset stat structure to zero, mtime will have
  8590. * garbage and strftime() will segfault later on in
  8591. * print_dir_entry(). memset is required only if mg_stat()
  8592. * fails. For more details, see
  8593. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8594. memset(&de.file, 0, sizeof(de.file));
  8595. if (truncated) {
  8596. /* Do not delete anything shorter */
  8597. ok = 0;
  8598. continue;
  8599. }
  8600. if (!mg_stat(conn, path, &de.file)) {
  8601. mg_cry_internal(conn,
  8602. "%s: mg_stat(%s) failed: %s",
  8603. __func__,
  8604. path,
  8605. strerror(ERRNO));
  8606. ok = 0;
  8607. }
  8608. if (de.file.is_directory) {
  8609. if (remove_directory(conn, path) == 0) {
  8610. ok = 0;
  8611. }
  8612. } else {
  8613. /* This will fail file is the file is in memory */
  8614. if (mg_remove(conn, path) == 0) {
  8615. ok = 0;
  8616. }
  8617. }
  8618. }
  8619. (void)mg_closedir(dirp);
  8620. IGNORE_UNUSED_RESULT(rmdir(dir));
  8621. }
  8622. return ok;
  8623. }
  8624. #endif
  8625. struct dir_scan_data {
  8626. struct de *entries;
  8627. size_t num_entries;
  8628. size_t arr_size;
  8629. };
  8630. #if !defined(NO_FILESYSTEMS)
  8631. static int
  8632. dir_scan_callback(struct de *de, void *data)
  8633. {
  8634. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8635. struct de *entries = dsd->entries;
  8636. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8637. /* Here "entries" is a temporary pointer and can be replaced,
  8638. * "dsd->entries" is the original pointer */
  8639. entries =
  8640. (struct de *)mg_realloc(entries,
  8641. dsd->arr_size * 2 * sizeof(entries[0]));
  8642. if (entries == NULL) {
  8643. /* stop scan */
  8644. return 1;
  8645. }
  8646. dsd->entries = entries;
  8647. dsd->arr_size *= 2;
  8648. }
  8649. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8650. if (entries[dsd->num_entries].file_name == NULL) {
  8651. /* stop scan */
  8652. return 1;
  8653. }
  8654. entries[dsd->num_entries].file = de->file;
  8655. dsd->num_entries++;
  8656. return 0;
  8657. }
  8658. static void
  8659. handle_directory_request(struct mg_connection *conn, const char *dir)
  8660. {
  8661. size_t i;
  8662. int sort_direction;
  8663. struct dir_scan_data data = {NULL, 0, 128};
  8664. char date[64], *esc, *p;
  8665. const char *title;
  8666. time_t curtime = time(NULL);
  8667. if (!conn) {
  8668. return;
  8669. }
  8670. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8671. mg_send_http_error(conn,
  8672. 500,
  8673. "Error: Cannot open directory\nopendir(%s): %s",
  8674. dir,
  8675. strerror(ERRNO));
  8676. return;
  8677. }
  8678. gmt_time_string(date, sizeof(date), &curtime);
  8679. esc = NULL;
  8680. title = conn->request_info.local_uri;
  8681. if (title[strcspn(title, "&<>")]) {
  8682. /* HTML escaping needed */
  8683. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8684. if (esc) {
  8685. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8686. mg_strlcpy(p, title + i, 2);
  8687. if (*p == '&') {
  8688. strcpy(p, "&amp;");
  8689. } else if (*p == '<') {
  8690. strcpy(p, "&lt;");
  8691. } else if (*p == '>') {
  8692. strcpy(p, "&gt;");
  8693. }
  8694. }
  8695. } else {
  8696. title = "";
  8697. }
  8698. }
  8699. sort_direction = ((conn->request_info.query_string != NULL)
  8700. && (conn->request_info.query_string[0] != '\0')
  8701. && (conn->request_info.query_string[1] == 'd'))
  8702. ? 'a'
  8703. : 'd';
  8704. conn->must_close = 1;
  8705. /* Create 200 OK response */
  8706. mg_response_header_start(conn, 200);
  8707. send_static_cache_header(conn);
  8708. send_additional_header(conn);
  8709. mg_response_header_add(conn,
  8710. "Content-Type",
  8711. "text/html; charset=utf-8",
  8712. -1);
  8713. /* Send all headers */
  8714. mg_response_header_send(conn);
  8715. /* Body */
  8716. mg_printf(conn,
  8717. "<!DOCTYPE html>"
  8718. "<html><head><title>Index of %s</title>"
  8719. "<style>th {text-align: left;}</style></head>"
  8720. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8721. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8722. "<th><a href=\"?d%c\">Modified</a></th>"
  8723. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8724. "<tr><td colspan=\"3\"><hr></td></tr>",
  8725. esc ? esc : title,
  8726. esc ? esc : title,
  8727. sort_direction,
  8728. sort_direction,
  8729. sort_direction);
  8730. mg_free(esc);
  8731. /* Print first entry - link to a parent directory */
  8732. mg_printf(conn,
  8733. "<tr><td><a href=\"%s\">%s</a></td>"
  8734. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8735. "..",
  8736. "Parent directory",
  8737. "-",
  8738. "-");
  8739. /* Sort and print directory entries */
  8740. if (data.entries != NULL) {
  8741. mg_sort(data.entries,
  8742. data.num_entries,
  8743. sizeof(data.entries[0]),
  8744. compare_dir_entries,
  8745. (void *)conn->request_info.query_string);
  8746. for (i = 0; i < data.num_entries; i++) {
  8747. print_dir_entry(conn, &data.entries[i]);
  8748. mg_free(data.entries[i].file_name);
  8749. }
  8750. mg_free(data.entries);
  8751. }
  8752. mg_printf(conn, "%s", "</table></pre></body></html>");
  8753. conn->status_code = 200;
  8754. }
  8755. #endif /* NO_FILESYSTEMS */
  8756. /* Send len bytes from the opened file to the client. */
  8757. static void
  8758. send_file_data(struct mg_connection *conn,
  8759. struct mg_file *filep,
  8760. int64_t offset,
  8761. int64_t len,
  8762. int no_buffering)
  8763. {
  8764. char buf[MG_BUF_LEN];
  8765. int to_read, num_read, num_written;
  8766. int64_t size;
  8767. if (!filep || !conn) {
  8768. return;
  8769. }
  8770. /* Sanity check the offset */
  8771. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8772. : (int64_t)(filep->stat.size);
  8773. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8774. if (len > 0 && filep->access.fp != NULL) {
  8775. /* file stored on disk */
  8776. #if defined(__linux__)
  8777. /* sendfile is only available for Linux */
  8778. if ((conn->ssl == 0) && (conn->throttle == 0)
  8779. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8780. "yes"))) {
  8781. off_t sf_offs = (off_t)offset;
  8782. ssize_t sf_sent;
  8783. int sf_file = fileno(filep->access.fp);
  8784. int loop_cnt = 0;
  8785. do {
  8786. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8787. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8788. size_t sf_tosend =
  8789. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8790. sf_sent =
  8791. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8792. if (sf_sent > 0) {
  8793. len -= sf_sent;
  8794. offset += sf_sent;
  8795. } else if (loop_cnt == 0) {
  8796. /* This file can not be sent using sendfile.
  8797. * This might be the case for pseudo-files in the
  8798. * /sys/ and /proc/ file system.
  8799. * Use the regular user mode copy code instead. */
  8800. break;
  8801. } else if (sf_sent == 0) {
  8802. /* No error, but 0 bytes sent. May be EOF? */
  8803. return;
  8804. }
  8805. loop_cnt++;
  8806. } while ((len > 0) && (sf_sent >= 0));
  8807. if (sf_sent > 0) {
  8808. return; /* OK */
  8809. }
  8810. /* sf_sent<0 means error, thus fall back to the classic way */
  8811. /* This is always the case, if sf_file is not a "normal" file,
  8812. * e.g., for sending data from the output of a CGI process. */
  8813. offset = (int64_t)sf_offs;
  8814. }
  8815. #endif
  8816. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8817. mg_cry_internal(conn,
  8818. "%s: fseeko() failed: %s",
  8819. __func__,
  8820. strerror(ERRNO));
  8821. mg_send_http_error(
  8822. conn,
  8823. 500,
  8824. "%s",
  8825. "Error: Unable to access file at requested position.");
  8826. } else {
  8827. while (len > 0) {
  8828. /* Calculate how much to read from the file into the buffer. */
  8829. /* If no_buffering is set, we should not wait until the
  8830. * CGI->Server buffer is filled, but send everything
  8831. * immediately. In theory buffering could be turned off using
  8832. * setbuf(filep->access.fp, NULL);
  8833. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8834. * but in practice this does not work. A "Linux only" solution
  8835. * may be to use select(). The only portable way is to read byte
  8836. * by byte, but this is quite inefficient from a performance
  8837. * point of view. */
  8838. to_read = no_buffering ? 1 : sizeof(buf);
  8839. if ((int64_t)to_read > len) {
  8840. to_read = (int)len;
  8841. }
  8842. /* Read from file, exit the loop on error */
  8843. if ((num_read =
  8844. pull_inner(filep->access.fp, NULL, buf, to_read, /* unused */ 0.0))
  8845. <= 0) {
  8846. break;
  8847. }
  8848. /* Send read bytes to the client, exit the loop on error */
  8849. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8850. != num_read) {
  8851. break;
  8852. }
  8853. /* Both read and were successful, adjust counters */
  8854. len -= num_written;
  8855. }
  8856. }
  8857. }
  8858. }
  8859. static int
  8860. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8861. {
  8862. return sscanf(header,
  8863. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8864. a,
  8865. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8866. // to an integer value, but function will not report
  8867. // conversion errors; consider using 'strtol' instead
  8868. }
  8869. static void
  8870. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8871. {
  8872. if ((filestat != NULL) && (buf != NULL)) {
  8873. mg_snprintf(NULL,
  8874. NULL, /* All calls to construct_etag use 64 byte buffer */
  8875. buf,
  8876. buf_len,
  8877. "\"%lx.%" INT64_FMT "\"",
  8878. (unsigned long)filestat->last_modified,
  8879. filestat->size);
  8880. }
  8881. }
  8882. static void
  8883. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8884. {
  8885. if (filep != NULL && filep->fp != NULL) {
  8886. #if defined(_WIN32)
  8887. (void)conn; /* Unused. */
  8888. #else
  8889. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8890. mg_cry_internal(conn,
  8891. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8892. __func__,
  8893. strerror(ERRNO));
  8894. }
  8895. #endif
  8896. }
  8897. }
  8898. #if defined(USE_ZLIB)
  8899. #include "mod_zlib.inl"
  8900. #endif
  8901. #if !defined(NO_FILESYSTEMS)
  8902. static void
  8903. handle_static_file_request(struct mg_connection *conn,
  8904. const char *path,
  8905. struct mg_file *filep,
  8906. const char *mime_type,
  8907. const char *additional_headers)
  8908. {
  8909. char lm[64], etag[64];
  8910. char range[128]; /* large enough, so there will be no overflow */
  8911. const char *range_hdr;
  8912. int64_t cl, r1, r2;
  8913. struct vec mime_vec;
  8914. int n, truncated;
  8915. char gz_path[UTF8_PATH_MAX];
  8916. const char *encoding = 0;
  8917. int is_head_request;
  8918. #if defined(USE_ZLIB)
  8919. /* Compression is allowed, unless there is a reason not to use
  8920. * compression. If the file is already compressed, too small or a
  8921. * "range" request was made, on the fly compression is not possible. */
  8922. int allow_on_the_fly_compression = 1;
  8923. #endif
  8924. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8925. return;
  8926. }
  8927. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8928. if (mime_type == NULL) {
  8929. get_mime_type(conn, path, &mime_vec);
  8930. } else {
  8931. mime_vec.ptr = mime_type;
  8932. mime_vec.len = strlen(mime_type);
  8933. }
  8934. if (filep->stat.size > INT64_MAX) {
  8935. mg_send_http_error(conn,
  8936. 500,
  8937. "Error: File size is too large to send\n%" INT64_FMT,
  8938. filep->stat.size);
  8939. return;
  8940. }
  8941. cl = (int64_t)filep->stat.size;
  8942. conn->status_code = 200;
  8943. range[0] = '\0';
  8944. #if defined(USE_ZLIB)
  8945. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8946. * it's important to rewrite the filename after resolving
  8947. * the mime type from it, to preserve the actual file's type */
  8948. if (!conn->accept_gzip) {
  8949. allow_on_the_fly_compression = 0;
  8950. }
  8951. #endif
  8952. /* Check if there is a range header */
  8953. range_hdr = mg_get_header(conn, "Range");
  8954. /* For gzipped files, add *.gz */
  8955. if (filep->stat.is_gzipped) {
  8956. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8957. if (truncated) {
  8958. mg_send_http_error(conn,
  8959. 500,
  8960. "Error: Path of zipped file too long (%s)",
  8961. path);
  8962. return;
  8963. }
  8964. path = gz_path;
  8965. encoding = "gzip";
  8966. #if defined(USE_ZLIB)
  8967. /* File is already compressed. No "on the fly" compression. */
  8968. allow_on_the_fly_compression = 0;
  8969. #endif
  8970. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8971. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8972. struct mg_file_stat file_stat;
  8973. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8974. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8975. && !file_stat.is_directory) {
  8976. file_stat.is_gzipped = 1;
  8977. filep->stat = file_stat;
  8978. cl = (int64_t)filep->stat.size;
  8979. path = gz_path;
  8980. encoding = "gzip";
  8981. #if defined(USE_ZLIB)
  8982. /* File is already compressed. No "on the fly" compression. */
  8983. allow_on_the_fly_compression = 0;
  8984. #endif
  8985. }
  8986. }
  8987. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8988. mg_send_http_error(conn,
  8989. 500,
  8990. "Error: Cannot open file\nfopen(%s): %s",
  8991. path,
  8992. strerror(ERRNO));
  8993. return;
  8994. }
  8995. fclose_on_exec(&filep->access, conn);
  8996. /* If "Range" request was made: parse header, send only selected part
  8997. * of the file. */
  8998. r1 = r2 = 0;
  8999. if ((range_hdr != NULL)
  9000. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9001. && (r2 >= 0)) {
  9002. /* actually, range requests don't play well with a pre-gzipped
  9003. * file (since the range is specified in the uncompressed space) */
  9004. if (filep->stat.is_gzipped) {
  9005. mg_send_http_error(
  9006. conn,
  9007. 416, /* 416 = Range Not Satisfiable */
  9008. "%s",
  9009. "Error: Range requests in gzipped files are not supported");
  9010. (void)mg_fclose(
  9011. &filep->access); /* ignore error on read only file */
  9012. return;
  9013. }
  9014. conn->status_code = 206;
  9015. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9016. mg_snprintf(conn,
  9017. NULL, /* range buffer is big enough */
  9018. range,
  9019. sizeof(range),
  9020. "bytes "
  9021. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9022. r1,
  9023. r1 + cl - 1,
  9024. filep->stat.size);
  9025. #if defined(USE_ZLIB)
  9026. /* Do not compress ranges. */
  9027. allow_on_the_fly_compression = 0;
  9028. #endif
  9029. }
  9030. /* Do not compress small files. Small files do not benefit from file
  9031. * compression, but there is still some overhead. */
  9032. #if defined(USE_ZLIB)
  9033. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9034. /* File is below the size limit. */
  9035. allow_on_the_fly_compression = 0;
  9036. }
  9037. #endif
  9038. /* Prepare Etag, and Last-Modified headers. */
  9039. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9040. construct_etag(etag, sizeof(etag), &filep->stat);
  9041. /* Create 2xx (200, 206) response */
  9042. mg_response_header_start(conn, conn->status_code);
  9043. send_static_cache_header(conn);
  9044. send_additional_header(conn);
  9045. send_cors_header(conn);
  9046. mg_response_header_add(conn,
  9047. "Content-Type",
  9048. mime_vec.ptr,
  9049. (int)mime_vec.len);
  9050. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9051. mg_response_header_add(conn, "Etag", etag, -1);
  9052. #if defined(USE_ZLIB)
  9053. /* On the fly compression allowed */
  9054. if (allow_on_the_fly_compression) {
  9055. /* For on the fly compression, we don't know the content size in
  9056. * advance, so we have to use chunked encoding */
  9057. encoding = "gzip";
  9058. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9059. /* HTTP/2 is always using "chunks" (frames) */
  9060. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9061. }
  9062. } else
  9063. #endif
  9064. {
  9065. /* Without on-the-fly compression, we know the content-length
  9066. * and we can use ranges (with on-the-fly compression we cannot).
  9067. * So we send these response headers only in this case. */
  9068. char len[32];
  9069. int trunc = 0;
  9070. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9071. if (!trunc) {
  9072. mg_response_header_add(conn, "Content-Length", len, -1);
  9073. }
  9074. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9075. }
  9076. if (encoding) {
  9077. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9078. }
  9079. if (range[0] != 0) {
  9080. mg_response_header_add(conn, "Content-Range", range, -1);
  9081. }
  9082. /* The code above does not add any header starting with X- to make
  9083. * sure no one of the additional_headers is included twice */
  9084. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9085. mg_response_header_add_lines(conn, additional_headers);
  9086. }
  9087. /* Send all headers */
  9088. mg_response_header_send(conn);
  9089. if (!is_head_request) {
  9090. #if defined(USE_ZLIB)
  9091. if (allow_on_the_fly_compression) {
  9092. /* Compress and send */
  9093. send_compressed_data(conn, filep);
  9094. } else
  9095. #endif
  9096. {
  9097. /* Send file directly */
  9098. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9099. }
  9100. }
  9101. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9102. }
  9103. CIVETWEB_API int
  9104. mg_send_file_body(struct mg_connection *conn, const char *path)
  9105. {
  9106. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9107. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9108. return -1;
  9109. }
  9110. fclose_on_exec(&file.access, conn);
  9111. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9112. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9113. return 0; /* >= 0 for OK */
  9114. }
  9115. #endif /* NO_FILESYSTEMS */
  9116. #if !defined(NO_CACHING)
  9117. /* Return True if we should reply 304 Not Modified. */
  9118. static int
  9119. is_not_modified(const struct mg_connection *conn,
  9120. const struct mg_file_stat *filestat)
  9121. {
  9122. char etag[64];
  9123. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9124. const char *inm = mg_get_header(conn, "If-None-Match");
  9125. construct_etag(etag, sizeof(etag), filestat);
  9126. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9127. || ((ims != NULL)
  9128. && (filestat->last_modified <= parse_date_string(ims)));
  9129. }
  9130. static void
  9131. handle_not_modified_static_file_request(struct mg_connection *conn,
  9132. struct mg_file *filep)
  9133. {
  9134. char lm[64], etag[64];
  9135. if ((conn == NULL) || (filep == NULL)) {
  9136. return;
  9137. }
  9138. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9139. construct_etag(etag, sizeof(etag), &filep->stat);
  9140. /* Create 304 "not modified" response */
  9141. mg_response_header_start(conn, 304);
  9142. send_static_cache_header(conn);
  9143. send_additional_header(conn);
  9144. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9145. mg_response_header_add(conn, "Etag", etag, -1);
  9146. /* Send all headers */
  9147. mg_response_header_send(conn);
  9148. }
  9149. #endif
  9150. #if !defined(NO_FILESYSTEMS)
  9151. CIVETWEB_API void
  9152. mg_send_file(struct mg_connection *conn, const char *path)
  9153. {
  9154. mg_send_mime_file2(conn, path, NULL, NULL);
  9155. }
  9156. CIVETWEB_API void
  9157. mg_send_mime_file(struct mg_connection *conn,
  9158. const char *path,
  9159. const char *mime_type)
  9160. {
  9161. mg_send_mime_file2(conn, path, mime_type, NULL);
  9162. }
  9163. CIVETWEB_API void
  9164. mg_send_mime_file2(struct mg_connection *conn,
  9165. const char *path,
  9166. const char *mime_type,
  9167. const char *additional_headers)
  9168. {
  9169. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9170. if (!conn) {
  9171. /* No conn */
  9172. return;
  9173. }
  9174. if (mg_stat(conn, path, &file.stat)) {
  9175. #if !defined(NO_CACHING)
  9176. if (is_not_modified(conn, &file.stat)) {
  9177. /* Send 304 "Not Modified" - this must not send any body data */
  9178. handle_not_modified_static_file_request(conn, &file);
  9179. } else
  9180. #endif /* NO_CACHING */
  9181. if (file.stat.is_directory) {
  9182. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9183. "yes")) {
  9184. handle_directory_request(conn, path);
  9185. } else {
  9186. mg_send_http_error(conn,
  9187. 403,
  9188. "%s",
  9189. "Error: Directory listing denied");
  9190. }
  9191. } else {
  9192. handle_static_file_request(
  9193. conn, path, &file, mime_type, additional_headers);
  9194. }
  9195. } else {
  9196. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9197. }
  9198. }
  9199. /* For a given PUT path, create all intermediate subdirectories.
  9200. * Return 0 if the path itself is a directory.
  9201. * Return 1 if the path leads to a file.
  9202. * Return -1 for if the path is too long.
  9203. * Return -2 if path can not be created.
  9204. */
  9205. static int
  9206. put_dir(struct mg_connection *conn, const char *path)
  9207. {
  9208. char buf[UTF8_PATH_MAX];
  9209. const char *s, *p;
  9210. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9211. size_t len;
  9212. int res = 1;
  9213. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9214. len = (size_t)(p - path);
  9215. if (len >= sizeof(buf)) {
  9216. /* path too long */
  9217. res = -1;
  9218. break;
  9219. }
  9220. memcpy(buf, path, len);
  9221. buf[len] = '\0';
  9222. /* Try to create intermediate directory */
  9223. DEBUG_TRACE("mkdir(%s)", buf);
  9224. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9225. /* path does not exist and can not be created */
  9226. res = -2;
  9227. break;
  9228. }
  9229. /* Is path itself a directory? */
  9230. if (p[1] == '\0') {
  9231. res = 0;
  9232. }
  9233. }
  9234. return res;
  9235. }
  9236. static void
  9237. remove_bad_file(const struct mg_connection *conn, const char *path)
  9238. {
  9239. int r = mg_remove(conn, path);
  9240. if (r != 0) {
  9241. mg_cry_internal(conn,
  9242. "%s: Cannot remove invalid file %s",
  9243. __func__,
  9244. path);
  9245. }
  9246. }
  9247. CIVETWEB_API long long
  9248. mg_store_body(struct mg_connection *conn, const char *path)
  9249. {
  9250. char buf[MG_BUF_LEN];
  9251. long long len = 0;
  9252. int ret, n;
  9253. struct mg_file fi;
  9254. if (conn->consumed_content != 0) {
  9255. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9256. return -11;
  9257. }
  9258. ret = put_dir(conn, path);
  9259. if (ret < 0) {
  9260. /* -1 for path too long,
  9261. * -2 for path can not be created. */
  9262. return ret;
  9263. }
  9264. if (ret != 1) {
  9265. /* Return 0 means, path itself is a directory. */
  9266. return 0;
  9267. }
  9268. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9269. return -12;
  9270. }
  9271. ret = mg_read(conn, buf, sizeof(buf));
  9272. while (ret > 0) {
  9273. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9274. if (n != ret) {
  9275. (void)mg_fclose(
  9276. &fi.access); /* File is bad and will be removed anyway. */
  9277. remove_bad_file(conn, path);
  9278. return -13;
  9279. }
  9280. len += ret;
  9281. ret = mg_read(conn, buf, sizeof(buf));
  9282. }
  9283. /* File is open for writing. If fclose fails, there was probably an
  9284. * error flushing the buffer to disk, so the file on disk might be
  9285. * broken. Delete it and return an error to the caller. */
  9286. if (mg_fclose(&fi.access) != 0) {
  9287. remove_bad_file(conn, path);
  9288. return -14;
  9289. }
  9290. return len;
  9291. }
  9292. #endif /* NO_FILESYSTEMS */
  9293. /* Parse a buffer:
  9294. * Forward the string pointer till the end of a word, then
  9295. * terminate it and forward till the begin of the next word.
  9296. */
  9297. static int
  9298. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9299. {
  9300. /* Forward until a space is found - use isgraph here */
  9301. /* Extended ASCII characters are also treated as word characters. */
  9302. /* See http://www.cplusplus.com/reference/cctype/ */
  9303. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9304. (*ppw)++;
  9305. }
  9306. /* Check end of word */
  9307. if (eol) {
  9308. /* must be a end of line */
  9309. if ((**ppw != '\r') && (**ppw != '\n')) {
  9310. return -1;
  9311. }
  9312. } else {
  9313. /* must be a end of a word, but not a line */
  9314. if (**ppw != ' ') {
  9315. return -1;
  9316. }
  9317. }
  9318. /* Terminate and forward to the next word */
  9319. do {
  9320. **ppw = 0;
  9321. (*ppw)++;
  9322. } while (isspace((unsigned char)**ppw));
  9323. /* Check after term */
  9324. if (!eol) {
  9325. /* if it's not the end of line, there must be a next word */
  9326. if (!isgraph((unsigned char)**ppw)) {
  9327. return -1;
  9328. }
  9329. }
  9330. /* ok */
  9331. return 1;
  9332. }
  9333. /* Parse HTTP headers from the given buffer, advance buf pointer
  9334. * to the point where parsing stopped.
  9335. * All parameters must be valid pointers (not NULL).
  9336. * Return <0 on error. */
  9337. static int
  9338. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9339. {
  9340. int i;
  9341. int num_headers = 0;
  9342. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9343. char *dp = *buf;
  9344. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9345. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9346. dp++;
  9347. }
  9348. if (dp == *buf) {
  9349. /* End of headers reached. */
  9350. break;
  9351. }
  9352. /* Drop all spaces after header name before : */
  9353. while (*dp == ' ') {
  9354. *dp = 0;
  9355. dp++;
  9356. }
  9357. if (*dp != ':') {
  9358. /* This is not a valid field. */
  9359. return -1;
  9360. }
  9361. /* End of header key (*dp == ':') */
  9362. /* Truncate here and set the key name */
  9363. *dp = 0;
  9364. hdr[i].name = *buf;
  9365. /* Skip all spaces */
  9366. do {
  9367. dp++;
  9368. } while ((*dp == ' ') || (*dp == '\t'));
  9369. /* The rest of the line is the value */
  9370. hdr[i].value = dp;
  9371. /* Find end of line */
  9372. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9373. dp++;
  9374. };
  9375. /* eliminate \r */
  9376. if (*dp == '\r') {
  9377. *dp = 0;
  9378. dp++;
  9379. if (*dp != '\n') {
  9380. /* This is not a valid line. */
  9381. return -1;
  9382. }
  9383. }
  9384. /* here *dp is either 0 or '\n' */
  9385. /* in any case, we have a new header */
  9386. num_headers = i + 1;
  9387. if (*dp) {
  9388. *dp = 0;
  9389. dp++;
  9390. *buf = dp;
  9391. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9392. /* This is the end of the header */
  9393. break;
  9394. }
  9395. } else {
  9396. *buf = dp;
  9397. break;
  9398. }
  9399. }
  9400. return num_headers;
  9401. }
  9402. struct mg_http_method_info {
  9403. const char *name;
  9404. int request_has_body;
  9405. int response_has_body;
  9406. int is_safe;
  9407. int is_idempotent;
  9408. int is_cacheable;
  9409. };
  9410. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9411. static const struct mg_http_method_info http_methods[] = {
  9412. /* HTTP (RFC 2616) */
  9413. {"GET", 0, 1, 1, 1, 1},
  9414. {"POST", 1, 1, 0, 0, 0},
  9415. {"PUT", 1, 0, 0, 1, 0},
  9416. {"DELETE", 0, 0, 0, 1, 0},
  9417. {"HEAD", 0, 0, 1, 1, 1},
  9418. {"OPTIONS", 0, 0, 1, 1, 0},
  9419. {"CONNECT", 1, 1, 0, 0, 0},
  9420. /* TRACE method (RFC 2616) is not supported for security reasons */
  9421. /* PATCH method (RFC 5789) */
  9422. {"PATCH", 1, 0, 0, 0, 0},
  9423. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9424. /* WEBDAV (RFC 2518) */
  9425. {"PROPFIND", 0, 1, 1, 1, 0},
  9426. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9427. * Some PROPFIND results MAY be cached, with care,
  9428. * as there is no cache validation mechanism for
  9429. * most properties. This method is both safe and
  9430. * idempotent (see Section 9.1 of [RFC2616]). */
  9431. {"MKCOL", 0, 0, 0, 1, 0},
  9432. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9433. * When MKCOL is invoked without a request body,
  9434. * the newly created collection SHOULD have no
  9435. * members. A MKCOL request message may contain
  9436. * a message body. The precise behavior of a MKCOL
  9437. * request when the body is present is undefined,
  9438. * ... ==> We do not support MKCOL with body data.
  9439. * This method is idempotent, but not safe (see
  9440. * Section 9.1 of [RFC2616]). Responses to this
  9441. * method MUST NOT be cached. */
  9442. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9443. {"LOCK", 1, 1, 0, 0, 0},
  9444. {"UNLOCK", 1, 0, 0, 0, 0},
  9445. {"PROPPATCH", 1, 1, 0, 0, 0},
  9446. {"COPY", 1, 0, 0, 0, 0},
  9447. {"MOVE", 1, 1, 0, 0, 0},
  9448. /* Unsupported WEBDAV Methods: */
  9449. /* + 11 methods from RFC 3253 */
  9450. /* ORDERPATCH (RFC 3648) */
  9451. /* ACL (RFC 3744) */
  9452. /* SEARCH (RFC 5323) */
  9453. /* + MicroSoft extensions
  9454. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9455. /* REPORT method (RFC 3253) */
  9456. {"REPORT", 1, 1, 1, 1, 1},
  9457. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9458. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9459. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9460. * to be useful for REST in case a "GET request with body" is
  9461. * required. */
  9462. {NULL, 0, 0, 0, 0, 0}
  9463. /* end of list */
  9464. };
  9465. /* All method names */
  9466. static char *all_methods = NULL; /* Built by mg_init_library */
  9467. static const struct mg_http_method_info *
  9468. get_http_method_info(const char *method)
  9469. {
  9470. /* Check if the method is known to the server. The list of all known
  9471. * HTTP methods can be found here at
  9472. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9473. */
  9474. const struct mg_http_method_info *m = http_methods;
  9475. while (m->name) {
  9476. if (!strcmp(m->name, method)) {
  9477. return m;
  9478. }
  9479. m++;
  9480. }
  9481. return NULL;
  9482. }
  9483. static int
  9484. is_valid_http_method(const char *method)
  9485. {
  9486. return (get_http_method_info(method) != NULL);
  9487. }
  9488. /* Parse HTTP request, fill in mg_request_info structure.
  9489. * This function modifies the buffer by NUL-terminating
  9490. * HTTP request components, header names and header values.
  9491. * Parameters:
  9492. * buf (in/out): pointer to the HTTP header to parse and split
  9493. * len (in): length of HTTP header buffer
  9494. * re (out): parsed header as mg_request_info
  9495. * buf and ri must be valid pointers (not NULL), len>0.
  9496. * Returns <0 on error. */
  9497. static int
  9498. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9499. {
  9500. int request_length;
  9501. int init_skip = 0;
  9502. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9503. * remote_port */
  9504. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9505. NULL;
  9506. ri->num_headers = 0;
  9507. /* RFC says that all initial whitespaces should be ignored */
  9508. /* This included all leading \r and \n (isspace) */
  9509. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9510. while ((len > 0) && isspace((unsigned char)*buf)) {
  9511. buf++;
  9512. len--;
  9513. init_skip++;
  9514. }
  9515. if (len == 0) {
  9516. /* Incomplete request */
  9517. return 0;
  9518. }
  9519. /* Control characters are not allowed, including zero */
  9520. if (iscntrl((unsigned char)*buf)) {
  9521. return -1;
  9522. }
  9523. /* Find end of HTTP header */
  9524. request_length = get_http_header_len(buf, len);
  9525. if (request_length <= 0) {
  9526. return request_length;
  9527. }
  9528. buf[request_length - 1] = '\0';
  9529. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9530. return -1;
  9531. }
  9532. /* The first word has to be the HTTP method */
  9533. ri->request_method = buf;
  9534. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9535. return -1;
  9536. }
  9537. /* The second word is the URI */
  9538. ri->request_uri = buf;
  9539. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9540. return -1;
  9541. }
  9542. /* Next would be the HTTP version */
  9543. ri->http_version = buf;
  9544. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9545. return -1;
  9546. }
  9547. /* Check for a valid HTTP version key */
  9548. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9549. /* Invalid request */
  9550. return -1;
  9551. }
  9552. ri->http_version += 5;
  9553. /* Check for a valid http method */
  9554. if (!is_valid_http_method(ri->request_method)) {
  9555. return -1;
  9556. }
  9557. /* Parse all HTTP headers */
  9558. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9559. if (ri->num_headers < 0) {
  9560. /* Error while parsing headers */
  9561. return -1;
  9562. }
  9563. return request_length + init_skip;
  9564. }
  9565. static int
  9566. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9567. {
  9568. int response_length;
  9569. int init_skip = 0;
  9570. char *tmp, *tmp2;
  9571. long l;
  9572. /* Initialize elements. */
  9573. ri->http_version = ri->status_text = NULL;
  9574. ri->num_headers = ri->status_code = 0;
  9575. /* RFC says that all initial whitespaces should be ignored */
  9576. /* This included all leading \r and \n (isspace) */
  9577. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9578. while ((len > 0) && isspace((unsigned char)*buf)) {
  9579. buf++;
  9580. len--;
  9581. init_skip++;
  9582. }
  9583. if (len == 0) {
  9584. /* Incomplete request */
  9585. return 0;
  9586. }
  9587. /* Control characters are not allowed, including zero */
  9588. if (iscntrl((unsigned char)*buf)) {
  9589. return -1;
  9590. }
  9591. /* Find end of HTTP header */
  9592. response_length = get_http_header_len(buf, len);
  9593. if (response_length <= 0) {
  9594. return response_length;
  9595. }
  9596. buf[response_length - 1] = '\0';
  9597. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9598. return -1;
  9599. }
  9600. /* The first word is the HTTP version */
  9601. /* Check for a valid HTTP version key */
  9602. if (strncmp(buf, "HTTP/", 5) != 0) {
  9603. /* Invalid request */
  9604. return -1;
  9605. }
  9606. buf += 5;
  9607. if (!isgraph((unsigned char)buf[0])) {
  9608. /* Invalid request */
  9609. return -1;
  9610. }
  9611. ri->http_version = buf;
  9612. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9613. return -1;
  9614. }
  9615. /* The second word is the status as a number */
  9616. tmp = buf;
  9617. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9618. return -1;
  9619. }
  9620. l = strtol(tmp, &tmp2, 10);
  9621. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9622. /* Everything else but a 3 digit code is invalid */
  9623. return -1;
  9624. }
  9625. ri->status_code = (int)l;
  9626. /* The rest of the line is the status text */
  9627. ri->status_text = buf;
  9628. /* Find end of status text */
  9629. /* isgraph or isspace = isprint */
  9630. while (isprint((unsigned char)*buf)) {
  9631. buf++;
  9632. }
  9633. if ((*buf != '\r') && (*buf != '\n')) {
  9634. return -1;
  9635. }
  9636. /* Terminate string and forward buf to next line */
  9637. do {
  9638. *buf = 0;
  9639. buf++;
  9640. } while (isspace((unsigned char)*buf));
  9641. /* Parse all HTTP headers */
  9642. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9643. if (ri->num_headers < 0) {
  9644. /* Error while parsing headers */
  9645. return -1;
  9646. }
  9647. return response_length + init_skip;
  9648. }
  9649. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9650. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9651. * buffer (which marks the end of HTTP request). Buffer buf may already
  9652. * have some data. The length of the data is stored in nread.
  9653. * Upon every read operation, increase nread by the number of bytes read. */
  9654. static int
  9655. read_message(FILE *fp,
  9656. struct mg_connection *conn,
  9657. char *buf,
  9658. int bufsiz,
  9659. int *nread)
  9660. {
  9661. int request_len, n = 0;
  9662. struct timespec last_action_time;
  9663. double request_timeout;
  9664. if (!conn) {
  9665. return 0;
  9666. }
  9667. memset(&last_action_time, 0, sizeof(last_action_time));
  9668. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9669. /* value of request_timeout is in seconds, config in milliseconds */
  9670. request_timeout =
  9671. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9672. } else {
  9673. request_timeout =
  9674. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9675. / 1000.0;
  9676. }
  9677. if (conn->handled_requests > 0) {
  9678. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9679. request_timeout =
  9680. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9681. / 1000.0;
  9682. }
  9683. }
  9684. request_len = get_http_header_len(buf, *nread);
  9685. while (request_len == 0) {
  9686. /* Full request not yet received */
  9687. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9688. /* Server is to be stopped. */
  9689. return -1;
  9690. }
  9691. if (*nread >= bufsiz) {
  9692. /* Request too long */
  9693. return -2;
  9694. }
  9695. n = pull_inner(
  9696. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9697. if (n == -2) {
  9698. /* Receive error */
  9699. return -1;
  9700. }
  9701. /* update clock after every read request */
  9702. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9703. if (n > 0) {
  9704. *nread += n;
  9705. request_len = get_http_header_len(buf, *nread);
  9706. }
  9707. if ((n <= 0) && (request_timeout >= 0)) {
  9708. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9709. > request_timeout) {
  9710. /* Timeout */
  9711. return -3;
  9712. }
  9713. }
  9714. }
  9715. return request_len;
  9716. }
  9717. #if !defined(NO_CGI) || !defined(NO_FILES)
  9718. static int
  9719. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9720. {
  9721. const char *expect;
  9722. char buf[MG_BUF_LEN];
  9723. int success = 0;
  9724. if (!conn) {
  9725. return 0;
  9726. }
  9727. expect = mg_get_header(conn, "Expect");
  9728. DEBUG_ASSERT(fp != NULL);
  9729. if (!fp) {
  9730. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9731. return 0;
  9732. }
  9733. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9734. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9735. */
  9736. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9737. } else {
  9738. if (expect != NULL) {
  9739. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9740. conn->status_code = 100;
  9741. } else {
  9742. conn->status_code = 200;
  9743. }
  9744. DEBUG_ASSERT(conn->consumed_content == 0);
  9745. if (conn->consumed_content != 0) {
  9746. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9747. return 0;
  9748. }
  9749. for (;;) {
  9750. int nread = mg_read(conn, buf, sizeof(buf));
  9751. if (nread <= 0) {
  9752. success = (nread == 0);
  9753. break;
  9754. }
  9755. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9756. break;
  9757. }
  9758. }
  9759. /* Each error code path in this function must send an error */
  9760. if (!success) {
  9761. /* NOTE: Maybe some data has already been sent. */
  9762. /* TODO (low): If some data has been sent, a correct error
  9763. * reply can no longer be sent, so just close the connection */
  9764. mg_send_http_error(conn, 500, "%s", "");
  9765. }
  9766. }
  9767. return success;
  9768. }
  9769. #endif
  9770. #if defined(USE_TIMERS)
  9771. #define TIMER_API static
  9772. #include "timer.inl"
  9773. #endif /* USE_TIMERS */
  9774. #if !defined(NO_CGI)
  9775. /* This structure helps to create an environment for the spawned CGI
  9776. * program.
  9777. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9778. * last element must be NULL.
  9779. * However, on Windows there is a requirement that all these
  9780. * VARIABLE=VALUE\0
  9781. * strings must reside in a contiguous buffer. The end of the buffer is
  9782. * marked by two '\0' characters.
  9783. * We satisfy both worlds: we create an envp array (which is vars), all
  9784. * entries are actually pointers inside buf. */
  9785. struct cgi_environment {
  9786. struct mg_connection *conn;
  9787. /* Data block */
  9788. char *buf; /* Environment buffer */
  9789. size_t buflen; /* Space available in buf */
  9790. size_t bufused; /* Space taken in buf */
  9791. /* Index block */
  9792. char **var; /* char **envp */
  9793. size_t varlen; /* Number of variables available in var */
  9794. size_t varused; /* Number of variables stored in var */
  9795. };
  9796. static void addenv(struct cgi_environment *env,
  9797. PRINTF_FORMAT_STRING(const char *fmt),
  9798. ...) PRINTF_ARGS(2, 3);
  9799. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9800. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9801. static void
  9802. addenv(struct cgi_environment *env, const char *fmt, ...)
  9803. {
  9804. size_t i, n, space;
  9805. int truncated = 0;
  9806. char *added;
  9807. va_list ap;
  9808. if ((env->varlen - env->varused) < 2) {
  9809. mg_cry_internal(env->conn,
  9810. "%s: Cannot register CGI variable [%s]",
  9811. __func__,
  9812. fmt);
  9813. return;
  9814. }
  9815. /* Calculate how much space is left in the buffer */
  9816. space = (env->buflen - env->bufused);
  9817. do {
  9818. /* Space for "\0\0" is always needed. */
  9819. if (space <= 2) {
  9820. /* Allocate new buffer */
  9821. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9822. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9823. if (!added) {
  9824. /* Out of memory */
  9825. mg_cry_internal(
  9826. env->conn,
  9827. "%s: Cannot allocate memory for CGI variable [%s]",
  9828. __func__,
  9829. fmt);
  9830. return;
  9831. }
  9832. /* Retarget pointers */
  9833. env->buf = added;
  9834. env->buflen = n;
  9835. for (i = 0, n = 0; i < env->varused; i++) {
  9836. env->var[i] = added + n;
  9837. n += strlen(added + n) + 1;
  9838. }
  9839. space = (env->buflen - env->bufused);
  9840. }
  9841. /* Make a pointer to the free space int the buffer */
  9842. added = env->buf + env->bufused;
  9843. /* Copy VARIABLE=VALUE\0 string into the free space */
  9844. va_start(ap, fmt);
  9845. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9846. va_end(ap);
  9847. /* Do not add truncated strings to the environment */
  9848. if (truncated) {
  9849. /* Reallocate the buffer */
  9850. space = 0;
  9851. }
  9852. } while (truncated);
  9853. /* Calculate number of bytes added to the environment */
  9854. n = strlen(added) + 1;
  9855. env->bufused += n;
  9856. /* Append a pointer to the added string into the envp array */
  9857. env->var[env->varused] = added;
  9858. env->varused++;
  9859. }
  9860. /* Return 0 on success, non-zero if an error occurs. */
  9861. static int
  9862. prepare_cgi_environment(struct mg_connection *conn,
  9863. const char *prog,
  9864. struct cgi_environment *env,
  9865. int cgi_config_idx)
  9866. {
  9867. const char *s;
  9868. struct vec var_vec;
  9869. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9870. int i, truncated, uri_len;
  9871. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9872. return -1;
  9873. }
  9874. env->conn = conn;
  9875. env->buflen = CGI_ENVIRONMENT_SIZE;
  9876. env->bufused = 0;
  9877. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9878. if (env->buf == NULL) {
  9879. mg_cry_internal(conn,
  9880. "%s: Not enough memory for environmental buffer",
  9881. __func__);
  9882. return -1;
  9883. }
  9884. env->varlen = MAX_CGI_ENVIR_VARS;
  9885. env->varused = 0;
  9886. env->var =
  9887. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9888. if (env->var == NULL) {
  9889. mg_cry_internal(conn,
  9890. "%s: Not enough memory for environmental variables",
  9891. __func__);
  9892. mg_free(env->buf);
  9893. return -1;
  9894. }
  9895. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9896. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9897. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9898. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  9899. addenv(env,
  9900. "FALLBACK_DOCUMENT_ROOT=%s",
  9901. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  9902. }
  9903. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9904. /* Prepare the environment block */
  9905. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9906. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9907. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9908. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9909. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9910. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9911. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9912. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9913. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9914. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9915. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9916. /* SCRIPT_NAME */
  9917. uri_len = (int)strlen(conn->request_info.local_uri);
  9918. if (conn->path_info == NULL) {
  9919. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9920. /* URI: /path_to_script/script.cgi */
  9921. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9922. } else {
  9923. /* URI: /path_to_script/ ... using index.cgi */
  9924. const char *index_file = strrchr(prog, '/');
  9925. if (index_file) {
  9926. addenv(env,
  9927. "SCRIPT_NAME=%s%s",
  9928. conn->request_info.local_uri,
  9929. index_file + 1);
  9930. }
  9931. }
  9932. } else {
  9933. /* URI: /path_to_script/script.cgi/path_info */
  9934. addenv(env,
  9935. "SCRIPT_NAME=%.*s",
  9936. uri_len - (int)strlen(conn->path_info),
  9937. conn->request_info.local_uri);
  9938. }
  9939. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9940. if (conn->path_info == NULL) {
  9941. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9942. } else {
  9943. addenv(env,
  9944. "PATH_TRANSLATED=%s%s",
  9945. conn->dom_ctx->config[DOCUMENT_ROOT],
  9946. conn->path_info);
  9947. }
  9948. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9949. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9950. addenv(env, "CONTENT_TYPE=%s", s);
  9951. }
  9952. if (conn->request_info.query_string != NULL) {
  9953. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9954. }
  9955. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9956. addenv(env, "CONTENT_LENGTH=%s", s);
  9957. }
  9958. if ((s = getenv("PATH")) != NULL) {
  9959. addenv(env, "PATH=%s", s);
  9960. }
  9961. if (conn->path_info != NULL) {
  9962. addenv(env, "PATH_INFO=%s", conn->path_info);
  9963. }
  9964. if (conn->status_code > 0) {
  9965. /* CGI error handler should show the status code */
  9966. addenv(env, "STATUS=%d", conn->status_code);
  9967. }
  9968. #if defined(_WIN32)
  9969. if ((s = getenv("COMSPEC")) != NULL) {
  9970. addenv(env, "COMSPEC=%s", s);
  9971. }
  9972. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9973. addenv(env, "SYSTEMROOT=%s", s);
  9974. }
  9975. if ((s = getenv("SystemDrive")) != NULL) {
  9976. addenv(env, "SystemDrive=%s", s);
  9977. }
  9978. if ((s = getenv("ProgramFiles")) != NULL) {
  9979. addenv(env, "ProgramFiles=%s", s);
  9980. }
  9981. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9982. addenv(env, "ProgramFiles(x86)=%s", s);
  9983. }
  9984. #else
  9985. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9986. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9987. }
  9988. #endif /* _WIN32 */
  9989. if ((s = getenv("PERLLIB")) != NULL) {
  9990. addenv(env, "PERLLIB=%s", s);
  9991. }
  9992. if (conn->request_info.remote_user != NULL) {
  9993. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9994. addenv(env, "%s", "AUTH_TYPE=Digest");
  9995. }
  9996. /* Add all headers as HTTP_* variables */
  9997. for (i = 0; i < conn->request_info.num_headers; i++) {
  9998. (void)mg_snprintf(conn,
  9999. &truncated,
  10000. http_var_name,
  10001. sizeof(http_var_name),
  10002. "HTTP_%s",
  10003. conn->request_info.http_headers[i].name);
  10004. if (truncated) {
  10005. mg_cry_internal(conn,
  10006. "%s: HTTP header variable too long [%s]",
  10007. __func__,
  10008. conn->request_info.http_headers[i].name);
  10009. continue;
  10010. }
  10011. /* Convert variable name into uppercase, and change - to _ */
  10012. for (p = http_var_name; *p != '\0'; p++) {
  10013. if (*p == '-') {
  10014. *p = '_';
  10015. }
  10016. *p = (char)toupper((unsigned char)*p);
  10017. }
  10018. addenv(env,
  10019. "%s=%s",
  10020. http_var_name,
  10021. conn->request_info.http_headers[i].value);
  10022. }
  10023. /* Add user-specified variables */
  10024. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10025. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10026. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10027. }
  10028. env->var[env->varused] = NULL;
  10029. env->buf[env->bufused] = '\0';
  10030. return 0;
  10031. }
  10032. /* Data for CGI process control: PID and number of references */
  10033. struct process_control_data {
  10034. pid_t pid;
  10035. ptrdiff_t references;
  10036. };
  10037. static int
  10038. abort_cgi_process(void *data)
  10039. {
  10040. /* Waitpid checks for child status and won't work for a pid that does
  10041. * not identify a child of the current process. Thus, if the pid is
  10042. * reused, we will not affect a different process. */
  10043. struct process_control_data *proc = (struct process_control_data *)data;
  10044. int status = 0;
  10045. ptrdiff_t refs;
  10046. pid_t ret_pid;
  10047. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10048. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10049. /* Stop child process */
  10050. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10051. kill(proc->pid, SIGABRT);
  10052. /* Wait until process is terminated (don't leave zombies) */
  10053. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10054. ;
  10055. } else {
  10056. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10057. }
  10058. /* Dec reference counter */
  10059. refs = mg_atomic_dec(&proc->references);
  10060. if (refs == 0) {
  10061. /* no more references - free data */
  10062. mg_free(data);
  10063. }
  10064. return 0;
  10065. }
  10066. /* Local (static) function assumes all arguments are valid. */
  10067. static void
  10068. handle_cgi_request(struct mg_connection *conn,
  10069. const char *prog,
  10070. int cgi_config_idx)
  10071. {
  10072. char *buf;
  10073. size_t buflen;
  10074. int headers_len, data_len, i, truncated;
  10075. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10076. const char *status, *status_text;
  10077. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10078. struct mg_request_info ri;
  10079. struct cgi_environment blk;
  10080. FILE *in = NULL, *out = NULL, *err = NULL;
  10081. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10082. pid_t pid = (pid_t)-1;
  10083. struct process_control_data *proc = NULL;
  10084. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10085. int no_buffering = 0;
  10086. #if defined(USE_TIMERS)
  10087. double cgi_timeout;
  10088. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10089. /* Get timeout in seconds */
  10090. cgi_timeout =
  10091. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10092. } else {
  10093. cgi_timeout =
  10094. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10095. }
  10096. #endif
  10097. if (cfg_buffering != NULL) {
  10098. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10099. no_buffering = 1;
  10100. }
  10101. }
  10102. buf = NULL;
  10103. buflen = conn->phys_ctx->max_request_size;
  10104. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10105. if (i != 0) {
  10106. blk.buf = NULL;
  10107. blk.var = NULL;
  10108. goto done;
  10109. }
  10110. /* CGI must be executed in its own directory. 'dir' must point to the
  10111. * directory containing executable program, 'p' must point to the
  10112. * executable program name relative to 'dir'. */
  10113. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10114. if (truncated) {
  10115. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10116. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10117. goto done;
  10118. }
  10119. if ((p = strrchr(dir, '/')) != NULL) {
  10120. *p++ = '\0';
  10121. } else {
  10122. dir[0] = '.';
  10123. dir[1] = '\0';
  10124. p = (char *)prog;
  10125. }
  10126. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10127. status = strerror(ERRNO);
  10128. mg_cry_internal(
  10129. conn,
  10130. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10131. prog,
  10132. status);
  10133. mg_send_http_error(conn,
  10134. 500,
  10135. "Error: Cannot create CGI pipe: %s",
  10136. status);
  10137. goto done;
  10138. }
  10139. proc = (struct process_control_data *)
  10140. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10141. if (proc == NULL) {
  10142. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10143. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10144. goto done;
  10145. }
  10146. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10147. pid = spawn_process(
  10148. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10149. if (pid == (pid_t)-1) {
  10150. status = strerror(ERRNO);
  10151. mg_cry_internal(
  10152. conn,
  10153. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10154. prog,
  10155. status);
  10156. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10157. mg_free(proc);
  10158. proc = NULL;
  10159. goto done;
  10160. }
  10161. /* Store data in shared process_control_data */
  10162. proc->pid = pid;
  10163. proc->references = 1;
  10164. #if defined(USE_TIMERS)
  10165. if (cgi_timeout > 0.0) {
  10166. proc->references = 2;
  10167. // Start a timer for CGI
  10168. timer_add(conn->phys_ctx,
  10169. cgi_timeout /* in seconds */,
  10170. 0.0,
  10171. 1,
  10172. abort_cgi_process,
  10173. (void *)proc,
  10174. NULL);
  10175. }
  10176. #endif
  10177. /* Parent closes only one side of the pipes.
  10178. * If we don't mark them as closed, close() attempt before
  10179. * return from this function throws an exception on Windows.
  10180. * Windows does not like when closed descriptor is closed again. */
  10181. (void)close(fdin[0]);
  10182. (void)close(fdout[1]);
  10183. (void)close(fderr[1]);
  10184. fdin[0] = fdout[1] = fderr[1] = -1;
  10185. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10186. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10187. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10188. status = strerror(ERRNO);
  10189. mg_cry_internal(conn,
  10190. "Error: CGI program \"%s\": Can not open fd: %s",
  10191. prog,
  10192. status);
  10193. mg_send_http_error(conn,
  10194. 500,
  10195. "Error: CGI can not open fd\nfdopen: %s",
  10196. status);
  10197. goto done;
  10198. }
  10199. setbuf(in, NULL);
  10200. setbuf(out, NULL);
  10201. setbuf(err, NULL);
  10202. fout.access.fp = out;
  10203. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10204. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10205. conn->content_len);
  10206. /* This is a POST/PUT request, or another request with body data. */
  10207. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10208. /* Error sending the body data */
  10209. mg_cry_internal(
  10210. conn,
  10211. "Error: CGI program \"%s\": Forward body data failed",
  10212. prog);
  10213. goto done;
  10214. }
  10215. }
  10216. /* Close so child gets an EOF. */
  10217. fclose(in);
  10218. in = NULL;
  10219. fdin[1] = -1;
  10220. /* Now read CGI reply into a buffer. We need to set correct
  10221. * status code, thus we need to see all HTTP headers first.
  10222. * Do not send anything back to client, until we buffer in all
  10223. * HTTP headers. */
  10224. data_len = 0;
  10225. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10226. if (buf == NULL) {
  10227. mg_send_http_error(conn,
  10228. 500,
  10229. "Error: Not enough memory for CGI buffer (%u bytes)",
  10230. (unsigned int)buflen);
  10231. mg_cry_internal(
  10232. conn,
  10233. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10234. "bytes)",
  10235. prog,
  10236. (unsigned int)buflen);
  10237. goto done;
  10238. }
  10239. DEBUG_TRACE("CGI: %s", "wait for response");
  10240. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10241. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10242. if (headers_len <= 0) {
  10243. /* Could not parse the CGI response. Check if some error message on
  10244. * stderr. */
  10245. i = pull_all(err, conn, buf, (int)buflen);
  10246. if (i > 0) {
  10247. /* CGI program explicitly sent an error */
  10248. /* Write the error message to the internal log */
  10249. mg_cry_internal(conn,
  10250. "Error: CGI program \"%s\" sent error "
  10251. "message: [%.*s]",
  10252. prog,
  10253. i,
  10254. buf);
  10255. /* Don't send the error message back to the client */
  10256. mg_send_http_error(conn,
  10257. 500,
  10258. "Error: CGI program \"%s\" failed.",
  10259. prog);
  10260. } else {
  10261. /* CGI program did not explicitly send an error, but a broken
  10262. * respon header */
  10263. mg_cry_internal(conn,
  10264. "Error: CGI program sent malformed or too big "
  10265. "(>%u bytes) HTTP headers: [%.*s]",
  10266. (unsigned)buflen,
  10267. data_len,
  10268. buf);
  10269. mg_send_http_error(conn,
  10270. 500,
  10271. "Error: CGI program sent malformed or too big "
  10272. "(>%u bytes) HTTP headers: [%.*s]",
  10273. (unsigned)buflen,
  10274. data_len,
  10275. buf);
  10276. }
  10277. /* in both cases, abort processing CGI */
  10278. goto done;
  10279. }
  10280. pbuf = buf;
  10281. buf[headers_len - 1] = '\0';
  10282. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10283. /* Make up and send the status line */
  10284. status_text = "OK";
  10285. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10286. != NULL) {
  10287. conn->status_code = atoi(status);
  10288. status_text = status;
  10289. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10290. status_text++;
  10291. }
  10292. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10293. != NULL) {
  10294. conn->status_code = 307;
  10295. } else {
  10296. conn->status_code = 200;
  10297. }
  10298. if (!should_keep_alive(conn)) {
  10299. conn->must_close = 1;
  10300. }
  10301. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10302. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10303. /* Send headers */
  10304. for (i = 0; i < ri.num_headers; i++) {
  10305. DEBUG_TRACE("CGI header: %s: %s",
  10306. ri.http_headers[i].name,
  10307. ri.http_headers[i].value);
  10308. mg_printf(conn,
  10309. "%s: %s\r\n",
  10310. ri.http_headers[i].name,
  10311. ri.http_headers[i].value);
  10312. }
  10313. mg_write(conn, "\r\n", 2);
  10314. /* Send chunk of data that may have been read after the headers */
  10315. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10316. /* Read the rest of CGI output and send to the client */
  10317. DEBUG_TRACE("CGI: %s", "forward all data");
  10318. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10319. DEBUG_TRACE("CGI: %s", "all data sent");
  10320. done:
  10321. mg_free(blk.var);
  10322. mg_free(blk.buf);
  10323. if (pid != (pid_t)-1) {
  10324. abort_cgi_process((void *)proc);
  10325. }
  10326. if (fdin[0] != -1) {
  10327. close(fdin[0]);
  10328. }
  10329. if (fdout[1] != -1) {
  10330. close(fdout[1]);
  10331. }
  10332. if (fderr[1] != -1) {
  10333. close(fderr[1]);
  10334. }
  10335. if (in != NULL) {
  10336. fclose(in);
  10337. } else if (fdin[1] != -1) {
  10338. close(fdin[1]);
  10339. }
  10340. if (out != NULL) {
  10341. fclose(out);
  10342. } else if (fdout[0] != -1) {
  10343. close(fdout[0]);
  10344. }
  10345. if (err != NULL) {
  10346. fclose(err);
  10347. } else if (fderr[0] != -1) {
  10348. close(fderr[0]);
  10349. }
  10350. mg_free(buf);
  10351. }
  10352. #endif /* !NO_CGI */
  10353. #if !defined(NO_FILES)
  10354. static void
  10355. dav_mkcol(struct mg_connection *conn, const char *path)
  10356. {
  10357. int rc, body_len;
  10358. struct de de;
  10359. if (conn == NULL) {
  10360. return;
  10361. }
  10362. /* TODO (mid): Check the mg_send_http_error situations in this function
  10363. */
  10364. memset(&de.file, 0, sizeof(de.file));
  10365. if (!mg_stat(conn, path, &de.file)) {
  10366. mg_cry_internal(conn,
  10367. "%s: mg_stat(%s) failed: %s",
  10368. __func__,
  10369. path,
  10370. strerror(ERRNO));
  10371. }
  10372. if (de.file.last_modified) {
  10373. /* TODO (mid): This check does not seem to make any sense ! */
  10374. /* TODO (mid): Add a webdav unit test first, before changing
  10375. * anything here. */
  10376. mg_send_http_error(
  10377. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10378. return;
  10379. }
  10380. body_len = conn->data_len - conn->request_len;
  10381. if (body_len > 0) {
  10382. mg_send_http_error(
  10383. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10384. return;
  10385. }
  10386. rc = mg_mkdir(conn, path, 0755);
  10387. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10388. if (rc == 0) {
  10389. /* Create 201 "Created" response */
  10390. mg_response_header_start(conn, 201);
  10391. send_static_cache_header(conn);
  10392. send_additional_header(conn);
  10393. mg_response_header_add(conn, "Content-Length", "0", -1);
  10394. /* Send all headers - there is no body */
  10395. mg_response_header_send(conn);
  10396. } else {
  10397. int http_status = 500;
  10398. switch (errno) {
  10399. case EEXIST:
  10400. http_status = 405;
  10401. break;
  10402. case EACCES:
  10403. http_status = 403;
  10404. break;
  10405. case ENOENT:
  10406. http_status = 409;
  10407. break;
  10408. }
  10409. mg_send_http_error(conn,
  10410. http_status,
  10411. "Error processing %s: %s",
  10412. path,
  10413. strerror(ERRNO));
  10414. }
  10415. }
  10416. /* Forward decrlaration */
  10417. static int get_uri_type(const char *uri);
  10418. static const char *
  10419. get_rel_url_at_current_server(const char *uri,
  10420. const struct mg_connection *conn);
  10421. static void
  10422. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10423. {
  10424. const char *overwrite_hdr;
  10425. const char *destination_hdr;
  10426. const char *root;
  10427. int rc, dest_uri_type;
  10428. int http_status = 400;
  10429. int do_overwrite = 0;
  10430. int destination_ok = 0;
  10431. char dest_path[UTF8_PATH_MAX];
  10432. struct mg_file_stat ignored;
  10433. if (conn == NULL) {
  10434. return;
  10435. }
  10436. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10437. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10438. destination_hdr = mg_get_header(conn, "Destination");
  10439. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10440. do_overwrite = 1;
  10441. }
  10442. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10443. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10444. return;
  10445. }
  10446. if (root != NULL) {
  10447. char *local_dest = NULL;
  10448. dest_uri_type = get_uri_type(destination_hdr);
  10449. if (dest_uri_type == 2) {
  10450. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10451. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10452. const char *h =
  10453. get_rel_url_at_current_server(destination_hdr, conn);
  10454. if (h) {
  10455. size_t len = strlen(h);
  10456. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10457. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10458. }
  10459. }
  10460. if (local_dest != NULL) {
  10461. remove_dot_segments(local_dest);
  10462. if (local_dest[0] == '/') {
  10463. int trunc_check = 0;
  10464. mg_snprintf(conn,
  10465. &trunc_check,
  10466. dest_path,
  10467. sizeof(dest_path),
  10468. "%s/%s",
  10469. root,
  10470. local_dest);
  10471. if (trunc_check == 0) {
  10472. destination_ok = 1;
  10473. }
  10474. }
  10475. mg_free(local_dest);
  10476. }
  10477. }
  10478. if (!destination_ok) {
  10479. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10480. return;
  10481. }
  10482. /* Check now if this file exists */
  10483. if (mg_stat(conn, dest_path, &ignored)) {
  10484. /* File exists */
  10485. if (do_overwrite) {
  10486. /* Overwrite allowed: delete the file first */
  10487. if (0 != remove(dest_path)) {
  10488. /* No overwrite: return error */
  10489. mg_send_http_error(conn,
  10490. 403,
  10491. "Cannot overwrite file: %s",
  10492. dest_path);
  10493. return;
  10494. }
  10495. } else {
  10496. /* No overwrite: return error */
  10497. mg_send_http_error(conn,
  10498. 412,
  10499. "Destination already exists: %s",
  10500. dest_path);
  10501. return;
  10502. }
  10503. }
  10504. /* Copy / Move / Rename operation. */
  10505. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10506. #if defined(_WIN32)
  10507. {
  10508. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10509. wchar_t wSource[UTF16_PATH_MAX];
  10510. wchar_t wDest[UTF16_PATH_MAX];
  10511. BOOL ok;
  10512. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10513. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10514. if (do_copy) {
  10515. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10516. } else {
  10517. ok = MoveFileExW(wSource,
  10518. wDest,
  10519. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10520. }
  10521. if (ok) {
  10522. rc = 0;
  10523. } else {
  10524. DWORD lastErr = GetLastError();
  10525. if (lastErr == ERROR_ALREADY_EXISTS) {
  10526. mg_send_http_error(conn,
  10527. 412,
  10528. "Destination already exists: %s",
  10529. dest_path);
  10530. return;
  10531. }
  10532. rc = -1;
  10533. http_status = 400;
  10534. }
  10535. }
  10536. #else
  10537. {
  10538. /* Linux uses already UTF-8, we don't need to convert file names. */
  10539. if (do_copy) {
  10540. /* TODO: COPY for Linux. */
  10541. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10542. return;
  10543. }
  10544. rc = rename(path, dest_path);
  10545. if (rc) {
  10546. switch (errno) {
  10547. case EEXIST:
  10548. http_status = 412;
  10549. break;
  10550. case EACCES:
  10551. http_status = 403;
  10552. break;
  10553. case ENOENT:
  10554. http_status = 409;
  10555. break;
  10556. }
  10557. }
  10558. }
  10559. #endif
  10560. if (rc == 0) {
  10561. /* Create 204 "No Content" response */
  10562. mg_response_header_start(conn, 204);
  10563. mg_response_header_add(conn, "Content-Length", "0", -1);
  10564. /* Send all headers - there is no body */
  10565. mg_response_header_send(conn);
  10566. } else {
  10567. mg_send_http_error(conn, http_status, "Operation failed");
  10568. }
  10569. }
  10570. static void
  10571. put_file(struct mg_connection *conn, const char *path)
  10572. {
  10573. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10574. const char *range;
  10575. int64_t r1, r2;
  10576. int rc;
  10577. if (conn == NULL) {
  10578. return;
  10579. }
  10580. DEBUG_TRACE("store %s", path);
  10581. if (mg_stat(conn, path, &file.stat)) {
  10582. /* File already exists */
  10583. conn->status_code = 200;
  10584. if (file.stat.is_directory) {
  10585. /* This is an already existing directory,
  10586. * so there is nothing to do for the server. */
  10587. rc = 0;
  10588. } else {
  10589. /* File exists and is not a directory. */
  10590. /* Can it be replaced? */
  10591. /* Check if the server may write this file */
  10592. if (access(path, W_OK) == 0) {
  10593. /* Access granted */
  10594. rc = 1;
  10595. } else {
  10596. mg_send_http_error(
  10597. conn,
  10598. 403,
  10599. "Error: Put not possible\nReplacing %s is not allowed",
  10600. path);
  10601. return;
  10602. }
  10603. }
  10604. } else {
  10605. /* File should be created */
  10606. conn->status_code = 201;
  10607. rc = put_dir(conn, path);
  10608. }
  10609. if (rc == 0) {
  10610. /* put_dir returns 0 if path is a directory */
  10611. /* Create response */
  10612. mg_response_header_start(conn, conn->status_code);
  10613. send_no_cache_header(conn);
  10614. send_additional_header(conn);
  10615. mg_response_header_add(conn, "Content-Length", "0", -1);
  10616. /* Send all headers - there is no body */
  10617. mg_response_header_send(conn);
  10618. /* Request to create a directory has been fulfilled successfully.
  10619. * No need to put a file. */
  10620. return;
  10621. }
  10622. if (rc == -1) {
  10623. /* put_dir returns -1 if the path is too long */
  10624. mg_send_http_error(conn,
  10625. 414,
  10626. "Error: Path too long\nput_dir(%s): %s",
  10627. path,
  10628. strerror(ERRNO));
  10629. return;
  10630. }
  10631. if (rc == -2) {
  10632. /* put_dir returns -2 if the directory can not be created */
  10633. mg_send_http_error(conn,
  10634. 500,
  10635. "Error: Can not create directory\nput_dir(%s): %s",
  10636. path,
  10637. strerror(ERRNO));
  10638. return;
  10639. }
  10640. /* A file should be created or overwritten. */
  10641. /* Currently CivetWeb does not need read+write access. */
  10642. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10643. || file.access.fp == NULL) {
  10644. (void)mg_fclose(&file.access);
  10645. mg_send_http_error(conn,
  10646. 500,
  10647. "Error: Can not create file\nfopen(%s): %s",
  10648. path,
  10649. strerror(ERRNO));
  10650. return;
  10651. }
  10652. fclose_on_exec(&file.access, conn);
  10653. range = mg_get_header(conn, "Content-Range");
  10654. r1 = r2 = 0;
  10655. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10656. conn->status_code = 206; /* Partial content */
  10657. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10658. mg_send_http_error(conn,
  10659. 500,
  10660. "Error: Internal error processing file %s",
  10661. path);
  10662. return;
  10663. }
  10664. }
  10665. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10666. /* forward_body_data failed.
  10667. * The error code has already been sent to the client,
  10668. * and conn->status_code is already set. */
  10669. (void)mg_fclose(&file.access);
  10670. return;
  10671. }
  10672. if (mg_fclose(&file.access) != 0) {
  10673. /* fclose failed. This might have different reasons, but a likely
  10674. * one is "no space on disk", http 507. */
  10675. conn->status_code = 507;
  10676. }
  10677. /* Create response (status_code has been set before) */
  10678. mg_response_header_start(conn, conn->status_code);
  10679. send_no_cache_header(conn);
  10680. send_additional_header(conn);
  10681. mg_response_header_add(conn, "Content-Length", "0", -1);
  10682. /* Send all headers - there is no body */
  10683. mg_response_header_send(conn);
  10684. }
  10685. static void
  10686. delete_file(struct mg_connection *conn, const char *path)
  10687. {
  10688. struct de de;
  10689. memset(&de.file, 0, sizeof(de.file));
  10690. if (!mg_stat(conn, path, &de.file)) {
  10691. /* mg_stat returns 0 if the file does not exist */
  10692. mg_send_http_error(conn,
  10693. 404,
  10694. "Error: Cannot delete file\nFile %s not found",
  10695. path);
  10696. return;
  10697. }
  10698. DEBUG_TRACE("delete %s", path);
  10699. if (de.file.is_directory) {
  10700. if (remove_directory(conn, path)) {
  10701. /* Delete is successful: Return 204 without content. */
  10702. mg_send_http_error(conn, 204, "%s", "");
  10703. } else {
  10704. /* Delete is not successful: Return 500 (Server error). */
  10705. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10706. }
  10707. return;
  10708. }
  10709. /* This is an existing file (not a directory).
  10710. * Check if write permission is granted. */
  10711. if (access(path, W_OK) != 0) {
  10712. /* File is read only */
  10713. mg_send_http_error(
  10714. conn,
  10715. 403,
  10716. "Error: Delete not possible\nDeleting %s is not allowed",
  10717. path);
  10718. return;
  10719. }
  10720. /* Try to delete it. */
  10721. if (mg_remove(conn, path) == 0) {
  10722. /* Delete was successful: Return 204 without content. */
  10723. mg_response_header_start(conn, 204);
  10724. send_no_cache_header(conn);
  10725. send_additional_header(conn);
  10726. mg_response_header_add(conn, "Content-Length", "0", -1);
  10727. mg_response_header_send(conn);
  10728. } else {
  10729. /* Delete not successful (file locked). */
  10730. mg_send_http_error(conn,
  10731. 423,
  10732. "Error: Cannot delete file\nremove(%s): %s",
  10733. path,
  10734. strerror(ERRNO));
  10735. }
  10736. }
  10737. #endif /* !NO_FILES */
  10738. #if !defined(NO_FILESYSTEMS)
  10739. static void
  10740. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10741. static void
  10742. do_ssi_include(struct mg_connection *conn,
  10743. const char *ssi,
  10744. char *tag,
  10745. int include_level)
  10746. {
  10747. char file_name[MG_BUF_LEN], path[512], *p;
  10748. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10749. size_t len;
  10750. int truncated = 0;
  10751. if (conn == NULL) {
  10752. return;
  10753. }
  10754. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10755. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10756. * always < MG_BUF_LEN. */
  10757. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10758. /* File name is relative to the webserver root */
  10759. file_name[511] = 0;
  10760. (void)mg_snprintf(conn,
  10761. &truncated,
  10762. path,
  10763. sizeof(path),
  10764. "%s/%s",
  10765. conn->dom_ctx->config[DOCUMENT_ROOT],
  10766. file_name);
  10767. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10768. /* File name is relative to the webserver working directory
  10769. * or it is absolute system path */
  10770. file_name[511] = 0;
  10771. (void)
  10772. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10773. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10774. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10775. /* File name is relative to the current document */
  10776. file_name[511] = 0;
  10777. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10778. if (!truncated) {
  10779. if ((p = strrchr(path, '/')) != NULL) {
  10780. p[1] = '\0';
  10781. }
  10782. len = strlen(path);
  10783. (void)mg_snprintf(conn,
  10784. &truncated,
  10785. path + len,
  10786. sizeof(path) - len,
  10787. "%s",
  10788. file_name);
  10789. }
  10790. } else {
  10791. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10792. return;
  10793. }
  10794. if (truncated) {
  10795. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10796. return;
  10797. }
  10798. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10799. mg_cry_internal(conn,
  10800. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10801. tag,
  10802. path,
  10803. strerror(ERRNO));
  10804. } else {
  10805. fclose_on_exec(&file.access, conn);
  10806. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10807. > 0) {
  10808. send_ssi_file(conn, path, &file, include_level + 1);
  10809. } else {
  10810. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10811. }
  10812. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10813. }
  10814. }
  10815. #if !defined(NO_POPEN)
  10816. static void
  10817. do_ssi_exec(struct mg_connection *conn, char *tag)
  10818. {
  10819. char cmd[1024] = "";
  10820. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10821. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10822. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10823. } else {
  10824. cmd[1023] = 0;
  10825. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10826. mg_cry_internal(conn,
  10827. "Cannot SSI #exec: [%s]: %s",
  10828. cmd,
  10829. strerror(ERRNO));
  10830. } else {
  10831. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10832. pclose(file.access.fp);
  10833. }
  10834. }
  10835. }
  10836. #endif /* !NO_POPEN */
  10837. static int
  10838. mg_fgetc(struct mg_file *filep)
  10839. {
  10840. if (filep == NULL) {
  10841. return EOF;
  10842. }
  10843. if (filep->access.fp != NULL) {
  10844. return fgetc(filep->access.fp);
  10845. } else {
  10846. return EOF;
  10847. }
  10848. }
  10849. static void
  10850. send_ssi_file(struct mg_connection *conn,
  10851. const char *path,
  10852. struct mg_file *filep,
  10853. int include_level)
  10854. {
  10855. char buf[MG_BUF_LEN];
  10856. int ch, len, in_tag, in_ssi_tag;
  10857. if (include_level > 10) {
  10858. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10859. return;
  10860. }
  10861. in_tag = in_ssi_tag = len = 0;
  10862. /* Read file, byte by byte, and look for SSI include tags */
  10863. while ((ch = mg_fgetc(filep)) != EOF) {
  10864. if (in_tag) {
  10865. /* We are in a tag, either SSI tag or html tag */
  10866. if (ch == '>') {
  10867. /* Tag is closing */
  10868. buf[len++] = '>';
  10869. if (in_ssi_tag) {
  10870. /* Handle SSI tag */
  10871. buf[len] = 0;
  10872. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10873. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10874. #if !defined(NO_POPEN)
  10875. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10876. do_ssi_exec(conn, buf + 9);
  10877. #endif /* !NO_POPEN */
  10878. } else {
  10879. mg_cry_internal(conn,
  10880. "%s: unknown SSI "
  10881. "command: \"%s\"",
  10882. path,
  10883. buf);
  10884. }
  10885. len = 0;
  10886. in_ssi_tag = in_tag = 0;
  10887. } else {
  10888. /* Not an SSI tag */
  10889. /* Flush buffer */
  10890. (void)mg_write(conn, buf, (size_t)len);
  10891. len = 0;
  10892. in_tag = 0;
  10893. }
  10894. } else {
  10895. /* Tag is still open */
  10896. buf[len++] = (char)(ch & 0xff);
  10897. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10898. /* All SSI tags start with <!--# */
  10899. in_ssi_tag = 1;
  10900. }
  10901. if ((len + 2) > (int)sizeof(buf)) {
  10902. /* Tag to long for buffer */
  10903. mg_cry_internal(conn, "%s: tag is too large", path);
  10904. return;
  10905. }
  10906. }
  10907. } else {
  10908. /* We are not in a tag yet. */
  10909. if (ch == '<') {
  10910. /* Tag is opening */
  10911. in_tag = 1;
  10912. if (len > 0) {
  10913. /* Flush current buffer.
  10914. * Buffer is filled with "len" bytes. */
  10915. (void)mg_write(conn, buf, (size_t)len);
  10916. }
  10917. /* Store the < */
  10918. len = 1;
  10919. buf[0] = '<';
  10920. } else {
  10921. /* No Tag */
  10922. /* Add data to buffer */
  10923. buf[len++] = (char)(ch & 0xff);
  10924. /* Flush if buffer is full */
  10925. if (len == (int)sizeof(buf)) {
  10926. mg_write(conn, buf, (size_t)len);
  10927. len = 0;
  10928. }
  10929. }
  10930. }
  10931. }
  10932. /* Send the rest of buffered data */
  10933. if (len > 0) {
  10934. mg_write(conn, buf, (size_t)len);
  10935. }
  10936. }
  10937. static void
  10938. handle_ssi_file_request(struct mg_connection *conn,
  10939. const char *path,
  10940. struct mg_file *filep)
  10941. {
  10942. char date[64];
  10943. time_t curtime = time(NULL);
  10944. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10945. return;
  10946. }
  10947. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10948. /* File exists (precondition for calling this function),
  10949. * but can not be opened by the server. */
  10950. mg_send_http_error(conn,
  10951. 500,
  10952. "Error: Cannot read file\nfopen(%s): %s",
  10953. path,
  10954. strerror(ERRNO));
  10955. } else {
  10956. /* Set "must_close" for HTTP/1.x, since we do not know the
  10957. * content length */
  10958. conn->must_close = 1;
  10959. gmt_time_string(date, sizeof(date), &curtime);
  10960. fclose_on_exec(&filep->access, conn);
  10961. /* 200 OK response */
  10962. mg_response_header_start(conn, 200);
  10963. send_no_cache_header(conn);
  10964. send_additional_header(conn);
  10965. send_cors_header(conn);
  10966. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10967. mg_response_header_send(conn);
  10968. /* Header sent, now send body */
  10969. send_ssi_file(conn, path, filep, 0);
  10970. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10971. }
  10972. }
  10973. #endif /* NO_FILESYSTEMS */
  10974. #if !defined(NO_FILES)
  10975. static void
  10976. send_options(struct mg_connection *conn)
  10977. {
  10978. if (!conn || !all_methods) {
  10979. return;
  10980. }
  10981. /* We do not set a "Cache-Control" header here, but leave the default.
  10982. * Since browsers do not send an OPTIONS request, we can not test the
  10983. * effect anyway. */
  10984. mg_response_header_start(conn, 200);
  10985. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10986. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10987. /* Use the same as before */
  10988. mg_response_header_add(conn, "Allow", all_methods, -1);
  10989. mg_response_header_add(conn, "DAV", "1", -1);
  10990. } else {
  10991. /* TODO: Check this later for HTTP/2 */
  10992. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10993. }
  10994. send_additional_header(conn);
  10995. mg_response_header_send(conn);
  10996. }
  10997. /* Writes PROPFIND properties for a collection element */
  10998. static int
  10999. print_props(struct mg_connection *conn,
  11000. const char *uri,
  11001. const char *name,
  11002. struct mg_file_stat *filep)
  11003. {
  11004. size_t i;
  11005. char mtime[64];
  11006. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11007. char *link_concat;
  11008. size_t link_concat_len;
  11009. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11010. return 0;
  11011. }
  11012. link_concat_len = strlen(uri) + strlen(name) + 1;
  11013. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11014. if (!link_concat) {
  11015. return 0;
  11016. }
  11017. strcpy(link_concat, uri);
  11018. strcat(link_concat, name);
  11019. /* Get full link used in request */
  11020. mg_construct_local_link(
  11021. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11022. /*
  11023. OutputDebugStringA("print_props:\n uri: ");
  11024. OutputDebugStringA(uri);
  11025. OutputDebugStringA("\n name: ");
  11026. OutputDebugStringA(name);
  11027. OutputDebugStringA("\n link: ");
  11028. OutputDebugStringA(link_buf);
  11029. OutputDebugStringA("\n");
  11030. */
  11031. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11032. mg_printf(conn,
  11033. "<d:response>"
  11034. "<d:href>%s</d:href>"
  11035. "<d:propstat>"
  11036. "<d:prop>"
  11037. "<d:resourcetype>%s</d:resourcetype>"
  11038. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11039. "<d:getlastmodified>%s</d:getlastmodified>"
  11040. "<d:lockdiscovery>",
  11041. link_buf,
  11042. filep->is_directory ? "<d:collection/>" : "",
  11043. filep->size,
  11044. mtime);
  11045. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11046. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11047. if (!strcmp(dav_lock[i].path, link_buf)) {
  11048. mg_printf(conn,
  11049. "<d:activelock>"
  11050. "<d:locktype><d:write/></d:locktype>"
  11051. "<d:lockscope><d:exclusive/></d:lockscope>"
  11052. "<d:depth>0</d:depth>"
  11053. "<d:owner>%s</d:owner>"
  11054. "<d:timeout>Second-%u</d:timeout>"
  11055. "<d:locktoken>"
  11056. "<d:href>%s</d:href>"
  11057. "</d:locktoken>"
  11058. "</d:activelock>\n",
  11059. dav_lock[i].user,
  11060. (unsigned)LOCK_DURATION_S,
  11061. dav_lock[i].token);
  11062. }
  11063. }
  11064. mg_printf(conn,
  11065. "</d:lockdiscovery>"
  11066. "</d:prop>"
  11067. "<d:status>HTTP/1.1 200 OK</d:status>"
  11068. "</d:propstat>"
  11069. "</d:response>\n");
  11070. mg_free(link_concat);
  11071. return 1;
  11072. }
  11073. static int
  11074. print_dav_dir_entry(struct de *de, void *data)
  11075. {
  11076. struct mg_connection *conn = (struct mg_connection *)data;
  11077. if (!de || !conn
  11078. || !print_props(
  11079. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11080. /* stop scan */
  11081. return 1;
  11082. }
  11083. return 0;
  11084. }
  11085. static void
  11086. handle_propfind(struct mg_connection *conn,
  11087. const char *path,
  11088. struct mg_file_stat *filep)
  11089. {
  11090. const char *depth = mg_get_header(conn, "Depth");
  11091. if (!conn || !path || !filep || !conn->dom_ctx) {
  11092. return;
  11093. }
  11094. /* return 207 "Multi-Status" */
  11095. conn->must_close = 1;
  11096. mg_response_header_start(conn, 207);
  11097. send_static_cache_header(conn);
  11098. send_additional_header(conn);
  11099. mg_response_header_add(conn,
  11100. "Content-Type",
  11101. "application/xml; charset=utf-8",
  11102. -1);
  11103. mg_response_header_send(conn);
  11104. /* Content */
  11105. mg_printf(conn,
  11106. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11107. "<d:multistatus xmlns:d='DAV:'>\n");
  11108. /* Print properties for the requested resource itself */
  11109. print_props(conn, conn->request_info.local_uri, "", filep);
  11110. /* If it is a directory, print directory entries too if Depth is not 0
  11111. */
  11112. if (filep->is_directory
  11113. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11114. "yes")
  11115. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11116. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11117. }
  11118. mg_printf(conn, "%s\n", "</d:multistatus>");
  11119. }
  11120. static void
  11121. dav_lock_file(struct mg_connection *conn, const char *path)
  11122. {
  11123. /* internal function - therefore conn is assumed to be valid */
  11124. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11125. uint64_t new_locktime;
  11126. int lock_index = -1;
  11127. int i;
  11128. uint64_t LOCK_DURATION_NS =
  11129. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11130. struct twebdav_lock *dav_lock = NULL;
  11131. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11132. || !conn->phys_ctx) {
  11133. return;
  11134. }
  11135. dav_lock = conn->phys_ctx->webdav_lock;
  11136. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11137. /* const char *refresh = mg_get_header(conn, "If"); */
  11138. /* Link refresh should have an "If" header:
  11139. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11140. * But it seems Windows Explorer does not send them.
  11141. */
  11142. mg_lock_context(conn->phys_ctx);
  11143. new_locktime = mg_get_current_time_ns();
  11144. /* Find a slot for a lock */
  11145. while (lock_index < 0) {
  11146. /* find existing lock */
  11147. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11148. if (!strcmp(dav_lock[i].path, link_buf)) {
  11149. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11150. /* locked by the same user */
  11151. dav_lock[i].locktime = new_locktime;
  11152. lock_index = i;
  11153. break;
  11154. } else {
  11155. /* already locked by someone else */
  11156. if (new_locktime
  11157. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11158. /* Lock expired */
  11159. dav_lock[i].path[0] = 0;
  11160. } else {
  11161. /* Lock still valid */
  11162. mg_unlock_context(conn->phys_ctx);
  11163. mg_send_http_error(conn, 423, "%s", "Already locked");
  11164. return;
  11165. }
  11166. }
  11167. }
  11168. }
  11169. /* create new lock token */
  11170. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11171. if (dav_lock[i].path[0] == 0) {
  11172. char s[32];
  11173. dav_lock[i].locktime = mg_get_current_time_ns();
  11174. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11175. mg_md5(dav_lock[i].token,
  11176. link_buf,
  11177. "\x01",
  11178. s,
  11179. "\x01",
  11180. conn->request_info.remote_user,
  11181. NULL);
  11182. mg_strlcpy(dav_lock[i].path,
  11183. link_buf,
  11184. sizeof(dav_lock[i].path));
  11185. mg_strlcpy(dav_lock[i].user,
  11186. conn->request_info.remote_user,
  11187. sizeof(dav_lock[i].user));
  11188. lock_index = i;
  11189. break;
  11190. }
  11191. }
  11192. if (lock_index < 0) {
  11193. /* too many locks. Find oldest lock */
  11194. uint64_t oldest_locktime = dav_lock[0].locktime;
  11195. lock_index = 0;
  11196. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11197. if (dav_lock[i].locktime < oldest_locktime) {
  11198. oldest_locktime = dav_lock[i].locktime;
  11199. lock_index = i;
  11200. }
  11201. }
  11202. /* invalidate oldest lock */
  11203. dav_lock[lock_index].path[0] = 0;
  11204. }
  11205. }
  11206. mg_unlock_context(conn->phys_ctx);
  11207. /* return 200 "OK" */
  11208. conn->must_close = 1;
  11209. mg_response_header_start(conn, 200);
  11210. send_static_cache_header(conn);
  11211. send_additional_header(conn);
  11212. mg_response_header_add(conn,
  11213. "Content-Type",
  11214. "application/xml; charset=utf-8",
  11215. -1);
  11216. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11217. mg_response_header_send(conn);
  11218. /* Content */
  11219. mg_printf(conn,
  11220. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11221. "<d:prop xmlns:d=\"DAV:\">\n"
  11222. " <d:lockdiscovery>\n"
  11223. " <d:activelock>\n"
  11224. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11225. " <d:locktype><d:write/></d:locktype>\n"
  11226. " <d:owner>\n"
  11227. " <d:href>%s</d:href>\n"
  11228. " </d:owner>\n"
  11229. " <d:timeout>Second-%u</d:timeout>\n"
  11230. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11231. " <d:lockroot>\n"
  11232. " <d:href>%s</d:href>\n"
  11233. " </d:lockroot>\n"
  11234. " </d:activelock>\n"
  11235. " </d:lockdiscovery>\n"
  11236. " </d:prop>\n",
  11237. dav_lock[lock_index].user,
  11238. (LOCK_DURATION_S),
  11239. dav_lock[lock_index].token,
  11240. dav_lock[lock_index].path);
  11241. }
  11242. static void
  11243. dav_unlock_file(struct mg_connection *conn, const char *path)
  11244. {
  11245. /* internal function - therefore conn is assumed to be valid */
  11246. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11247. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11248. int lock_index;
  11249. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11250. return;
  11251. }
  11252. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11253. mg_lock_context(conn->phys_ctx);
  11254. /* find existing lock */
  11255. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11256. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11257. /* Success: return 204 "No Content" */
  11258. mg_unlock_context(conn->phys_ctx);
  11259. conn->must_close = 1;
  11260. mg_response_header_start(conn, 204);
  11261. mg_response_header_send(conn);
  11262. return;
  11263. }
  11264. }
  11265. mg_unlock_context(conn->phys_ctx);
  11266. /* Error: Cannot unlock a resource that is not locked */
  11267. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11268. }
  11269. static void
  11270. dav_proppatch(struct mg_connection *conn, const char *path)
  11271. {
  11272. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11273. if (!conn || !path || !conn->dom_ctx) {
  11274. return;
  11275. }
  11276. /* return 207 "Multi-Status" */
  11277. conn->must_close = 1;
  11278. mg_response_header_start(conn, 207);
  11279. send_static_cache_header(conn);
  11280. send_additional_header(conn);
  11281. mg_response_header_add(conn,
  11282. "Content-Type",
  11283. "application/xml; charset=utf-8",
  11284. -1);
  11285. mg_response_header_send(conn);
  11286. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11287. /* Content */
  11288. mg_printf(conn,
  11289. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11290. "<d:multistatus xmlns:d='DAV:'>\n"
  11291. "<d:response>\n<d:href>%s</d:href>\n",
  11292. link_buf);
  11293. mg_printf(conn,
  11294. "<d:propstat><d:status>HTTP/1.1 403 "
  11295. "Forbidden</d:status></d:propstat>\n");
  11296. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11297. }
  11298. #endif
  11299. CIVETWEB_API void
  11300. mg_lock_connection(struct mg_connection *conn)
  11301. {
  11302. if (conn) {
  11303. (void)pthread_mutex_lock(&conn->mutex);
  11304. }
  11305. }
  11306. CIVETWEB_API void
  11307. mg_unlock_connection(struct mg_connection *conn)
  11308. {
  11309. if (conn) {
  11310. (void)pthread_mutex_unlock(&conn->mutex);
  11311. }
  11312. }
  11313. CIVETWEB_API void
  11314. mg_lock_context(struct mg_context *ctx)
  11315. {
  11316. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11317. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11318. }
  11319. }
  11320. CIVETWEB_API void
  11321. mg_unlock_context(struct mg_context *ctx)
  11322. {
  11323. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11324. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11325. }
  11326. }
  11327. #if defined(USE_LUA)
  11328. #include "mod_lua.inl"
  11329. #endif /* USE_LUA */
  11330. #if defined(USE_DUKTAPE)
  11331. #include "mod_duktape.inl"
  11332. #endif /* USE_DUKTAPE */
  11333. #if defined(USE_WEBSOCKET)
  11334. #if !defined(NO_SSL_DL)
  11335. #if !defined(OPENSSL_API_3_0)
  11336. #define SHA_API static
  11337. #include "sha1.inl"
  11338. #endif
  11339. #endif
  11340. static int
  11341. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11342. {
  11343. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11344. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11345. size_t dst_len = sizeof(b64_sha);
  11346. #if !defined(OPENSSL_API_3_0)
  11347. SHA_CTX sha_ctx;
  11348. #endif
  11349. int truncated;
  11350. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11351. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11352. if (truncated) {
  11353. conn->must_close = 1;
  11354. return 0;
  11355. }
  11356. DEBUG_TRACE("%s", "Send websocket handshake");
  11357. #if defined(OPENSSL_API_3_0)
  11358. EVP_Digest((unsigned char *)buf,
  11359. (uint32_t)strlen(buf),
  11360. (unsigned char *)sha,
  11361. NULL,
  11362. EVP_get_digestbyname("sha1"),
  11363. NULL);
  11364. #else
  11365. SHA1_Init(&sha_ctx);
  11366. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11367. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11368. #endif
  11369. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11370. mg_printf(conn,
  11371. "HTTP/1.1 101 Switching Protocols\r\n"
  11372. "Upgrade: websocket\r\n"
  11373. "Connection: Upgrade\r\n"
  11374. "Sec-WebSocket-Accept: %s\r\n",
  11375. b64_sha);
  11376. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11377. // Send negotiated compression extension parameters
  11378. websocket_deflate_response(conn);
  11379. #endif
  11380. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11381. mg_printf(conn,
  11382. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11383. conn->request_info.acceptedWebSocketSubprotocol);
  11384. } else {
  11385. mg_printf(conn, "%s", "\r\n");
  11386. }
  11387. return 1;
  11388. }
  11389. #if !defined(MG_MAX_UNANSWERED_PING)
  11390. /* Configuration of the maximum number of websocket PINGs that might
  11391. * stay unanswered before the connection is considered broken.
  11392. * Note: The name of this define may still change (until it is
  11393. * defined as a compile parameter in a documentation).
  11394. */
  11395. #define MG_MAX_UNANSWERED_PING (5)
  11396. #endif
  11397. static void
  11398. read_websocket(struct mg_connection *conn,
  11399. mg_websocket_data_handler ws_data_handler,
  11400. void *callback_data)
  11401. {
  11402. /* Pointer to the beginning of the portion of the incoming websocket
  11403. * message queue.
  11404. * The original websocket upgrade request is never removed, so the queue
  11405. * begins after it. */
  11406. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11407. int n, error, exit_by_callback;
  11408. int ret;
  11409. /* body_len is the length of the entire queue in bytes
  11410. * len is the length of the current message
  11411. * data_len is the length of the current message's data payload
  11412. * header_len is the length of the current message's header */
  11413. size_t i, len, mask_len = 0, header_len, body_len;
  11414. uint64_t data_len = 0;
  11415. /* "The masking key is a 32-bit value chosen at random by the client."
  11416. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11417. */
  11418. unsigned char mask[4];
  11419. /* data points to the place where the message is stored when passed to
  11420. * the websocket_data callback. This is either mem on the stack, or a
  11421. * dynamically allocated buffer if it is too large. */
  11422. unsigned char mem[4096];
  11423. unsigned char mop; /* mask flag and opcode */
  11424. /* Variables used for connection monitoring */
  11425. double timeout = -1.0;
  11426. int enable_ping_pong = 0;
  11427. int ping_count = 0;
  11428. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11429. enable_ping_pong =
  11430. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11431. "yes");
  11432. }
  11433. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11434. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11435. }
  11436. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11437. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11438. }
  11439. if (timeout <= 0.0) {
  11440. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11441. }
  11442. /* Enter data processing loop */
  11443. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11444. conn->request_info.remote_addr,
  11445. conn->request_info.remote_port);
  11446. conn->in_websocket_handling = 1;
  11447. mg_set_thread_name("wsock");
  11448. /* Loop continuously, reading messages from the socket, invoking the
  11449. * callback, and waiting repeatedly until an error occurs. */
  11450. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11451. && (!conn->must_close)) {
  11452. header_len = 0;
  11453. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11454. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11455. len = buf[1] & 127;
  11456. mask_len = (buf[1] & 128) ? 4 : 0;
  11457. if ((len < 126) && (body_len >= mask_len)) {
  11458. /* inline 7-bit length field */
  11459. data_len = len;
  11460. header_len = 2 + mask_len;
  11461. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11462. /* 16-bit length field */
  11463. header_len = 4 + mask_len;
  11464. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11465. } else if (body_len >= (10 + mask_len)) {
  11466. /* 64-bit length field */
  11467. uint32_t l1, l2;
  11468. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11469. memcpy(&l2, &buf[6], 4);
  11470. header_len = 10 + mask_len;
  11471. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11472. if (data_len > (uint64_t)0x7FFF0000ul) {
  11473. /* no can do */
  11474. mg_cry_internal(
  11475. conn,
  11476. "%s",
  11477. "websocket out of memory; closing connection");
  11478. break;
  11479. }
  11480. }
  11481. }
  11482. if ((header_len > 0) && (body_len >= header_len)) {
  11483. /* Allocate space to hold websocket payload */
  11484. unsigned char *data = mem;
  11485. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11486. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11487. conn->phys_ctx);
  11488. if (data == NULL) {
  11489. /* Allocation failed, exit the loop and then close the
  11490. * connection */
  11491. mg_cry_internal(
  11492. conn,
  11493. "%s",
  11494. "websocket out of memory; closing connection");
  11495. break;
  11496. }
  11497. }
  11498. /* Copy the mask before we shift the queue and destroy it */
  11499. if (mask_len > 0) {
  11500. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11501. } else {
  11502. memset(mask, 0, sizeof(mask));
  11503. }
  11504. /* Read frame payload from the first message in the queue into
  11505. * data and advance the queue by moving the memory in place. */
  11506. DEBUG_ASSERT(body_len >= header_len);
  11507. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11508. mop = buf[0]; /* current mask and opcode */
  11509. /* Overflow case */
  11510. len = body_len - header_len;
  11511. memcpy(data, buf + header_len, len);
  11512. error = 0;
  11513. while ((uint64_t)len < data_len) {
  11514. n = pull_inner(NULL,
  11515. conn,
  11516. (char *)(data + len),
  11517. (int)(data_len - len),
  11518. timeout);
  11519. if (n <= -2) {
  11520. error = 1;
  11521. break;
  11522. } else if (n > 0) {
  11523. len += (size_t)n;
  11524. } else {
  11525. /* Timeout: should retry */
  11526. /* TODO: retry condition */
  11527. }
  11528. }
  11529. if (error) {
  11530. mg_cry_internal(
  11531. conn,
  11532. "%s",
  11533. "Websocket pull failed; closing connection");
  11534. if (data != mem) {
  11535. mg_free(data);
  11536. }
  11537. break;
  11538. }
  11539. conn->data_len = conn->request_len;
  11540. } else {
  11541. mop = buf[0]; /* current mask and opcode, overwritten by
  11542. * memmove() */
  11543. /* Length of the message being read at the front of the
  11544. * queue. Cast to 31 bit is OK, since we limited
  11545. * data_len before. */
  11546. len = (size_t)data_len + header_len;
  11547. /* Copy the data payload into the data pointer for the
  11548. * callback. Cast to 31 bit is OK, since we
  11549. * limited data_len */
  11550. memcpy(data, buf + header_len, (size_t)data_len);
  11551. /* Move the queue forward len bytes */
  11552. memmove(buf, buf + len, body_len - len);
  11553. /* Mark the queue as advanced */
  11554. conn->data_len -= (int)len;
  11555. }
  11556. /* Apply mask if necessary */
  11557. if (mask_len > 0) {
  11558. for (i = 0; i < (size_t)data_len; i++) {
  11559. data[i] ^= mask[i & 3];
  11560. }
  11561. }
  11562. exit_by_callback = 0;
  11563. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11564. /* filter PONG messages */
  11565. DEBUG_TRACE("PONG from %s:%u",
  11566. conn->request_info.remote_addr,
  11567. conn->request_info.remote_port);
  11568. /* No unanwered PINGs left */
  11569. ping_count = 0;
  11570. } else if (enable_ping_pong
  11571. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11572. /* reply PING messages */
  11573. DEBUG_TRACE("Reply PING from %s:%u",
  11574. conn->request_info.remote_addr,
  11575. conn->request_info.remote_port);
  11576. ret = mg_websocket_write(conn,
  11577. MG_WEBSOCKET_OPCODE_PONG,
  11578. (char *)data,
  11579. (size_t)data_len);
  11580. if (ret <= 0) {
  11581. /* Error: send failed */
  11582. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11583. break;
  11584. }
  11585. } else {
  11586. /* Exit the loop if callback signals to exit (server side),
  11587. * or "connection close" opcode received (client side). */
  11588. if (ws_data_handler != NULL) {
  11589. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11590. if (mop & 0x40) {
  11591. /* Inflate the data received if bit RSV1 is set. */
  11592. if (!conn->websocket_deflate_initialized) {
  11593. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11594. exit_by_callback = 1;
  11595. }
  11596. if (!exit_by_callback) {
  11597. size_t inflate_buf_size_old = 0;
  11598. size_t inflate_buf_size =
  11599. data_len
  11600. * 4; // Initial guess of the inflated message
  11601. // size. We double the memory when needed.
  11602. Bytef *inflated = NULL;
  11603. Bytef *new_mem = NULL;
  11604. conn->websocket_inflate_state.avail_in =
  11605. (uInt)(data_len + 4);
  11606. conn->websocket_inflate_state.next_in = data;
  11607. // Add trailing 0x00 0x00 0xff 0xff bytes
  11608. data[data_len] = '\x00';
  11609. data[data_len + 1] = '\x00';
  11610. data[data_len + 2] = '\xff';
  11611. data[data_len + 3] = '\xff';
  11612. do {
  11613. if (inflate_buf_size_old == 0) {
  11614. new_mem =
  11615. (Bytef *)mg_calloc(inflate_buf_size,
  11616. sizeof(Bytef));
  11617. } else {
  11618. inflate_buf_size *= 2;
  11619. new_mem =
  11620. (Bytef *)mg_realloc(inflated,
  11621. inflate_buf_size);
  11622. }
  11623. if (new_mem == NULL) {
  11624. mg_cry_internal(
  11625. conn,
  11626. "Out of memory: Cannot allocate "
  11627. "inflate buffer of %lu bytes",
  11628. (unsigned long)inflate_buf_size);
  11629. exit_by_callback = 1;
  11630. break;
  11631. }
  11632. inflated = new_mem;
  11633. conn->websocket_inflate_state.avail_out =
  11634. (uInt)(inflate_buf_size
  11635. - inflate_buf_size_old);
  11636. conn->websocket_inflate_state.next_out =
  11637. inflated + inflate_buf_size_old;
  11638. ret = inflate(&conn->websocket_inflate_state,
  11639. Z_SYNC_FLUSH);
  11640. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11641. || ret == Z_MEM_ERROR) {
  11642. mg_cry_internal(
  11643. conn,
  11644. "ZLIB inflate error: %i %s",
  11645. ret,
  11646. (conn->websocket_inflate_state.msg
  11647. ? conn->websocket_inflate_state.msg
  11648. : "<no error message>"));
  11649. exit_by_callback = 1;
  11650. break;
  11651. }
  11652. inflate_buf_size_old = inflate_buf_size;
  11653. } while (conn->websocket_inflate_state.avail_out
  11654. == 0);
  11655. inflate_buf_size -=
  11656. conn->websocket_inflate_state.avail_out;
  11657. if (!ws_data_handler(conn,
  11658. mop,
  11659. (char *)inflated,
  11660. inflate_buf_size,
  11661. callback_data)) {
  11662. exit_by_callback = 1;
  11663. }
  11664. mg_free(inflated);
  11665. }
  11666. } else
  11667. #endif
  11668. if (!ws_data_handler(conn,
  11669. mop,
  11670. (char *)data,
  11671. (size_t)data_len,
  11672. callback_data)) {
  11673. exit_by_callback = 1;
  11674. }
  11675. }
  11676. }
  11677. /* It a buffer has been allocated, free it again */
  11678. if (data != mem) {
  11679. mg_free(data);
  11680. }
  11681. if (exit_by_callback) {
  11682. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11683. conn->request_info.remote_addr,
  11684. conn->request_info.remote_port);
  11685. break;
  11686. }
  11687. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11688. /* Opcode == 8, connection close */
  11689. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11690. conn->request_info.remote_addr,
  11691. conn->request_info.remote_port);
  11692. break;
  11693. }
  11694. /* Not breaking the loop, process next websocket frame. */
  11695. } else {
  11696. /* Read from the socket into the next available location in the
  11697. * message queue. */
  11698. n = pull_inner(NULL,
  11699. conn,
  11700. conn->buf + conn->data_len,
  11701. conn->buf_size - conn->data_len,
  11702. timeout);
  11703. if (n <= -2) {
  11704. /* Error, no bytes read */
  11705. DEBUG_TRACE("PULL from %s:%u failed",
  11706. conn->request_info.remote_addr,
  11707. conn->request_info.remote_port);
  11708. break;
  11709. }
  11710. if (n > 0) {
  11711. conn->data_len += n;
  11712. /* Reset open PING count */
  11713. ping_count = 0;
  11714. } else {
  11715. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11716. && (!conn->must_close)) {
  11717. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11718. /* Stop sending PING */
  11719. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11720. "- closing connection",
  11721. ping_count,
  11722. conn->request_info.remote_addr,
  11723. conn->request_info.remote_port);
  11724. break;
  11725. }
  11726. if (enable_ping_pong) {
  11727. /* Send Websocket PING message */
  11728. DEBUG_TRACE("PING to %s:%u",
  11729. conn->request_info.remote_addr,
  11730. conn->request_info.remote_port);
  11731. ret = mg_websocket_write(conn,
  11732. MG_WEBSOCKET_OPCODE_PING,
  11733. NULL,
  11734. 0);
  11735. if (ret <= 0) {
  11736. /* Error: send failed */
  11737. DEBUG_TRACE("Send PING failed (%i)", ret);
  11738. break;
  11739. }
  11740. ping_count++;
  11741. }
  11742. }
  11743. /* Timeout: should retry */
  11744. /* TODO: get timeout def */
  11745. }
  11746. }
  11747. }
  11748. /* Leave data processing loop */
  11749. mg_set_thread_name("worker");
  11750. conn->in_websocket_handling = 0;
  11751. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11752. conn->request_info.remote_addr,
  11753. conn->request_info.remote_port);
  11754. }
  11755. static int
  11756. mg_websocket_write_exec(struct mg_connection *conn,
  11757. int opcode,
  11758. const char *data,
  11759. size_t dataLen,
  11760. uint32_t masking_key)
  11761. {
  11762. unsigned char header[14];
  11763. size_t headerLen;
  11764. int retval;
  11765. #if defined(GCC_DIAGNOSTIC)
  11766. /* Disable spurious conversion warning for GCC */
  11767. #pragma GCC diagnostic push
  11768. #pragma GCC diagnostic ignored "-Wconversion"
  11769. #endif
  11770. /* Note that POSIX/Winsock's send() is threadsafe
  11771. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11772. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11773. * push(), although that is only a problem if the packet is large or
  11774. * outgoing buffer is full). */
  11775. /* TODO: Check if this lock should be moved to user land.
  11776. * Currently the server sets this lock for websockets, but
  11777. * not for any other connection. It must be set for every
  11778. * conn read/written by more than one thread, no matter if
  11779. * it is a websocket or regular connection. */
  11780. (void)mg_lock_connection(conn);
  11781. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11782. size_t deflated_size = 0;
  11783. Bytef *deflated = 0;
  11784. // Deflate websocket messages over 100kb
  11785. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11786. if (use_deflate) {
  11787. if (!conn->websocket_deflate_initialized) {
  11788. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11789. return 0;
  11790. }
  11791. // Deflating the message
  11792. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11793. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11794. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11795. deflated_size = (size_t)compressBound((uLong)dataLen);
  11796. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11797. if (deflated == NULL) {
  11798. mg_cry_internal(
  11799. conn,
  11800. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11801. (unsigned long)deflated_size);
  11802. mg_unlock_connection(conn);
  11803. return -1;
  11804. }
  11805. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11806. conn->websocket_deflate_state.next_out = deflated;
  11807. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11808. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11809. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11810. } else
  11811. #endif
  11812. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11813. #if defined(GCC_DIAGNOSTIC)
  11814. #pragma GCC diagnostic pop
  11815. #endif
  11816. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11817. if (dataLen < 126) {
  11818. /* inline 7-bit length field */
  11819. header[1] = (unsigned char)dataLen;
  11820. headerLen = 2;
  11821. } else if (dataLen <= 0xFFFF) {
  11822. /* 16-bit length field */
  11823. uint16_t len = htons((uint16_t)dataLen);
  11824. header[1] = 126;
  11825. memcpy(header + 2, &len, 2);
  11826. headerLen = 4;
  11827. } else {
  11828. /* 64-bit length field */
  11829. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11830. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11831. header[1] = 127;
  11832. memcpy(header + 2, &len1, 4);
  11833. memcpy(header + 6, &len2, 4);
  11834. headerLen = 10;
  11835. }
  11836. if (masking_key) {
  11837. /* add mask */
  11838. header[1] |= 0x80;
  11839. memcpy(header + headerLen, &masking_key, 4);
  11840. headerLen += 4;
  11841. }
  11842. retval = mg_write(conn, header, headerLen);
  11843. if (retval != (int)headerLen) {
  11844. /* Did not send complete header */
  11845. retval = -1;
  11846. } else {
  11847. if (dataLen > 0) {
  11848. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11849. if (use_deflate) {
  11850. retval = mg_write(conn, deflated, dataLen);
  11851. mg_free(deflated);
  11852. } else
  11853. #endif
  11854. retval = mg_write(conn, data, dataLen);
  11855. }
  11856. /* if dataLen == 0, the header length (2) is returned */
  11857. }
  11858. /* TODO: Remove this unlock as well, when lock is removed. */
  11859. mg_unlock_connection(conn);
  11860. return retval;
  11861. }
  11862. CIVETWEB_API int
  11863. mg_websocket_write(struct mg_connection *conn,
  11864. int opcode,
  11865. const char *data,
  11866. size_t dataLen)
  11867. {
  11868. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11869. }
  11870. static void
  11871. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11872. {
  11873. size_t i = 0;
  11874. i = 0;
  11875. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11876. /* Convert in 32 bit words, if data is 4 byte aligned */
  11877. while (i < (in_len - 3)) {
  11878. *(uint32_t *)(void *)(out + i) =
  11879. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11880. i += 4;
  11881. }
  11882. }
  11883. if (i != in_len) {
  11884. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11885. while (i < in_len) {
  11886. *(uint8_t *)(void *)(out + i) =
  11887. *(uint8_t *)(void *)(in + i)
  11888. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11889. i++;
  11890. }
  11891. }
  11892. }
  11893. CIVETWEB_API int
  11894. mg_websocket_client_write(struct mg_connection *conn,
  11895. int opcode,
  11896. const char *data,
  11897. size_t dataLen)
  11898. {
  11899. int retval = -1;
  11900. char *masked_data =
  11901. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11902. uint32_t masking_key = 0;
  11903. if (masked_data == NULL) {
  11904. /* Return -1 in an error case */
  11905. mg_cry_internal(conn,
  11906. "%s",
  11907. "Cannot allocate buffer for masked websocket response: "
  11908. "Out of memory");
  11909. return -1;
  11910. }
  11911. do {
  11912. /* Get a masking key - but not 0 */
  11913. masking_key = (uint32_t)get_random();
  11914. } while (masking_key == 0);
  11915. mask_data(data, dataLen, masking_key, masked_data);
  11916. retval = mg_websocket_write_exec(
  11917. conn, opcode, masked_data, dataLen, masking_key);
  11918. mg_free(masked_data);
  11919. return retval;
  11920. }
  11921. static void
  11922. handle_websocket_request(struct mg_connection *conn,
  11923. const char *path,
  11924. int is_callback_resource,
  11925. struct mg_websocket_subprotocols *subprotocols,
  11926. mg_websocket_connect_handler ws_connect_handler,
  11927. mg_websocket_ready_handler ws_ready_handler,
  11928. mg_websocket_data_handler ws_data_handler,
  11929. mg_websocket_close_handler ws_close_handler,
  11930. void *cbData)
  11931. {
  11932. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11933. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11934. ptrdiff_t lua_websock = 0;
  11935. #if !defined(USE_LUA)
  11936. (void)path;
  11937. #endif
  11938. /* Step 1: Check websocket protocol version. */
  11939. /* Step 1.1: Check Sec-WebSocket-Key. */
  11940. if (!websock_key) {
  11941. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11942. * requires a Sec-WebSocket-Key header.
  11943. */
  11944. /* It could be the hixie draft version
  11945. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11946. */
  11947. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11948. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11949. char key3[8];
  11950. if ((key1 != NULL) && (key2 != NULL)) {
  11951. /* This version uses 8 byte body data in a GET request */
  11952. conn->content_len = 8;
  11953. if (8 == mg_read(conn, key3, 8)) {
  11954. /* This is the hixie version */
  11955. mg_send_http_error(conn,
  11956. 426,
  11957. "%s",
  11958. "Protocol upgrade to RFC 6455 required");
  11959. return;
  11960. }
  11961. }
  11962. /* This is an unknown version */
  11963. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11964. return;
  11965. }
  11966. /* Step 1.2: Check websocket protocol version. */
  11967. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11968. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11969. /* Reject wrong versions */
  11970. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11971. return;
  11972. }
  11973. /* Step 1.3: Could check for "Host", but we do not really need this
  11974. * value for anything, so just ignore it. */
  11975. /* Step 2: If a callback is responsible, call it. */
  11976. if (is_callback_resource) {
  11977. /* Step 2.1 check and select subprotocol */
  11978. const char *protocols[64]; // max 64 headers
  11979. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11980. "Sec-WebSocket-Protocol",
  11981. protocols,
  11982. 64);
  11983. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11984. int headerNo, idx;
  11985. size_t len;
  11986. const char *sep, *curSubProtocol,
  11987. *acceptedWebSocketSubprotocol = NULL;
  11988. /* look for matching subprotocol */
  11989. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11990. /* There might be multiple headers ... */
  11991. const char *protocol = protocols[headerNo];
  11992. curSubProtocol = protocol;
  11993. /* ... and in every header there might be a , separated list */
  11994. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11995. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11996. curSubProtocol++;
  11997. sep = strchr(curSubProtocol, ',');
  11998. if (sep) {
  11999. len = (size_t)(sep - curSubProtocol);
  12000. } else {
  12001. len = strlen(curSubProtocol);
  12002. }
  12003. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12004. // COMPARE: curSubProtocol ==
  12005. // subprotocols->subprotocols[idx]
  12006. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12007. && (strncmp(curSubProtocol,
  12008. subprotocols->subprotocols[idx],
  12009. len)
  12010. == 0)) {
  12011. acceptedWebSocketSubprotocol =
  12012. subprotocols->subprotocols[idx];
  12013. break;
  12014. }
  12015. }
  12016. curSubProtocol += len;
  12017. }
  12018. }
  12019. conn->request_info.acceptedWebSocketSubprotocol =
  12020. acceptedWebSocketSubprotocol;
  12021. }
  12022. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12023. websocket_deflate_negotiate(conn);
  12024. #endif
  12025. if ((ws_connect_handler != NULL)
  12026. && (ws_connect_handler(conn, cbData) != 0)) {
  12027. /* C callback has returned non-zero, do not proceed with
  12028. * handshake.
  12029. */
  12030. /* Note that C callbacks are no longer called when Lua is
  12031. * responsible, so C can no longer filter callbacks for Lua. */
  12032. return;
  12033. }
  12034. }
  12035. #if defined(USE_LUA)
  12036. /* Step 3: No callback. Check if Lua is responsible. */
  12037. else {
  12038. /* Step 3.1: Check if Lua is responsible. */
  12039. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12040. lua_websock = match_prefix_strlen(
  12041. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12042. }
  12043. if (lua_websock > 0) {
  12044. /* Step 3.2: Lua is responsible: call it. */
  12045. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12046. if (!conn->lua_websocket_state) {
  12047. /* Lua rejected the new client */
  12048. return;
  12049. }
  12050. }
  12051. }
  12052. #endif
  12053. /* Step 4: Check if there is a responsible websocket handler. */
  12054. if (!is_callback_resource && !lua_websock) {
  12055. /* There is no callback, and Lua is not responsible either. */
  12056. /* Reply with a 404 Not Found. We are still at a standard
  12057. * HTTP request here, before the websocket handshake, so
  12058. * we can still send standard HTTP error replies. */
  12059. mg_send_http_error(conn, 404, "%s", "Not found");
  12060. return;
  12061. }
  12062. /* Step 5: The websocket connection has been accepted */
  12063. if (!send_websocket_handshake(conn, websock_key)) {
  12064. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12065. return;
  12066. }
  12067. /* Step 6: Call the ready handler */
  12068. if (is_callback_resource) {
  12069. if (ws_ready_handler != NULL) {
  12070. ws_ready_handler(conn, cbData);
  12071. }
  12072. #if defined(USE_LUA)
  12073. } else if (lua_websock) {
  12074. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12075. /* the ready handler returned false */
  12076. return;
  12077. }
  12078. #endif
  12079. }
  12080. /* Step 7: Enter the read loop */
  12081. if (is_callback_resource) {
  12082. read_websocket(conn, ws_data_handler, cbData);
  12083. #if defined(USE_LUA)
  12084. } else if (lua_websock) {
  12085. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12086. #endif
  12087. }
  12088. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12089. /* Step 8: Close the deflate & inflate buffers */
  12090. if (conn->websocket_deflate_initialized) {
  12091. deflateEnd(&conn->websocket_deflate_state);
  12092. inflateEnd(&conn->websocket_inflate_state);
  12093. }
  12094. #endif
  12095. /* Step 9: Call the close handler */
  12096. if (ws_close_handler) {
  12097. ws_close_handler(conn, cbData);
  12098. }
  12099. }
  12100. #endif /* !USE_WEBSOCKET */
  12101. /* Is upgrade request:
  12102. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12103. * 1 = upgrade to websocket
  12104. * 2 = upgrade to HTTP/2
  12105. * -1 = upgrade to unknown protocol
  12106. */
  12107. static int
  12108. should_switch_to_protocol(const struct mg_connection *conn)
  12109. {
  12110. const char *connection_headers[8];
  12111. const char *upgrade_to;
  12112. int connection_header_count, i, should_upgrade;
  12113. /* A websocket protocol has the following HTTP headers:
  12114. *
  12115. * Connection: Upgrade
  12116. * Upgrade: Websocket
  12117. *
  12118. * It seems some clients use multiple headers:
  12119. * see https://github.com/civetweb/civetweb/issues/1083
  12120. */
  12121. connection_header_count = get_req_headers(&conn->request_info,
  12122. "Connection",
  12123. connection_headers,
  12124. 8);
  12125. should_upgrade = 0;
  12126. for (i = 0; i < connection_header_count; i++) {
  12127. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12128. should_upgrade = 1;
  12129. }
  12130. }
  12131. if (!should_upgrade) {
  12132. return PROTOCOL_TYPE_HTTP1;
  12133. }
  12134. upgrade_to = mg_get_header(conn, "Upgrade");
  12135. if (upgrade_to == NULL) {
  12136. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12137. return -1;
  12138. }
  12139. /* Upgrade to ... */
  12140. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12141. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12142. * "Sec-WebSocket-Version" are also required.
  12143. * Don't check them here, since even an unsupported websocket protocol
  12144. * request still IS a websocket request (in contrast to a standard HTTP
  12145. * request). It will fail later in handle_websocket_request.
  12146. */
  12147. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12148. }
  12149. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12150. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12151. }
  12152. /* Upgrade to another protocol */
  12153. return -1;
  12154. }
  12155. static int
  12156. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12157. {
  12158. int n;
  12159. unsigned int a, b, c, d, slash;
  12160. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12161. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12162. // integer value, but function will not report conversion
  12163. // errors; consider using 'strtol' instead
  12164. slash = 32;
  12165. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12166. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12167. // an integer value, but function will not report conversion
  12168. // errors; consider using 'strtol' instead
  12169. n = 0;
  12170. }
  12171. }
  12172. if ((n > 0) && ((size_t)n == vec->len)) {
  12173. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12174. /* IPv4 format */
  12175. if (sa->sa.sa_family == AF_INET) {
  12176. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12177. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12178. | ((uint32_t)c << 8) | (uint32_t)d;
  12179. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12180. return (ip & mask) == net;
  12181. }
  12182. return 0;
  12183. }
  12184. }
  12185. #if defined(USE_IPV6)
  12186. else {
  12187. char ad[50];
  12188. const char *p;
  12189. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12190. slash = 128;
  12191. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12192. n = 0;
  12193. }
  12194. }
  12195. if ((n <= 0) && no_strict) {
  12196. /* no square brackets? */
  12197. p = strchr(vec->ptr, '/');
  12198. if (p && (p < (vec->ptr + vec->len))) {
  12199. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12200. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12201. n += (int)(p - vec->ptr);
  12202. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12203. } else {
  12204. n = 0;
  12205. }
  12206. } else if (vec->len < sizeof(ad)) {
  12207. n = (int)vec->len;
  12208. slash = 128;
  12209. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12210. }
  12211. }
  12212. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12213. p = ad;
  12214. c = 0;
  12215. /* zone indexes are unsupported, at least two colons are needed */
  12216. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12217. if (*(p++) == ':') {
  12218. c++;
  12219. }
  12220. }
  12221. if ((*p == '\0') && (c >= 2)) {
  12222. struct sockaddr_in6 sin6;
  12223. unsigned int i;
  12224. /* for strict validation, an actual IPv6 argument is needed */
  12225. if (sa->sa.sa_family != AF_INET6) {
  12226. return 0;
  12227. }
  12228. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12229. /* IPv6 format */
  12230. for (i = 0; i < 16; i++) {
  12231. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12232. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12233. uint8_t mask = 0;
  12234. if (8 * i + 8 < slash) {
  12235. mask = 0xFFu;
  12236. } else if (8 * i < slash) {
  12237. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12238. }
  12239. if ((ip & mask) != net) {
  12240. return 0;
  12241. }
  12242. }
  12243. return 1;
  12244. }
  12245. }
  12246. }
  12247. }
  12248. #else
  12249. (void)no_strict;
  12250. #endif
  12251. /* malformed */
  12252. return -1;
  12253. }
  12254. static int
  12255. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12256. {
  12257. int throttle = 0;
  12258. struct vec vec, val;
  12259. char mult;
  12260. double v;
  12261. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12262. mult = ',';
  12263. if ((val.ptr == NULL)
  12264. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12265. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12266. // to an integer value, but function will not report
  12267. // conversion errors; consider using 'strtol' instead
  12268. || (v < 0)
  12269. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12270. && (mult != ','))) {
  12271. continue;
  12272. }
  12273. v *= (lowercase(&mult) == 'k')
  12274. ? 1024
  12275. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12276. if (vec.len == 1 && vec.ptr[0] == '*') {
  12277. throttle = (int)v;
  12278. } else {
  12279. int matched = parse_match_net(&vec, rsa, 0);
  12280. if (matched >= 0) {
  12281. /* a valid IP subnet */
  12282. if (matched) {
  12283. throttle = (int)v;
  12284. }
  12285. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12286. throttle = (int)v;
  12287. }
  12288. }
  12289. }
  12290. return throttle;
  12291. }
  12292. /* The mg_upload function is superseded by mg_handle_form_request. */
  12293. #include "handle_form.inl"
  12294. static int
  12295. get_first_ssl_listener_index(const struct mg_context *ctx)
  12296. {
  12297. unsigned int i;
  12298. int idx = -1;
  12299. if (ctx) {
  12300. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12301. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12302. }
  12303. }
  12304. return idx;
  12305. }
  12306. /* Return host (without port) */
  12307. static void
  12308. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12309. {
  12310. const char *host_header =
  12311. get_header(ri->http_headers, ri->num_headers, "Host");
  12312. host->ptr = NULL;
  12313. host->len = 0;
  12314. if (host_header != NULL) {
  12315. const char *pos;
  12316. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12317. * is found. */
  12318. if (*host_header == '[') {
  12319. pos = strchr(host_header, ']');
  12320. if (!pos) {
  12321. /* Malformed hostname starts with '[', but no ']' found */
  12322. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12323. return;
  12324. }
  12325. /* terminate after ']' */
  12326. host->ptr = host_header;
  12327. host->len = (size_t)(pos + 1 - host_header);
  12328. } else {
  12329. /* Otherwise, a ':' separates hostname and port number */
  12330. pos = strchr(host_header, ':');
  12331. if (pos != NULL) {
  12332. host->len = (size_t)(pos - host_header);
  12333. } else {
  12334. host->len = strlen(host_header);
  12335. }
  12336. host->ptr = host_header;
  12337. }
  12338. }
  12339. }
  12340. static int
  12341. switch_domain_context(struct mg_connection *conn)
  12342. {
  12343. struct vec host;
  12344. get_host_from_request_info(&host, &conn->request_info);
  12345. if (host.ptr) {
  12346. if (conn->ssl) {
  12347. /* This is a HTTPS connection, maybe we have a hostname
  12348. * from SNI (set in ssl_servername_callback). */
  12349. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12350. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12351. /* We are not using the default domain */
  12352. if ((strlen(sslhost) != host.len)
  12353. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12354. /* Mismatch between SNI domain and HTTP domain */
  12355. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12356. sslhost,
  12357. (int)host.len,
  12358. host.ptr);
  12359. return 0;
  12360. }
  12361. }
  12362. } else {
  12363. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12364. while (dom) {
  12365. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12366. size_t domNameLen = strlen(domName);
  12367. if ((domNameLen == host.len)
  12368. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12369. /* Found matching domain */
  12370. DEBUG_TRACE("HTTP domain %s found",
  12371. dom->config[AUTHENTICATION_DOMAIN]);
  12372. /* TODO: Check if this is a HTTP or HTTPS domain */
  12373. conn->dom_ctx = dom;
  12374. break;
  12375. }
  12376. mg_lock_context(conn->phys_ctx);
  12377. dom = dom->next;
  12378. mg_unlock_context(conn->phys_ctx);
  12379. }
  12380. }
  12381. DEBUG_TRACE("HTTP%s Host: %.*s",
  12382. conn->ssl ? "S" : "",
  12383. (int)host.len,
  12384. host.ptr);
  12385. } else {
  12386. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12387. return 1;
  12388. }
  12389. return 1;
  12390. }
  12391. static void
  12392. redirect_to_https_port(struct mg_connection *conn, int port)
  12393. {
  12394. char target_url[MG_BUF_LEN];
  12395. int truncated = 0;
  12396. const char *expect_proto =
  12397. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12398. /* Use "308 Permanent Redirect" */
  12399. int redirect_code = 308;
  12400. /* In any case, close the current connection */
  12401. conn->must_close = 1;
  12402. /* Send host, port, uri and (if it exists) ?query_string */
  12403. if (mg_construct_local_link(
  12404. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12405. < 0) {
  12406. truncated = 1;
  12407. } else if (conn->request_info.query_string != NULL) {
  12408. size_t slen1 = strlen(target_url);
  12409. size_t slen2 = strlen(conn->request_info.query_string);
  12410. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12411. target_url[slen1] = '?';
  12412. memcpy(target_url + slen1 + 1,
  12413. conn->request_info.query_string,
  12414. slen2);
  12415. target_url[slen1 + slen2 + 1] = 0;
  12416. } else {
  12417. truncated = 1;
  12418. }
  12419. }
  12420. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12421. * is used as buffer size) */
  12422. if (truncated) {
  12423. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12424. return;
  12425. }
  12426. /* Use redirect helper function */
  12427. mg_send_http_redirect(conn, target_url, redirect_code);
  12428. }
  12429. static void
  12430. mg_set_handler_type(struct mg_context *phys_ctx,
  12431. struct mg_domain_context *dom_ctx,
  12432. const char *uri,
  12433. int handler_type,
  12434. int is_delete_request,
  12435. mg_request_handler handler,
  12436. struct mg_websocket_subprotocols *subprotocols,
  12437. mg_websocket_connect_handler connect_handler,
  12438. mg_websocket_ready_handler ready_handler,
  12439. mg_websocket_data_handler data_handler,
  12440. mg_websocket_close_handler close_handler,
  12441. mg_authorization_handler auth_handler,
  12442. void *cbdata)
  12443. {
  12444. struct mg_handler_info *tmp_rh, **lastref;
  12445. size_t urilen = strlen(uri);
  12446. if (handler_type == WEBSOCKET_HANDLER) {
  12447. DEBUG_ASSERT(handler == NULL);
  12448. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12449. || ready_handler != NULL || data_handler != NULL
  12450. || close_handler != NULL);
  12451. DEBUG_ASSERT(auth_handler == NULL);
  12452. if (handler != NULL) {
  12453. return;
  12454. }
  12455. if (!is_delete_request && (connect_handler == NULL)
  12456. && (ready_handler == NULL) && (data_handler == NULL)
  12457. && (close_handler == NULL)) {
  12458. return;
  12459. }
  12460. if (auth_handler != NULL) {
  12461. return;
  12462. }
  12463. } else if (handler_type == REQUEST_HANDLER) {
  12464. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12465. && data_handler == NULL && close_handler == NULL);
  12466. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12467. DEBUG_ASSERT(auth_handler == NULL);
  12468. if ((connect_handler != NULL) || (ready_handler != NULL)
  12469. || (data_handler != NULL) || (close_handler != NULL)) {
  12470. return;
  12471. }
  12472. if (!is_delete_request && (handler == NULL)) {
  12473. return;
  12474. }
  12475. if (auth_handler != NULL) {
  12476. return;
  12477. }
  12478. } else if (handler_type == AUTH_HANDLER) {
  12479. DEBUG_ASSERT(handler == NULL);
  12480. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12481. && data_handler == NULL && close_handler == NULL);
  12482. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12483. if (handler != NULL) {
  12484. return;
  12485. }
  12486. if ((connect_handler != NULL) || (ready_handler != NULL)
  12487. || (data_handler != NULL) || (close_handler != NULL)) {
  12488. return;
  12489. }
  12490. if (!is_delete_request && (auth_handler == NULL)) {
  12491. return;
  12492. }
  12493. } else {
  12494. /* Unknown handler type. */
  12495. return;
  12496. }
  12497. if (!phys_ctx || !dom_ctx) {
  12498. /* no context available */
  12499. return;
  12500. }
  12501. mg_lock_context(phys_ctx);
  12502. /* first try to find an existing handler */
  12503. do {
  12504. lastref = &(dom_ctx->handlers);
  12505. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12506. tmp_rh = tmp_rh->next) {
  12507. if (tmp_rh->handler_type == handler_type
  12508. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12509. if (!is_delete_request) {
  12510. /* update existing handler */
  12511. if (handler_type == REQUEST_HANDLER) {
  12512. /* Wait for end of use before updating */
  12513. if (tmp_rh->refcount) {
  12514. mg_unlock_context(phys_ctx);
  12515. mg_sleep(1);
  12516. mg_lock_context(phys_ctx);
  12517. /* tmp_rh might have been freed, search again. */
  12518. break;
  12519. }
  12520. /* Ok, the handler is no more use -> Update it */
  12521. tmp_rh->handler = handler;
  12522. } else if (handler_type == WEBSOCKET_HANDLER) {
  12523. tmp_rh->subprotocols = subprotocols;
  12524. tmp_rh->connect_handler = connect_handler;
  12525. tmp_rh->ready_handler = ready_handler;
  12526. tmp_rh->data_handler = data_handler;
  12527. tmp_rh->close_handler = close_handler;
  12528. } else { /* AUTH_HANDLER */
  12529. tmp_rh->auth_handler = auth_handler;
  12530. }
  12531. tmp_rh->cbdata = cbdata;
  12532. } else {
  12533. /* remove existing handler */
  12534. if (handler_type == REQUEST_HANDLER) {
  12535. /* Wait for end of use before removing */
  12536. if (tmp_rh->refcount) {
  12537. tmp_rh->removing = 1;
  12538. mg_unlock_context(phys_ctx);
  12539. mg_sleep(1);
  12540. mg_lock_context(phys_ctx);
  12541. /* tmp_rh might have been freed, search again. */
  12542. break;
  12543. }
  12544. /* Ok, the handler is no more used */
  12545. }
  12546. *lastref = tmp_rh->next;
  12547. mg_free(tmp_rh->uri);
  12548. mg_free(tmp_rh);
  12549. }
  12550. mg_unlock_context(phys_ctx);
  12551. return;
  12552. }
  12553. lastref = &(tmp_rh->next);
  12554. }
  12555. } while (tmp_rh != NULL);
  12556. if (is_delete_request) {
  12557. /* no handler to set, this was a remove request to a non-existing
  12558. * handler */
  12559. mg_unlock_context(phys_ctx);
  12560. return;
  12561. }
  12562. tmp_rh =
  12563. (struct mg_handler_info *)mg_calloc_ctx(1,
  12564. sizeof(struct mg_handler_info),
  12565. phys_ctx);
  12566. if (tmp_rh == NULL) {
  12567. mg_unlock_context(phys_ctx);
  12568. mg_cry_ctx_internal(phys_ctx,
  12569. "%s",
  12570. "Cannot create new request handler struct, OOM");
  12571. return;
  12572. }
  12573. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12574. if (!tmp_rh->uri) {
  12575. mg_unlock_context(phys_ctx);
  12576. mg_free(tmp_rh);
  12577. mg_cry_ctx_internal(phys_ctx,
  12578. "%s",
  12579. "Cannot create new request handler struct, OOM");
  12580. return;
  12581. }
  12582. tmp_rh->uri_len = urilen;
  12583. if (handler_type == REQUEST_HANDLER) {
  12584. tmp_rh->refcount = 0;
  12585. tmp_rh->removing = 0;
  12586. tmp_rh->handler = handler;
  12587. } else if (handler_type == WEBSOCKET_HANDLER) {
  12588. tmp_rh->subprotocols = subprotocols;
  12589. tmp_rh->connect_handler = connect_handler;
  12590. tmp_rh->ready_handler = ready_handler;
  12591. tmp_rh->data_handler = data_handler;
  12592. tmp_rh->close_handler = close_handler;
  12593. } else { /* AUTH_HANDLER */
  12594. tmp_rh->auth_handler = auth_handler;
  12595. }
  12596. tmp_rh->cbdata = cbdata;
  12597. tmp_rh->handler_type = handler_type;
  12598. tmp_rh->next = NULL;
  12599. *lastref = tmp_rh;
  12600. mg_unlock_context(phys_ctx);
  12601. }
  12602. CIVETWEB_API void
  12603. mg_set_request_handler(struct mg_context *ctx,
  12604. const char *uri,
  12605. mg_request_handler handler,
  12606. void *cbdata)
  12607. {
  12608. mg_set_handler_type(ctx,
  12609. &(ctx->dd),
  12610. uri,
  12611. REQUEST_HANDLER,
  12612. handler == NULL,
  12613. handler,
  12614. NULL,
  12615. NULL,
  12616. NULL,
  12617. NULL,
  12618. NULL,
  12619. NULL,
  12620. cbdata);
  12621. }
  12622. CIVETWEB_API void
  12623. mg_set_websocket_handler(struct mg_context *ctx,
  12624. const char *uri,
  12625. mg_websocket_connect_handler connect_handler,
  12626. mg_websocket_ready_handler ready_handler,
  12627. mg_websocket_data_handler data_handler,
  12628. mg_websocket_close_handler close_handler,
  12629. void *cbdata)
  12630. {
  12631. mg_set_websocket_handler_with_subprotocols(ctx,
  12632. uri,
  12633. NULL,
  12634. connect_handler,
  12635. ready_handler,
  12636. data_handler,
  12637. close_handler,
  12638. cbdata);
  12639. }
  12640. CIVETWEB_API void
  12641. mg_set_websocket_handler_with_subprotocols(
  12642. struct mg_context *ctx,
  12643. const char *uri,
  12644. struct mg_websocket_subprotocols *subprotocols,
  12645. mg_websocket_connect_handler connect_handler,
  12646. mg_websocket_ready_handler ready_handler,
  12647. mg_websocket_data_handler data_handler,
  12648. mg_websocket_close_handler close_handler,
  12649. void *cbdata)
  12650. {
  12651. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12652. && (data_handler == NULL)
  12653. && (close_handler == NULL);
  12654. mg_set_handler_type(ctx,
  12655. &(ctx->dd),
  12656. uri,
  12657. WEBSOCKET_HANDLER,
  12658. is_delete_request,
  12659. NULL,
  12660. subprotocols,
  12661. connect_handler,
  12662. ready_handler,
  12663. data_handler,
  12664. close_handler,
  12665. NULL,
  12666. cbdata);
  12667. }
  12668. CIVETWEB_API void
  12669. mg_set_auth_handler(struct mg_context *ctx,
  12670. const char *uri,
  12671. mg_authorization_handler handler,
  12672. void *cbdata)
  12673. {
  12674. mg_set_handler_type(ctx,
  12675. &(ctx->dd),
  12676. uri,
  12677. AUTH_HANDLER,
  12678. handler == NULL,
  12679. NULL,
  12680. NULL,
  12681. NULL,
  12682. NULL,
  12683. NULL,
  12684. NULL,
  12685. handler,
  12686. cbdata);
  12687. }
  12688. static int
  12689. get_request_handler(struct mg_connection *conn,
  12690. int handler_type,
  12691. mg_request_handler *handler,
  12692. struct mg_websocket_subprotocols **subprotocols,
  12693. mg_websocket_connect_handler *connect_handler,
  12694. mg_websocket_ready_handler *ready_handler,
  12695. mg_websocket_data_handler *data_handler,
  12696. mg_websocket_close_handler *close_handler,
  12697. mg_authorization_handler *auth_handler,
  12698. void **cbdata,
  12699. struct mg_handler_info **handler_info)
  12700. {
  12701. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12702. if (request_info) {
  12703. const char *uri = request_info->local_uri;
  12704. size_t urilen = strlen(uri);
  12705. struct mg_handler_info *tmp_rh;
  12706. int step, matched;
  12707. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12708. return 0;
  12709. }
  12710. mg_lock_context(conn->phys_ctx);
  12711. for (step = 0; step < 3; step++) {
  12712. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12713. tmp_rh = tmp_rh->next) {
  12714. if (tmp_rh->handler_type != handler_type) {
  12715. continue;
  12716. }
  12717. if (step == 0) {
  12718. /* first try for an exact match */
  12719. matched = (tmp_rh->uri_len == urilen)
  12720. && (strcmp(tmp_rh->uri, uri) == 0);
  12721. } else if (step == 1) {
  12722. /* next try for a partial match, we will accept
  12723. uri/something */
  12724. matched =
  12725. (tmp_rh->uri_len < urilen)
  12726. && (uri[tmp_rh->uri_len] == '/')
  12727. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12728. } else {
  12729. /* finally try for pattern match */
  12730. matched =
  12731. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12732. }
  12733. if (matched) {
  12734. if (handler_type == WEBSOCKET_HANDLER) {
  12735. *subprotocols = tmp_rh->subprotocols;
  12736. *connect_handler = tmp_rh->connect_handler;
  12737. *ready_handler = tmp_rh->ready_handler;
  12738. *data_handler = tmp_rh->data_handler;
  12739. *close_handler = tmp_rh->close_handler;
  12740. } else if (handler_type == REQUEST_HANDLER) {
  12741. if (tmp_rh->removing) {
  12742. /* Treat as none found */
  12743. step = 2;
  12744. break;
  12745. }
  12746. *handler = tmp_rh->handler;
  12747. /* Acquire handler and give it back */
  12748. tmp_rh->refcount++;
  12749. *handler_info = tmp_rh;
  12750. } else { /* AUTH_HANDLER */
  12751. *auth_handler = tmp_rh->auth_handler;
  12752. }
  12753. *cbdata = tmp_rh->cbdata;
  12754. mg_unlock_context(conn->phys_ctx);
  12755. return 1;
  12756. }
  12757. }
  12758. }
  12759. mg_unlock_context(conn->phys_ctx);
  12760. }
  12761. return 0; /* none found */
  12762. }
  12763. /* Check if the script file is in a path, allowed for script files.
  12764. * This can be used if uploading files is possible not only for the server
  12765. * admin, and the upload mechanism does not check the file extension.
  12766. */
  12767. static int
  12768. is_in_script_path(const struct mg_connection *conn, const char *path)
  12769. {
  12770. /* TODO (Feature): Add config value for allowed script path.
  12771. * Default: All allowed. */
  12772. (void)conn;
  12773. (void)path;
  12774. return 1;
  12775. }
  12776. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12777. static int
  12778. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12779. int bits,
  12780. char *data,
  12781. size_t len,
  12782. void *cbdata)
  12783. {
  12784. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12785. if (pcallbacks->websocket_data) {
  12786. return pcallbacks->websocket_data(conn, bits, data, len);
  12787. }
  12788. /* No handler set - assume "OK" */
  12789. return 1;
  12790. }
  12791. static void
  12792. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12793. void *cbdata)
  12794. {
  12795. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12796. if (pcallbacks->connection_close) {
  12797. pcallbacks->connection_close(conn);
  12798. }
  12799. }
  12800. #endif
  12801. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12802. */
  12803. static void
  12804. release_handler_ref(struct mg_connection *conn,
  12805. struct mg_handler_info *handler_info)
  12806. {
  12807. if (handler_info != NULL) {
  12808. /* Use context lock for ref counter */
  12809. mg_lock_context(conn->phys_ctx);
  12810. handler_info->refcount--;
  12811. mg_unlock_context(conn->phys_ctx);
  12812. }
  12813. }
  12814. /* This is the heart of the Civetweb's logic.
  12815. * This function is called when the request is read, parsed and validated,
  12816. * and Civetweb must decide what action to take: serve a file, or
  12817. * a directory, or call embedded function, etcetera. */
  12818. static void
  12819. handle_request(struct mg_connection *conn)
  12820. {
  12821. struct mg_request_info *ri = &conn->request_info;
  12822. char path[UTF8_PATH_MAX];
  12823. int uri_len, ssl_index;
  12824. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12825. is_put_or_delete_request = 0, is_callback_resource = 0,
  12826. is_template_text_file = 0, is_webdav_request = 0;
  12827. int i;
  12828. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12829. mg_request_handler callback_handler = NULL;
  12830. struct mg_handler_info *handler_info = NULL;
  12831. struct mg_websocket_subprotocols *subprotocols;
  12832. mg_websocket_connect_handler ws_connect_handler = NULL;
  12833. mg_websocket_ready_handler ws_ready_handler = NULL;
  12834. mg_websocket_data_handler ws_data_handler = NULL;
  12835. mg_websocket_close_handler ws_close_handler = NULL;
  12836. void *callback_data = NULL;
  12837. mg_authorization_handler auth_handler = NULL;
  12838. void *auth_callback_data = NULL;
  12839. int handler_type;
  12840. time_t curtime = time(NULL);
  12841. char date[64];
  12842. char *tmp;
  12843. path[0] = 0;
  12844. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12845. conn->request_state = 0;
  12846. /* 1. get the request url */
  12847. /* 1.1. split into url and query string */
  12848. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12849. != NULL) {
  12850. *((char *)conn->request_info.query_string++) = '\0';
  12851. }
  12852. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12853. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12854. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12855. if (ssl_index >= 0) {
  12856. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12857. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12858. redirect_to_https_port(conn, port);
  12859. } else {
  12860. /* A http to https forward port has been specified,
  12861. * but no https port to forward to. */
  12862. mg_send_http_error(conn,
  12863. 503,
  12864. "%s",
  12865. "Error: SSL forward not configured properly");
  12866. mg_cry_internal(conn,
  12867. "%s",
  12868. "Can not redirect to SSL, no SSL port available");
  12869. }
  12870. return;
  12871. }
  12872. uri_len = (int)strlen(ri->local_uri);
  12873. /* 1.3. decode url (if config says so) */
  12874. if (should_decode_url(conn)) {
  12875. url_decode_in_place((char *)ri->local_uri);
  12876. }
  12877. /* URL decode the query-string only if explicitly set in the configuration
  12878. */
  12879. if (conn->request_info.query_string) {
  12880. if (should_decode_query_string(conn)) {
  12881. url_decode_in_place((char *)conn->request_info.query_string);
  12882. }
  12883. }
  12884. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12885. * possible. The fact that we cleaned the URI is stored in that the
  12886. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12887. * ri->local_uri_raw still points to memory allocated in
  12888. * worker_thread_run(). ri->local_uri is private to the request so we
  12889. * don't have to use preallocated memory here. */
  12890. tmp = mg_strdup(ri->local_uri_raw);
  12891. if (!tmp) {
  12892. /* Out of memory. We cannot do anything reasonable here. */
  12893. return;
  12894. }
  12895. remove_dot_segments(tmp);
  12896. ri->local_uri = tmp;
  12897. /* step 1. completed, the url is known now */
  12898. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12899. /* 2. if this ip has limited speed, set it for this connection */
  12900. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12901. &conn->client.rsa,
  12902. ri->local_uri);
  12903. /* 3. call a "handle everything" callback, if registered */
  12904. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12905. /* Note that since V1.7 the "begin_request" function is called
  12906. * before an authorization check. If an authorization check is
  12907. * required, use a request_handler instead. */
  12908. i = conn->phys_ctx->callbacks.begin_request(conn);
  12909. if (i > 0) {
  12910. /* callback already processed the request. Store the
  12911. return value as a status code for the access log. */
  12912. conn->status_code = i;
  12913. if (!conn->must_close) {
  12914. discard_unread_request_data(conn);
  12915. }
  12916. DEBUG_TRACE("%s", "begin_request handled request");
  12917. return;
  12918. } else if (i == 0) {
  12919. /* civetweb should process the request */
  12920. } else {
  12921. /* unspecified - may change with the next version */
  12922. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12923. return;
  12924. }
  12925. }
  12926. /* request not yet handled by a handler or redirect, so the request
  12927. * is processed here */
  12928. /* 4. Check for CORS preflight requests and handle them (if configured).
  12929. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12930. */
  12931. if (!strcmp(ri->request_method, "OPTIONS")) {
  12932. /* Send a response to CORS preflights only if
  12933. * access_control_allow_methods is not NULL and not an empty string.
  12934. * In this case, scripts can still handle CORS. */
  12935. const char *cors_meth_cfg =
  12936. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12937. const char *cors_orig_cfg =
  12938. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12939. const char *cors_origin =
  12940. get_header(ri->http_headers, ri->num_headers, "Origin");
  12941. const char *cors_acrm = get_header(ri->http_headers,
  12942. ri->num_headers,
  12943. "Access-Control-Request-Method");
  12944. /* Todo: check if cors_origin is in cors_orig_cfg.
  12945. * Or, let the client check this. */
  12946. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12947. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12948. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12949. /* This is a valid CORS preflight, and the server is configured
  12950. * to handle it automatically. */
  12951. const char *cors_acrh =
  12952. get_header(ri->http_headers,
  12953. ri->num_headers,
  12954. "Access-Control-Request-Headers");
  12955. const char *cors_cred_cfg =
  12956. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  12957. const char *cors_exphdr_cfg =
  12958. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  12959. gmt_time_string(date, sizeof(date), &curtime);
  12960. mg_printf(conn,
  12961. "HTTP/1.1 200 OK\r\n"
  12962. "Date: %s\r\n"
  12963. "Access-Control-Allow-Origin: %s\r\n"
  12964. "Access-Control-Allow-Methods: %s\r\n"
  12965. "Content-Length: 0\r\n"
  12966. "Connection: %s\r\n",
  12967. date,
  12968. cors_orig_cfg,
  12969. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12970. suggest_connection_header(conn));
  12971. if (cors_cred_cfg && *cors_cred_cfg) {
  12972. mg_printf(conn,
  12973. "Access-Control-Allow-Credentials: %s\r\n",
  12974. cors_cred_cfg);
  12975. }
  12976. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  12977. mg_printf(conn,
  12978. "Access-Control-Expose-Headers: %s\r\n",
  12979. cors_exphdr_cfg);
  12980. }
  12981. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  12982. /* CORS request is asking for additional headers */
  12983. const char *cors_hdr_cfg =
  12984. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12985. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12986. /* Allow only if access_control_allow_headers is
  12987. * not NULL and not an empty string. If this
  12988. * configuration is set to *, allow everything.
  12989. * Otherwise this configuration must be a list
  12990. * of allowed HTTP header names. */
  12991. mg_printf(conn,
  12992. "Access-Control-Allow-Headers: %s\r\n",
  12993. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12994. : cors_hdr_cfg));
  12995. }
  12996. }
  12997. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12998. mg_printf(conn, "\r\n");
  12999. DEBUG_TRACE("%s", "OPTIONS done");
  13000. return;
  13001. }
  13002. }
  13003. /* 5. interpret the url to find out how the request must be handled
  13004. */
  13005. /* 5.1. first test, if the request targets the regular http(s)://
  13006. * protocol namespace or the websocket ws(s):// protocol namespace.
  13007. */
  13008. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13009. #if defined(USE_WEBSOCKET)
  13010. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13011. #else
  13012. handler_type = REQUEST_HANDLER;
  13013. #endif /* defined(USE_WEBSOCKET) */
  13014. if (is_websocket_request) {
  13015. HTTP1_only;
  13016. }
  13017. /* 5.2. check if the request will be handled by a callback */
  13018. if (get_request_handler(conn,
  13019. handler_type,
  13020. &callback_handler,
  13021. &subprotocols,
  13022. &ws_connect_handler,
  13023. &ws_ready_handler,
  13024. &ws_data_handler,
  13025. &ws_close_handler,
  13026. NULL,
  13027. &callback_data,
  13028. &handler_info)) {
  13029. /* 5.2.1. A callback will handle this request. All requests
  13030. * handled by a callback have to be considered as requests
  13031. * to a script resource. */
  13032. is_callback_resource = 1;
  13033. is_script_resource = 1;
  13034. is_put_or_delete_request = is_put_or_delete_method(conn);
  13035. /* Never handle a C callback according to File WebDav rules,
  13036. * even if it is a webdav method */
  13037. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13038. } else {
  13039. no_callback_resource:
  13040. /* 5.2.2. No callback is responsible for this request. The URI
  13041. * addresses a file based resource (static content or Lua/cgi
  13042. * scripts in the file system). */
  13043. is_callback_resource = 0;
  13044. interpret_uri(conn,
  13045. path,
  13046. sizeof(path),
  13047. &file.stat,
  13048. &is_found,
  13049. &is_script_resource,
  13050. &is_websocket_request,
  13051. &is_put_or_delete_request,
  13052. &is_webdav_request,
  13053. &is_template_text_file);
  13054. }
  13055. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13056. if (is_webdav_request) {
  13057. /* TODO: Do we need a config option? */
  13058. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13059. if (webdav_enable[0] != 'y') {
  13060. mg_send_http_error(conn,
  13061. 405,
  13062. "%s method not allowed",
  13063. conn->request_info.request_method);
  13064. DEBUG_TRACE("%s", "webdav rejected");
  13065. return;
  13066. }
  13067. }
  13068. /* 6. authorization check */
  13069. /* 6.1. a custom authorization handler is installed */
  13070. if (get_request_handler(conn,
  13071. AUTH_HANDLER,
  13072. NULL,
  13073. NULL,
  13074. NULL,
  13075. NULL,
  13076. NULL,
  13077. NULL,
  13078. &auth_handler,
  13079. &auth_callback_data,
  13080. NULL)) {
  13081. if (!auth_handler(conn, auth_callback_data)) {
  13082. /* Callback handler will not be used anymore. Release it */
  13083. release_handler_ref(conn, handler_info);
  13084. DEBUG_TRACE("%s", "auth handler rejected request");
  13085. return;
  13086. }
  13087. } else if (is_put_or_delete_request && !is_script_resource
  13088. && !is_callback_resource) {
  13089. HTTP1_only;
  13090. /* 6.2. this request is a PUT/DELETE to a real file */
  13091. /* 6.2.1. thus, the server must have real files */
  13092. #if defined(NO_FILES)
  13093. if (1) {
  13094. #else
  13095. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13096. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13097. #endif
  13098. /* This code path will not be called for request handlers */
  13099. DEBUG_ASSERT(handler_info == NULL);
  13100. /* This server does not have any real files, thus the
  13101. * PUT/DELETE methods are not valid. */
  13102. mg_send_http_error(conn,
  13103. 405,
  13104. "%s method not allowed",
  13105. conn->request_info.request_method);
  13106. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13107. return;
  13108. }
  13109. #if !defined(NO_FILES)
  13110. /* 6.2.2. Check if put authorization for static files is
  13111. * available.
  13112. */
  13113. if (!is_authorized_for_put(conn)) {
  13114. send_authorization_request(conn, NULL);
  13115. DEBUG_TRACE("%s", "file write needs authorization");
  13116. return;
  13117. }
  13118. #endif
  13119. } else {
  13120. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13121. * or it is a PUT or DELETE request to a resource that does not
  13122. * correspond to a file. Check authorization. */
  13123. if (!check_authorization(conn, path)) {
  13124. send_authorization_request(conn, NULL);
  13125. /* Callback handler will not be used anymore. Release it */
  13126. release_handler_ref(conn, handler_info);
  13127. DEBUG_TRACE("%s", "access authorization required");
  13128. return;
  13129. }
  13130. }
  13131. /* request is authorized or does not need authorization */
  13132. /* 7. check if there are request handlers for this uri */
  13133. if (is_callback_resource) {
  13134. HTTP1_only;
  13135. if (!is_websocket_request) {
  13136. i = callback_handler(conn, callback_data);
  13137. /* Callback handler will not be used anymore. Release it */
  13138. release_handler_ref(conn, handler_info);
  13139. if (i > 0) {
  13140. /* Do nothing, callback has served the request. Store
  13141. * then return value as status code for the log and discard
  13142. * all data from the client not used by the callback. */
  13143. conn->status_code = i;
  13144. if (!conn->must_close) {
  13145. discard_unread_request_data(conn);
  13146. }
  13147. } else {
  13148. /* The handler did NOT handle the request. */
  13149. /* Some proper reactions would be:
  13150. * a) close the connections without sending anything
  13151. * b) send a 404 not found
  13152. * c) try if there is a file matching the URI
  13153. * It would be possible to do a, b or c in the callback
  13154. * implementation, and return 1 - we cannot do anything
  13155. * here, that is not possible in the callback.
  13156. *
  13157. * TODO: What would be the best reaction here?
  13158. * (Note: The reaction may change, if there is a better
  13159. * idea.)
  13160. */
  13161. /* For the moment, use option c: We look for a proper file,
  13162. * but since a file request is not always a script resource,
  13163. * the authorization check might be different. */
  13164. callback_handler = NULL;
  13165. /* Here we are at a dead end:
  13166. * According to URI matching, a callback should be
  13167. * responsible for handling the request,
  13168. * we called it, but the callback declared itself
  13169. * not responsible.
  13170. * We use a goto here, to get out of this dead end,
  13171. * and continue with the default handling.
  13172. * A goto here is simpler and better to understand
  13173. * than some curious loop. */
  13174. goto no_callback_resource;
  13175. }
  13176. } else {
  13177. #if defined(USE_WEBSOCKET)
  13178. handle_websocket_request(conn,
  13179. path,
  13180. is_callback_resource,
  13181. subprotocols,
  13182. ws_connect_handler,
  13183. ws_ready_handler,
  13184. ws_data_handler,
  13185. ws_close_handler,
  13186. callback_data);
  13187. #endif
  13188. }
  13189. DEBUG_TRACE("%s", "websocket handling done");
  13190. return;
  13191. }
  13192. /* 8. handle websocket requests */
  13193. #if defined(USE_WEBSOCKET)
  13194. if (is_websocket_request) {
  13195. HTTP1_only;
  13196. if (is_script_resource) {
  13197. if (is_in_script_path(conn, path)) {
  13198. /* Websocket Lua script */
  13199. handle_websocket_request(conn,
  13200. path,
  13201. 0 /* Lua Script */,
  13202. NULL,
  13203. NULL,
  13204. NULL,
  13205. NULL,
  13206. NULL,
  13207. conn->phys_ctx->user_data);
  13208. } else {
  13209. /* Script was in an illegal path */
  13210. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13211. }
  13212. } else {
  13213. mg_send_http_error(conn, 404, "%s", "Not found");
  13214. }
  13215. DEBUG_TRACE("%s", "websocket script done");
  13216. return;
  13217. } else
  13218. #endif
  13219. #if defined(NO_FILES)
  13220. /* 9a. In case the server uses only callbacks, this uri is
  13221. * unknown.
  13222. * Then, all request handling ends here. */
  13223. mg_send_http_error(conn, 404, "%s", "Not Found");
  13224. #else
  13225. /* 9b. This request is either for a static file or resource handled
  13226. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13227. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13228. mg_send_http_error(conn, 404, "%s", "Not Found");
  13229. DEBUG_TRACE("%s", "no document root available");
  13230. return;
  13231. }
  13232. /* 10. Request is handled by a script */
  13233. if (is_script_resource) {
  13234. HTTP1_only;
  13235. handle_file_based_request(conn, path, &file);
  13236. DEBUG_TRACE("%s", "script handling done");
  13237. return;
  13238. }
  13239. /* Request was not handled by a callback or script. It will be
  13240. * handled by a server internal method. */
  13241. /* 11. Handle put/delete/mkcol requests */
  13242. if (is_put_or_delete_request) {
  13243. HTTP1_only;
  13244. /* 11.1. PUT method */
  13245. if (!strcmp(ri->request_method, "PUT")) {
  13246. put_file(conn, path);
  13247. DEBUG_TRACE("handling %s request to %s done",
  13248. ri->request_method,
  13249. path);
  13250. return;
  13251. }
  13252. /* 11.2. DELETE method */
  13253. if (!strcmp(ri->request_method, "DELETE")) {
  13254. delete_file(conn, path);
  13255. DEBUG_TRACE("handling %s request to %s done",
  13256. ri->request_method,
  13257. path);
  13258. return;
  13259. }
  13260. /* 11.3. MKCOL method */
  13261. if (!strcmp(ri->request_method, "MKCOL")) {
  13262. dav_mkcol(conn, path);
  13263. DEBUG_TRACE("handling %s request to %s done",
  13264. ri->request_method,
  13265. path);
  13266. return;
  13267. }
  13268. /* 11.4. MOVE method */
  13269. if (!strcmp(ri->request_method, "MOVE")) {
  13270. dav_move_file(conn, path, 0);
  13271. DEBUG_TRACE("handling %s request to %s done",
  13272. ri->request_method,
  13273. path);
  13274. return;
  13275. }
  13276. if (!strcmp(ri->request_method, "COPY")) {
  13277. dav_move_file(conn, path, 1);
  13278. DEBUG_TRACE("handling %s request to %s done",
  13279. ri->request_method,
  13280. path);
  13281. return;
  13282. }
  13283. /* 11.5. LOCK method */
  13284. if (!strcmp(ri->request_method, "LOCK")) {
  13285. dav_lock_file(conn, path);
  13286. DEBUG_TRACE("handling %s request to %s done",
  13287. ri->request_method,
  13288. path);
  13289. return;
  13290. }
  13291. /* 11.6. UNLOCK method */
  13292. if (!strcmp(ri->request_method, "UNLOCK")) {
  13293. dav_unlock_file(conn, path);
  13294. DEBUG_TRACE("handling %s request to %s done",
  13295. ri->request_method,
  13296. path);
  13297. return;
  13298. }
  13299. /* 11.7. PROPPATCH method */
  13300. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13301. dav_proppatch(conn, path);
  13302. DEBUG_TRACE("handling %s request to %s done",
  13303. ri->request_method,
  13304. path);
  13305. return;
  13306. }
  13307. /* 11.8. Other methods, e.g.: PATCH
  13308. * This method is not supported for static resources,
  13309. * only for scripts (Lua, CGI) and callbacks. */
  13310. mg_send_http_error(conn,
  13311. 405,
  13312. "%s method not allowed",
  13313. conn->request_info.request_method);
  13314. DEBUG_TRACE("method %s on %s is not supported",
  13315. ri->request_method,
  13316. path);
  13317. return;
  13318. }
  13319. /* 11. File does not exist, or it was configured that it should be
  13320. * hidden */
  13321. if (!is_found || (must_hide_file(conn, path))) {
  13322. mg_send_http_error(conn, 404, "%s", "Not found");
  13323. DEBUG_TRACE("handling %s request to %s: file not found",
  13324. ri->request_method,
  13325. path);
  13326. return;
  13327. }
  13328. /* 12. Directory uris should end with a slash */
  13329. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13330. && (ri->local_uri[uri_len - 1] != '/')) {
  13331. /* Path + server root */
  13332. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13333. char *new_path;
  13334. if (ri->query_string) {
  13335. buflen += strlen(ri->query_string);
  13336. }
  13337. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13338. if (!new_path) {
  13339. mg_send_http_error(conn, 500, "out or memory");
  13340. } else {
  13341. mg_get_request_link(conn, new_path, buflen - 1);
  13342. strcat(new_path, "/");
  13343. if (ri->query_string) {
  13344. /* Append ? and query string */
  13345. strcat(new_path, "?");
  13346. strcat(new_path, ri->query_string);
  13347. }
  13348. mg_send_http_redirect(conn, new_path, 301);
  13349. mg_free(new_path);
  13350. }
  13351. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13352. ri->request_method,
  13353. path);
  13354. return;
  13355. }
  13356. /* 13. Handle other methods than GET/HEAD */
  13357. /* 13.1. Handle PROPFIND */
  13358. if (!strcmp(ri->request_method, "PROPFIND")) {
  13359. handle_propfind(conn, path, &file.stat);
  13360. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13361. return;
  13362. }
  13363. /* 13.2. Handle OPTIONS for files */
  13364. if (!strcmp(ri->request_method, "OPTIONS")) {
  13365. /* This standard handler is only used for real files.
  13366. * Scripts should support the OPTIONS method themselves, to allow a
  13367. * maximum flexibility.
  13368. * Lua and CGI scripts may fully support CORS this way (including
  13369. * preflights). */
  13370. send_options(conn);
  13371. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13372. return;
  13373. }
  13374. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13375. if ((0 != strcmp(ri->request_method, "GET"))
  13376. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13377. mg_send_http_error(conn,
  13378. 405,
  13379. "%s method not allowed",
  13380. conn->request_info.request_method);
  13381. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13382. return;
  13383. }
  13384. /* 14. directories */
  13385. if (file.stat.is_directory) {
  13386. /* Substitute files have already been handled above. */
  13387. /* Here we can either generate and send a directory listing,
  13388. * or send an "access denied" error. */
  13389. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13390. "yes")) {
  13391. handle_directory_request(conn, path);
  13392. } else {
  13393. mg_send_http_error(conn,
  13394. 403,
  13395. "%s",
  13396. "Error: Directory listing denied");
  13397. }
  13398. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13399. return;
  13400. }
  13401. /* 15. Files with search/replace patterns: LSP and SSI */
  13402. if (is_template_text_file) {
  13403. HTTP1_only;
  13404. handle_file_based_request(conn, path, &file);
  13405. DEBUG_TRACE("handling %s request to %s done (template)",
  13406. ri->request_method,
  13407. path);
  13408. return;
  13409. }
  13410. /* 16. Static file - maybe cached */
  13411. #if !defined(NO_CACHING)
  13412. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13413. /* Send 304 "Not Modified" - this must not send any body data */
  13414. handle_not_modified_static_file_request(conn, &file);
  13415. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13416. ri->request_method,
  13417. path);
  13418. return;
  13419. }
  13420. #endif /* !NO_CACHING */
  13421. /* 17. Static file - not cached */
  13422. handle_static_file_request(conn, path, &file, NULL, NULL);
  13423. DEBUG_TRACE("handling %s request to %s done (static)",
  13424. ri->request_method,
  13425. path);
  13426. #endif /* !defined(NO_FILES) */
  13427. }
  13428. #if !defined(NO_FILESYSTEMS)
  13429. static void
  13430. handle_file_based_request(struct mg_connection *conn,
  13431. const char *path,
  13432. struct mg_file *file)
  13433. {
  13434. #if !defined(NO_CGI)
  13435. int cgi_config_idx, inc, max;
  13436. #endif
  13437. if (!conn || !conn->dom_ctx) {
  13438. return;
  13439. }
  13440. #if defined(USE_LUA)
  13441. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13442. path)
  13443. > 0) {
  13444. if (is_in_script_path(conn, path)) {
  13445. /* Lua server page: an SSI like page containing mostly plain
  13446. * html code plus some tags with server generated contents. */
  13447. handle_lsp_request(conn, path, file, NULL);
  13448. } else {
  13449. /* Script was in an illegal path */
  13450. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13451. }
  13452. return;
  13453. }
  13454. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13455. > 0) {
  13456. if (is_in_script_path(conn, path)) {
  13457. /* Lua in-server module script: a CGI like script used to
  13458. * generate the entire reply. */
  13459. mg_exec_lua_script(conn, path, NULL);
  13460. } else {
  13461. /* Script was in an illegal path */
  13462. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13463. }
  13464. return;
  13465. }
  13466. #endif
  13467. #if defined(USE_DUKTAPE)
  13468. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13469. path)
  13470. > 0) {
  13471. if (is_in_script_path(conn, path)) {
  13472. /* Call duktape to generate the page */
  13473. mg_exec_duktape_script(conn, path);
  13474. } else {
  13475. /* Script was in an illegal path */
  13476. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13477. }
  13478. return;
  13479. }
  13480. #endif
  13481. #if !defined(NO_CGI)
  13482. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13483. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13484. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13485. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13486. if (match_prefix_strlen(
  13487. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13488. path)
  13489. > 0) {
  13490. if (is_in_script_path(conn, path)) {
  13491. /* CGI scripts may support all HTTP methods */
  13492. handle_cgi_request(conn, path, cgi_config_idx);
  13493. } else {
  13494. /* Script was in an illegal path */
  13495. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13496. }
  13497. return;
  13498. }
  13499. }
  13500. }
  13501. #endif /* !NO_CGI */
  13502. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13503. if (is_in_script_path(conn, path)) {
  13504. handle_ssi_file_request(conn, path, file);
  13505. } else {
  13506. /* Script was in an illegal path */
  13507. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13508. }
  13509. return;
  13510. }
  13511. #if !defined(NO_CACHING)
  13512. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13513. /* Send 304 "Not Modified" - this must not send any body data */
  13514. handle_not_modified_static_file_request(conn, file);
  13515. return;
  13516. }
  13517. #endif /* !NO_CACHING */
  13518. handle_static_file_request(conn, path, file, NULL, NULL);
  13519. }
  13520. #endif /* NO_FILESYSTEMS */
  13521. static void
  13522. close_all_listening_sockets(struct mg_context *ctx)
  13523. {
  13524. unsigned int i;
  13525. if (!ctx) {
  13526. return;
  13527. }
  13528. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13529. closesocket(ctx->listening_sockets[i].sock);
  13530. #if defined(USE_X_DOM_SOCKET)
  13531. /* For unix domain sockets, the socket name represents a file that has
  13532. * to be deleted. */
  13533. /* See
  13534. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13535. */
  13536. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13537. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13538. IGNORE_UNUSED_RESULT(
  13539. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13540. }
  13541. #endif
  13542. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13543. }
  13544. mg_free(ctx->listening_sockets);
  13545. ctx->listening_sockets = NULL;
  13546. mg_free(ctx->listening_socket_fds);
  13547. ctx->listening_socket_fds = NULL;
  13548. }
  13549. /* Valid listening port specification is: [ip_address:]port[s]
  13550. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13551. * Examples for IPv6: [::]:80, [::1]:80,
  13552. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13553. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13554. * In order to bind to both, IPv4 and IPv6, you can either add
  13555. * both ports using 8080,[::]:8080, or the short form +8080.
  13556. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13557. * one only accepting IPv4 the other only IPv6. +8080 creates
  13558. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13559. * environment, they might work differently, or might not work
  13560. * at all - it must be tested what options work best in the
  13561. * relevant network environment.
  13562. */
  13563. static int
  13564. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13565. {
  13566. unsigned int a, b, c, d;
  13567. unsigned port;
  13568. unsigned long portUL;
  13569. int len;
  13570. const char *cb;
  13571. char *endptr;
  13572. #if defined(USE_IPV6)
  13573. char buf[100] = {0};
  13574. #endif
  13575. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13576. * Also, all-zeroes in the socket address means binding to all addresses
  13577. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13578. memset(so, 0, sizeof(*so));
  13579. so->lsa.sin.sin_family = AF_INET;
  13580. *ip_version = 0;
  13581. /* Initialize len as invalid. */
  13582. port = 0;
  13583. len = 0;
  13584. /* Test for different ways to format this string */
  13585. if (sscanf(vec->ptr,
  13586. "%u.%u.%u.%u:%u%n",
  13587. &a,
  13588. &b,
  13589. &c,
  13590. &d,
  13591. &port,
  13592. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13593. // to an integer value, but function will not report
  13594. // conversion errors; consider using 'strtol' instead
  13595. == 5) {
  13596. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13597. so->lsa.sin.sin_addr.s_addr =
  13598. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13599. so->lsa.sin.sin_port = htons((uint16_t)port);
  13600. *ip_version = 4;
  13601. #if defined(USE_IPV6)
  13602. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13603. && ((size_t)len <= vec->len)
  13604. && mg_inet_pton(
  13605. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13606. /* IPv6 address, examples: see above */
  13607. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13608. */
  13609. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13610. *ip_version = 6;
  13611. #endif
  13612. } else if ((vec->ptr[0] == '+')
  13613. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13614. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13615. // string to an integer value, but function will not
  13616. // report conversion errors; consider using 'strtol'
  13617. // instead
  13618. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13619. /* Add 1 to len for the + character we skipped before */
  13620. len++;
  13621. #if defined(USE_IPV6)
  13622. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13623. so->lsa.sin6.sin6_family = AF_INET6;
  13624. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13625. *ip_version = 4 + 6;
  13626. #else
  13627. /* Bind to IPv4 only, since IPv6 is not built in. */
  13628. so->lsa.sin.sin_port = htons((uint16_t)port);
  13629. *ip_version = 4;
  13630. #endif
  13631. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13632. && (vec->ptr != endptr)) {
  13633. len = (int)(endptr - vec->ptr);
  13634. port = (uint16_t)portUL;
  13635. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13636. so->lsa.sin.sin_port = htons((uint16_t)port);
  13637. *ip_version = 4;
  13638. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13639. /* String could be a hostname. This check algorithm
  13640. * will only work for RFC 952 compliant hostnames,
  13641. * starting with a letter, containing only letters,
  13642. * digits and hyphen ('-'). Newer specs may allow
  13643. * more, but this is not guaranteed here, since it
  13644. * may interfere with rules for port option lists. */
  13645. /* According to RFC 1035, hostnames are restricted to 255 characters
  13646. * in total (63 between two dots). */
  13647. char hostname[256];
  13648. size_t hostnlen = (size_t)(cb - vec->ptr);
  13649. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13650. /* This would be invalid in any case */
  13651. *ip_version = 0;
  13652. return 0;
  13653. }
  13654. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13655. if (mg_inet_pton(
  13656. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13657. if (sscanf(cb + 1, "%u%n", &port, &len)
  13658. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13659. // string to an integer value, but function will not
  13660. // report conversion errors; consider using 'strtol'
  13661. // instead
  13662. *ip_version = 4;
  13663. so->lsa.sin.sin_port = htons((uint16_t)port);
  13664. len += (int)(hostnlen + 1);
  13665. } else {
  13666. len = 0;
  13667. }
  13668. #if defined(USE_IPV6)
  13669. } else if (mg_inet_pton(AF_INET6,
  13670. hostname,
  13671. &so->lsa.sin6,
  13672. sizeof(so->lsa.sin6),
  13673. 1)) {
  13674. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13675. *ip_version = 6;
  13676. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13677. len += (int)(hostnlen + 1);
  13678. } else {
  13679. len = 0;
  13680. }
  13681. #endif
  13682. } else {
  13683. len = 0;
  13684. }
  13685. #if defined(USE_X_DOM_SOCKET)
  13686. } else if (vec->ptr[0] == 'x') {
  13687. /* unix (linux) domain socket */
  13688. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13689. len = vec->len;
  13690. so->lsa.sun.sun_family = AF_UNIX;
  13691. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13692. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13693. port = 0;
  13694. *ip_version = 99;
  13695. } else {
  13696. /* String too long */
  13697. len = 0;
  13698. }
  13699. #endif
  13700. } else {
  13701. /* Parsing failure. */
  13702. len = 0;
  13703. }
  13704. /* sscanf and the option splitting code ensure the following condition
  13705. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13706. * 'r' */
  13707. if ((len > 0) && (is_valid_port(port))) {
  13708. int bad_suffix = 0;
  13709. size_t i;
  13710. /* Parse any suffix character(s) after the port number */
  13711. for (i = len; i < vec->len; i++) {
  13712. unsigned char *opt = NULL;
  13713. switch (vec->ptr[i]) {
  13714. case 'o':
  13715. opt = &so->is_optional;
  13716. break;
  13717. case 'r':
  13718. opt = &so->ssl_redir;
  13719. break;
  13720. case 's':
  13721. opt = &so->is_ssl;
  13722. break;
  13723. default: /* empty */
  13724. break;
  13725. }
  13726. if ((opt) && (*opt == 0))
  13727. *opt = 1;
  13728. else {
  13729. bad_suffix = 1;
  13730. break;
  13731. }
  13732. }
  13733. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13734. return 1;
  13735. }
  13736. }
  13737. /* Reset ip_version to 0 if there is an error */
  13738. *ip_version = 0;
  13739. return 0;
  13740. }
  13741. /* Is there any SSL port in use? */
  13742. static int
  13743. is_ssl_port_used(const char *ports)
  13744. {
  13745. if (ports) {
  13746. /* There are several different allowed syntax variants:
  13747. * - "80" for a single port using every network interface
  13748. * - "localhost:80" for a single port using only localhost
  13749. * - "80,localhost:8080" for two ports, one bound to localhost
  13750. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13751. * to IPv4 localhost, one to IPv6 localhost
  13752. * - "+80" use port 80 for IPv4 and IPv6
  13753. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13754. * for both: IPv4 and IPv4
  13755. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13756. * additionally port 8080 bound to localhost connections
  13757. *
  13758. * If we just look for 's' anywhere in the string, "localhost:80"
  13759. * will be detected as SSL (false positive).
  13760. * Looking for 's' after a digit may cause false positives in
  13761. * "my24service:8080".
  13762. * Looking from 's' backward if there are only ':' and numbers
  13763. * before will not work for "24service:8080" (non SSL, port 8080)
  13764. * or "24s" (SSL, port 24).
  13765. *
  13766. * Remark: Initially hostnames were not allowed to start with a
  13767. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13768. * Section 2.1).
  13769. *
  13770. * To get this correct, the entire string must be parsed as a whole,
  13771. * reading it as a list element for element and parsing with an
  13772. * algorithm equivalent to parse_port_string.
  13773. *
  13774. * In fact, we use local interface names here, not arbitrary
  13775. * hostnames, so in most cases the only name will be "localhost".
  13776. *
  13777. * So, for now, we use this simple algorithm, that may still return
  13778. * a false positive in bizarre cases.
  13779. */
  13780. int i;
  13781. int portslen = (int)strlen(ports);
  13782. char prevIsNumber = 0;
  13783. for (i = 0; i < portslen; i++) {
  13784. if (prevIsNumber) {
  13785. int suffixCharIdx = (ports[i] == 'o')
  13786. ? (i + 1)
  13787. : i; /* allow "os" and "or" suffixes */
  13788. if (ports[suffixCharIdx] == 's'
  13789. || ports[suffixCharIdx] == 'r') {
  13790. return 1;
  13791. }
  13792. }
  13793. if (ports[i] >= '0' && ports[i] <= '9') {
  13794. prevIsNumber = 1;
  13795. } else {
  13796. prevIsNumber = 0;
  13797. }
  13798. }
  13799. }
  13800. return 0;
  13801. }
  13802. static int
  13803. set_ports_option(struct mg_context *phys_ctx)
  13804. {
  13805. const char *list;
  13806. int on = 1;
  13807. #if defined(USE_IPV6)
  13808. int off = 0;
  13809. #endif
  13810. struct vec vec;
  13811. struct socket so, *ptr;
  13812. struct mg_pollfd *pfd;
  13813. union usa usa;
  13814. socklen_t len;
  13815. int ip_version;
  13816. int portsTotal = 0;
  13817. int portsOk = 0;
  13818. const char *opt_txt;
  13819. long opt_listen_backlog;
  13820. if (!phys_ctx) {
  13821. return 0;
  13822. }
  13823. memset(&so, 0, sizeof(so));
  13824. memset(&usa, 0, sizeof(usa));
  13825. len = sizeof(usa);
  13826. list = phys_ctx->dd.config[LISTENING_PORTS];
  13827. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13828. portsTotal++;
  13829. if (!parse_port_string(&vec, &so, &ip_version)) {
  13830. mg_cry_ctx_internal(
  13831. phys_ctx,
  13832. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13833. (int)vec.len,
  13834. vec.ptr,
  13835. portsTotal,
  13836. "[IP_ADDRESS:]PORT[s|r]");
  13837. continue;
  13838. }
  13839. #if !defined(NO_SSL)
  13840. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13841. mg_cry_ctx_internal(phys_ctx,
  13842. "Cannot add SSL socket (entry %i)",
  13843. portsTotal);
  13844. continue;
  13845. }
  13846. #endif
  13847. /* Create socket. */
  13848. /* For a list of protocol numbers (e.g., TCP==6) see:
  13849. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13850. */
  13851. if ((so.sock =
  13852. socket(so.lsa.sa.sa_family,
  13853. SOCK_STREAM,
  13854. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13855. == INVALID_SOCKET) {
  13856. mg_cry_ctx_internal(phys_ctx,
  13857. "cannot create socket (entry %i)",
  13858. portsTotal);
  13859. continue;
  13860. }
  13861. #if defined(_WIN32)
  13862. /* Windows SO_REUSEADDR lets many procs binds to a
  13863. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13864. * if someone already has the socket -- DTL */
  13865. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13866. * Windows might need a few seconds before
  13867. * the same port can be used again in the
  13868. * same process, so a short Sleep may be
  13869. * required between mg_stop and mg_start.
  13870. */
  13871. if (setsockopt(so.sock,
  13872. SOL_SOCKET,
  13873. SO_EXCLUSIVEADDRUSE,
  13874. (SOCK_OPT_TYPE)&on,
  13875. sizeof(on))
  13876. != 0) {
  13877. /* Set reuse option, but don't abort on errors. */
  13878. mg_cry_ctx_internal(
  13879. phys_ctx,
  13880. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13881. portsTotal);
  13882. }
  13883. #else
  13884. if (setsockopt(so.sock,
  13885. SOL_SOCKET,
  13886. SO_REUSEADDR,
  13887. (SOCK_OPT_TYPE)&on,
  13888. sizeof(on))
  13889. != 0) {
  13890. /* Set reuse option, but don't abort on errors. */
  13891. mg_cry_ctx_internal(
  13892. phys_ctx,
  13893. "cannot set socket option SO_REUSEADDR (entry %i)",
  13894. portsTotal);
  13895. }
  13896. #endif
  13897. #if defined(USE_X_DOM_SOCKET)
  13898. if (ip_version == 99) {
  13899. /* Unix domain socket */
  13900. } else
  13901. #endif
  13902. if (ip_version > 4) {
  13903. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13904. #if defined(USE_IPV6)
  13905. if (ip_version > 6) {
  13906. if (so.lsa.sa.sa_family == AF_INET6
  13907. && setsockopt(so.sock,
  13908. IPPROTO_IPV6,
  13909. IPV6_V6ONLY,
  13910. (void *)&off,
  13911. sizeof(off))
  13912. != 0) {
  13913. /* Set IPv6 only option, but don't abort on errors. */
  13914. mg_cry_ctx_internal(phys_ctx,
  13915. "cannot set socket option "
  13916. "IPV6_V6ONLY=off (entry %i)",
  13917. portsTotal);
  13918. }
  13919. } else {
  13920. if (so.lsa.sa.sa_family == AF_INET6
  13921. && setsockopt(so.sock,
  13922. IPPROTO_IPV6,
  13923. IPV6_V6ONLY,
  13924. (void *)&on,
  13925. sizeof(on))
  13926. != 0) {
  13927. /* Set IPv6 only option, but don't abort on errors. */
  13928. mg_cry_ctx_internal(phys_ctx,
  13929. "cannot set socket option "
  13930. "IPV6_V6ONLY=on (entry %i)",
  13931. portsTotal);
  13932. }
  13933. }
  13934. #else
  13935. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13936. closesocket(so.sock);
  13937. so.sock = INVALID_SOCKET;
  13938. continue;
  13939. #endif
  13940. }
  13941. if (so.lsa.sa.sa_family == AF_INET) {
  13942. len = sizeof(so.lsa.sin);
  13943. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13944. mg_cry_ctx_internal(phys_ctx,
  13945. "cannot bind to %.*s: %d (%s)",
  13946. (int)vec.len,
  13947. vec.ptr,
  13948. (int)ERRNO,
  13949. strerror(errno));
  13950. closesocket(so.sock);
  13951. so.sock = INVALID_SOCKET;
  13952. if (so.is_optional) {
  13953. portsOk++; /* it's okay if we couldn't bind, this port is
  13954. optional anyway */
  13955. }
  13956. continue;
  13957. }
  13958. }
  13959. #if defined(USE_IPV6)
  13960. else if (so.lsa.sa.sa_family == AF_INET6) {
  13961. len = sizeof(so.lsa.sin6);
  13962. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13963. mg_cry_ctx_internal(phys_ctx,
  13964. "cannot bind to IPv6 %.*s: %d (%s)",
  13965. (int)vec.len,
  13966. vec.ptr,
  13967. (int)ERRNO,
  13968. strerror(errno));
  13969. closesocket(so.sock);
  13970. so.sock = INVALID_SOCKET;
  13971. if (so.is_optional) {
  13972. portsOk++; /* it's okay if we couldn't bind, this port is
  13973. optional anyway */
  13974. }
  13975. continue;
  13976. }
  13977. }
  13978. #endif
  13979. #if defined(USE_X_DOM_SOCKET)
  13980. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13981. len = sizeof(so.lsa.sun);
  13982. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13983. mg_cry_ctx_internal(phys_ctx,
  13984. "cannot bind to unix socket %s: %d (%s)",
  13985. so.lsa.sun.sun_path,
  13986. (int)ERRNO,
  13987. strerror(errno));
  13988. closesocket(so.sock);
  13989. so.sock = INVALID_SOCKET;
  13990. if (so.is_optional) {
  13991. portsOk++; /* it's okay if we couldn't bind, this port is
  13992. optional anyway */
  13993. }
  13994. continue;
  13995. }
  13996. }
  13997. #endif
  13998. else {
  13999. mg_cry_ctx_internal(
  14000. phys_ctx,
  14001. "cannot bind: address family not supported (entry %i)",
  14002. portsTotal);
  14003. closesocket(so.sock);
  14004. so.sock = INVALID_SOCKET;
  14005. continue;
  14006. }
  14007. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14008. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14009. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14010. mg_cry_ctx_internal(phys_ctx,
  14011. "%s value \"%s\" is invalid",
  14012. config_options[LISTEN_BACKLOG_SIZE].name,
  14013. opt_txt);
  14014. closesocket(so.sock);
  14015. so.sock = INVALID_SOCKET;
  14016. continue;
  14017. }
  14018. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14019. mg_cry_ctx_internal(phys_ctx,
  14020. "cannot listen to %.*s: %d (%s)",
  14021. (int)vec.len,
  14022. vec.ptr,
  14023. (int)ERRNO,
  14024. strerror(errno));
  14025. closesocket(so.sock);
  14026. so.sock = INVALID_SOCKET;
  14027. continue;
  14028. }
  14029. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14030. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14031. int err = (int)ERRNO;
  14032. mg_cry_ctx_internal(phys_ctx,
  14033. "call to getsockname failed %.*s: %d (%s)",
  14034. (int)vec.len,
  14035. vec.ptr,
  14036. err,
  14037. strerror(errno));
  14038. closesocket(so.sock);
  14039. so.sock = INVALID_SOCKET;
  14040. continue;
  14041. }
  14042. /* Update lsa port in case of random free ports */
  14043. #if defined(USE_IPV6)
  14044. if (so.lsa.sa.sa_family == AF_INET6) {
  14045. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14046. } else
  14047. #endif
  14048. {
  14049. so.lsa.sin.sin_port = usa.sin.sin_port;
  14050. }
  14051. if ((ptr = (struct socket *)
  14052. mg_realloc_ctx(phys_ctx->listening_sockets,
  14053. (phys_ctx->num_listening_sockets + 1)
  14054. * sizeof(phys_ctx->listening_sockets[0]),
  14055. phys_ctx))
  14056. == NULL) {
  14057. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14058. closesocket(so.sock);
  14059. so.sock = INVALID_SOCKET;
  14060. continue;
  14061. }
  14062. /* The +2 below includes the original +1 (for the socket we're about to
  14063. * add), plus another +1 for the thread_shutdown_notification_socket
  14064. * that we'll also want to poll() on so that mg_stop() can return
  14065. * quickly
  14066. */
  14067. if ((pfd = (struct mg_pollfd *)
  14068. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14069. (phys_ctx->num_listening_sockets + 2)
  14070. * sizeof(phys_ctx->listening_socket_fds[0]),
  14071. phys_ctx))
  14072. == NULL) {
  14073. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14074. closesocket(so.sock);
  14075. so.sock = INVALID_SOCKET;
  14076. mg_free(ptr);
  14077. continue;
  14078. }
  14079. set_close_on_exec(so.sock, NULL, phys_ctx);
  14080. phys_ctx->listening_sockets = ptr;
  14081. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14082. phys_ctx->listening_socket_fds = pfd;
  14083. phys_ctx->num_listening_sockets++;
  14084. portsOk++;
  14085. }
  14086. if (portsOk != portsTotal) {
  14087. close_all_listening_sockets(phys_ctx);
  14088. portsOk = 0;
  14089. }
  14090. return portsOk;
  14091. }
  14092. static const char *
  14093. header_val(const struct mg_connection *conn, const char *header)
  14094. {
  14095. const char *header_value;
  14096. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14097. return "-";
  14098. } else {
  14099. return header_value;
  14100. }
  14101. }
  14102. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14103. #include "external_log_access.inl"
  14104. #elif !defined(NO_FILESYSTEMS)
  14105. static void
  14106. log_access(const struct mg_connection *conn)
  14107. {
  14108. const struct mg_request_info *ri;
  14109. struct mg_file fi;
  14110. char date[64], src_addr[IP_ADDR_STR_LEN];
  14111. #if defined(REENTRANT_TIME)
  14112. struct tm _tm;
  14113. struct tm *tm = &_tm;
  14114. #else
  14115. struct tm *tm;
  14116. #endif
  14117. const char *referer;
  14118. const char *user_agent;
  14119. char log_buf[4096];
  14120. if (!conn || !conn->dom_ctx) {
  14121. return;
  14122. }
  14123. /* Set log message to "empty" */
  14124. log_buf[0] = 0;
  14125. #if defined(USE_LUA)
  14126. if (conn->phys_ctx->lua_bg_log_available) {
  14127. int ret;
  14128. struct mg_context *ctx = conn->phys_ctx;
  14129. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14130. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14131. /* call "log()" in Lua */
  14132. lua_getglobal(lstate, "log");
  14133. prepare_lua_request_info_inner(conn, lstate);
  14134. push_lua_response_log_data(conn, lstate);
  14135. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14136. if (ret == 0) {
  14137. int t = lua_type(lstate, -1);
  14138. if (t == LUA_TBOOLEAN) {
  14139. if (lua_toboolean(lstate, -1) == 0) {
  14140. /* log() returned false: do not log */
  14141. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14142. return;
  14143. }
  14144. /* log returned true: continue logging */
  14145. } else if (t == LUA_TSTRING) {
  14146. size_t len;
  14147. const char *txt = lua_tolstring(lstate, -1, &len);
  14148. if ((len == 0) || (*txt == 0)) {
  14149. /* log() returned empty string: do not log */
  14150. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14151. return;
  14152. }
  14153. /* Copy test from Lua into log_buf */
  14154. if (len >= sizeof(log_buf)) {
  14155. len = sizeof(log_buf) - 1;
  14156. }
  14157. memcpy(log_buf, txt, len);
  14158. log_buf[len] = 0;
  14159. }
  14160. } else {
  14161. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14162. }
  14163. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14164. }
  14165. #endif
  14166. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14167. if (mg_fopen(conn,
  14168. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14169. MG_FOPEN_MODE_APPEND,
  14170. &fi)
  14171. == 0) {
  14172. fi.access.fp = NULL;
  14173. }
  14174. } else {
  14175. fi.access.fp = NULL;
  14176. }
  14177. /* Log is written to a file and/or a callback. If both are not set,
  14178. * executing the rest of the function is pointless. */
  14179. if ((fi.access.fp == NULL)
  14180. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14181. return;
  14182. }
  14183. /* If we did not get a log message from Lua, create it here. */
  14184. if (!log_buf[0]) {
  14185. #if defined(REENTRANT_TIME)
  14186. localtime_r(&conn->conn_birth_time, tm);
  14187. #else
  14188. tm = localtime(&conn->conn_birth_time);
  14189. #endif
  14190. if (tm != NULL) {
  14191. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14192. } else {
  14193. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14194. }
  14195. ri = &conn->request_info;
  14196. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14197. referer = header_val(conn, "Referer");
  14198. user_agent = header_val(conn, "User-Agent");
  14199. mg_snprintf(conn,
  14200. NULL, /* Ignore truncation in access log */
  14201. log_buf,
  14202. sizeof(log_buf),
  14203. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14204. " %s %s",
  14205. src_addr,
  14206. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14207. date,
  14208. ri->request_method ? ri->request_method : "-",
  14209. ri->request_uri ? ri->request_uri : "-",
  14210. ri->query_string ? "?" : "",
  14211. ri->query_string ? ri->query_string : "",
  14212. ri->http_version,
  14213. conn->status_code,
  14214. conn->num_bytes_sent,
  14215. referer,
  14216. user_agent);
  14217. }
  14218. /* Here we have a log message in log_buf. Call the callback */
  14219. if (conn->phys_ctx->callbacks.log_access) {
  14220. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14221. /* do not log if callback returns non-zero */
  14222. if (fi.access.fp) {
  14223. mg_fclose(&fi.access);
  14224. }
  14225. return;
  14226. }
  14227. }
  14228. /* Store in file */
  14229. if (fi.access.fp) {
  14230. int ok = 1;
  14231. flockfile(fi.access.fp);
  14232. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14233. ok = 0;
  14234. }
  14235. if (fflush(fi.access.fp) != 0) {
  14236. ok = 0;
  14237. }
  14238. funlockfile(fi.access.fp);
  14239. if (mg_fclose(&fi.access) != 0) {
  14240. ok = 0;
  14241. }
  14242. if (!ok) {
  14243. mg_cry_internal(conn,
  14244. "Error writing log file %s",
  14245. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14246. }
  14247. }
  14248. }
  14249. #else
  14250. #error "Either enable filesystems or provide a custom log_access implementation"
  14251. #endif /* Externally provided function */
  14252. /* Verify given socket address against the ACL.
  14253. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14254. */
  14255. static int
  14256. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14257. {
  14258. int allowed, flag, matched;
  14259. struct vec vec;
  14260. if (phys_ctx) {
  14261. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14262. /* If any ACL is set, deny by default */
  14263. allowed = (list == NULL) ? '+' : '-';
  14264. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14265. flag = vec.ptr[0];
  14266. matched = -1;
  14267. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14268. vec.ptr++;
  14269. vec.len--;
  14270. matched = parse_match_net(&vec, sa, 1);
  14271. }
  14272. if (matched < 0) {
  14273. mg_cry_ctx_internal(phys_ctx,
  14274. "%s: subnet must be [+|-]IP-addr[/x]",
  14275. __func__);
  14276. return -1;
  14277. }
  14278. if (matched) {
  14279. allowed = flag;
  14280. }
  14281. }
  14282. return allowed == '+';
  14283. }
  14284. return -1;
  14285. }
  14286. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14287. static int
  14288. set_uid_option(struct mg_context *phys_ctx)
  14289. {
  14290. int success = 0;
  14291. if (phys_ctx) {
  14292. /* We are currently running as curr_uid. */
  14293. const uid_t curr_uid = getuid();
  14294. /* If set, we want to run as run_as_user. */
  14295. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14296. const struct passwd *to_pw = NULL;
  14297. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14298. /* run_as_user does not exist on the system. We can't proceed
  14299. * further. */
  14300. mg_cry_ctx_internal(phys_ctx,
  14301. "%s: unknown user [%s]",
  14302. __func__,
  14303. run_as_user);
  14304. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14305. /* There was either no request to change user, or we're already
  14306. * running as run_as_user. Nothing else to do.
  14307. */
  14308. success = 1;
  14309. } else {
  14310. /* Valid change request. */
  14311. if (setgid(to_pw->pw_gid) == -1) {
  14312. mg_cry_ctx_internal(phys_ctx,
  14313. "%s: setgid(%s): %s",
  14314. __func__,
  14315. run_as_user,
  14316. strerror(errno));
  14317. } else if (setgroups(0, NULL) == -1) {
  14318. mg_cry_ctx_internal(phys_ctx,
  14319. "%s: setgroups(): %s",
  14320. __func__,
  14321. strerror(errno));
  14322. } else if (setuid(to_pw->pw_uid) == -1) {
  14323. mg_cry_ctx_internal(phys_ctx,
  14324. "%s: setuid(%s): %s",
  14325. __func__,
  14326. run_as_user,
  14327. strerror(errno));
  14328. } else {
  14329. success = 1;
  14330. }
  14331. }
  14332. }
  14333. return success;
  14334. }
  14335. #endif /* !_WIN32 */
  14336. static void
  14337. tls_dtor(void *key)
  14338. {
  14339. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14340. /* key == pthread_getspecific(sTlsKey); */
  14341. if (tls) {
  14342. if (tls->is_master == 2) {
  14343. tls->is_master = -3; /* Mark memory as dead */
  14344. mg_free(tls);
  14345. }
  14346. }
  14347. pthread_setspecific(sTlsKey, NULL);
  14348. }
  14349. #if defined(USE_MBEDTLS)
  14350. /* Check if SSL is required.
  14351. * If so, set up ctx->ssl_ctx pointer. */
  14352. static int
  14353. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14354. {
  14355. if (!phys_ctx) {
  14356. return 0;
  14357. }
  14358. if (!dom_ctx) {
  14359. dom_ctx = &(phys_ctx->dd);
  14360. }
  14361. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14362. /* No SSL port is set. No need to setup SSL. */
  14363. return 1;
  14364. }
  14365. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14366. if (dom_ctx->ssl_ctx == NULL) {
  14367. fprintf(stderr, "ssl_ctx malloc failed\n");
  14368. return 0;
  14369. }
  14370. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14371. == 0
  14372. ? 1
  14373. : 0;
  14374. }
  14375. #elif !defined(NO_SSL)
  14376. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14377. struct mg_domain_context *dom_ctx,
  14378. const char *pem,
  14379. const char *chain);
  14380. static const char *ssl_error(void);
  14381. static int
  14382. refresh_trust(struct mg_connection *conn)
  14383. {
  14384. struct stat cert_buf;
  14385. int64_t t = 0;
  14386. const char *pem;
  14387. const char *chain;
  14388. int should_verify_peer;
  14389. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14390. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14391. * refresh_trust still can not work. */
  14392. return 0;
  14393. }
  14394. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14395. if (chain == NULL) {
  14396. /* pem is not NULL here */
  14397. chain = pem;
  14398. }
  14399. if (*chain == 0) {
  14400. chain = NULL;
  14401. }
  14402. if (stat(pem, &cert_buf) != -1) {
  14403. t = (int64_t)cert_buf.st_mtime;
  14404. }
  14405. mg_lock_context(conn->phys_ctx);
  14406. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14407. conn->dom_ctx->ssl_cert_last_mtime = t;
  14408. should_verify_peer = 0;
  14409. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14410. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14411. == 0) {
  14412. should_verify_peer = 1;
  14413. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14414. "optional")
  14415. == 0) {
  14416. should_verify_peer = 1;
  14417. }
  14418. }
  14419. if (should_verify_peer) {
  14420. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14421. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14422. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14423. ca_file,
  14424. ca_path)
  14425. != 1) {
  14426. mg_unlock_context(conn->phys_ctx);
  14427. mg_cry_ctx_internal(
  14428. conn->phys_ctx,
  14429. "SSL_CTX_load_verify_locations error: %s "
  14430. "ssl_verify_peer requires setting "
  14431. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14432. "present in "
  14433. "the .conf file?",
  14434. ssl_error());
  14435. return 0;
  14436. }
  14437. }
  14438. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14439. mg_unlock_context(conn->phys_ctx);
  14440. return 0;
  14441. }
  14442. }
  14443. mg_unlock_context(conn->phys_ctx);
  14444. return 1;
  14445. }
  14446. #if defined(OPENSSL_API_1_1)
  14447. #else
  14448. static pthread_mutex_t *ssl_mutexes;
  14449. #endif /* OPENSSL_API_1_1 */
  14450. static int
  14451. sslize(struct mg_connection *conn,
  14452. int (*func)(SSL *),
  14453. const struct mg_client_options *client_options)
  14454. {
  14455. int ret, err;
  14456. int short_trust;
  14457. unsigned timeout = 1024;
  14458. unsigned i;
  14459. if (!conn) {
  14460. return 0;
  14461. }
  14462. short_trust =
  14463. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14464. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14465. if (short_trust) {
  14466. int trust_ret = refresh_trust(conn);
  14467. if (!trust_ret) {
  14468. return trust_ret;
  14469. }
  14470. }
  14471. mg_lock_context(conn->phys_ctx);
  14472. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14473. mg_unlock_context(conn->phys_ctx);
  14474. if (conn->ssl == NULL) {
  14475. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14476. OPENSSL_REMOVE_THREAD_STATE();
  14477. return 0;
  14478. }
  14479. SSL_set_app_data(conn->ssl, (char *)conn);
  14480. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14481. if (ret != 1) {
  14482. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14483. SSL_free(conn->ssl);
  14484. conn->ssl = NULL;
  14485. OPENSSL_REMOVE_THREAD_STATE();
  14486. return 0;
  14487. }
  14488. if (client_options) {
  14489. if (client_options->host_name) {
  14490. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14491. }
  14492. }
  14493. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14494. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14495. /* NOTE: The loop below acts as a back-off, so we can end
  14496. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14497. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14498. if (to >= 0) {
  14499. timeout = (unsigned)to;
  14500. }
  14501. }
  14502. /* SSL functions may fail and require to be called again:
  14503. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14504. * Here "func" could be SSL_connect or SSL_accept. */
  14505. for (i = 0; i <= timeout; i += 50) {
  14506. ERR_clear_error();
  14507. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14508. ret = func(conn->ssl);
  14509. if (ret != 1) {
  14510. err = SSL_get_error(conn->ssl, ret);
  14511. if ((err == SSL_ERROR_WANT_CONNECT)
  14512. || (err == SSL_ERROR_WANT_ACCEPT)
  14513. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14514. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14515. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14516. /* Don't wait if the server is going to be stopped. */
  14517. break;
  14518. }
  14519. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14520. /* Simply retry the function call. */
  14521. mg_sleep(50);
  14522. } else {
  14523. /* Need to retry the function call "later".
  14524. * See https://linux.die.net/man/3/ssl_get_error
  14525. * This is typical for non-blocking sockets. */
  14526. struct mg_pollfd pfd[2];
  14527. int pollres;
  14528. pfd[0].fd = conn->client.sock;
  14529. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14530. || (err == SSL_ERROR_WANT_WRITE))
  14531. ? POLLOUT
  14532. : POLLIN;
  14533. pfd[1].fd =
  14534. conn->phys_ctx->thread_shutdown_notification_socket;
  14535. pfd[1].events = POLLIN;
  14536. pollres = mg_poll(pfd, 2, 50, &(conn->phys_ctx->stop_flag));
  14537. if (pollres < 0) {
  14538. /* Break if error occurred (-1)
  14539. * or server shutdown (-2) */
  14540. break;
  14541. }
  14542. }
  14543. } else if (err == SSL_ERROR_SYSCALL) {
  14544. /* This is an IO error. Look at errno. */
  14545. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14546. break;
  14547. } else {
  14548. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14549. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14550. break;
  14551. }
  14552. } else {
  14553. /* success */
  14554. break;
  14555. }
  14556. }
  14557. ERR_clear_error();
  14558. if (ret != 1) {
  14559. SSL_free(conn->ssl);
  14560. conn->ssl = NULL;
  14561. OPENSSL_REMOVE_THREAD_STATE();
  14562. return 0;
  14563. }
  14564. return 1;
  14565. }
  14566. /* Return OpenSSL error message (from CRYPTO lib) */
  14567. static const char *
  14568. ssl_error(void)
  14569. {
  14570. unsigned long err;
  14571. err = ERR_get_error();
  14572. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14573. }
  14574. static int
  14575. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14576. {
  14577. int i;
  14578. const char hexdigit[] = "0123456789abcdef";
  14579. if ((memlen <= 0) || (buflen <= 0)) {
  14580. return 0;
  14581. }
  14582. if (buflen < (3 * memlen)) {
  14583. return 0;
  14584. }
  14585. for (i = 0; i < memlen; i++) {
  14586. if (i > 0) {
  14587. buf[3 * i - 1] = ' ';
  14588. }
  14589. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14590. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14591. }
  14592. buf[3 * memlen - 1] = 0;
  14593. return 1;
  14594. }
  14595. static int
  14596. ssl_get_client_cert_info(const struct mg_connection *conn,
  14597. struct mg_client_cert *client_cert)
  14598. {
  14599. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14600. if (cert) {
  14601. char str_buf[1024];
  14602. unsigned char buf[256];
  14603. char *str_serial = NULL;
  14604. unsigned int ulen;
  14605. int ilen;
  14606. unsigned char *tmp_buf;
  14607. unsigned char *tmp_p;
  14608. /* Handle to algorithm used for fingerprint */
  14609. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14610. /* Get Subject and issuer */
  14611. X509_NAME *subj = X509_get_subject_name(cert);
  14612. X509_NAME *iss = X509_get_issuer_name(cert);
  14613. /* Get serial number */
  14614. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14615. /* Translate serial number to a hex string */
  14616. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14617. if (serial_bn) {
  14618. str_serial = BN_bn2hex(serial_bn);
  14619. BN_free(serial_bn);
  14620. }
  14621. client_cert->serial =
  14622. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14623. /* Translate subject and issuer to a string */
  14624. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14625. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14626. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14627. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14628. /* Calculate SHA1 fingerprint and store as a hex string */
  14629. ulen = 0;
  14630. /* ASN1_digest is deprecated. Do the calculation manually,
  14631. * using EVP_Digest. */
  14632. ilen = i2d_X509(cert, NULL);
  14633. tmp_buf = (ilen > 0)
  14634. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14635. conn->phys_ctx)
  14636. : NULL;
  14637. if (tmp_buf) {
  14638. tmp_p = tmp_buf;
  14639. (void)i2d_X509(cert, &tmp_p);
  14640. if (!EVP_Digest(
  14641. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14642. ulen = 0;
  14643. }
  14644. mg_free(tmp_buf);
  14645. }
  14646. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14647. *str_buf = 0;
  14648. }
  14649. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14650. client_cert->peer_cert = (void *)cert;
  14651. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14652. * see https://linux.die.net/man/3/bn_bn2hex */
  14653. OPENSSL_free(str_serial);
  14654. return 1;
  14655. }
  14656. return 0;
  14657. }
  14658. #if defined(OPENSSL_API_1_1)
  14659. #else
  14660. static void
  14661. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14662. {
  14663. (void)line;
  14664. (void)file;
  14665. if (mode & 1) {
  14666. /* 1 is CRYPTO_LOCK */
  14667. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14668. } else {
  14669. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14670. }
  14671. }
  14672. #endif /* OPENSSL_API_1_1 */
  14673. #if !defined(NO_SSL_DL)
  14674. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14675. static void *
  14676. load_tls_dll(char *ebuf,
  14677. size_t ebuf_len,
  14678. const char *dll_name,
  14679. struct ssl_func *sw,
  14680. int *feature_missing)
  14681. {
  14682. union {
  14683. void *p;
  14684. void (*fp)(void);
  14685. } u;
  14686. void *dll_handle;
  14687. struct ssl_func *fp;
  14688. int ok;
  14689. int truncated = 0;
  14690. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14691. mg_snprintf(NULL,
  14692. NULL, /* No truncation check for ebuf */
  14693. ebuf,
  14694. ebuf_len,
  14695. "%s: cannot load %s",
  14696. __func__,
  14697. dll_name);
  14698. return NULL;
  14699. }
  14700. ok = 1;
  14701. for (fp = sw; fp->name != NULL; fp++) {
  14702. #if defined(_WIN32)
  14703. /* GetProcAddress() returns pointer to function */
  14704. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14705. #else
  14706. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14707. * pointers to function pointers. We need to use a union to make a
  14708. * cast. */
  14709. u.p = dlsym(dll_handle, fp->name);
  14710. #endif /* _WIN32 */
  14711. /* Set pointer (might be NULL) */
  14712. fp->ptr = u.fp;
  14713. if (u.fp == NULL) {
  14714. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14715. if (feature_missing) {
  14716. feature_missing[fp->required]++;
  14717. }
  14718. if (fp->required == TLS_Mandatory) {
  14719. /* Mandatory function is missing */
  14720. if (ok) {
  14721. /* This is the first missing function.
  14722. * Create a new error message. */
  14723. mg_snprintf(NULL,
  14724. &truncated,
  14725. ebuf,
  14726. ebuf_len,
  14727. "%s: %s: cannot find %s",
  14728. __func__,
  14729. dll_name,
  14730. fp->name);
  14731. ok = 0;
  14732. } else {
  14733. /* This is yet anothermissing function.
  14734. * Append existing error message. */
  14735. size_t cur_len = strlen(ebuf);
  14736. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14737. mg_snprintf(NULL,
  14738. &truncated,
  14739. ebuf + cur_len,
  14740. ebuf_len - cur_len - 3,
  14741. ", %s",
  14742. fp->name);
  14743. if (truncated) {
  14744. /* If truncated, add "..." */
  14745. strcat(ebuf, "...");
  14746. }
  14747. }
  14748. }
  14749. }
  14750. }
  14751. }
  14752. if (!ok) {
  14753. (void)dlclose(dll_handle);
  14754. return NULL;
  14755. }
  14756. return dll_handle;
  14757. }
  14758. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14759. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14760. #endif /* NO_SSL_DL */
  14761. #if defined(SSL_ALREADY_INITIALIZED)
  14762. static volatile ptrdiff_t cryptolib_users =
  14763. 1; /* Reference counter for crypto library. */
  14764. #else
  14765. static volatile ptrdiff_t cryptolib_users =
  14766. 0; /* Reference counter for crypto library. */
  14767. #endif
  14768. static int
  14769. initialize_openssl(char *ebuf, size_t ebuf_len)
  14770. {
  14771. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14772. int i, num_locks;
  14773. size_t size;
  14774. #endif
  14775. if (ebuf_len > 0) {
  14776. ebuf[0] = 0;
  14777. }
  14778. #if !defined(NO_SSL_DL)
  14779. if (!cryptolib_dll_handle) {
  14780. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14781. cryptolib_dll_handle = load_tls_dll(
  14782. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14783. if (!cryptolib_dll_handle) {
  14784. mg_snprintf(NULL,
  14785. NULL, /* No truncation check for ebuf */
  14786. ebuf,
  14787. ebuf_len,
  14788. "%s: error loading library %s",
  14789. __func__,
  14790. CRYPTO_LIB);
  14791. DEBUG_TRACE("%s", ebuf);
  14792. return 0;
  14793. }
  14794. }
  14795. #endif /* NO_SSL_DL */
  14796. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14797. return 1;
  14798. }
  14799. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14800. /* Initialize locking callbacks, needed for thread safety.
  14801. * http://www.openssl.org/support/faq.html#PROG1
  14802. */
  14803. num_locks = CRYPTO_num_locks();
  14804. if (num_locks < 0) {
  14805. num_locks = 0;
  14806. }
  14807. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14808. /* allocate mutex array, if required */
  14809. if (num_locks == 0) {
  14810. /* No mutex array required */
  14811. ssl_mutexes = NULL;
  14812. } else {
  14813. /* Mutex array required - allocate it */
  14814. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14815. /* Check OOM */
  14816. if (ssl_mutexes == NULL) {
  14817. mg_snprintf(NULL,
  14818. NULL, /* No truncation check for ebuf */
  14819. ebuf,
  14820. ebuf_len,
  14821. "%s: cannot allocate mutexes: %s",
  14822. __func__,
  14823. ssl_error());
  14824. DEBUG_TRACE("%s", ebuf);
  14825. return 0;
  14826. }
  14827. /* initialize mutex array */
  14828. for (i = 0; i < num_locks; i++) {
  14829. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14830. mg_snprintf(NULL,
  14831. NULL, /* No truncation check for ebuf */
  14832. ebuf,
  14833. ebuf_len,
  14834. "%s: error initializing mutex %i of %i",
  14835. __func__,
  14836. i,
  14837. num_locks);
  14838. DEBUG_TRACE("%s", ebuf);
  14839. mg_free(ssl_mutexes);
  14840. return 0;
  14841. }
  14842. }
  14843. }
  14844. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14845. CRYPTO_set_id_callback(&mg_current_thread_id);
  14846. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14847. #if !defined(NO_SSL_DL)
  14848. if (!ssllib_dll_handle) {
  14849. ssllib_dll_handle =
  14850. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14851. if (!ssllib_dll_handle) {
  14852. #if !defined(OPENSSL_API_1_1)
  14853. mg_free(ssl_mutexes);
  14854. #endif
  14855. DEBUG_TRACE("%s", ebuf);
  14856. return 0;
  14857. }
  14858. }
  14859. #endif /* NO_SSL_DL */
  14860. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14861. && !defined(NO_SSL_DL)
  14862. /* Initialize SSL library */
  14863. OPENSSL_init_ssl(0, NULL);
  14864. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14865. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14866. NULL);
  14867. #else
  14868. /* Initialize SSL library */
  14869. SSL_library_init();
  14870. SSL_load_error_strings();
  14871. #endif
  14872. return 1;
  14873. }
  14874. static int
  14875. ssl_use_pem_file(struct mg_context *phys_ctx,
  14876. struct mg_domain_context *dom_ctx,
  14877. const char *pem,
  14878. const char *chain)
  14879. {
  14880. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14881. mg_cry_ctx_internal(phys_ctx,
  14882. "%s: cannot open certificate file %s: %s",
  14883. __func__,
  14884. pem,
  14885. ssl_error());
  14886. return 0;
  14887. }
  14888. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14889. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14890. mg_cry_ctx_internal(phys_ctx,
  14891. "%s: cannot open private key file %s: %s",
  14892. __func__,
  14893. pem,
  14894. ssl_error());
  14895. return 0;
  14896. }
  14897. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14898. mg_cry_ctx_internal(phys_ctx,
  14899. "%s: certificate and private key do not match: %s",
  14900. __func__,
  14901. pem);
  14902. return 0;
  14903. }
  14904. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14905. * chain files that contain private keys and certificates in
  14906. * SSL_CTX_use_certificate_chain_file.
  14907. * The CivetWeb-Server used pem-Files that contained both information.
  14908. * In order to make wolfSSL work, it is split in two files.
  14909. * One file that contains key and certificate used by the server and
  14910. * an optional chain file for the ssl stack.
  14911. */
  14912. if (chain) {
  14913. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14914. mg_cry_ctx_internal(phys_ctx,
  14915. "%s: cannot use certificate chain file %s: %s",
  14916. __func__,
  14917. chain,
  14918. ssl_error());
  14919. return 0;
  14920. }
  14921. }
  14922. return 1;
  14923. }
  14924. #if defined(OPENSSL_API_1_1)
  14925. static unsigned long
  14926. ssl_get_protocol(int version_id)
  14927. {
  14928. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14929. if (version_id > 0)
  14930. ret |= SSL_OP_NO_SSLv2;
  14931. if (version_id > 1)
  14932. ret |= SSL_OP_NO_SSLv3;
  14933. if (version_id > 2)
  14934. ret |= SSL_OP_NO_TLSv1;
  14935. if (version_id > 3)
  14936. ret |= SSL_OP_NO_TLSv1_1;
  14937. if (version_id > 4)
  14938. ret |= SSL_OP_NO_TLSv1_2;
  14939. #if defined(SSL_OP_NO_TLSv1_3)
  14940. if (version_id > 5)
  14941. ret |= SSL_OP_NO_TLSv1_3;
  14942. #endif
  14943. return ret;
  14944. }
  14945. #else
  14946. static long
  14947. ssl_get_protocol(int version_id)
  14948. {
  14949. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14950. if (version_id > 0)
  14951. ret |= SSL_OP_NO_SSLv2;
  14952. if (version_id > 1)
  14953. ret |= SSL_OP_NO_SSLv3;
  14954. if (version_id > 2)
  14955. ret |= SSL_OP_NO_TLSv1;
  14956. if (version_id > 3)
  14957. ret |= SSL_OP_NO_TLSv1_1;
  14958. if (version_id > 4)
  14959. ret |= SSL_OP_NO_TLSv1_2;
  14960. #if defined(SSL_OP_NO_TLSv1_3)
  14961. if (version_id > 5)
  14962. ret |= SSL_OP_NO_TLSv1_3;
  14963. #endif
  14964. return (long)ret;
  14965. }
  14966. #endif /* OPENSSL_API_1_1 */
  14967. /* SSL callback documentation:
  14968. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14969. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14970. * https://linux.die.net/man/3/ssl_set_info_callback */
  14971. /* Note: There is no "const" for the first argument in the documentation
  14972. * examples, however some (maybe most, but not all) headers of OpenSSL
  14973. * versions / OpenSSL compatibility layers have it. Having a different
  14974. * definition will cause a warning in C and an error in C++. Use "const SSL
  14975. * *", while automatic conversion from "SSL *" works for all compilers,
  14976. * but not other way around */
  14977. static void
  14978. ssl_info_callback(const SSL *ssl, int what, int ret)
  14979. {
  14980. (void)ret;
  14981. if (what & SSL_CB_HANDSHAKE_START) {
  14982. SSL_get_app_data(ssl);
  14983. }
  14984. if (what & SSL_CB_HANDSHAKE_DONE) {
  14985. /* TODO: check for openSSL 1.1 */
  14986. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14987. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14988. }
  14989. }
  14990. static int
  14991. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14992. {
  14993. #if defined(GCC_DIAGNOSTIC)
  14994. #pragma GCC diagnostic push
  14995. #pragma GCC diagnostic ignored "-Wcast-align"
  14996. #endif /* defined(GCC_DIAGNOSTIC) */
  14997. /* We used an aligned pointer in SSL_set_app_data */
  14998. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14999. #if defined(GCC_DIAGNOSTIC)
  15000. #pragma GCC diagnostic pop
  15001. #endif /* defined(GCC_DIAGNOSTIC) */
  15002. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15003. (void)ad;
  15004. (void)arg;
  15005. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15006. DEBUG_ASSERT(0);
  15007. return SSL_TLSEXT_ERR_NOACK;
  15008. }
  15009. conn->dom_ctx = &(conn->phys_ctx->dd);
  15010. /* Old clients (Win XP) will not support SNI. Then, there
  15011. * is no server name available in the request - we can
  15012. * only work with the default certificate.
  15013. * Multiple HTTPS hosts on one IP+port are only possible
  15014. * with a certificate containing all alternative names.
  15015. */
  15016. if ((servername == NULL) || (*servername == 0)) {
  15017. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15018. mg_lock_context(conn->phys_ctx);
  15019. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15020. mg_unlock_context(conn->phys_ctx);
  15021. return SSL_TLSEXT_ERR_NOACK;
  15022. }
  15023. DEBUG_TRACE("TLS connection to host %s", servername);
  15024. while (conn->dom_ctx) {
  15025. if (!mg_strcasecmp(servername,
  15026. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15027. /* Found matching domain */
  15028. DEBUG_TRACE("TLS domain %s found",
  15029. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15030. break;
  15031. }
  15032. mg_lock_context(conn->phys_ctx);
  15033. conn->dom_ctx = conn->dom_ctx->next;
  15034. mg_unlock_context(conn->phys_ctx);
  15035. }
  15036. if (conn->dom_ctx == NULL) {
  15037. /* Default domain */
  15038. DEBUG_TRACE("TLS default domain %s used",
  15039. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15040. conn->dom_ctx = &(conn->phys_ctx->dd);
  15041. }
  15042. mg_lock_context(conn->phys_ctx);
  15043. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15044. mg_unlock_context(conn->phys_ctx);
  15045. return SSL_TLSEXT_ERR_OK;
  15046. }
  15047. #if defined(USE_ALPN)
  15048. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15049. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15050. alpn_proto_list + 3 + 8,
  15051. NULL};
  15052. #if defined(USE_HTTP2)
  15053. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15054. alpn_proto_list + 3,
  15055. alpn_proto_list + 3 + 8,
  15056. NULL};
  15057. #endif
  15058. static int
  15059. alpn_select_cb(SSL *ssl,
  15060. const unsigned char **out,
  15061. unsigned char *outlen,
  15062. const unsigned char *in,
  15063. unsigned int inlen,
  15064. void *arg)
  15065. {
  15066. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15067. unsigned int i, j, enable_http2 = 0;
  15068. const char **alpn_proto_order = alpn_proto_order_http1;
  15069. struct mg_workerTLS *tls =
  15070. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15071. (void)ssl;
  15072. if (tls == NULL) {
  15073. /* Need to store protocol in Thread Local Storage */
  15074. /* If there is no Thread Local Storage, don't use ALPN */
  15075. return SSL_TLSEXT_ERR_NOACK;
  15076. }
  15077. #if defined(USE_HTTP2)
  15078. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15079. if (enable_http2) {
  15080. alpn_proto_order = alpn_proto_order_http2;
  15081. }
  15082. #endif
  15083. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15084. /* check all accepted protocols in this order */
  15085. const char *alpn_proto = alpn_proto_order[j];
  15086. /* search input for matching protocol */
  15087. for (i = 0; i < inlen; i++) {
  15088. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15089. *out = in + i + 1;
  15090. *outlen = in[i];
  15091. tls->alpn_proto = alpn_proto;
  15092. return SSL_TLSEXT_ERR_OK;
  15093. }
  15094. }
  15095. }
  15096. /* Nothing found */
  15097. return SSL_TLSEXT_ERR_NOACK;
  15098. }
  15099. static int
  15100. next_protos_advertised_cb(SSL *ssl,
  15101. const unsigned char **data,
  15102. unsigned int *len,
  15103. void *arg)
  15104. {
  15105. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15106. *data = (const unsigned char *)alpn_proto_list;
  15107. *len = (unsigned int)strlen((const char *)data);
  15108. (void)ssl;
  15109. (void)dom_ctx;
  15110. return SSL_TLSEXT_ERR_OK;
  15111. }
  15112. static int
  15113. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15114. {
  15115. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15116. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15117. (const unsigned char *)alpn_proto_list,
  15118. alpn_len);
  15119. if (ret != 0) {
  15120. mg_cry_ctx_internal(phys_ctx,
  15121. "SSL_CTX_set_alpn_protos error: %s",
  15122. ssl_error());
  15123. }
  15124. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15125. alpn_select_cb,
  15126. (void *)dom_ctx);
  15127. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15128. next_protos_advertised_cb,
  15129. (void *)dom_ctx);
  15130. return ret;
  15131. }
  15132. #endif
  15133. /* Setup SSL CTX as required by CivetWeb */
  15134. static int
  15135. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15136. struct mg_domain_context *dom_ctx,
  15137. const char *pem,
  15138. const char *chain)
  15139. {
  15140. int callback_ret;
  15141. int should_verify_peer;
  15142. int peer_certificate_optional;
  15143. const char *ca_path;
  15144. const char *ca_file;
  15145. int use_default_verify_paths;
  15146. int verify_depth;
  15147. struct timespec now_mt;
  15148. md5_byte_t ssl_context_id[16];
  15149. md5_state_t md5state;
  15150. int protocol_ver;
  15151. int ssl_cache_timeout;
  15152. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15153. && !defined(NO_SSL_DL)
  15154. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15155. mg_cry_ctx_internal(phys_ctx,
  15156. "SSL_CTX_new (server) error: %s",
  15157. ssl_error());
  15158. return 0;
  15159. }
  15160. #else
  15161. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15162. mg_cry_ctx_internal(phys_ctx,
  15163. "SSL_CTX_new (server) error: %s",
  15164. ssl_error());
  15165. return 0;
  15166. }
  15167. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15168. #if defined(SSL_OP_NO_TLSv1_3)
  15169. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15170. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15171. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15172. | SSL_OP_NO_TLSv1_3);
  15173. #else
  15174. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15175. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15176. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15177. #endif
  15178. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15179. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15180. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15181. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15182. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15183. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15184. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15185. #if defined(SSL_OP_NO_RENEGOTIATION)
  15186. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15187. #endif
  15188. #if !defined(NO_SSL_DL)
  15189. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15190. #endif /* NO_SSL_DL */
  15191. /* In SSL documentation examples callback defined without const
  15192. * specifier 'void (*)(SSL *, int, int)' See:
  15193. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15194. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15195. * But in the source code const SSL is used:
  15196. * 'void (*)(const SSL *, int, int)' See:
  15197. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15198. * Problem about wrong documentation described, but not resolved:
  15199. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15200. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15201. * But when compiled with modern C++ compiler, correct const should be
  15202. * provided
  15203. */
  15204. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15205. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15206. ssl_servername_callback);
  15207. /* If a callback has been specified, call it. */
  15208. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15209. ? 0
  15210. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15211. phys_ctx->user_data));
  15212. /* If callback returns 0, civetweb sets up the SSL certificate.
  15213. * If it returns 1, civetweb assumes the callback already did this.
  15214. * If it returns -1, initializing ssl fails. */
  15215. if (callback_ret < 0) {
  15216. mg_cry_ctx_internal(phys_ctx,
  15217. "SSL callback returned error: %i",
  15218. callback_ret);
  15219. return 0;
  15220. }
  15221. if (callback_ret > 0) {
  15222. /* Callback did everything. */
  15223. return 1;
  15224. }
  15225. /* If a domain callback has been specified, call it. */
  15226. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15227. ? 0
  15228. : (phys_ctx->callbacks.init_ssl_domain(
  15229. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15230. dom_ctx->ssl_ctx,
  15231. phys_ctx->user_data));
  15232. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15233. * If it returns 1, civetweb assumes the callback already did this.
  15234. * If it returns -1, initializing ssl fails. */
  15235. if (callback_ret < 0) {
  15236. mg_cry_ctx_internal(phys_ctx,
  15237. "Domain SSL callback returned error: %i",
  15238. callback_ret);
  15239. return 0;
  15240. }
  15241. if (callback_ret > 0) {
  15242. /* Domain callback did everything. */
  15243. return 1;
  15244. }
  15245. /* Use some combination of start time, domain and port as a SSL
  15246. * context ID. This should be unique on the current machine. */
  15247. md5_init(&md5state);
  15248. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15249. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15250. md5_append(&md5state,
  15251. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15252. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15253. md5_append(&md5state,
  15254. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15255. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15256. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15257. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15258. md5_finish(&md5state, ssl_context_id);
  15259. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15260. (unsigned char *)ssl_context_id,
  15261. sizeof(ssl_context_id));
  15262. if (pem != NULL) {
  15263. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15264. return 0;
  15265. }
  15266. }
  15267. /* Should we support client certificates? */
  15268. /* Default is "no". */
  15269. should_verify_peer = 0;
  15270. peer_certificate_optional = 0;
  15271. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15272. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15273. /* Yes, they are mandatory */
  15274. should_verify_peer = 1;
  15275. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15276. "optional")
  15277. == 0) {
  15278. /* Yes, they are optional */
  15279. should_verify_peer = 1;
  15280. peer_certificate_optional = 1;
  15281. }
  15282. }
  15283. use_default_verify_paths =
  15284. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15285. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15286. == 0);
  15287. if (should_verify_peer) {
  15288. ca_path = dom_ctx->config[SSL_CA_PATH];
  15289. ca_file = dom_ctx->config[SSL_CA_FILE];
  15290. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15291. != 1) {
  15292. mg_cry_ctx_internal(phys_ctx,
  15293. "SSL_CTX_load_verify_locations error: %s "
  15294. "ssl_verify_peer requires setting "
  15295. "either ssl_ca_path or ssl_ca_file. "
  15296. "Is any of them present in the "
  15297. ".conf file?",
  15298. ssl_error());
  15299. return 0;
  15300. }
  15301. if (peer_certificate_optional) {
  15302. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15303. } else {
  15304. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15305. SSL_VERIFY_PEER
  15306. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15307. NULL);
  15308. }
  15309. if (use_default_verify_paths
  15310. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15311. mg_cry_ctx_internal(phys_ctx,
  15312. "SSL_CTX_set_default_verify_paths error: %s",
  15313. ssl_error());
  15314. return 0;
  15315. }
  15316. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15317. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15318. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15319. }
  15320. }
  15321. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15322. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15323. dom_ctx->config[SSL_CIPHER_LIST])
  15324. != 1) {
  15325. mg_cry_ctx_internal(phys_ctx,
  15326. "SSL_CTX_set_cipher_list error: %s",
  15327. ssl_error());
  15328. }
  15329. }
  15330. /* SSL session caching */
  15331. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15332. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15333. : 0);
  15334. if (ssl_cache_timeout > 0) {
  15335. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15336. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15337. * default */
  15338. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15339. }
  15340. #if defined(USE_ALPN)
  15341. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15342. #if !defined(NO_SSL_DL)
  15343. if (!tls_feature_missing[TLS_ALPN])
  15344. #endif
  15345. {
  15346. init_alpn(phys_ctx, dom_ctx);
  15347. }
  15348. #endif
  15349. return 1;
  15350. }
  15351. /* Check if SSL is required.
  15352. * If so, dynamically load SSL library
  15353. * and set up ctx->ssl_ctx pointer. */
  15354. static int
  15355. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15356. {
  15357. void *ssl_ctx = 0;
  15358. int callback_ret;
  15359. const char *pem;
  15360. const char *chain;
  15361. char ebuf[128];
  15362. if (!phys_ctx) {
  15363. return 0;
  15364. }
  15365. if (!dom_ctx) {
  15366. dom_ctx = &(phys_ctx->dd);
  15367. }
  15368. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15369. /* No SSL port is set. No need to setup SSL. */
  15370. return 1;
  15371. }
  15372. /* Check for external SSL_CTX */
  15373. callback_ret =
  15374. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15375. ? 0
  15376. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15377. phys_ctx->user_data));
  15378. if (callback_ret < 0) {
  15379. /* Callback exists and returns <0: Initializing failed. */
  15380. mg_cry_ctx_internal(phys_ctx,
  15381. "external_ssl_ctx callback returned error: %i",
  15382. callback_ret);
  15383. return 0;
  15384. } else if (callback_ret > 0) {
  15385. /* Callback exists and returns >0: Initializing complete,
  15386. * civetweb should not modify the SSL context. */
  15387. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15388. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15389. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15390. return 0;
  15391. }
  15392. return 1;
  15393. }
  15394. /* If the callback does not exist or return 0, civetweb must initialize
  15395. * the SSL context. Handle "domain" callback next. */
  15396. /* Check for external domain SSL_CTX callback. */
  15397. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15398. ? 0
  15399. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15400. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15401. &ssl_ctx,
  15402. phys_ctx->user_data));
  15403. if (callback_ret < 0) {
  15404. /* Callback < 0: Error. Abort init. */
  15405. mg_cry_ctx_internal(
  15406. phys_ctx,
  15407. "external_ssl_ctx_domain callback returned error: %i",
  15408. callback_ret);
  15409. return 0;
  15410. } else if (callback_ret > 0) {
  15411. /* Callback > 0: Consider init done. */
  15412. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15413. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15414. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15415. return 0;
  15416. }
  15417. return 1;
  15418. }
  15419. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15420. * 0, CivetWeb should continue initializing SSL */
  15421. /* If PEM file is not specified and the init_ssl callbacks
  15422. * are not specified, setup will fail. */
  15423. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15424. && (phys_ctx->callbacks.init_ssl == NULL)
  15425. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15426. /* No certificate and no init_ssl callbacks:
  15427. * Essential data to set up TLS is missing.
  15428. */
  15429. mg_cry_ctx_internal(phys_ctx,
  15430. "Initializing SSL failed: -%s is not set",
  15431. config_options[SSL_CERTIFICATE].name);
  15432. return 0;
  15433. }
  15434. /* If a certificate chain is configured, use it. */
  15435. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15436. if (chain == NULL) {
  15437. /* Default: certificate chain in PEM file */
  15438. chain = pem;
  15439. }
  15440. if ((chain != NULL) && (*chain == 0)) {
  15441. /* If the chain is an empty string, don't use it. */
  15442. chain = NULL;
  15443. }
  15444. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15445. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15446. return 0;
  15447. }
  15448. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15449. }
  15450. static void
  15451. uninitialize_openssl(void)
  15452. {
  15453. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15454. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15455. /* Shutdown according to
  15456. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15457. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15458. */
  15459. CONF_modules_unload(1);
  15460. #else
  15461. int i;
  15462. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15463. /* Shutdown according to
  15464. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15465. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15466. */
  15467. CRYPTO_set_locking_callback(NULL);
  15468. CRYPTO_set_id_callback(NULL);
  15469. ENGINE_cleanup();
  15470. CONF_modules_unload(1);
  15471. ERR_free_strings();
  15472. EVP_cleanup();
  15473. CRYPTO_cleanup_all_ex_data();
  15474. OPENSSL_REMOVE_THREAD_STATE();
  15475. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15476. pthread_mutex_destroy(&ssl_mutexes[i]);
  15477. }
  15478. mg_free(ssl_mutexes);
  15479. ssl_mutexes = NULL;
  15480. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15481. }
  15482. }
  15483. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15484. #if !defined(NO_FILESYSTEMS)
  15485. static int
  15486. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15487. {
  15488. if (phys_ctx) {
  15489. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15490. const char *path;
  15491. struct mg_connection fc;
  15492. if (!dom_ctx) {
  15493. dom_ctx = &(phys_ctx->dd);
  15494. }
  15495. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15496. if ((path != NULL)
  15497. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15498. mg_cry_ctx_internal(phys_ctx,
  15499. "Cannot open %s: %s",
  15500. path,
  15501. strerror(ERRNO));
  15502. return 0;
  15503. }
  15504. return 1;
  15505. }
  15506. return 0;
  15507. }
  15508. #endif /* NO_FILESYSTEMS */
  15509. static int
  15510. set_acl_option(struct mg_context *phys_ctx)
  15511. {
  15512. union usa sa;
  15513. memset(&sa, 0, sizeof(sa));
  15514. #if defined(USE_IPV6)
  15515. sa.sin6.sin6_family = AF_INET6;
  15516. #else
  15517. sa.sin.sin_family = AF_INET;
  15518. #endif
  15519. return check_acl(phys_ctx, &sa) != -1;
  15520. }
  15521. static void
  15522. reset_per_request_attributes(struct mg_connection *conn)
  15523. {
  15524. if (!conn) {
  15525. return;
  15526. }
  15527. conn->num_bytes_sent = conn->consumed_content = 0;
  15528. conn->path_info = NULL;
  15529. conn->status_code = -1;
  15530. conn->content_len = -1;
  15531. conn->is_chunked = 0;
  15532. conn->must_close = 0;
  15533. conn->request_len = 0;
  15534. conn->request_state = 0;
  15535. conn->throttle = 0;
  15536. conn->accept_gzip = 0;
  15537. conn->response_info.content_length = conn->request_info.content_length = -1;
  15538. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15539. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15540. conn->response_info.status_text = NULL;
  15541. conn->response_info.status_code = 0;
  15542. conn->request_info.remote_user = NULL;
  15543. conn->request_info.request_method = NULL;
  15544. conn->request_info.request_uri = NULL;
  15545. /* Free cleaned local URI (if any) */
  15546. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15547. mg_free((void *)conn->request_info.local_uri);
  15548. conn->request_info.local_uri = NULL;
  15549. }
  15550. conn->request_info.local_uri = NULL;
  15551. #if defined(USE_SERVER_STATS)
  15552. conn->processing_time = 0;
  15553. #endif
  15554. }
  15555. static int
  15556. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15557. {
  15558. if ((so->lsa.sa.sa_family == AF_INET)
  15559. || (so->lsa.sa.sa_family == AF_INET6)) {
  15560. /* Only for TCP sockets */
  15561. if (setsockopt(so->sock,
  15562. IPPROTO_TCP,
  15563. TCP_NODELAY,
  15564. (SOCK_OPT_TYPE)&nodelay_on,
  15565. sizeof(nodelay_on))
  15566. != 0) {
  15567. /* Error */
  15568. return 1;
  15569. }
  15570. }
  15571. /* OK */
  15572. return 0;
  15573. }
  15574. #if !defined(__ZEPHYR__)
  15575. static void
  15576. close_socket_gracefully(struct mg_connection *conn)
  15577. {
  15578. #if defined(_WIN32)
  15579. char buf[MG_BUF_LEN];
  15580. int n;
  15581. #endif
  15582. struct linger linger;
  15583. int error_code = 0;
  15584. int linger_timeout = -2;
  15585. socklen_t opt_len = sizeof(error_code);
  15586. if (!conn) {
  15587. return;
  15588. }
  15589. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15590. * "Note that enabling a nonzero timeout on a nonblocking socket
  15591. * is not recommended.", so set it to blocking now */
  15592. set_blocking_mode(conn->client.sock);
  15593. /* Send FIN to the client */
  15594. shutdown(conn->client.sock, SHUTDOWN_WR);
  15595. #if defined(_WIN32)
  15596. /* Read and discard pending incoming data. If we do not do that and
  15597. * close
  15598. * the socket, the data in the send buffer may be discarded. This
  15599. * behaviour is seen on Windows, when client keeps sending data
  15600. * when server decides to close the connection; then when client
  15601. * does recv() it gets no data back. */
  15602. do {
  15603. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15604. } while (n > 0);
  15605. #endif
  15606. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15607. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15608. }
  15609. /* Set linger option according to configuration */
  15610. if (linger_timeout >= 0) {
  15611. /* Set linger option to avoid socket hanging out after close. This
  15612. * prevent ephemeral port exhaust problem under high QPS. */
  15613. linger.l_onoff = 1;
  15614. #if defined(_MSC_VER)
  15615. #pragma warning(push)
  15616. #pragma warning(disable : 4244)
  15617. #endif
  15618. #if defined(GCC_DIAGNOSTIC)
  15619. #pragma GCC diagnostic push
  15620. #pragma GCC diagnostic ignored "-Wconversion"
  15621. #endif
  15622. /* Data type of linger structure elements may differ,
  15623. * so we don't know what cast we need here.
  15624. * Disable type conversion warnings. */
  15625. linger.l_linger = (linger_timeout + 999) / 1000;
  15626. #if defined(GCC_DIAGNOSTIC)
  15627. #pragma GCC diagnostic pop
  15628. #endif
  15629. #if defined(_MSC_VER)
  15630. #pragma warning(pop)
  15631. #endif
  15632. } else {
  15633. linger.l_onoff = 0;
  15634. linger.l_linger = 0;
  15635. }
  15636. if (linger_timeout < -1) {
  15637. /* Default: don't configure any linger */
  15638. } else if (getsockopt(conn->client.sock,
  15639. SOL_SOCKET,
  15640. SO_ERROR,
  15641. #if defined(_WIN32) /* WinSock uses different data type here */
  15642. (char *)&error_code,
  15643. #else
  15644. &error_code,
  15645. #endif
  15646. &opt_len)
  15647. != 0) {
  15648. /* Cannot determine if socket is already closed. This should
  15649. * not occur and never did in a test. Log an error message
  15650. * and continue. */
  15651. mg_cry_internal(conn,
  15652. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15653. __func__,
  15654. strerror(ERRNO));
  15655. #if defined(_WIN32)
  15656. } else if (error_code == WSAECONNRESET) {
  15657. #else
  15658. } else if (error_code == ECONNRESET) {
  15659. #endif
  15660. /* Socket already closed by client/peer, close socket without linger
  15661. */
  15662. } else {
  15663. /* Set linger timeout */
  15664. if (setsockopt(conn->client.sock,
  15665. SOL_SOCKET,
  15666. SO_LINGER,
  15667. (char *)&linger,
  15668. sizeof(linger))
  15669. != 0) {
  15670. mg_cry_internal(
  15671. conn,
  15672. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15673. __func__,
  15674. linger.l_onoff,
  15675. linger.l_linger,
  15676. strerror(ERRNO));
  15677. }
  15678. }
  15679. /* Now we know that our FIN is ACK-ed, safe to close */
  15680. closesocket(conn->client.sock);
  15681. conn->client.sock = INVALID_SOCKET;
  15682. }
  15683. #endif
  15684. static void
  15685. close_connection(struct mg_connection *conn)
  15686. {
  15687. #if defined(USE_SERVER_STATS)
  15688. conn->conn_state = 6; /* to close */
  15689. #endif
  15690. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15691. if (conn->lua_websocket_state) {
  15692. lua_websocket_close(conn, conn->lua_websocket_state);
  15693. conn->lua_websocket_state = NULL;
  15694. }
  15695. #endif
  15696. mg_lock_connection(conn);
  15697. /* Set close flag, so keep-alive loops will stop */
  15698. conn->must_close = 1;
  15699. /* call the connection_close callback if assigned */
  15700. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15701. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15702. conn->phys_ctx->callbacks.connection_close(conn);
  15703. }
  15704. }
  15705. /* Reset user data, after close callback is called.
  15706. * Do not reuse it. If the user needs a destructor,
  15707. * it must be done in the connection_close callback. */
  15708. mg_set_user_connection_data(conn, NULL);
  15709. #if defined(USE_SERVER_STATS)
  15710. conn->conn_state = 7; /* closing */
  15711. #endif
  15712. #if defined(USE_MBEDTLS)
  15713. if (conn->ssl != NULL) {
  15714. mbed_ssl_close(conn->ssl);
  15715. conn->ssl = NULL;
  15716. }
  15717. #elif !defined(NO_SSL)
  15718. if (conn->ssl != NULL) {
  15719. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15720. */
  15721. SSL_shutdown(conn->ssl);
  15722. SSL_free(conn->ssl);
  15723. OPENSSL_REMOVE_THREAD_STATE();
  15724. conn->ssl = NULL;
  15725. }
  15726. #endif
  15727. if (conn->client.sock != INVALID_SOCKET) {
  15728. #if defined(__ZEPHYR__)
  15729. closesocket(conn->client.sock);
  15730. #else
  15731. close_socket_gracefully(conn);
  15732. #endif
  15733. conn->client.sock = INVALID_SOCKET;
  15734. }
  15735. /* call the connection_closed callback if assigned */
  15736. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15737. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15738. conn->phys_ctx->callbacks.connection_closed(conn);
  15739. }
  15740. }
  15741. mg_unlock_connection(conn);
  15742. #if defined(USE_SERVER_STATS)
  15743. conn->conn_state = 8; /* closed */
  15744. #endif
  15745. }
  15746. CIVETWEB_API void
  15747. mg_close_connection(struct mg_connection *conn)
  15748. {
  15749. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15750. return;
  15751. }
  15752. #if defined(USE_WEBSOCKET)
  15753. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15754. if (conn->in_websocket_handling) {
  15755. /* Set close flag, so the server thread can exit. */
  15756. conn->must_close = 1;
  15757. return;
  15758. }
  15759. }
  15760. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15761. unsigned int i;
  15762. /* client context: loops must end */
  15763. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15764. conn->must_close = 1;
  15765. /* We need to get the client thread out of the select/recv call
  15766. * here. */
  15767. /* Since we use a sleep quantum of some seconds to check for recv
  15768. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15769. /* join worker thread */
  15770. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15771. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15772. }
  15773. }
  15774. #endif /* defined(USE_WEBSOCKET) */
  15775. close_connection(conn);
  15776. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15777. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15778. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15779. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15780. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15781. }
  15782. #endif
  15783. #if defined(USE_WEBSOCKET)
  15784. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15785. mg_free(conn->phys_ctx->worker_threadids);
  15786. (void)pthread_mutex_destroy(&conn->mutex);
  15787. mg_free(conn);
  15788. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15789. (void)pthread_mutex_destroy(&conn->mutex);
  15790. mg_free(conn);
  15791. }
  15792. #else
  15793. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15794. (void)pthread_mutex_destroy(&conn->mutex);
  15795. mg_free(conn);
  15796. }
  15797. #endif /* defined(USE_WEBSOCKET) */
  15798. }
  15799. static struct mg_connection *
  15800. mg_connect_client_impl(const struct mg_client_options *client_options,
  15801. int use_ssl,
  15802. struct mg_init_data *init,
  15803. struct mg_error_data *error)
  15804. {
  15805. struct mg_connection *conn = NULL;
  15806. SOCKET sock;
  15807. union usa sa;
  15808. struct sockaddr *psa;
  15809. socklen_t len;
  15810. unsigned max_req_size =
  15811. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15812. /* Size of structures, aligned to 8 bytes */
  15813. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15814. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15815. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15816. (void)init; /* TODO: Implement required options */
  15817. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15818. if (error != NULL) {
  15819. error->code = MG_ERROR_DATA_CODE_OK;
  15820. error->code_sub = 0;
  15821. if (error->text_buffer_size > 0) {
  15822. error->text[0] = 0;
  15823. }
  15824. }
  15825. if (conn == NULL) {
  15826. if (error != NULL) {
  15827. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15828. error->code_sub = (unsigned)alloc_size;
  15829. mg_snprintf(NULL,
  15830. NULL, /* No truncation check for ebuf */
  15831. error->text,
  15832. error->text_buffer_size,
  15833. "calloc(): %s",
  15834. strerror(ERRNO));
  15835. }
  15836. return NULL;
  15837. }
  15838. #if defined(GCC_DIAGNOSTIC)
  15839. #pragma GCC diagnostic push
  15840. #pragma GCC diagnostic ignored "-Wcast-align"
  15841. #endif /* defined(GCC_DIAGNOSTIC) */
  15842. /* conn_size is aligned to 8 bytes */
  15843. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15844. #if defined(GCC_DIAGNOSTIC)
  15845. #pragma GCC diagnostic pop
  15846. #endif /* defined(GCC_DIAGNOSTIC) */
  15847. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15848. conn->buf_size = (int)max_req_size;
  15849. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15850. conn->dom_ctx = &(conn->phys_ctx->dd);
  15851. if (!connect_socket(conn->phys_ctx,
  15852. client_options->host,
  15853. client_options->port,
  15854. use_ssl,
  15855. error,
  15856. &sock,
  15857. &sa)) {
  15858. /* "error" will be set by connect_socket. */
  15859. /* free all memory and return NULL; */
  15860. mg_free(conn);
  15861. return NULL;
  15862. }
  15863. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15864. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15865. && !defined(NO_SSL_DL)
  15866. if (use_ssl
  15867. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15868. == NULL) {
  15869. if (error != NULL) {
  15870. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15871. mg_snprintf(NULL,
  15872. NULL, /* No truncation check for ebuf */
  15873. error->text,
  15874. error->text_buffer_size,
  15875. "SSL_CTX_new error: %s",
  15876. ssl_error());
  15877. }
  15878. closesocket(sock);
  15879. mg_free(conn);
  15880. return NULL;
  15881. }
  15882. #else
  15883. if (use_ssl
  15884. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15885. == NULL) {
  15886. if (error != NULL) {
  15887. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15888. mg_snprintf(NULL,
  15889. NULL, /* No truncation check for ebuf */
  15890. error->text,
  15891. error->text_buffer_size,
  15892. "SSL_CTX_new error: %s",
  15893. ssl_error());
  15894. }
  15895. closesocket(sock);
  15896. mg_free(conn);
  15897. return NULL;
  15898. }
  15899. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15900. #endif /* NO_SSL */
  15901. #if defined(USE_IPV6)
  15902. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15903. : sizeof(conn->client.rsa.sin6);
  15904. psa = (sa.sa.sa_family == AF_INET)
  15905. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15906. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15907. #else
  15908. len = sizeof(conn->client.rsa.sin);
  15909. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15910. #endif
  15911. conn->client.sock = sock;
  15912. conn->client.lsa = sa;
  15913. if (getsockname(sock, psa, &len) != 0) {
  15914. mg_cry_internal(conn,
  15915. "%s: getsockname() failed: %s",
  15916. __func__,
  15917. strerror(ERRNO));
  15918. }
  15919. conn->client.is_ssl = use_ssl ? 1 : 0;
  15920. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15921. if (error != NULL) {
  15922. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15923. error->code_sub = (unsigned)ERRNO;
  15924. mg_snprintf(NULL,
  15925. NULL, /* No truncation check for ebuf */
  15926. error->text,
  15927. error->text_buffer_size,
  15928. "Can not create mutex");
  15929. }
  15930. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15931. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15932. #endif
  15933. closesocket(sock);
  15934. mg_free(conn);
  15935. return NULL;
  15936. }
  15937. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15938. if (use_ssl) {
  15939. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15940. * SSL_CTX_set_verify call is needed to switch off server
  15941. * certificate checking, which is off by default in OpenSSL and
  15942. * on in yaSSL. */
  15943. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15944. * SSL_VERIFY_PEER, verify_ssl_server); */
  15945. if (client_options->client_cert) {
  15946. if (!ssl_use_pem_file(conn->phys_ctx,
  15947. conn->dom_ctx,
  15948. client_options->client_cert,
  15949. NULL)) {
  15950. if (error != NULL) {
  15951. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15952. mg_snprintf(NULL,
  15953. NULL, /* No truncation check for ebuf */
  15954. error->text,
  15955. error->text_buffer_size,
  15956. "Can not use SSL client certificate");
  15957. }
  15958. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15959. closesocket(sock);
  15960. mg_free(conn);
  15961. return NULL;
  15962. }
  15963. }
  15964. if (client_options->server_cert) {
  15965. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15966. client_options->server_cert,
  15967. NULL)
  15968. != 1) {
  15969. if (error != NULL) {
  15970. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15971. mg_snprintf(NULL,
  15972. NULL, /* No truncation check for ebuf */
  15973. error->text,
  15974. error->text_buffer_size,
  15975. "SSL_CTX_load_verify_locations error: %s",
  15976. ssl_error());
  15977. }
  15978. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15979. closesocket(sock);
  15980. mg_free(conn);
  15981. return NULL;
  15982. }
  15983. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15984. } else {
  15985. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15986. }
  15987. if (!sslize(conn, SSL_connect, client_options)) {
  15988. if (error != NULL) {
  15989. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15990. mg_snprintf(NULL,
  15991. NULL, /* No truncation check for ebuf */
  15992. error->text,
  15993. error->text_buffer_size,
  15994. "SSL connection error");
  15995. }
  15996. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15997. closesocket(sock);
  15998. mg_free(conn);
  15999. return NULL;
  16000. }
  16001. }
  16002. #endif
  16003. return conn;
  16004. }
  16005. CIVETWEB_API struct mg_connection *
  16006. mg_connect_client_secure(const struct mg_client_options *client_options,
  16007. char *error_buffer,
  16008. size_t error_buffer_size)
  16009. {
  16010. struct mg_init_data init;
  16011. struct mg_error_data error;
  16012. memset(&init, 0, sizeof(init));
  16013. memset(&error, 0, sizeof(error));
  16014. error.text_buffer_size = error_buffer_size;
  16015. error.text = error_buffer;
  16016. return mg_connect_client_impl(client_options, 1, &init, &error);
  16017. }
  16018. CIVETWEB_API struct mg_connection *
  16019. mg_connect_client(const char *host,
  16020. int port,
  16021. int use_ssl,
  16022. char *error_buffer,
  16023. size_t error_buffer_size)
  16024. {
  16025. struct mg_client_options opts;
  16026. struct mg_init_data init;
  16027. struct mg_error_data error;
  16028. memset(&init, 0, sizeof(init));
  16029. memset(&error, 0, sizeof(error));
  16030. error.text_buffer_size = error_buffer_size;
  16031. error.text = error_buffer;
  16032. memset(&opts, 0, sizeof(opts));
  16033. opts.host = host;
  16034. opts.port = port;
  16035. if (use_ssl) {
  16036. opts.host_name = host;
  16037. }
  16038. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16039. }
  16040. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16041. CIVETWEB_API struct mg_connection *
  16042. mg_connect_client2(const char *host,
  16043. const char *protocol,
  16044. int port,
  16045. const char *path,
  16046. struct mg_init_data *init,
  16047. struct mg_error_data *error)
  16048. {
  16049. (void)path;
  16050. int is_ssl, is_ws;
  16051. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16052. if (error != NULL) {
  16053. error->code = MG_ERROR_DATA_CODE_OK;
  16054. error->code_sub = 0;
  16055. if (error->text_buffer_size > 0) {
  16056. *error->text = 0;
  16057. }
  16058. }
  16059. if ((host == NULL) || (protocol == NULL)) {
  16060. if (error != NULL) {
  16061. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16062. mg_snprintf(NULL,
  16063. NULL, /* No truncation check for error buffers */
  16064. error->text,
  16065. error->text_buffer_size,
  16066. "%s",
  16067. "Invalid parameters");
  16068. }
  16069. return NULL;
  16070. }
  16071. /* check all known protocols */
  16072. if (!mg_strcasecmp(protocol, "http")) {
  16073. is_ssl = 0;
  16074. is_ws = 0;
  16075. } else if (!mg_strcasecmp(protocol, "https")) {
  16076. is_ssl = 1;
  16077. is_ws = 0;
  16078. #if defined(USE_WEBSOCKET)
  16079. } else if (!mg_strcasecmp(protocol, "ws")) {
  16080. is_ssl = 0;
  16081. is_ws = 1;
  16082. } else if (!mg_strcasecmp(protocol, "wss")) {
  16083. is_ssl = 1;
  16084. is_ws = 1;
  16085. #endif
  16086. } else {
  16087. if (error != NULL) {
  16088. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16089. mg_snprintf(NULL,
  16090. NULL, /* No truncation check for error buffers */
  16091. error->text,
  16092. error->text_buffer_size,
  16093. "Protocol %s not supported",
  16094. protocol);
  16095. }
  16096. return NULL;
  16097. }
  16098. /* TODO: The current implementation here just calls the old
  16099. * implementations, without using any new options. This is just a first
  16100. * step to test the new interfaces. */
  16101. #if defined(USE_WEBSOCKET)
  16102. if (is_ws) {
  16103. /* TODO: implement all options */
  16104. return mg_connect_websocket_client(
  16105. host,
  16106. port,
  16107. is_ssl,
  16108. ((error != NULL) ? error->text : NULL),
  16109. ((error != NULL) ? error->text_buffer_size : 0),
  16110. (path ? path : ""),
  16111. NULL /* TODO: origin */,
  16112. experimental_websocket_client_data_wrapper,
  16113. experimental_websocket_client_close_wrapper,
  16114. (void *)init->callbacks);
  16115. }
  16116. #else
  16117. (void)is_ws;
  16118. #endif
  16119. /* TODO: all additional options */
  16120. struct mg_client_options opts;
  16121. memset(&opts, 0, sizeof(opts));
  16122. opts.host = host;
  16123. opts.port = port;
  16124. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16125. }
  16126. #endif
  16127. static const struct {
  16128. const char *proto;
  16129. size_t proto_len;
  16130. unsigned default_port;
  16131. } abs_uri_protocols[] = {{"http://", 7, 80},
  16132. {"https://", 8, 443},
  16133. {"ws://", 5, 80},
  16134. {"wss://", 6, 443},
  16135. {NULL, 0, 0}};
  16136. /* Check if the uri is valid.
  16137. * return 0 for invalid uri,
  16138. * return 1 for *,
  16139. * return 2 for relative uri,
  16140. * return 3 for absolute uri without port,
  16141. * return 4 for absolute uri with port */
  16142. static int
  16143. get_uri_type(const char *uri)
  16144. {
  16145. int i;
  16146. const char *hostend, *portbegin;
  16147. char *portend;
  16148. unsigned long port;
  16149. /* According to the HTTP standard
  16150. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16151. * URI can be an asterisk (*) or should start with slash (relative uri),
  16152. * or it should start with the protocol (absolute uri). */
  16153. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16154. /* asterisk */
  16155. return 1;
  16156. }
  16157. /* Valid URIs according to RFC 3986
  16158. * (https://www.ietf.org/rfc/rfc3986.txt)
  16159. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16160. * and unreserved characters A-Z a-z 0-9 and -._~
  16161. * and % encoded symbols.
  16162. */
  16163. for (i = 0; uri[i] != 0; i++) {
  16164. if ((unsigned char)uri[i] < 33) {
  16165. /* control characters and spaces are invalid */
  16166. return 0;
  16167. }
  16168. /* Allow everything else here (See #894) */
  16169. }
  16170. /* A relative uri starts with a / character */
  16171. if (uri[0] == '/') {
  16172. /* relative uri */
  16173. return 2;
  16174. }
  16175. /* It could be an absolute uri: */
  16176. /* This function only checks if the uri is valid, not if it is
  16177. * addressing the current server. So civetweb can also be used
  16178. * as a proxy server. */
  16179. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16180. if (mg_strncasecmp(uri,
  16181. abs_uri_protocols[i].proto,
  16182. abs_uri_protocols[i].proto_len)
  16183. == 0) {
  16184. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16185. if (!hostend) {
  16186. return 0;
  16187. }
  16188. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16189. if (!portbegin) {
  16190. return 3;
  16191. }
  16192. port = strtoul(portbegin + 1, &portend, 10);
  16193. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16194. return 0;
  16195. }
  16196. return 4;
  16197. }
  16198. }
  16199. return 0;
  16200. }
  16201. /* Return NULL or the relative uri at the current server */
  16202. static const char *
  16203. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16204. {
  16205. const char *server_domain;
  16206. size_t server_domain_len;
  16207. size_t request_domain_len = 0;
  16208. unsigned long port = 0;
  16209. int i, auth_domain_check_enabled;
  16210. const char *hostbegin = NULL;
  16211. const char *hostend = NULL;
  16212. const char *portbegin;
  16213. char *portend;
  16214. auth_domain_check_enabled =
  16215. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16216. /* DNS is case insensitive, so use case insensitive string compare here
  16217. */
  16218. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16219. if (mg_strncasecmp(uri,
  16220. abs_uri_protocols[i].proto,
  16221. abs_uri_protocols[i].proto_len)
  16222. == 0) {
  16223. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16224. hostend = strchr(hostbegin, '/');
  16225. if (!hostend) {
  16226. return 0;
  16227. }
  16228. portbegin = strchr(hostbegin, ':');
  16229. if ((!portbegin) || (portbegin > hostend)) {
  16230. port = abs_uri_protocols[i].default_port;
  16231. request_domain_len = (size_t)(hostend - hostbegin);
  16232. } else {
  16233. port = strtoul(portbegin + 1, &portend, 10);
  16234. if ((portend != hostend) || (port <= 0)
  16235. || !is_valid_port(port)) {
  16236. return 0;
  16237. }
  16238. request_domain_len = (size_t)(portbegin - hostbegin);
  16239. }
  16240. /* protocol found, port set */
  16241. break;
  16242. }
  16243. }
  16244. if (!port) {
  16245. /* port remains 0 if the protocol is not found */
  16246. return 0;
  16247. }
  16248. /* Check if the request is directed to a different server. */
  16249. /* First check if the port is the same. */
  16250. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16251. /* Request is directed to a different port */
  16252. return 0;
  16253. }
  16254. /* Finally check if the server corresponds to the authentication
  16255. * domain of the server (the server domain).
  16256. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16257. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16258. * but do not allow substrings (like
  16259. * http://notmydomain.com/path/file.ext
  16260. * or http://mydomain.com.fake/path/file.ext).
  16261. */
  16262. if (auth_domain_check_enabled) {
  16263. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16264. server_domain_len = strlen(server_domain);
  16265. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16266. return 0;
  16267. }
  16268. if ((request_domain_len == server_domain_len)
  16269. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16270. /* Request is directed to this server - full name match. */
  16271. } else {
  16272. if (request_domain_len < (server_domain_len + 2)) {
  16273. /* Request is directed to another server: The server name
  16274. * is longer than the request name.
  16275. * Drop this case here to avoid overflows in the
  16276. * following checks. */
  16277. return 0;
  16278. }
  16279. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16280. /* Request is directed to another server: It could be a
  16281. * substring
  16282. * like notmyserver.com */
  16283. return 0;
  16284. }
  16285. if (0
  16286. != memcmp(server_domain,
  16287. hostbegin + request_domain_len - server_domain_len,
  16288. server_domain_len)) {
  16289. /* Request is directed to another server:
  16290. * The server name is different. */
  16291. return 0;
  16292. }
  16293. }
  16294. }
  16295. return hostend;
  16296. }
  16297. static int
  16298. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16299. {
  16300. if (ebuf_len > 0) {
  16301. ebuf[0] = '\0';
  16302. }
  16303. *err = 0;
  16304. reset_per_request_attributes(conn);
  16305. if (!conn) {
  16306. mg_snprintf(conn,
  16307. NULL, /* No truncation check for ebuf */
  16308. ebuf,
  16309. ebuf_len,
  16310. "%s",
  16311. "Internal error");
  16312. *err = 500;
  16313. return 0;
  16314. }
  16315. /* Set the time the request was received. This value should be used for
  16316. * timeouts. */
  16317. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16318. conn->request_len =
  16319. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16320. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16321. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16322. mg_snprintf(conn,
  16323. NULL, /* No truncation check for ebuf */
  16324. ebuf,
  16325. ebuf_len,
  16326. "%s",
  16327. "Invalid message size");
  16328. *err = 500;
  16329. return 0;
  16330. }
  16331. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16332. mg_snprintf(conn,
  16333. NULL, /* No truncation check for ebuf */
  16334. ebuf,
  16335. ebuf_len,
  16336. "%s",
  16337. "Message too large");
  16338. *err = 413;
  16339. return 0;
  16340. }
  16341. if (conn->request_len <= 0) {
  16342. if (conn->data_len > 0) {
  16343. mg_snprintf(conn,
  16344. NULL, /* No truncation check for ebuf */
  16345. ebuf,
  16346. ebuf_len,
  16347. "%s",
  16348. conn->request_len == -3 ? "Request timeout"
  16349. : "Malformed message");
  16350. *err = 400;
  16351. } else {
  16352. /* Server did not recv anything -> just close the connection */
  16353. conn->must_close = 1;
  16354. mg_snprintf(conn,
  16355. NULL, /* No truncation check for ebuf */
  16356. ebuf,
  16357. ebuf_len,
  16358. "%s",
  16359. "No data received");
  16360. *err = 0;
  16361. }
  16362. return 0;
  16363. }
  16364. return 1;
  16365. }
  16366. static int
  16367. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16368. {
  16369. const char *cl;
  16370. conn->connection_type =
  16371. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16372. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16373. return 0;
  16374. }
  16375. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16376. <= 0) {
  16377. mg_snprintf(conn,
  16378. NULL, /* No truncation check for ebuf */
  16379. ebuf,
  16380. ebuf_len,
  16381. "%s",
  16382. "Bad request");
  16383. *err = 400;
  16384. return 0;
  16385. }
  16386. /* Message is a valid request */
  16387. if (!switch_domain_context(conn)) {
  16388. mg_snprintf(conn,
  16389. NULL, /* No truncation check for ebuf */
  16390. ebuf,
  16391. ebuf_len,
  16392. "%s",
  16393. "Bad request: Host mismatch");
  16394. *err = 400;
  16395. return 0;
  16396. }
  16397. #if USE_ZLIB
  16398. if (((cl = get_header(conn->request_info.http_headers,
  16399. conn->request_info.num_headers,
  16400. "Accept-Encoding"))
  16401. != NULL)
  16402. && strstr(cl, "gzip")) {
  16403. conn->accept_gzip = 1;
  16404. }
  16405. #endif
  16406. if (((cl = get_header(conn->request_info.http_headers,
  16407. conn->request_info.num_headers,
  16408. "Transfer-Encoding"))
  16409. != NULL)
  16410. && mg_strcasecmp(cl, "identity")) {
  16411. if (mg_strcasecmp(cl, "chunked")) {
  16412. mg_snprintf(conn,
  16413. NULL, /* No truncation check for ebuf */
  16414. ebuf,
  16415. ebuf_len,
  16416. "%s",
  16417. "Bad request");
  16418. *err = 400;
  16419. return 0;
  16420. }
  16421. conn->is_chunked = 1;
  16422. conn->content_len = 0; /* not yet read */
  16423. } else if ((cl = get_header(conn->request_info.http_headers,
  16424. conn->request_info.num_headers,
  16425. "Content-Length"))
  16426. != NULL) {
  16427. /* Request has content length set */
  16428. char *endptr = NULL;
  16429. conn->content_len = strtoll(cl, &endptr, 10);
  16430. if ((endptr == cl) || (conn->content_len < 0)) {
  16431. mg_snprintf(conn,
  16432. NULL, /* No truncation check for ebuf */
  16433. ebuf,
  16434. ebuf_len,
  16435. "%s",
  16436. "Bad request");
  16437. *err = 411;
  16438. return 0;
  16439. }
  16440. /* Publish the content length back to the request info. */
  16441. conn->request_info.content_length = conn->content_len;
  16442. } else {
  16443. /* There is no exception, see RFC7230. */
  16444. conn->content_len = 0;
  16445. }
  16446. return 1;
  16447. }
  16448. /* conn is assumed to be valid in this internal function */
  16449. static int
  16450. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16451. {
  16452. const char *cl;
  16453. conn->connection_type =
  16454. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16455. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16456. return 0;
  16457. }
  16458. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16459. <= 0) {
  16460. mg_snprintf(conn,
  16461. NULL, /* No truncation check for ebuf */
  16462. ebuf,
  16463. ebuf_len,
  16464. "%s",
  16465. "Bad response");
  16466. *err = 400;
  16467. return 0;
  16468. }
  16469. /* Message is a valid response */
  16470. if (((cl = get_header(conn->response_info.http_headers,
  16471. conn->response_info.num_headers,
  16472. "Transfer-Encoding"))
  16473. != NULL)
  16474. && mg_strcasecmp(cl, "identity")) {
  16475. if (mg_strcasecmp(cl, "chunked")) {
  16476. mg_snprintf(conn,
  16477. NULL, /* No truncation check for ebuf */
  16478. ebuf,
  16479. ebuf_len,
  16480. "%s",
  16481. "Bad request");
  16482. *err = 400;
  16483. return 0;
  16484. }
  16485. conn->is_chunked = 1;
  16486. conn->content_len = 0; /* not yet read */
  16487. } else if ((cl = get_header(conn->response_info.http_headers,
  16488. conn->response_info.num_headers,
  16489. "Content-Length"))
  16490. != NULL) {
  16491. char *endptr = NULL;
  16492. conn->content_len = strtoll(cl, &endptr, 10);
  16493. if ((endptr == cl) || (conn->content_len < 0)) {
  16494. mg_snprintf(conn,
  16495. NULL, /* No truncation check for ebuf */
  16496. ebuf,
  16497. ebuf_len,
  16498. "%s",
  16499. "Bad request");
  16500. *err = 411;
  16501. return 0;
  16502. }
  16503. /* Publish the content length back to the response info. */
  16504. conn->response_info.content_length = conn->content_len;
  16505. /* TODO: check if it is still used in response_info */
  16506. conn->request_info.content_length = conn->content_len;
  16507. /* TODO: we should also consider HEAD method */
  16508. if (conn->response_info.status_code == 304) {
  16509. conn->content_len = 0;
  16510. }
  16511. } else {
  16512. /* TODO: we should also consider HEAD method */
  16513. if (((conn->response_info.status_code >= 100)
  16514. && (conn->response_info.status_code <= 199))
  16515. || (conn->response_info.status_code == 204)
  16516. || (conn->response_info.status_code == 304)) {
  16517. conn->content_len = 0;
  16518. } else {
  16519. conn->content_len = -1; /* unknown content length */
  16520. }
  16521. }
  16522. return 1;
  16523. }
  16524. CIVETWEB_API int
  16525. mg_get_response(struct mg_connection *conn,
  16526. char *ebuf,
  16527. size_t ebuf_len,
  16528. int timeout)
  16529. {
  16530. int err, ret;
  16531. char txt[32]; /* will not overflow */
  16532. char *save_timeout;
  16533. char *new_timeout;
  16534. if (ebuf_len > 0) {
  16535. ebuf[0] = '\0';
  16536. }
  16537. if (!conn) {
  16538. mg_snprintf(conn,
  16539. NULL, /* No truncation check for ebuf */
  16540. ebuf,
  16541. ebuf_len,
  16542. "%s",
  16543. "Parameter error");
  16544. return -1;
  16545. }
  16546. /* Reset the previous responses */
  16547. conn->data_len = 0;
  16548. /* Implementation of API function for HTTP clients */
  16549. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16550. if (timeout >= 0) {
  16551. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16552. new_timeout = txt;
  16553. } else {
  16554. new_timeout = NULL;
  16555. }
  16556. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16557. ret = get_response(conn, ebuf, ebuf_len, &err);
  16558. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16559. /* TODO: here, the URI is the http response code */
  16560. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16561. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16562. /* TODO (mid): Define proper return values - maybe return length?
  16563. * For the first test use <0 for error and >0 for OK */
  16564. return (ret == 0) ? -1 : +1;
  16565. }
  16566. CIVETWEB_API struct mg_connection *
  16567. mg_download(const char *host,
  16568. int port,
  16569. int use_ssl,
  16570. char *ebuf,
  16571. size_t ebuf_len,
  16572. const char *fmt,
  16573. ...)
  16574. {
  16575. struct mg_connection *conn;
  16576. va_list ap;
  16577. int i;
  16578. int reqerr;
  16579. if (ebuf_len > 0) {
  16580. ebuf[0] = '\0';
  16581. }
  16582. va_start(ap, fmt);
  16583. /* open a connection */
  16584. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16585. if (conn != NULL) {
  16586. i = mg_vprintf(conn, fmt, ap);
  16587. if (i <= 0) {
  16588. mg_snprintf(conn,
  16589. NULL, /* No truncation check for ebuf */
  16590. ebuf,
  16591. ebuf_len,
  16592. "%s",
  16593. "Error sending request");
  16594. } else {
  16595. /* make sure the buffer is clear */
  16596. conn->data_len = 0;
  16597. get_response(conn, ebuf, ebuf_len, &reqerr);
  16598. /* TODO: here, the URI is the http response code */
  16599. conn->request_info.local_uri = conn->request_info.request_uri;
  16600. }
  16601. }
  16602. /* if an error occurred, close the connection */
  16603. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16604. mg_close_connection(conn);
  16605. conn = NULL;
  16606. }
  16607. va_end(ap);
  16608. return conn;
  16609. }
  16610. struct websocket_client_thread_data {
  16611. struct mg_connection *conn;
  16612. mg_websocket_data_handler data_handler;
  16613. mg_websocket_close_handler close_handler;
  16614. void *callback_data;
  16615. };
  16616. #if defined(USE_WEBSOCKET)
  16617. #if defined(_WIN32)
  16618. static unsigned __stdcall websocket_client_thread(void *data)
  16619. #else
  16620. static void *
  16621. websocket_client_thread(void *data)
  16622. #endif
  16623. {
  16624. struct websocket_client_thread_data *cdata =
  16625. (struct websocket_client_thread_data *)data;
  16626. void *user_thread_ptr = NULL;
  16627. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16628. struct sigaction sa;
  16629. /* Ignore SIGPIPE */
  16630. memset(&sa, 0, sizeof(sa));
  16631. sa.sa_handler = SIG_IGN;
  16632. sigaction(SIGPIPE, &sa, NULL);
  16633. #endif
  16634. mg_set_thread_name("ws-clnt");
  16635. if (cdata->conn->phys_ctx) {
  16636. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16637. /* 3 indicates a websocket client thread */
  16638. /* TODO: check if conn->phys_ctx can be set */
  16639. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16640. cdata->conn->phys_ctx, 3);
  16641. }
  16642. }
  16643. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16644. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16645. if (cdata->close_handler != NULL) {
  16646. cdata->close_handler(cdata->conn, cdata->callback_data);
  16647. }
  16648. /* The websocket_client context has only this thread. If it runs out,
  16649. set the stop_flag to 2 (= "stopped"). */
  16650. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16651. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16652. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16653. 3,
  16654. user_thread_ptr);
  16655. }
  16656. mg_free((void *)cdata);
  16657. #if defined(_WIN32)
  16658. return 0;
  16659. #else
  16660. return NULL;
  16661. #endif
  16662. }
  16663. #endif
  16664. #if defined(USE_WEBSOCKET)
  16665. static void
  16666. generate_websocket_magic(char *magic25)
  16667. {
  16668. uint64_t rnd;
  16669. unsigned char buffer[2 * sizeof(rnd)];
  16670. rnd = get_random();
  16671. memcpy(buffer, &rnd, sizeof(rnd));
  16672. rnd = get_random();
  16673. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16674. size_t dst_len = 24 + 1;
  16675. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16676. }
  16677. #endif
  16678. static struct mg_connection *
  16679. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16680. int use_ssl,
  16681. char *error_buffer,
  16682. size_t error_buffer_size,
  16683. const char *path,
  16684. const char *origin,
  16685. const char *extensions,
  16686. mg_websocket_data_handler data_func,
  16687. mg_websocket_close_handler close_func,
  16688. void *user_data)
  16689. {
  16690. struct mg_connection *conn = NULL;
  16691. #if defined(USE_WEBSOCKET)
  16692. struct websocket_client_thread_data *thread_data;
  16693. char magic[32];
  16694. generate_websocket_magic(magic);
  16695. const char *host = client_options->host;
  16696. int i;
  16697. struct mg_init_data init;
  16698. struct mg_error_data error;
  16699. memset(&init, 0, sizeof(init));
  16700. memset(&error, 0, sizeof(error));
  16701. error.text_buffer_size = error_buffer_size;
  16702. error.text = error_buffer;
  16703. #if defined(__clang__)
  16704. #pragma clang diagnostic push
  16705. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16706. #endif
  16707. /* Establish the client connection and request upgrade */
  16708. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16709. /* Connection object will be null if something goes wrong */
  16710. if (conn == NULL) {
  16711. /* error_buffer should be already filled ... */
  16712. if (!error_buffer[0]) {
  16713. /* ... if not add an error message */
  16714. mg_snprintf(conn,
  16715. NULL, /* No truncation check for ebuf */
  16716. error_buffer,
  16717. error_buffer_size,
  16718. "Unexpected error");
  16719. }
  16720. return NULL;
  16721. }
  16722. if (origin != NULL) {
  16723. if (extensions != NULL) {
  16724. i = mg_printf(conn,
  16725. "GET %s HTTP/1.1\r\n"
  16726. "Host: %s\r\n"
  16727. "Upgrade: websocket\r\n"
  16728. "Connection: Upgrade\r\n"
  16729. "Sec-WebSocket-Key: %s\r\n"
  16730. "Sec-WebSocket-Version: 13\r\n"
  16731. "Sec-WebSocket-Extensions: %s\r\n"
  16732. "Origin: %s\r\n"
  16733. "\r\n",
  16734. path,
  16735. host,
  16736. magic,
  16737. extensions,
  16738. origin);
  16739. } else {
  16740. i = mg_printf(conn,
  16741. "GET %s HTTP/1.1\r\n"
  16742. "Host: %s\r\n"
  16743. "Upgrade: websocket\r\n"
  16744. "Connection: Upgrade\r\n"
  16745. "Sec-WebSocket-Key: %s\r\n"
  16746. "Sec-WebSocket-Version: 13\r\n"
  16747. "Origin: %s\r\n"
  16748. "\r\n",
  16749. path,
  16750. host,
  16751. magic,
  16752. origin);
  16753. }
  16754. } else {
  16755. if (extensions != NULL) {
  16756. i = mg_printf(conn,
  16757. "GET %s HTTP/1.1\r\n"
  16758. "Host: %s\r\n"
  16759. "Upgrade: websocket\r\n"
  16760. "Connection: Upgrade\r\n"
  16761. "Sec-WebSocket-Key: %s\r\n"
  16762. "Sec-WebSocket-Version: 13\r\n"
  16763. "Sec-WebSocket-Extensions: %s\r\n"
  16764. "\r\n",
  16765. path,
  16766. host,
  16767. magic,
  16768. extensions);
  16769. } else {
  16770. i = mg_printf(conn,
  16771. "GET %s HTTP/1.1\r\n"
  16772. "Host: %s\r\n"
  16773. "Upgrade: websocket\r\n"
  16774. "Connection: Upgrade\r\n"
  16775. "Sec-WebSocket-Key: %s\r\n"
  16776. "Sec-WebSocket-Version: 13\r\n"
  16777. "\r\n",
  16778. path,
  16779. host,
  16780. magic);
  16781. }
  16782. }
  16783. if (i <= 0) {
  16784. mg_snprintf(conn,
  16785. NULL, /* No truncation check for ebuf */
  16786. error_buffer,
  16787. error_buffer_size,
  16788. "%s",
  16789. "Error sending request");
  16790. mg_close_connection(conn);
  16791. return NULL;
  16792. }
  16793. conn->data_len = 0;
  16794. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16795. mg_close_connection(conn);
  16796. return NULL;
  16797. }
  16798. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16799. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16800. #if defined(__clang__)
  16801. #pragma clang diagnostic pop
  16802. #endif
  16803. if (conn->response_info.status_code != 101) {
  16804. /* We sent an "upgrade" request. For a correct websocket
  16805. * protocol handshake, we expect a "101 Continue" response.
  16806. * Otherwise it is a protocol violation. Maybe the HTTP
  16807. * Server does not know websockets. */
  16808. if (!*error_buffer) {
  16809. /* set an error, if not yet set */
  16810. mg_snprintf(conn,
  16811. NULL, /* No truncation check for ebuf */
  16812. error_buffer,
  16813. error_buffer_size,
  16814. "Unexpected server reply");
  16815. }
  16816. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16817. mg_close_connection(conn);
  16818. return NULL;
  16819. }
  16820. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16821. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16822. if (!thread_data) {
  16823. DEBUG_TRACE("%s\r\n", "Out of memory");
  16824. mg_close_connection(conn);
  16825. return NULL;
  16826. }
  16827. thread_data->conn = conn;
  16828. thread_data->data_handler = data_func;
  16829. thread_data->close_handler = close_func;
  16830. thread_data->callback_data = user_data;
  16831. conn->phys_ctx->worker_threadids =
  16832. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16833. if (!conn->phys_ctx->worker_threadids) {
  16834. DEBUG_TRACE("%s\r\n", "Out of memory");
  16835. mg_free(thread_data);
  16836. mg_close_connection(conn);
  16837. return NULL;
  16838. }
  16839. /* Now upgrade to ws/wss client context */
  16840. conn->phys_ctx->user_data = user_data;
  16841. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16842. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16843. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16844. /* Start a thread to read the websocket client connection
  16845. * This thread will automatically stop when mg_disconnect is
  16846. * called on the client connection */
  16847. if (mg_start_thread_with_id(websocket_client_thread,
  16848. thread_data,
  16849. conn->phys_ctx->worker_threadids)
  16850. != 0) {
  16851. conn->phys_ctx->spawned_worker_threads = 0;
  16852. mg_free(thread_data);
  16853. mg_close_connection(conn);
  16854. conn = NULL;
  16855. DEBUG_TRACE("%s",
  16856. "Websocket client connect thread could not be started\r\n");
  16857. }
  16858. #else
  16859. /* Appease "unused parameter" warnings */
  16860. (void)client_options;
  16861. (void)use_ssl;
  16862. (void)error_buffer;
  16863. (void)error_buffer_size;
  16864. (void)path;
  16865. (void)origin;
  16866. (void)extensions;
  16867. (void)user_data;
  16868. (void)data_func;
  16869. (void)close_func;
  16870. #endif
  16871. return conn;
  16872. }
  16873. CIVETWEB_API struct mg_connection *
  16874. mg_connect_websocket_client(const char *host,
  16875. int port,
  16876. int use_ssl,
  16877. char *error_buffer,
  16878. size_t error_buffer_size,
  16879. const char *path,
  16880. const char *origin,
  16881. mg_websocket_data_handler data_func,
  16882. mg_websocket_close_handler close_func,
  16883. void *user_data)
  16884. {
  16885. struct mg_client_options client_options;
  16886. memset(&client_options, 0, sizeof(client_options));
  16887. client_options.host = host;
  16888. client_options.port = port;
  16889. return mg_connect_websocket_client_impl(&client_options,
  16890. use_ssl,
  16891. error_buffer,
  16892. error_buffer_size,
  16893. path,
  16894. origin,
  16895. NULL,
  16896. data_func,
  16897. close_func,
  16898. user_data);
  16899. }
  16900. CIVETWEB_API struct mg_connection *
  16901. mg_connect_websocket_client_secure(
  16902. const struct mg_client_options *client_options,
  16903. char *error_buffer,
  16904. size_t error_buffer_size,
  16905. const char *path,
  16906. const char *origin,
  16907. mg_websocket_data_handler data_func,
  16908. mg_websocket_close_handler close_func,
  16909. void *user_data)
  16910. {
  16911. if (!client_options) {
  16912. return NULL;
  16913. }
  16914. return mg_connect_websocket_client_impl(client_options,
  16915. 1,
  16916. error_buffer,
  16917. error_buffer_size,
  16918. path,
  16919. origin,
  16920. NULL,
  16921. data_func,
  16922. close_func,
  16923. user_data);
  16924. }
  16925. CIVETWEB_API struct mg_connection *
  16926. mg_connect_websocket_client_extensions(const char *host,
  16927. int port,
  16928. int use_ssl,
  16929. char *error_buffer,
  16930. size_t error_buffer_size,
  16931. const char *path,
  16932. const char *origin,
  16933. const char *extensions,
  16934. mg_websocket_data_handler data_func,
  16935. mg_websocket_close_handler close_func,
  16936. void *user_data)
  16937. {
  16938. struct mg_client_options client_options;
  16939. memset(&client_options, 0, sizeof(client_options));
  16940. client_options.host = host;
  16941. client_options.port = port;
  16942. return mg_connect_websocket_client_impl(&client_options,
  16943. use_ssl,
  16944. error_buffer,
  16945. error_buffer_size,
  16946. path,
  16947. origin,
  16948. extensions,
  16949. data_func,
  16950. close_func,
  16951. user_data);
  16952. }
  16953. CIVETWEB_API struct mg_connection *
  16954. mg_connect_websocket_client_secure_extensions(
  16955. const struct mg_client_options *client_options,
  16956. char *error_buffer,
  16957. size_t error_buffer_size,
  16958. const char *path,
  16959. const char *origin,
  16960. const char *extensions,
  16961. mg_websocket_data_handler data_func,
  16962. mg_websocket_close_handler close_func,
  16963. void *user_data)
  16964. {
  16965. if (!client_options) {
  16966. return NULL;
  16967. }
  16968. return mg_connect_websocket_client_impl(client_options,
  16969. 1,
  16970. error_buffer,
  16971. error_buffer_size,
  16972. path,
  16973. origin,
  16974. extensions,
  16975. data_func,
  16976. close_func,
  16977. user_data);
  16978. }
  16979. /* Prepare connection data structure */
  16980. static void
  16981. init_connection(struct mg_connection *conn)
  16982. {
  16983. /* Is keep alive allowed by the server */
  16984. int keep_alive_enabled =
  16985. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16986. if (!keep_alive_enabled) {
  16987. conn->must_close = 1;
  16988. }
  16989. /* Important: on new connection, reset the receiving buffer. Credit
  16990. * goes to crule42. */
  16991. conn->data_len = 0;
  16992. conn->handled_requests = 0;
  16993. conn->connection_type = CONNECTION_TYPE_INVALID;
  16994. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16995. mg_set_user_connection_data(conn, NULL);
  16996. #if defined(USE_SERVER_STATS)
  16997. conn->conn_state = 2; /* init */
  16998. #endif
  16999. /* call the init_connection callback if assigned */
  17000. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17001. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17002. void *conn_data = NULL;
  17003. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17004. mg_set_user_connection_data(conn, conn_data);
  17005. }
  17006. }
  17007. }
  17008. /* Process a connection - may handle multiple requests
  17009. * using the same connection.
  17010. * Must be called with a valid connection (conn and
  17011. * conn->phys_ctx must be valid).
  17012. */
  17013. static void
  17014. process_new_connection(struct mg_connection *conn)
  17015. {
  17016. struct mg_request_info *ri = &conn->request_info;
  17017. int keep_alive, discard_len;
  17018. char ebuf[100];
  17019. const char *hostend;
  17020. int reqerr, uri_type;
  17021. #if defined(USE_SERVER_STATS)
  17022. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17023. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17024. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17025. #endif
  17026. DEBUG_TRACE("Start processing connection from %s",
  17027. conn->request_info.remote_addr);
  17028. /* Loop over multiple requests sent using the same connection
  17029. * (while "keep alive"). */
  17030. do {
  17031. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17032. conn->handled_requests + 1);
  17033. #if defined(USE_SERVER_STATS)
  17034. conn->conn_state = 3; /* ready */
  17035. #endif
  17036. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17037. /* The request sent by the client could not be understood by
  17038. * the server, or it was incomplete or a timeout. Send an
  17039. * error message and close the connection. */
  17040. if (reqerr > 0) {
  17041. DEBUG_ASSERT(ebuf[0] != '\0');
  17042. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17043. }
  17044. } else if (strcmp(ri->http_version, "1.0")
  17045. && strcmp(ri->http_version, "1.1")) {
  17046. /* HTTP/2 is not allowed here */
  17047. mg_snprintf(conn,
  17048. NULL, /* No truncation check for ebuf */
  17049. ebuf,
  17050. sizeof(ebuf),
  17051. "Bad HTTP version: [%s]",
  17052. ri->http_version);
  17053. mg_send_http_error(conn, 505, "%s", ebuf);
  17054. }
  17055. if (ebuf[0] == '\0') {
  17056. uri_type = get_uri_type(conn->request_info.request_uri);
  17057. switch (uri_type) {
  17058. case 1:
  17059. /* Asterisk */
  17060. conn->request_info.local_uri_raw = 0;
  17061. /* TODO: Deal with '*'. */
  17062. break;
  17063. case 2:
  17064. /* relative uri */
  17065. conn->request_info.local_uri_raw =
  17066. conn->request_info.request_uri;
  17067. break;
  17068. case 3:
  17069. case 4:
  17070. /* absolute uri (with/without port) */
  17071. hostend = get_rel_url_at_current_server(
  17072. conn->request_info.request_uri, conn);
  17073. if (hostend) {
  17074. conn->request_info.local_uri_raw = hostend;
  17075. } else {
  17076. conn->request_info.local_uri_raw = NULL;
  17077. }
  17078. break;
  17079. default:
  17080. mg_snprintf(conn,
  17081. NULL, /* No truncation check for ebuf */
  17082. ebuf,
  17083. sizeof(ebuf),
  17084. "Invalid URI");
  17085. mg_send_http_error(conn, 400, "%s", ebuf);
  17086. conn->request_info.local_uri_raw = NULL;
  17087. break;
  17088. }
  17089. conn->request_info.local_uri =
  17090. (char *)conn->request_info.local_uri_raw;
  17091. }
  17092. if (ebuf[0] != '\0') {
  17093. conn->protocol_type = -1;
  17094. } else {
  17095. /* HTTP/1 allows protocol upgrade */
  17096. conn->protocol_type = should_switch_to_protocol(conn);
  17097. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17098. /* This will occur, if a HTTP/1.1 request should be upgraded
  17099. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17100. * Since most (all?) major browsers only support HTTP/2 using
  17101. * ALPN, this is hard to test and very low priority.
  17102. * Deactivate it (at least for now).
  17103. */
  17104. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17105. }
  17106. }
  17107. DEBUG_TRACE("http: %s, error: %s",
  17108. (ri->http_version ? ri->http_version : "none"),
  17109. (ebuf[0] ? ebuf : "none"));
  17110. if (ebuf[0] == '\0') {
  17111. if (conn->request_info.local_uri) {
  17112. /* handle request to local server */
  17113. handle_request_stat_log(conn);
  17114. } else {
  17115. /* TODO: handle non-local request (PROXY) */
  17116. conn->must_close = 1;
  17117. }
  17118. } else {
  17119. conn->must_close = 1;
  17120. }
  17121. /* Response complete. Free header buffer */
  17122. free_buffered_response_header_list(conn);
  17123. if (ri->remote_user != NULL) {
  17124. mg_free((void *)ri->remote_user);
  17125. /* Important! When having connections with and without auth
  17126. * would cause double free and then crash */
  17127. ri->remote_user = NULL;
  17128. }
  17129. /* NOTE(lsm): order is important here. should_keep_alive() call
  17130. * is using parsed request, which will be invalid after
  17131. * memmove's below.
  17132. * Therefore, memorize should_keep_alive() result now for later
  17133. * use in loop exit condition. */
  17134. /* Enable it only if this request is completely discardable. */
  17135. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17136. && should_keep_alive(conn) && (conn->content_len >= 0)
  17137. && (conn->request_len > 0)
  17138. && ((conn->is_chunked == 4)
  17139. || (!conn->is_chunked
  17140. && ((conn->consumed_content == conn->content_len)
  17141. || ((conn->request_len + conn->content_len)
  17142. <= conn->data_len))))
  17143. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17144. if (keep_alive) {
  17145. /* Discard all buffered data for this request */
  17146. discard_len =
  17147. ((conn->request_len + conn->content_len) < conn->data_len)
  17148. ? (int)(conn->request_len + conn->content_len)
  17149. : conn->data_len;
  17150. conn->data_len -= discard_len;
  17151. if (conn->data_len > 0) {
  17152. DEBUG_TRACE("discard_len = %d", discard_len);
  17153. memmove(conn->buf,
  17154. conn->buf + discard_len,
  17155. (size_t)conn->data_len);
  17156. }
  17157. }
  17158. DEBUG_ASSERT(conn->data_len >= 0);
  17159. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17160. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17161. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17162. (long int)conn->data_len,
  17163. (long int)conn->buf_size);
  17164. break;
  17165. }
  17166. conn->handled_requests++;
  17167. } while (keep_alive);
  17168. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17169. conn->request_info.remote_addr,
  17170. difftime(time(NULL), conn->conn_birth_time));
  17171. close_connection(conn);
  17172. #if defined(USE_SERVER_STATS)
  17173. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17174. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17175. #endif
  17176. }
  17177. static int
  17178. mg_start_worker_thread(struct mg_context *ctx,
  17179. int only_if_no_idle_threads); /* forward declaration */
  17180. #if defined(ALTERNATIVE_QUEUE)
  17181. static void
  17182. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17183. {
  17184. unsigned int i;
  17185. (void)mg_start_worker_thread(
  17186. ctx, 1); /* will start a worker-thread only if there aren't currently
  17187. any idle worker-threads */
  17188. while (!ctx->stop_flag) {
  17189. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17190. /* find a free worker slot and signal it */
  17191. if (ctx->client_socks[i].in_use == 2) {
  17192. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17193. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17194. ctx->client_socks[i] = *sp;
  17195. ctx->client_socks[i].in_use = 1;
  17196. /* socket has been moved to the consumer */
  17197. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17198. (void)event_signal(ctx->client_wait_events[i]);
  17199. return;
  17200. }
  17201. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17202. }
  17203. }
  17204. /* queue is full */
  17205. mg_sleep(1);
  17206. }
  17207. /* must consume */
  17208. set_blocking_mode(sp->sock);
  17209. closesocket(sp->sock);
  17210. }
  17211. static int
  17212. consume_socket(struct mg_context *ctx,
  17213. struct socket *sp,
  17214. int thread_index,
  17215. int counter_was_preincremented)
  17216. {
  17217. DEBUG_TRACE("%s", "going idle");
  17218. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17219. if (counter_was_preincremented
  17220. == 0) { /* first call only: the master-thread pre-incremented this
  17221. before he spawned us */
  17222. ctx->idle_worker_thread_count++;
  17223. }
  17224. ctx->client_socks[thread_index].in_use = 2;
  17225. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17226. event_wait(ctx->client_wait_events[thread_index]);
  17227. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17228. *sp = ctx->client_socks[thread_index];
  17229. if (ctx->stop_flag) {
  17230. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17231. if (sp->in_use == 1) {
  17232. /* must consume */
  17233. set_blocking_mode(sp->sock);
  17234. closesocket(sp->sock);
  17235. }
  17236. return 0;
  17237. }
  17238. ctx->idle_worker_thread_count--;
  17239. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17240. if (sp->in_use == 1) {
  17241. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17242. return 1;
  17243. }
  17244. /* must not reach here */
  17245. DEBUG_ASSERT(0);
  17246. return 0;
  17247. }
  17248. #else /* ALTERNATIVE_QUEUE */
  17249. /* Worker threads take accepted socket from the queue */
  17250. static int
  17251. consume_socket(struct mg_context *ctx,
  17252. struct socket *sp,
  17253. int thread_index,
  17254. int counter_was_preincremented)
  17255. {
  17256. (void)thread_index;
  17257. DEBUG_TRACE("%s", "going idle");
  17258. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17259. if (counter_was_preincremented
  17260. == 0) { /* first call only: the master-thread pre-incremented this
  17261. before he spawned us */
  17262. ctx->idle_worker_thread_count++;
  17263. }
  17264. /* If the queue is empty, wait. We're idle at this point. */
  17265. while ((ctx->sq_head == ctx->sq_tail)
  17266. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17267. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17268. }
  17269. /* If we're stopping, sq_head may be equal to sq_tail. */
  17270. if (ctx->sq_head > ctx->sq_tail) {
  17271. /* Copy socket from the queue and increment tail */
  17272. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17273. ctx->sq_tail++;
  17274. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17275. /* Wrap pointers if needed */
  17276. while (ctx->sq_tail > ctx->sq_size) {
  17277. ctx->sq_tail -= ctx->sq_size;
  17278. ctx->sq_head -= ctx->sq_size;
  17279. }
  17280. }
  17281. (void)pthread_cond_signal(&ctx->sq_empty);
  17282. ctx->idle_worker_thread_count--;
  17283. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17284. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17285. }
  17286. /* Master thread adds accepted socket to a queue */
  17287. static void
  17288. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17289. {
  17290. int queue_filled;
  17291. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17292. queue_filled = ctx->sq_head - ctx->sq_tail;
  17293. /* If the queue is full, wait */
  17294. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17295. && (queue_filled >= ctx->sq_size)) {
  17296. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17297. #if defined(USE_SERVER_STATS)
  17298. if (queue_filled > ctx->sq_max_fill) {
  17299. ctx->sq_max_fill = queue_filled;
  17300. }
  17301. #endif
  17302. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17303. ctx->sq_blocked = 0; /* Not blocked now */
  17304. queue_filled = ctx->sq_head - ctx->sq_tail;
  17305. }
  17306. if (queue_filled < ctx->sq_size) {
  17307. /* Copy socket to the queue and increment head */
  17308. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17309. ctx->sq_head++;
  17310. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17311. }
  17312. queue_filled = ctx->sq_head - ctx->sq_tail;
  17313. #if defined(USE_SERVER_STATS)
  17314. if (queue_filled > ctx->sq_max_fill) {
  17315. ctx->sq_max_fill = queue_filled;
  17316. }
  17317. #endif
  17318. (void)pthread_cond_signal(&ctx->sq_full);
  17319. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17320. (void)mg_start_worker_thread(
  17321. ctx, 1); /* will start a worker-thread only if there aren't currently
  17322. any idle worker-threads */
  17323. }
  17324. #endif /* ALTERNATIVE_QUEUE */
  17325. static void
  17326. worker_thread_run(struct mg_connection *conn)
  17327. {
  17328. struct mg_context *ctx = conn->phys_ctx;
  17329. int thread_index;
  17330. struct mg_workerTLS tls;
  17331. int first_call_to_consume_socket = 1;
  17332. mg_set_thread_name("worker");
  17333. tls.is_master = 0;
  17334. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17335. #if defined(_WIN32)
  17336. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17337. #endif
  17338. /* Initialize thread local storage before calling any callback */
  17339. pthread_setspecific(sTlsKey, &tls);
  17340. /* Check if there is a user callback */
  17341. if (ctx->callbacks.init_thread) {
  17342. /* call init_thread for a worker thread (type 1), and store the
  17343. * return value */
  17344. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17345. } else {
  17346. /* No callback: set user pointer to NULL */
  17347. tls.user_ptr = NULL;
  17348. }
  17349. /* Connection structure has been pre-allocated */
  17350. thread_index = (int)(conn - ctx->worker_connections);
  17351. if ((thread_index < 0)
  17352. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17353. mg_cry_ctx_internal(ctx,
  17354. "Internal error: Invalid worker index %i",
  17355. thread_index);
  17356. return;
  17357. }
  17358. /* Request buffers are not pre-allocated. They are private to the
  17359. * request and do not contain any state information that might be
  17360. * of interest to anyone observing a server status. */
  17361. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17362. if (conn->buf == NULL) {
  17363. mg_cry_ctx_internal(
  17364. ctx,
  17365. "Out of memory: Cannot allocate buffer for worker %i",
  17366. thread_index);
  17367. return;
  17368. }
  17369. conn->buf_size = (int)ctx->max_request_size;
  17370. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17371. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17372. conn->request_info.user_data = ctx->user_data;
  17373. /* Allocate a mutex for this connection to allow communication both
  17374. * within the request handler and from elsewhere in the application
  17375. */
  17376. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17377. mg_free(conn->buf);
  17378. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17379. return;
  17380. }
  17381. #if defined(USE_SERVER_STATS)
  17382. conn->conn_state = 1; /* not consumed */
  17383. #endif
  17384. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17385. * signal sq_empty condvar to wake up the master waiting in
  17386. * produce_socket() */
  17387. while (consume_socket(
  17388. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17389. first_call_to_consume_socket = 0;
  17390. /* New connections must start with new protocol negotiation */
  17391. tls.alpn_proto = NULL;
  17392. #if defined(USE_SERVER_STATS)
  17393. conn->conn_close_time = 0;
  17394. #endif
  17395. conn->conn_birth_time = time(NULL);
  17396. /* Fill in IP, port info early so even if SSL setup below fails,
  17397. * error handler would have the corresponding info.
  17398. * Thanks to Johannes Winkelmann for the patch.
  17399. */
  17400. conn->request_info.remote_port =
  17401. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17402. conn->request_info.server_port =
  17403. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17404. sockaddr_to_string(conn->request_info.remote_addr,
  17405. sizeof(conn->request_info.remote_addr),
  17406. &conn->client.rsa);
  17407. DEBUG_TRACE("Incoming %sconnection from %s",
  17408. (conn->client.is_ssl ? "SSL " : ""),
  17409. conn->request_info.remote_addr);
  17410. conn->request_info.is_ssl = conn->client.is_ssl;
  17411. if (conn->client.is_ssl) {
  17412. #if defined(USE_MBEDTLS)
  17413. /* HTTPS connection */
  17414. if (mbed_ssl_accept(&(conn->ssl),
  17415. conn->dom_ctx->ssl_ctx,
  17416. (int *)&(conn->client.sock),
  17417. conn->phys_ctx)
  17418. == 0) {
  17419. /* conn->dom_ctx is set in get_request */
  17420. /* process HTTPS connection */
  17421. init_connection(conn);
  17422. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17423. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17424. process_new_connection(conn);
  17425. } else {
  17426. /* make sure the connection is cleaned up on SSL failure */
  17427. close_connection(conn);
  17428. }
  17429. #elif !defined(NO_SSL)
  17430. /* HTTPS connection */
  17431. if (sslize(conn, SSL_accept, NULL)) {
  17432. /* conn->dom_ctx is set in get_request */
  17433. /* Get SSL client certificate information (if set) */
  17434. struct mg_client_cert client_cert;
  17435. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17436. conn->request_info.client_cert = &client_cert;
  17437. }
  17438. /* process HTTPS connection */
  17439. #if defined(USE_HTTP2)
  17440. if ((tls.alpn_proto != NULL)
  17441. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17442. /* process HTTPS/2 connection */
  17443. init_connection(conn);
  17444. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17445. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17446. conn->content_len =
  17447. -1; /* content length is not predefined */
  17448. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17449. process_new_http2_connection(conn);
  17450. } else
  17451. #endif
  17452. {
  17453. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17454. init_connection(conn);
  17455. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17456. /* Start with HTTP, WS will be an "upgrade" request later */
  17457. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17458. process_new_connection(conn);
  17459. }
  17460. /* Free client certificate info */
  17461. if (conn->request_info.client_cert) {
  17462. mg_free((void *)(conn->request_info.client_cert->subject));
  17463. mg_free((void *)(conn->request_info.client_cert->issuer));
  17464. mg_free((void *)(conn->request_info.client_cert->serial));
  17465. mg_free((void *)(conn->request_info.client_cert->finger));
  17466. /* Free certificate memory */
  17467. X509_free(
  17468. (X509 *)conn->request_info.client_cert->peer_cert);
  17469. conn->request_info.client_cert->peer_cert = 0;
  17470. conn->request_info.client_cert->subject = 0;
  17471. conn->request_info.client_cert->issuer = 0;
  17472. conn->request_info.client_cert->serial = 0;
  17473. conn->request_info.client_cert->finger = 0;
  17474. conn->request_info.client_cert = 0;
  17475. }
  17476. } else {
  17477. /* make sure the connection is cleaned up on SSL failure */
  17478. close_connection(conn);
  17479. }
  17480. #endif
  17481. } else {
  17482. /* process HTTP connection */
  17483. init_connection(conn);
  17484. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17485. /* Start with HTTP, WS will be an "upgrade" request later */
  17486. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17487. process_new_connection(conn);
  17488. }
  17489. DEBUG_TRACE("%s", "Connection closed");
  17490. #if defined(USE_SERVER_STATS)
  17491. conn->conn_close_time = time(NULL);
  17492. #endif
  17493. }
  17494. /* Call exit thread user callback */
  17495. if (ctx->callbacks.exit_thread) {
  17496. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17497. }
  17498. /* delete thread local storage objects */
  17499. pthread_setspecific(sTlsKey, NULL);
  17500. #if defined(_WIN32)
  17501. CloseHandle(tls.pthread_cond_helper_mutex);
  17502. #endif
  17503. pthread_mutex_destroy(&conn->mutex);
  17504. /* Free the request buffer. */
  17505. conn->buf_size = 0;
  17506. mg_free(conn->buf);
  17507. conn->buf = NULL;
  17508. /* Free cleaned URI (if any) */
  17509. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17510. mg_free((void *)conn->request_info.local_uri);
  17511. conn->request_info.local_uri = NULL;
  17512. }
  17513. #if defined(USE_SERVER_STATS)
  17514. conn->conn_state = 9; /* done */
  17515. #endif
  17516. DEBUG_TRACE("%s", "exiting");
  17517. }
  17518. /* Threads have different return types on Windows and Unix. */
  17519. #if defined(_WIN32)
  17520. static unsigned __stdcall worker_thread(void *thread_func_param)
  17521. {
  17522. worker_thread_run((struct mg_connection *)thread_func_param);
  17523. return 0;
  17524. }
  17525. #else
  17526. static void *
  17527. worker_thread(void *thread_func_param)
  17528. {
  17529. #if !defined(__ZEPHYR__)
  17530. struct sigaction sa;
  17531. /* Ignore SIGPIPE */
  17532. memset(&sa, 0, sizeof(sa));
  17533. sa.sa_handler = SIG_IGN;
  17534. sigaction(SIGPIPE, &sa, NULL);
  17535. #endif
  17536. worker_thread_run((struct mg_connection *)thread_func_param);
  17537. return NULL;
  17538. }
  17539. #endif /* _WIN32 */
  17540. /* This is an internal function, thus all arguments are expected to be
  17541. * valid - a NULL check is not required. */
  17542. static void
  17543. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17544. {
  17545. struct socket so;
  17546. char src_addr[IP_ADDR_STR_LEN];
  17547. socklen_t len = sizeof(so.rsa);
  17548. #if !defined(__ZEPHYR__)
  17549. int on = 1;
  17550. #endif
  17551. memset(&so, 0, sizeof(so));
  17552. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17553. == INVALID_SOCKET) {
  17554. } else if (check_acl(ctx, &so.rsa) != 1) {
  17555. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17556. mg_cry_ctx_internal(ctx,
  17557. "%s: %s is not allowed to connect",
  17558. __func__,
  17559. src_addr);
  17560. closesocket(so.sock);
  17561. } else {
  17562. /* Put so socket structure into the queue */
  17563. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17564. set_close_on_exec(so.sock, NULL, ctx);
  17565. so.is_ssl = listener->is_ssl;
  17566. so.ssl_redir = listener->ssl_redir;
  17567. so.is_optional = listener->is_optional;
  17568. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17569. mg_cry_ctx_internal(ctx,
  17570. "%s: getsockname() failed: %s",
  17571. __func__,
  17572. strerror(ERRNO));
  17573. }
  17574. #if !defined(__ZEPHYR__)
  17575. if ((so.lsa.sa.sa_family == AF_INET)
  17576. || (so.lsa.sa.sa_family == AF_INET6)) {
  17577. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17578. * This is needed because if HTTP-level keep-alive
  17579. * is enabled, and client resets the connection, server won't get
  17580. * TCP FIN or RST and will keep the connection open forever. With
  17581. * TCP keep-alive, next keep-alive handshake will figure out that
  17582. * the client is down and will close the server end.
  17583. * Thanks to Igor Klopov who suggested the patch. */
  17584. if (setsockopt(so.sock,
  17585. SOL_SOCKET,
  17586. SO_KEEPALIVE,
  17587. (SOCK_OPT_TYPE)&on,
  17588. sizeof(on))
  17589. != 0) {
  17590. mg_cry_ctx_internal(
  17591. ctx,
  17592. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17593. __func__,
  17594. strerror(ERRNO));
  17595. }
  17596. }
  17597. #endif
  17598. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17599. * to effectively fill up the underlying IP packet payload and
  17600. * reduce the overhead of sending lots of small buffers. However
  17601. * this hurts the server's throughput (ie. operations per second)
  17602. * when HTTP 1.1 persistent connections are used and the responses
  17603. * are relatively small (eg. less than 1400 bytes).
  17604. */
  17605. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17606. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17607. if (set_tcp_nodelay(&so, 1) != 0) {
  17608. mg_cry_ctx_internal(
  17609. ctx,
  17610. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17611. __func__,
  17612. strerror(ERRNO));
  17613. }
  17614. }
  17615. /* The "non blocking" property should already be
  17616. * inherited from the parent socket. Set it for
  17617. * non-compliant socket implementations. */
  17618. set_non_blocking_mode(so.sock);
  17619. so.in_use = 0;
  17620. produce_socket(ctx, &so);
  17621. }
  17622. }
  17623. static void
  17624. master_thread_run(struct mg_context *ctx)
  17625. {
  17626. struct mg_workerTLS tls;
  17627. struct mg_pollfd *pfd;
  17628. unsigned int i;
  17629. unsigned int workerthreadcount;
  17630. if (!ctx) {
  17631. return;
  17632. }
  17633. mg_set_thread_name("master");
  17634. /* Increase priority of the master thread */
  17635. #if defined(_WIN32)
  17636. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17637. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17638. int min_prio = sched_get_priority_min(SCHED_RR);
  17639. int max_prio = sched_get_priority_max(SCHED_RR);
  17640. if ((min_prio >= 0) && (max_prio >= 0)
  17641. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17642. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17643. struct sched_param sched_param = {0};
  17644. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17645. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17646. }
  17647. #endif
  17648. /* Initialize thread local storage */
  17649. #if defined(_WIN32)
  17650. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17651. #endif
  17652. tls.is_master = 1;
  17653. pthread_setspecific(sTlsKey, &tls);
  17654. if (ctx->callbacks.init_thread) {
  17655. /* Callback for the master thread (type 0) */
  17656. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17657. } else {
  17658. tls.user_ptr = NULL;
  17659. }
  17660. /* Lua background script "start" event */
  17661. #if defined(USE_LUA)
  17662. if (ctx->lua_background_state) {
  17663. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17664. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17665. /* call "start()" in Lua */
  17666. lua_getglobal(lstate, "start");
  17667. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17668. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17669. if (ret != 0) {
  17670. struct mg_connection fc;
  17671. lua_cry(fake_connection(&fc, ctx),
  17672. ret,
  17673. lstate,
  17674. "lua_background_script",
  17675. "start");
  17676. }
  17677. } else {
  17678. lua_pop(lstate, 1);
  17679. }
  17680. /* determine if there is a "log()" function in Lua background script */
  17681. lua_getglobal(lstate, "log");
  17682. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17683. ctx->lua_bg_log_available = 1;
  17684. }
  17685. lua_pop(lstate, 1);
  17686. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17687. }
  17688. #endif
  17689. /* Server starts *now* */
  17690. ctx->start_time = time(NULL);
  17691. /* Server accept loop */
  17692. pfd = ctx->listening_socket_fds;
  17693. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17694. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17695. pfd[i].fd = ctx->listening_sockets[i].sock;
  17696. pfd[i].events = POLLIN;
  17697. }
  17698. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17699. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17700. * of listening_socket_fds[] just to hold this
  17701. */
  17702. pfd[ctx->num_listening_sockets].fd =
  17703. ctx->thread_shutdown_notification_socket;
  17704. pfd[ctx->num_listening_sockets].events = POLLIN;
  17705. if (mg_poll(pfd,
  17706. ctx->num_listening_sockets
  17707. + 1, // +1 for the thread_shutdown_notification_socket
  17708. SOCKET_TIMEOUT_QUANTUM,
  17709. &(ctx->stop_flag))
  17710. > 0) {
  17711. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17712. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17713. * successful poll, and POLLIN is defined as
  17714. * (POLLRDNORM | POLLRDBAND)
  17715. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17716. * pfd[i].revents == POLLIN. */
  17717. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17718. && (pfd[i].revents & POLLIN)) {
  17719. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17720. }
  17721. }
  17722. }
  17723. }
  17724. /* Here stop_flag is 1 - Initiate shutdown. */
  17725. DEBUG_TRACE("%s", "stopping workers");
  17726. /* Stop signal received: somebody called mg_stop. Quit. */
  17727. close_all_listening_sockets(ctx);
  17728. /* Wakeup workers that are waiting for connections to handle. */
  17729. #if defined(ALTERNATIVE_QUEUE)
  17730. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17731. event_signal(ctx->client_wait_events[i]);
  17732. }
  17733. #else
  17734. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17735. pthread_cond_broadcast(&ctx->sq_full);
  17736. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17737. #endif
  17738. /* Join all worker threads to avoid leaking threads. */
  17739. workerthreadcount = ctx->spawned_worker_threads;
  17740. for (i = 0; i < workerthreadcount; i++) {
  17741. if (ctx->worker_threadids[i] != 0) {
  17742. mg_join_thread(ctx->worker_threadids[i]);
  17743. }
  17744. }
  17745. #if defined(USE_LUA)
  17746. /* Free Lua state of lua background task */
  17747. if (ctx->lua_background_state) {
  17748. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17749. ctx->lua_bg_log_available = 0;
  17750. /* call "stop()" in Lua */
  17751. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17752. lua_getglobal(lstate, "stop");
  17753. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17754. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17755. if (ret != 0) {
  17756. struct mg_connection fc;
  17757. lua_cry(fake_connection(&fc, ctx),
  17758. ret,
  17759. lstate,
  17760. "lua_background_script",
  17761. "stop");
  17762. }
  17763. }
  17764. DEBUG_TRACE("Close Lua background state %p", lstate);
  17765. lua_close(lstate);
  17766. ctx->lua_background_state = 0;
  17767. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17768. }
  17769. #endif
  17770. DEBUG_TRACE("%s", "exiting");
  17771. /* call exit thread callback */
  17772. if (ctx->callbacks.exit_thread) {
  17773. /* Callback for the master thread (type 0) */
  17774. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17775. }
  17776. #if defined(_WIN32)
  17777. CloseHandle(tls.pthread_cond_helper_mutex);
  17778. #endif
  17779. pthread_setspecific(sTlsKey, NULL);
  17780. /* Signal mg_stop() that we're done.
  17781. * WARNING: This must be the very last thing this
  17782. * thread does, as ctx becomes invalid after this line. */
  17783. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17784. }
  17785. /* Threads have different return types on Windows and Unix. */
  17786. #if defined(_WIN32)
  17787. static unsigned __stdcall master_thread(void *thread_func_param)
  17788. {
  17789. master_thread_run((struct mg_context *)thread_func_param);
  17790. return 0;
  17791. }
  17792. #else
  17793. static void *
  17794. master_thread(void *thread_func_param)
  17795. {
  17796. #if !defined(__ZEPHYR__)
  17797. struct sigaction sa;
  17798. /* Ignore SIGPIPE */
  17799. memset(&sa, 0, sizeof(sa));
  17800. sa.sa_handler = SIG_IGN;
  17801. sigaction(SIGPIPE, &sa, NULL);
  17802. #endif
  17803. master_thread_run((struct mg_context *)thread_func_param);
  17804. return NULL;
  17805. }
  17806. #endif /* _WIN32 */
  17807. static void
  17808. free_context(struct mg_context *ctx)
  17809. {
  17810. int i;
  17811. struct mg_handler_info *tmp_rh;
  17812. if (ctx == NULL) {
  17813. return;
  17814. }
  17815. /* Call user callback */
  17816. if (ctx->callbacks.exit_context) {
  17817. ctx->callbacks.exit_context(ctx);
  17818. }
  17819. /* All threads exited, no sync is needed. Destroy thread mutex and
  17820. * condvars
  17821. */
  17822. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17823. #if defined(ALTERNATIVE_QUEUE)
  17824. mg_free(ctx->client_socks);
  17825. if (ctx->client_wait_events != NULL) {
  17826. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17827. event_destroy(ctx->client_wait_events[i]);
  17828. }
  17829. mg_free(ctx->client_wait_events);
  17830. }
  17831. #else
  17832. (void)pthread_cond_destroy(&ctx->sq_empty);
  17833. (void)pthread_cond_destroy(&ctx->sq_full);
  17834. mg_free(ctx->squeue);
  17835. #endif
  17836. /* Destroy other context global data structures mutex */
  17837. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17838. #if defined(USE_LUA)
  17839. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17840. #endif
  17841. /* Deallocate shutdown-triggering socket-pair */
  17842. if (ctx->user_shutdown_notification_socket >= 0) {
  17843. closesocket(ctx->user_shutdown_notification_socket);
  17844. }
  17845. if (ctx->thread_shutdown_notification_socket >= 0) {
  17846. closesocket(ctx->thread_shutdown_notification_socket);
  17847. }
  17848. /* Deallocate config parameters */
  17849. for (i = 0; i < NUM_OPTIONS; i++) {
  17850. if (ctx->dd.config[i] != NULL) {
  17851. #if defined(_MSC_VER)
  17852. #pragma warning(suppress : 6001)
  17853. #endif
  17854. mg_free(ctx->dd.config[i]);
  17855. }
  17856. }
  17857. /* Deallocate request handlers */
  17858. while (ctx->dd.handlers) {
  17859. tmp_rh = ctx->dd.handlers;
  17860. ctx->dd.handlers = tmp_rh->next;
  17861. mg_free(tmp_rh->uri);
  17862. mg_free(tmp_rh);
  17863. }
  17864. #if defined(USE_MBEDTLS)
  17865. if (ctx->dd.ssl_ctx != NULL) {
  17866. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17867. mg_free(ctx->dd.ssl_ctx);
  17868. ctx->dd.ssl_ctx = NULL;
  17869. }
  17870. #elif !defined(NO_SSL)
  17871. /* Deallocate SSL context */
  17872. if (ctx->dd.ssl_ctx != NULL) {
  17873. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17874. int callback_ret =
  17875. (ctx->callbacks.external_ssl_ctx == NULL)
  17876. ? 0
  17877. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17878. if (callback_ret == 0) {
  17879. SSL_CTX_free(ctx->dd.ssl_ctx);
  17880. }
  17881. /* else: ignore error and omit SSL_CTX_free in case
  17882. * callback_ret is 1 */
  17883. }
  17884. #endif /* !NO_SSL */
  17885. /* Deallocate worker thread ID array */
  17886. mg_free(ctx->worker_threadids);
  17887. /* Deallocate worker thread ID array */
  17888. mg_free(ctx->worker_connections);
  17889. /* deallocate system name string */
  17890. mg_free(ctx->systemName);
  17891. /* Deallocate context itself */
  17892. mg_free(ctx);
  17893. }
  17894. CIVETWEB_API void
  17895. mg_stop(struct mg_context *ctx)
  17896. {
  17897. pthread_t mt;
  17898. if (!ctx) {
  17899. return;
  17900. }
  17901. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17902. * two threads is not allowed. */
  17903. mt = ctx->masterthreadid;
  17904. if (mt == 0) {
  17905. return;
  17906. }
  17907. ctx->masterthreadid = 0;
  17908. /* Set stop flag, so all threads know they have to exit. */
  17909. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17910. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  17911. * immediately */
  17912. closesocket(ctx->user_shutdown_notification_socket);
  17913. ctx->user_shutdown_notification_socket =
  17914. -1; /* to avoid calling closesocket() again in free_context() */
  17915. /* Join timer thread */
  17916. #if defined(USE_TIMERS)
  17917. timers_exit(ctx);
  17918. #endif
  17919. /* Wait until everything has stopped. */
  17920. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17921. (void)mg_sleep(10);
  17922. }
  17923. /* Wait to stop master thread */
  17924. mg_join_thread(mt);
  17925. /* Close remaining Lua states */
  17926. #if defined(USE_LUA)
  17927. lua_ctx_exit(ctx);
  17928. #endif
  17929. /* Free memory */
  17930. free_context(ctx);
  17931. }
  17932. static void
  17933. get_system_name(char **sysName)
  17934. {
  17935. #if defined(_WIN32)
  17936. char name[128];
  17937. DWORD dwVersion = 0;
  17938. DWORD dwMajorVersion = 0;
  17939. DWORD dwMinorVersion = 0;
  17940. DWORD dwBuild = 0;
  17941. BOOL wowRet, isWoW = FALSE;
  17942. #if defined(_MSC_VER)
  17943. #pragma warning(push)
  17944. /* GetVersion was declared deprecated */
  17945. #pragma warning(disable : 4996)
  17946. #endif
  17947. dwVersion = GetVersion();
  17948. #if defined(_MSC_VER)
  17949. #pragma warning(pop)
  17950. #endif
  17951. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17952. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17953. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17954. (void)dwBuild;
  17955. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17956. sprintf(name,
  17957. "Windows %u.%u%s",
  17958. (unsigned)dwMajorVersion,
  17959. (unsigned)dwMinorVersion,
  17960. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17961. *sysName = mg_strdup(name);
  17962. #elif defined(__ZEPHYR__)
  17963. *sysName = mg_strdup("Zephyr OS");
  17964. #else
  17965. struct utsname name;
  17966. memset(&name, 0, sizeof(name));
  17967. uname(&name);
  17968. *sysName = mg_strdup(name.sysname);
  17969. #endif
  17970. }
  17971. static void
  17972. legacy_init(const char **options)
  17973. {
  17974. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17975. if (options) {
  17976. const char **run_options = options;
  17977. const char *optname = config_options[LISTENING_PORTS].name;
  17978. /* Try to find the "listening_ports" option */
  17979. while (*run_options) {
  17980. if (!strcmp(*run_options, optname)) {
  17981. ports_option = run_options[1];
  17982. }
  17983. run_options += 2;
  17984. }
  17985. }
  17986. if (is_ssl_port_used(ports_option)) {
  17987. /* Initialize with SSL support */
  17988. mg_init_library(MG_FEATURES_TLS);
  17989. } else {
  17990. /* Initialize without SSL support */
  17991. mg_init_library(MG_FEATURES_DEFAULT);
  17992. }
  17993. }
  17994. /* we'll assume it's only Windows that doesn't have socketpair() available */
  17995. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  17996. #define HAVE_SOCKETPAIR 1
  17997. #endif
  17998. static int
  17999. mg_socketpair(int *sockA, int *sockB)
  18000. {
  18001. int temp[2] = {-1, -1};
  18002. int asock = -1;
  18003. /** Default to unallocated */
  18004. *sockA = -1;
  18005. *sockB = -1;
  18006. #if defined(HAVE_SOCKETPAIR)
  18007. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18008. if (ret == 0) {
  18009. *sockA = temp[0];
  18010. *sockB = temp[1];
  18011. set_close_on_exec(*sockA, NULL, NULL);
  18012. set_close_on_exec(*sockB, NULL, NULL);
  18013. }
  18014. (void)asock; /* not used */
  18015. return ret;
  18016. #else
  18017. /** No socketpair() call is available, so we'll have to roll our own
  18018. * implementation */
  18019. asock = socket(PF_INET, SOCK_STREAM, 0);
  18020. if (asock >= 0) {
  18021. struct sockaddr_in addr;
  18022. struct sockaddr *pa = (struct sockaddr *)&addr;
  18023. socklen_t addrLen = sizeof(addr);
  18024. memset(&addr, 0, sizeof(addr));
  18025. addr.sin_family = AF_INET;
  18026. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18027. addr.sin_port = 0;
  18028. if ((bind(asock, pa, sizeof(addr)) == 0)
  18029. && (getsockname(asock, pa, &addrLen) == 0)
  18030. && (listen(asock, 1) == 0)) {
  18031. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18032. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18033. temp[1] = accept(asock, pa, &addrLen);
  18034. if (temp[1] >= 0) {
  18035. closesocket(asock);
  18036. *sockA = temp[0];
  18037. *sockB = temp[1];
  18038. set_close_on_exec(*sockA, NULL, NULL);
  18039. set_close_on_exec(*sockB, NULL, NULL);
  18040. return 0; /* success! */
  18041. }
  18042. }
  18043. }
  18044. }
  18045. /* Cleanup */
  18046. if (asock >= 0)
  18047. closesocket(asock);
  18048. if (temp[0] >= 0)
  18049. closesocket(temp[0]);
  18050. if (temp[1] >= 0)
  18051. closesocket(temp[1]);
  18052. return -1; /* fail! */
  18053. #endif
  18054. }
  18055. static int
  18056. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18057. {
  18058. const unsigned int i = ctx->spawned_worker_threads;
  18059. if (i >= ctx->cfg_max_worker_threads) {
  18060. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18061. threads, ever! */
  18062. }
  18063. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18064. #if defined(ALTERNATIVE_QUEUE)
  18065. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18066. #else
  18067. if ((only_if_no_idle_threads)
  18068. && (ctx->idle_worker_thread_count
  18069. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18070. #endif
  18071. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18072. return -2; /* There are idle threads available, so no need to spawn a
  18073. new worker thread now */
  18074. }
  18075. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18076. condition while the thread is starting
  18077. up */
  18078. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18079. ctx->worker_connections[i].phys_ctx = ctx;
  18080. int ret = mg_start_thread_with_id(worker_thread,
  18081. &ctx->worker_connections[i],
  18082. &ctx->worker_threadids[i]);
  18083. if (ret == 0) {
  18084. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18085. the table */
  18086. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18087. } else {
  18088. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18089. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18090. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18091. }
  18092. return ret;
  18093. }
  18094. CIVETWEB_API struct mg_context *
  18095. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18096. {
  18097. struct mg_context *ctx;
  18098. const char *name, *value, *default_value;
  18099. int idx, ok, prespawnthreadcount, workerthreadcount;
  18100. unsigned int i;
  18101. int itmp;
  18102. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18103. const char **options =
  18104. ((init != NULL) ? (init->configuration_options) : (NULL));
  18105. struct mg_workerTLS tls;
  18106. if (error != NULL) {
  18107. error->code = MG_ERROR_DATA_CODE_OK;
  18108. error->code_sub = 0;
  18109. if (error->text_buffer_size > 0) {
  18110. *error->text = 0;
  18111. }
  18112. }
  18113. if (mg_init_library_called == 0) {
  18114. /* Legacy INIT, if mg_start is called without mg_init_library.
  18115. * Note: This will cause a memory leak when unloading the library.
  18116. */
  18117. legacy_init(options);
  18118. }
  18119. if (mg_init_library_called == 0) {
  18120. if (error != NULL) {
  18121. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18122. mg_snprintf(NULL,
  18123. NULL, /* No truncation check for error buffers */
  18124. error->text,
  18125. error->text_buffer_size,
  18126. "%s",
  18127. "Library uninitialized");
  18128. }
  18129. return NULL;
  18130. }
  18131. /* Allocate context and initialize reasonable general case defaults. */
  18132. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18133. if (ctx == NULL) {
  18134. if (error != NULL) {
  18135. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18136. error->code_sub = (unsigned)sizeof(*ctx);
  18137. mg_snprintf(NULL,
  18138. NULL, /* No truncation check for error buffers */
  18139. error->text,
  18140. error->text_buffer_size,
  18141. "%s",
  18142. "Out of memory");
  18143. }
  18144. return NULL;
  18145. }
  18146. /* Random number generator will initialize at the first call */
  18147. ctx->dd.auth_nonce_mask =
  18148. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18149. /* Save started thread index to reuse in other external API calls
  18150. * For the sake of thread synchronization all non-civetweb threads
  18151. * can be considered as single external thread */
  18152. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18153. tls.is_master = -1; /* Thread calling mg_start */
  18154. tls.thread_idx = ctx->starter_thread_idx;
  18155. #if defined(_WIN32)
  18156. tls.pthread_cond_helper_mutex = NULL;
  18157. #endif
  18158. pthread_setspecific(sTlsKey, &tls);
  18159. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18160. #if !defined(ALTERNATIVE_QUEUE)
  18161. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18162. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18163. ctx->sq_blocked = 0;
  18164. #endif
  18165. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18166. #if defined(USE_LUA)
  18167. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18168. #endif
  18169. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18170. * will cause poll() to return immediately in the master-thread, so that
  18171. * mg_stop() can also return immediately.
  18172. */
  18173. ok &= (0
  18174. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18175. &ctx->thread_shutdown_notification_socket));
  18176. if (!ok) {
  18177. unsigned error_id = (unsigned)ERRNO;
  18178. const char *err_msg =
  18179. "Cannot initialize thread synchronization objects";
  18180. /* Fatal error - abort start. However, this situation should never
  18181. * occur in practice. */
  18182. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18183. if (error != NULL) {
  18184. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18185. error->code_sub = error_id;
  18186. mg_snprintf(NULL,
  18187. NULL, /* No truncation check for error buffers */
  18188. error->text,
  18189. error->text_buffer_size,
  18190. "%s",
  18191. err_msg);
  18192. }
  18193. mg_free(ctx);
  18194. pthread_setspecific(sTlsKey, NULL);
  18195. return NULL;
  18196. }
  18197. if ((init != NULL) && (init->callbacks != NULL)) {
  18198. /* Set all callbacks except exit_context. */
  18199. ctx->callbacks = *init->callbacks;
  18200. exit_callback = init->callbacks->exit_context;
  18201. /* The exit callback is activated once the context is successfully
  18202. * created. It should not be called, if an incomplete context object
  18203. * is deleted during a failed initialization. */
  18204. ctx->callbacks.exit_context = 0;
  18205. }
  18206. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18207. ctx->dd.handlers = NULL;
  18208. ctx->dd.next = NULL;
  18209. #if defined(USE_LUA)
  18210. lua_ctx_init(ctx);
  18211. #endif
  18212. /* Store options */
  18213. while (options && (name = *options++) != NULL) {
  18214. idx = get_option_index(name);
  18215. if (idx == -1) {
  18216. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18217. if (error != NULL) {
  18218. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18219. error->code_sub = (unsigned)-1;
  18220. mg_snprintf(NULL,
  18221. NULL, /* No truncation check for error buffers */
  18222. error->text,
  18223. error->text_buffer_size,
  18224. "Invalid configuration option: %s",
  18225. name);
  18226. }
  18227. free_context(ctx);
  18228. pthread_setspecific(sTlsKey, NULL);
  18229. return NULL;
  18230. } else if ((value = *options++) == NULL) {
  18231. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18232. if (error != NULL) {
  18233. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18234. error->code_sub = (unsigned)idx;
  18235. mg_snprintf(NULL,
  18236. NULL, /* No truncation check for error buffers */
  18237. error->text,
  18238. error->text_buffer_size,
  18239. "Invalid configuration option value: %s",
  18240. name);
  18241. }
  18242. free_context(ctx);
  18243. pthread_setspecific(sTlsKey, NULL);
  18244. return NULL;
  18245. }
  18246. if (ctx->dd.config[idx] != NULL) {
  18247. /* A duplicate configuration option is not an error - the last
  18248. * option value will be used. */
  18249. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18250. mg_free(ctx->dd.config[idx]);
  18251. }
  18252. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18253. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18254. }
  18255. /* Set default value if needed */
  18256. for (i = 0; config_options[i].name != NULL; i++) {
  18257. default_value = config_options[i].default_value;
  18258. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18259. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18260. }
  18261. }
  18262. /* Request size option */
  18263. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18264. if (itmp < 1024) {
  18265. mg_cry_ctx_internal(ctx,
  18266. "%s too small",
  18267. config_options[MAX_REQUEST_SIZE].name);
  18268. if (error != NULL) {
  18269. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18270. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18271. mg_snprintf(NULL,
  18272. NULL, /* No truncation check for error buffers */
  18273. error->text,
  18274. error->text_buffer_size,
  18275. "Invalid configuration option value: %s",
  18276. config_options[MAX_REQUEST_SIZE].name);
  18277. }
  18278. free_context(ctx);
  18279. pthread_setspecific(sTlsKey, NULL);
  18280. return NULL;
  18281. }
  18282. ctx->max_request_size = (unsigned)itmp;
  18283. /* Queue length */
  18284. #if !defined(ALTERNATIVE_QUEUE)
  18285. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18286. if (itmp < 1) {
  18287. mg_cry_ctx_internal(ctx,
  18288. "%s too small",
  18289. config_options[CONNECTION_QUEUE_SIZE].name);
  18290. if (error != NULL) {
  18291. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18292. error->code_sub = CONNECTION_QUEUE_SIZE;
  18293. mg_snprintf(NULL,
  18294. NULL, /* No truncation check for error buffers */
  18295. error->text,
  18296. error->text_buffer_size,
  18297. "Invalid configuration option value: %s",
  18298. config_options[CONNECTION_QUEUE_SIZE].name);
  18299. }
  18300. free_context(ctx);
  18301. pthread_setspecific(sTlsKey, NULL);
  18302. return NULL;
  18303. }
  18304. ctx->squeue =
  18305. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18306. if (ctx->squeue == NULL) {
  18307. mg_cry_ctx_internal(ctx,
  18308. "Out of memory: Cannot allocate %s",
  18309. config_options[CONNECTION_QUEUE_SIZE].name);
  18310. if (error != NULL) {
  18311. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18312. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18313. mg_snprintf(NULL,
  18314. NULL, /* No truncation check for error buffers */
  18315. error->text,
  18316. error->text_buffer_size,
  18317. "Out of memory: Cannot allocate %s",
  18318. config_options[CONNECTION_QUEUE_SIZE].name);
  18319. }
  18320. free_context(ctx);
  18321. pthread_setspecific(sTlsKey, NULL);
  18322. return NULL;
  18323. }
  18324. ctx->sq_size = itmp;
  18325. #endif
  18326. /* Worker thread count option */
  18327. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18328. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18329. if ((prespawnthreadcount < 0)
  18330. || (prespawnthreadcount > workerthreadcount)) {
  18331. prespawnthreadcount =
  18332. workerthreadcount; /* can't prespawn more than all of them! */
  18333. }
  18334. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18335. if (workerthreadcount <= 0) {
  18336. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18337. } else {
  18338. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18339. }
  18340. if (error != NULL) {
  18341. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18342. error->code_sub = NUM_THREADS;
  18343. mg_snprintf(NULL,
  18344. NULL, /* No truncation check for error buffers */
  18345. error->text,
  18346. error->text_buffer_size,
  18347. "Invalid configuration option value: %s",
  18348. config_options[NUM_THREADS].name);
  18349. }
  18350. free_context(ctx);
  18351. pthread_setspecific(sTlsKey, NULL);
  18352. return NULL;
  18353. }
  18354. /* Document root */
  18355. #if defined(NO_FILES)
  18356. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18357. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18358. if (error != NULL) {
  18359. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18360. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18361. mg_snprintf(NULL,
  18362. NULL, /* No truncation check for error buffers */
  18363. error->text,
  18364. error->text_buffer_size,
  18365. "Invalid configuration option value: %s",
  18366. config_options[DOCUMENT_ROOT].name);
  18367. }
  18368. free_context(ctx);
  18369. pthread_setspecific(sTlsKey, NULL);
  18370. return NULL;
  18371. }
  18372. #endif
  18373. get_system_name(&ctx->systemName);
  18374. #if defined(USE_LUA)
  18375. /* If a Lua background script has been configured, start it. */
  18376. ctx->lua_bg_log_available = 0;
  18377. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18378. char ebuf[256];
  18379. struct vec opt_vec;
  18380. struct vec eq_vec;
  18381. const char *sparams;
  18382. memset(ebuf, 0, sizeof(ebuf));
  18383. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18384. /* Create a Lua state, load all standard libraries and the mg table */
  18385. lua_State *state = mg_lua_context_script_prepare(
  18386. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18387. if (!state) {
  18388. mg_cry_ctx_internal(ctx,
  18389. "lua_background_script load error: %s",
  18390. ebuf);
  18391. if (error != NULL) {
  18392. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18393. mg_snprintf(NULL,
  18394. NULL, /* No truncation check for error buffers */
  18395. error->text,
  18396. error->text_buffer_size,
  18397. "Error in script %s: %s",
  18398. config_options[LUA_BACKGROUND_SCRIPT].name,
  18399. ebuf);
  18400. }
  18401. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18402. free_context(ctx);
  18403. pthread_setspecific(sTlsKey, NULL);
  18404. return NULL;
  18405. }
  18406. /* Add a table with parameters into mg.params */
  18407. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18408. if (sparams && sparams[0]) {
  18409. lua_getglobal(state, "mg");
  18410. lua_pushstring(state, "params");
  18411. lua_newtable(state);
  18412. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18413. != NULL) {
  18414. reg_llstring(
  18415. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18416. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18417. break;
  18418. }
  18419. lua_rawset(state, -3);
  18420. lua_pop(state, 1);
  18421. }
  18422. /* Call script */
  18423. state = mg_lua_context_script_run(state,
  18424. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18425. ctx,
  18426. ebuf,
  18427. sizeof(ebuf));
  18428. if (!state) {
  18429. mg_cry_ctx_internal(ctx,
  18430. "lua_background_script start error: %s",
  18431. ebuf);
  18432. if (error != NULL) {
  18433. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18434. mg_snprintf(NULL,
  18435. NULL, /* No truncation check for error buffers */
  18436. error->text,
  18437. error->text_buffer_size,
  18438. "Error in script %s: %s",
  18439. config_options[DOCUMENT_ROOT].name,
  18440. ebuf);
  18441. }
  18442. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18443. free_context(ctx);
  18444. pthread_setspecific(sTlsKey, NULL);
  18445. return NULL;
  18446. }
  18447. /* state remains valid */
  18448. ctx->lua_background_state = (void *)state;
  18449. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18450. } else {
  18451. ctx->lua_background_state = 0;
  18452. }
  18453. #endif
  18454. /* Step by step initialization of ctx - depending on build options */
  18455. #if !defined(NO_FILESYSTEMS)
  18456. if (!set_gpass_option(ctx, NULL)) {
  18457. const char *err_msg = "Invalid global password file";
  18458. /* Fatal error - abort start. */
  18459. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18460. if (error != NULL) {
  18461. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18462. mg_snprintf(NULL,
  18463. NULL, /* No truncation check for error buffers */
  18464. error->text,
  18465. error->text_buffer_size,
  18466. "%s",
  18467. err_msg);
  18468. }
  18469. free_context(ctx);
  18470. pthread_setspecific(sTlsKey, NULL);
  18471. return NULL;
  18472. }
  18473. #endif
  18474. #if defined(USE_MBEDTLS)
  18475. if (!mg_sslctx_init(ctx, NULL)) {
  18476. const char *err_msg = "Error initializing SSL context";
  18477. /* Fatal error - abort start. */
  18478. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18479. if (error != NULL) {
  18480. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18481. mg_snprintf(NULL,
  18482. NULL, /* No truncation check for error buffers */
  18483. error->text,
  18484. error->text_buffer_size,
  18485. "%s",
  18486. err_msg);
  18487. }
  18488. free_context(ctx);
  18489. pthread_setspecific(sTlsKey, NULL);
  18490. return NULL;
  18491. }
  18492. #elif !defined(NO_SSL)
  18493. if (!init_ssl_ctx(ctx, NULL)) {
  18494. const char *err_msg = "Error initializing SSL context";
  18495. /* Fatal error - abort start. */
  18496. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18497. if (error != NULL) {
  18498. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18499. mg_snprintf(NULL,
  18500. NULL, /* No truncation check for error buffers */
  18501. error->text,
  18502. error->text_buffer_size,
  18503. "%s",
  18504. err_msg);
  18505. }
  18506. free_context(ctx);
  18507. pthread_setspecific(sTlsKey, NULL);
  18508. return NULL;
  18509. }
  18510. #endif
  18511. if (!set_ports_option(ctx)) {
  18512. const char *err_msg = "Failed to setup server ports";
  18513. /* Fatal error - abort start. */
  18514. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18515. if (error != NULL) {
  18516. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18517. mg_snprintf(NULL,
  18518. NULL, /* No truncation check for error buffers */
  18519. error->text,
  18520. error->text_buffer_size,
  18521. "%s",
  18522. err_msg);
  18523. }
  18524. free_context(ctx);
  18525. pthread_setspecific(sTlsKey, NULL);
  18526. return NULL;
  18527. }
  18528. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18529. if (!set_uid_option(ctx)) {
  18530. const char *err_msg = "Failed to run as configured user";
  18531. /* Fatal error - abort start. */
  18532. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18533. if (error != NULL) {
  18534. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18535. mg_snprintf(NULL,
  18536. NULL, /* No truncation check for error buffers */
  18537. error->text,
  18538. error->text_buffer_size,
  18539. "%s",
  18540. err_msg);
  18541. }
  18542. free_context(ctx);
  18543. pthread_setspecific(sTlsKey, NULL);
  18544. return NULL;
  18545. }
  18546. #endif
  18547. if (!set_acl_option(ctx)) {
  18548. const char *err_msg = "Failed to setup access control list";
  18549. /* Fatal error - abort start. */
  18550. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18551. if (error != NULL) {
  18552. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18553. mg_snprintf(NULL,
  18554. NULL, /* No truncation check for error buffers */
  18555. error->text,
  18556. error->text_buffer_size,
  18557. "%s",
  18558. err_msg);
  18559. }
  18560. free_context(ctx);
  18561. pthread_setspecific(sTlsKey, NULL);
  18562. return NULL;
  18563. }
  18564. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18565. ctx->worker_threadids =
  18566. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18567. sizeof(pthread_t),
  18568. ctx);
  18569. if (ctx->worker_threadids == NULL) {
  18570. const char *err_msg = "Not enough memory for worker thread ID array";
  18571. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18572. if (error != NULL) {
  18573. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18574. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18575. * (unsigned)sizeof(pthread_t);
  18576. mg_snprintf(NULL,
  18577. NULL, /* No truncation check for error buffers */
  18578. error->text,
  18579. error->text_buffer_size,
  18580. "%s",
  18581. err_msg);
  18582. }
  18583. free_context(ctx);
  18584. pthread_setspecific(sTlsKey, NULL);
  18585. return NULL;
  18586. }
  18587. ctx->worker_connections =
  18588. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18589. sizeof(struct mg_connection),
  18590. ctx);
  18591. if (ctx->worker_connections == NULL) {
  18592. const char *err_msg =
  18593. "Not enough memory for worker thread connection array";
  18594. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18595. if (error != NULL) {
  18596. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18597. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18598. * (unsigned)sizeof(struct mg_connection);
  18599. mg_snprintf(NULL,
  18600. NULL, /* No truncation check for error buffers */
  18601. error->text,
  18602. error->text_buffer_size,
  18603. "%s",
  18604. err_msg);
  18605. }
  18606. free_context(ctx);
  18607. pthread_setspecific(sTlsKey, NULL);
  18608. return NULL;
  18609. }
  18610. #if defined(ALTERNATIVE_QUEUE)
  18611. ctx->client_wait_events =
  18612. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18613. sizeof(ctx->client_wait_events[0]),
  18614. ctx);
  18615. if (ctx->client_wait_events == NULL) {
  18616. const char *err_msg = "Not enough memory for worker event array";
  18617. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18618. mg_free(ctx->worker_threadids);
  18619. if (error != NULL) {
  18620. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18621. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18622. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18623. mg_snprintf(NULL,
  18624. NULL, /* No truncation check for error buffers */
  18625. error->text,
  18626. error->text_buffer_size,
  18627. "%s",
  18628. err_msg);
  18629. }
  18630. free_context(ctx);
  18631. pthread_setspecific(sTlsKey, NULL);
  18632. return NULL;
  18633. }
  18634. ctx->client_socks =
  18635. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18636. sizeof(ctx->client_socks[0]),
  18637. ctx);
  18638. if (ctx->client_socks == NULL) {
  18639. const char *err_msg = "Not enough memory for worker socket array";
  18640. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18641. mg_free(ctx->client_wait_events);
  18642. mg_free(ctx->worker_threadids);
  18643. if (error != NULL) {
  18644. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18645. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18646. * (unsigned)sizeof(ctx->client_socks[0]);
  18647. mg_snprintf(NULL,
  18648. NULL, /* No truncation check for error buffers */
  18649. error->text,
  18650. error->text_buffer_size,
  18651. "%s",
  18652. err_msg);
  18653. }
  18654. free_context(ctx);
  18655. pthread_setspecific(sTlsKey, NULL);
  18656. return NULL;
  18657. }
  18658. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18659. ctx->client_wait_events[i] = event_create();
  18660. if (ctx->client_wait_events[i] == 0) {
  18661. const char *err_msg = "Error creating worker event %i";
  18662. mg_cry_ctx_internal(ctx, err_msg, i);
  18663. while (i > 0) {
  18664. i--;
  18665. event_destroy(ctx->client_wait_events[i]);
  18666. }
  18667. mg_free(ctx->client_socks);
  18668. mg_free(ctx->client_wait_events);
  18669. mg_free(ctx->worker_threadids);
  18670. if (error != NULL) {
  18671. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18672. error->code_sub = (unsigned)ERRNO;
  18673. mg_snprintf(NULL,
  18674. NULL, /* No truncation check for error buffers */
  18675. error->text,
  18676. error->text_buffer_size,
  18677. err_msg,
  18678. i);
  18679. }
  18680. free_context(ctx);
  18681. pthread_setspecific(sTlsKey, NULL);
  18682. return NULL;
  18683. }
  18684. }
  18685. #endif
  18686. #if defined(USE_TIMERS)
  18687. if (timers_init(ctx) != 0) {
  18688. const char *err_msg = "Error creating timers";
  18689. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18690. if (error != NULL) {
  18691. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18692. error->code_sub = (unsigned)ERRNO;
  18693. mg_snprintf(NULL,
  18694. NULL, /* No truncation check for error buffers */
  18695. error->text,
  18696. error->text_buffer_size,
  18697. "%s",
  18698. err_msg);
  18699. }
  18700. free_context(ctx);
  18701. pthread_setspecific(sTlsKey, NULL);
  18702. return NULL;
  18703. }
  18704. #endif
  18705. /* Context has been created - init user libraries */
  18706. if (ctx->callbacks.init_context) {
  18707. ctx->callbacks.init_context(ctx);
  18708. }
  18709. /* From now, the context is successfully created.
  18710. * When it is destroyed, the exit callback should be called. */
  18711. ctx->callbacks.exit_context = exit_callback;
  18712. ctx->context_type = CONTEXT_SERVER; /* server context */
  18713. /* Start worker threads */
  18714. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18715. /* worker_thread sets up the other fields */
  18716. if (mg_start_worker_thread(ctx, 0) != 0) {
  18717. long error_no = (long)ERRNO;
  18718. /* thread was not created */
  18719. if (ctx->spawned_worker_threads > 0) {
  18720. /* If the second, third, ... thread cannot be created, set a
  18721. * warning, but keep running. */
  18722. mg_cry_ctx_internal(ctx,
  18723. "Cannot start worker thread %i: error %ld",
  18724. ctx->spawned_worker_threads + 1,
  18725. error_no);
  18726. /* If the server initialization should stop here, all
  18727. * threads that have already been created must be stopped
  18728. * first, before any free_context(ctx) call.
  18729. */
  18730. } else {
  18731. /* If the first worker thread cannot be created, stop
  18732. * initialization and free the entire server context. */
  18733. mg_cry_ctx_internal(ctx,
  18734. "Cannot create threads: error %ld",
  18735. error_no);
  18736. if (error != NULL) {
  18737. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18738. error->code_sub = (unsigned)error_no;
  18739. mg_snprintf(
  18740. NULL,
  18741. NULL, /* No truncation check for error buffers */
  18742. error->text,
  18743. error->text_buffer_size,
  18744. "Cannot create first worker thread: error %ld",
  18745. error_no);
  18746. }
  18747. free_context(ctx);
  18748. pthread_setspecific(sTlsKey, NULL);
  18749. return NULL;
  18750. }
  18751. break;
  18752. }
  18753. }
  18754. /* Start master (listening) thread */
  18755. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18756. pthread_setspecific(sTlsKey, NULL);
  18757. return ctx;
  18758. }
  18759. CIVETWEB_API struct mg_context *
  18760. mg_start(const struct mg_callbacks *callbacks,
  18761. void *user_data,
  18762. const char **options)
  18763. {
  18764. struct mg_init_data init = {0};
  18765. init.callbacks = callbacks;
  18766. init.user_data = user_data;
  18767. init.configuration_options = options;
  18768. return mg_start2(&init, NULL);
  18769. }
  18770. /* Add an additional domain to an already running web server. */
  18771. CIVETWEB_API int
  18772. mg_start_domain2(struct mg_context *ctx,
  18773. const char **options,
  18774. struct mg_error_data *error)
  18775. {
  18776. const char *name;
  18777. const char *value;
  18778. const char *default_value;
  18779. struct mg_domain_context *new_dom;
  18780. struct mg_domain_context *dom;
  18781. int idx, i;
  18782. if (error != NULL) {
  18783. error->code = MG_ERROR_DATA_CODE_OK;
  18784. error->code_sub = 0;
  18785. if (error->text_buffer_size > 0) {
  18786. *error->text = 0;
  18787. }
  18788. }
  18789. if ((ctx == NULL) || (options == NULL)) {
  18790. if (error != NULL) {
  18791. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18792. mg_snprintf(NULL,
  18793. NULL, /* No truncation check for error buffers */
  18794. error->text,
  18795. error->text_buffer_size,
  18796. "%s",
  18797. "Invalid parameters");
  18798. }
  18799. return -1;
  18800. }
  18801. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18802. if (error != NULL) {
  18803. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18804. mg_snprintf(NULL,
  18805. NULL, /* No truncation check for error buffers */
  18806. error->text,
  18807. error->text_buffer_size,
  18808. "%s",
  18809. "Server already stopped");
  18810. }
  18811. return -7;
  18812. }
  18813. new_dom = (struct mg_domain_context *)
  18814. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18815. if (!new_dom) {
  18816. /* Out of memory */
  18817. if (error != NULL) {
  18818. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18819. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18820. mg_snprintf(NULL,
  18821. NULL, /* No truncation check for error buffers */
  18822. error->text,
  18823. error->text_buffer_size,
  18824. "%s",
  18825. "Out or memory");
  18826. }
  18827. return -6;
  18828. }
  18829. /* Store options - TODO: unite duplicate code */
  18830. while (options && (name = *options++) != NULL) {
  18831. idx = get_option_index(name);
  18832. if (idx == -1) {
  18833. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18834. if (error != NULL) {
  18835. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18836. error->code_sub = (unsigned)-1;
  18837. mg_snprintf(NULL,
  18838. NULL, /* No truncation check for error buffers */
  18839. error->text,
  18840. error->text_buffer_size,
  18841. "Invalid option: %s",
  18842. name);
  18843. }
  18844. mg_free(new_dom);
  18845. return -2;
  18846. } else if ((value = *options++) == NULL) {
  18847. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18848. if (error != NULL) {
  18849. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18850. error->code_sub = (unsigned)idx;
  18851. mg_snprintf(NULL,
  18852. NULL, /* No truncation check for error buffers */
  18853. error->text,
  18854. error->text_buffer_size,
  18855. "Invalid option value: %s",
  18856. name);
  18857. }
  18858. mg_free(new_dom);
  18859. return -2;
  18860. }
  18861. if (new_dom->config[idx] != NULL) {
  18862. /* Duplicate option: Later values overwrite earlier ones. */
  18863. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18864. mg_free(new_dom->config[idx]);
  18865. }
  18866. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18867. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18868. }
  18869. /* Authentication domain is mandatory */
  18870. /* TODO: Maybe use a new option hostname? */
  18871. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18872. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18873. if (error != NULL) {
  18874. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18875. error->code_sub = AUTHENTICATION_DOMAIN;
  18876. mg_snprintf(NULL,
  18877. NULL, /* No truncation check for error buffers */
  18878. error->text,
  18879. error->text_buffer_size,
  18880. "Mandatory option %s missing",
  18881. config_options[AUTHENTICATION_DOMAIN].name);
  18882. }
  18883. mg_free(new_dom);
  18884. return -4;
  18885. }
  18886. /* Set default value if needed. Take the config value from
  18887. * ctx as a default value. */
  18888. for (i = 0; config_options[i].name != NULL; i++) {
  18889. default_value = ctx->dd.config[i];
  18890. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18891. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18892. }
  18893. }
  18894. new_dom->handlers = NULL;
  18895. new_dom->next = NULL;
  18896. new_dom->nonce_count = 0;
  18897. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18898. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18899. new_dom->shared_lua_websockets = NULL;
  18900. #endif
  18901. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18902. if (!init_ssl_ctx(ctx, new_dom)) {
  18903. /* Init SSL failed */
  18904. if (error != NULL) {
  18905. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18906. mg_snprintf(NULL,
  18907. NULL, /* No truncation check for error buffers */
  18908. error->text,
  18909. error->text_buffer_size,
  18910. "%s",
  18911. "Initializing SSL context failed");
  18912. }
  18913. mg_free(new_dom);
  18914. return -3;
  18915. }
  18916. #endif
  18917. /* Add element to linked list. */
  18918. mg_lock_context(ctx);
  18919. idx = 0;
  18920. dom = &(ctx->dd);
  18921. for (;;) {
  18922. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18923. dom->config[AUTHENTICATION_DOMAIN])) {
  18924. /* Domain collision */
  18925. mg_cry_ctx_internal(ctx,
  18926. "domain %s already in use",
  18927. new_dom->config[AUTHENTICATION_DOMAIN]);
  18928. if (error != NULL) {
  18929. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18930. mg_snprintf(NULL,
  18931. NULL, /* No truncation check for error buffers */
  18932. error->text,
  18933. error->text_buffer_size,
  18934. "Domain %s specified by %s is already in use",
  18935. new_dom->config[AUTHENTICATION_DOMAIN],
  18936. config_options[AUTHENTICATION_DOMAIN].name);
  18937. }
  18938. mg_free(new_dom);
  18939. mg_unlock_context(ctx);
  18940. return -5;
  18941. }
  18942. /* Count number of domains */
  18943. idx++;
  18944. if (dom->next == NULL) {
  18945. dom->next = new_dom;
  18946. break;
  18947. }
  18948. dom = dom->next;
  18949. }
  18950. mg_unlock_context(ctx);
  18951. /* Return domain number */
  18952. return idx;
  18953. }
  18954. CIVETWEB_API int
  18955. mg_start_domain(struct mg_context *ctx, const char **options)
  18956. {
  18957. return mg_start_domain2(ctx, options, NULL);
  18958. }
  18959. /* Feature check API function */
  18960. CIVETWEB_API unsigned
  18961. mg_check_feature(unsigned feature)
  18962. {
  18963. static const unsigned feature_set = 0
  18964. /* Set bits for available features according to API documentation.
  18965. * This bit mask is created at compile time, according to the active
  18966. * preprocessor defines. It is a single const value at runtime. */
  18967. #if !defined(NO_FILES)
  18968. | MG_FEATURES_FILES
  18969. #endif
  18970. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18971. | MG_FEATURES_SSL
  18972. #endif
  18973. #if !defined(NO_CGI)
  18974. | MG_FEATURES_CGI
  18975. #endif
  18976. #if defined(USE_IPV6)
  18977. | MG_FEATURES_IPV6
  18978. #endif
  18979. #if defined(USE_WEBSOCKET)
  18980. | MG_FEATURES_WEBSOCKET
  18981. #endif
  18982. #if defined(USE_LUA)
  18983. | MG_FEATURES_LUA
  18984. #endif
  18985. #if defined(USE_DUKTAPE)
  18986. | MG_FEATURES_SSJS
  18987. #endif
  18988. #if !defined(NO_CACHING)
  18989. | MG_FEATURES_CACHE
  18990. #endif
  18991. #if defined(USE_SERVER_STATS)
  18992. | MG_FEATURES_STATS
  18993. #endif
  18994. #if defined(USE_ZLIB)
  18995. | MG_FEATURES_COMPRESSION
  18996. #endif
  18997. #if defined(USE_HTTP2)
  18998. | MG_FEATURES_HTTP2
  18999. #endif
  19000. #if defined(USE_X_DOM_SOCKET)
  19001. | MG_FEATURES_X_DOMAIN_SOCKET
  19002. #endif
  19003. /* Set some extra bits not defined in the API documentation.
  19004. * These bits may change without further notice. */
  19005. #if defined(MG_LEGACY_INTERFACE)
  19006. | 0x80000000u
  19007. #endif
  19008. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19009. | 0x40000000u
  19010. #endif
  19011. #if !defined(NO_RESPONSE_BUFFERING)
  19012. | 0x20000000u
  19013. #endif
  19014. #if defined(MEMORY_DEBUGGING)
  19015. | 0x10000000u
  19016. #endif
  19017. ;
  19018. return (feature & feature_set);
  19019. }
  19020. static size_t
  19021. mg_str_append(char **dst, char *end, const char *src)
  19022. {
  19023. size_t len = strlen(src);
  19024. if (*dst != end) {
  19025. /* Append src if enough space, or close dst. */
  19026. if ((size_t)(end - *dst) > len) {
  19027. strcpy(*dst, src);
  19028. *dst += len;
  19029. } else {
  19030. *dst = end;
  19031. }
  19032. }
  19033. return len;
  19034. }
  19035. /* Get system information. It can be printed or stored by the caller.
  19036. * Return the size of available information. */
  19037. CIVETWEB_API int
  19038. mg_get_system_info(char *buffer, int buflen)
  19039. {
  19040. char *end, *append_eoobj = NULL, block[256];
  19041. size_t system_info_length = 0;
  19042. #if defined(_WIN32)
  19043. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19044. #else
  19045. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19046. #endif
  19047. if ((buffer == NULL) || (buflen < 1)) {
  19048. buflen = 0;
  19049. end = buffer;
  19050. } else {
  19051. *buffer = 0;
  19052. end = buffer + buflen;
  19053. }
  19054. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19055. /* has enough space to append eoobj */
  19056. append_eoobj = buffer;
  19057. if (end) {
  19058. end -= sizeof(eoobj) - 1;
  19059. }
  19060. }
  19061. system_info_length += mg_str_append(&buffer, end, "{");
  19062. /* Server version */
  19063. {
  19064. const char *version = mg_version();
  19065. mg_snprintf(NULL,
  19066. NULL,
  19067. block,
  19068. sizeof(block),
  19069. "%s\"version\" : \"%s\"",
  19070. eol,
  19071. version);
  19072. system_info_length += mg_str_append(&buffer, end, block);
  19073. }
  19074. /* System info */
  19075. {
  19076. #if defined(_WIN32)
  19077. DWORD dwVersion = 0;
  19078. DWORD dwMajorVersion = 0;
  19079. DWORD dwMinorVersion = 0;
  19080. SYSTEM_INFO si;
  19081. GetSystemInfo(&si);
  19082. #if defined(_MSC_VER)
  19083. #pragma warning(push)
  19084. /* GetVersion was declared deprecated */
  19085. #pragma warning(disable : 4996)
  19086. #endif
  19087. dwVersion = GetVersion();
  19088. #if defined(_MSC_VER)
  19089. #pragma warning(pop)
  19090. #endif
  19091. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19092. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19093. mg_snprintf(NULL,
  19094. NULL,
  19095. block,
  19096. sizeof(block),
  19097. ",%s\"os\" : \"Windows %u.%u\"",
  19098. eol,
  19099. (unsigned)dwMajorVersion,
  19100. (unsigned)dwMinorVersion);
  19101. system_info_length += mg_str_append(&buffer, end, block);
  19102. mg_snprintf(NULL,
  19103. NULL,
  19104. block,
  19105. sizeof(block),
  19106. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19107. eol,
  19108. (unsigned)si.wProcessorArchitecture,
  19109. (unsigned)si.dwNumberOfProcessors,
  19110. (unsigned)si.dwActiveProcessorMask);
  19111. system_info_length += mg_str_append(&buffer, end, block);
  19112. #elif defined(__ZEPHYR__)
  19113. mg_snprintf(NULL,
  19114. NULL,
  19115. block,
  19116. sizeof(block),
  19117. ",%s\"os\" : \"%s %s\"",
  19118. eol,
  19119. "Zephyr OS",
  19120. ZEPHYR_VERSION);
  19121. system_info_length += mg_str_append(&buffer, end, block);
  19122. #else
  19123. struct utsname name;
  19124. memset(&name, 0, sizeof(name));
  19125. uname(&name);
  19126. mg_snprintf(NULL,
  19127. NULL,
  19128. block,
  19129. sizeof(block),
  19130. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19131. eol,
  19132. name.sysname,
  19133. name.version,
  19134. name.release,
  19135. name.machine);
  19136. system_info_length += mg_str_append(&buffer, end, block);
  19137. #endif
  19138. }
  19139. /* Features */
  19140. {
  19141. mg_snprintf(NULL,
  19142. NULL,
  19143. block,
  19144. sizeof(block),
  19145. ",%s\"features\" : %lu"
  19146. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19147. eol,
  19148. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19149. eol,
  19150. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19151. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19152. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19153. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19154. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19155. : "",
  19156. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19157. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19158. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19159. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19160. system_info_length += mg_str_append(&buffer, end, block);
  19161. #if defined(USE_LUA)
  19162. mg_snprintf(NULL,
  19163. NULL,
  19164. block,
  19165. sizeof(block),
  19166. ",%s\"lua_version\" : \"%u (%s)\"",
  19167. eol,
  19168. (unsigned)LUA_VERSION_NUM,
  19169. LUA_RELEASE);
  19170. system_info_length += mg_str_append(&buffer, end, block);
  19171. #endif
  19172. #if defined(USE_DUKTAPE)
  19173. mg_snprintf(NULL,
  19174. NULL,
  19175. block,
  19176. sizeof(block),
  19177. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19178. eol,
  19179. (unsigned)DUK_VERSION / 10000,
  19180. ((unsigned)DUK_VERSION / 100) % 100,
  19181. (unsigned)DUK_VERSION % 100);
  19182. system_info_length += mg_str_append(&buffer, end, block);
  19183. #endif
  19184. }
  19185. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19186. {
  19187. #if defined(BUILD_DATE)
  19188. const char *bd = BUILD_DATE;
  19189. #else
  19190. #if defined(GCC_DIAGNOSTIC)
  19191. #if GCC_VERSION >= 40900
  19192. #pragma GCC diagnostic push
  19193. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19194. * does not work in some versions. If "BUILD_DATE" is defined to some
  19195. * string, it is used instead of __DATE__. */
  19196. #pragma GCC diagnostic ignored "-Wdate-time"
  19197. #endif
  19198. #endif
  19199. const char *bd = __DATE__;
  19200. #if defined(GCC_DIAGNOSTIC)
  19201. #if GCC_VERSION >= 40900
  19202. #pragma GCC diagnostic pop
  19203. #endif
  19204. #endif
  19205. #endif
  19206. mg_snprintf(
  19207. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19208. system_info_length += mg_str_append(&buffer, end, block);
  19209. }
  19210. /* Compiler information */
  19211. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19212. {
  19213. #if defined(_MSC_VER)
  19214. mg_snprintf(NULL,
  19215. NULL,
  19216. block,
  19217. sizeof(block),
  19218. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19219. eol,
  19220. (unsigned)_MSC_VER,
  19221. (unsigned)_MSC_FULL_VER);
  19222. system_info_length += mg_str_append(&buffer, end, block);
  19223. #elif defined(__MINGW64__)
  19224. mg_snprintf(NULL,
  19225. NULL,
  19226. block,
  19227. sizeof(block),
  19228. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19229. eol,
  19230. (unsigned)__MINGW64_VERSION_MAJOR,
  19231. (unsigned)__MINGW64_VERSION_MINOR);
  19232. system_info_length += mg_str_append(&buffer, end, block);
  19233. mg_snprintf(NULL,
  19234. NULL,
  19235. block,
  19236. sizeof(block),
  19237. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19238. eol,
  19239. (unsigned)__MINGW32_MAJOR_VERSION,
  19240. (unsigned)__MINGW32_MINOR_VERSION);
  19241. system_info_length += mg_str_append(&buffer, end, block);
  19242. #elif defined(__MINGW32__)
  19243. mg_snprintf(NULL,
  19244. NULL,
  19245. block,
  19246. sizeof(block),
  19247. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19248. eol,
  19249. (unsigned)__MINGW32_MAJOR_VERSION,
  19250. (unsigned)__MINGW32_MINOR_VERSION);
  19251. system_info_length += mg_str_append(&buffer, end, block);
  19252. #elif defined(__clang__)
  19253. mg_snprintf(NULL,
  19254. NULL,
  19255. block,
  19256. sizeof(block),
  19257. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19258. eol,
  19259. __clang_major__,
  19260. __clang_minor__,
  19261. __clang_patchlevel__,
  19262. __clang_version__);
  19263. system_info_length += mg_str_append(&buffer, end, block);
  19264. #elif defined(__GNUC__)
  19265. mg_snprintf(NULL,
  19266. NULL,
  19267. block,
  19268. sizeof(block),
  19269. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19270. eol,
  19271. (unsigned)__GNUC__,
  19272. (unsigned)__GNUC_MINOR__,
  19273. (unsigned)__GNUC_PATCHLEVEL__);
  19274. system_info_length += mg_str_append(&buffer, end, block);
  19275. #elif defined(__INTEL_COMPILER)
  19276. mg_snprintf(NULL,
  19277. NULL,
  19278. block,
  19279. sizeof(block),
  19280. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19281. eol,
  19282. (unsigned)__INTEL_COMPILER);
  19283. system_info_length += mg_str_append(&buffer, end, block);
  19284. #elif defined(__BORLANDC__)
  19285. mg_snprintf(NULL,
  19286. NULL,
  19287. block,
  19288. sizeof(block),
  19289. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19290. eol,
  19291. (unsigned)__BORLANDC__);
  19292. system_info_length += mg_str_append(&buffer, end, block);
  19293. #elif defined(__SUNPRO_C)
  19294. mg_snprintf(NULL,
  19295. NULL,
  19296. block,
  19297. sizeof(block),
  19298. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19299. eol,
  19300. (unsigned)__SUNPRO_C);
  19301. system_info_length += mg_str_append(&buffer, end, block);
  19302. #else
  19303. mg_snprintf(NULL,
  19304. NULL,
  19305. block,
  19306. sizeof(block),
  19307. ",%s\"compiler\" : \"other\"",
  19308. eol);
  19309. system_info_length += mg_str_append(&buffer, end, block);
  19310. #endif
  19311. }
  19312. /* Determine 32/64 bit data mode.
  19313. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19314. {
  19315. mg_snprintf(NULL,
  19316. NULL,
  19317. block,
  19318. sizeof(block),
  19319. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19320. "char:%u/%u, "
  19321. "ptr:%u, size:%u, time:%u\"",
  19322. eol,
  19323. (unsigned)sizeof(short),
  19324. (unsigned)sizeof(int),
  19325. (unsigned)sizeof(long),
  19326. (unsigned)sizeof(long long),
  19327. (unsigned)sizeof(float),
  19328. (unsigned)sizeof(double),
  19329. (unsigned)sizeof(long double),
  19330. (unsigned)sizeof(char),
  19331. (unsigned)sizeof(wchar_t),
  19332. (unsigned)sizeof(void *),
  19333. (unsigned)sizeof(size_t),
  19334. (unsigned)sizeof(time_t));
  19335. system_info_length += mg_str_append(&buffer, end, block);
  19336. }
  19337. /* Terminate string */
  19338. if (append_eoobj) {
  19339. strcat(append_eoobj, eoobj);
  19340. }
  19341. system_info_length += sizeof(eoobj) - 1;
  19342. return (int)system_info_length;
  19343. }
  19344. /* Get context information. It can be printed or stored by the caller.
  19345. * Return the size of available information. */
  19346. CIVETWEB_API int
  19347. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19348. {
  19349. #if defined(USE_SERVER_STATS)
  19350. char *end, *append_eoobj = NULL, block[256];
  19351. size_t context_info_length = 0;
  19352. #if defined(_WIN32)
  19353. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19354. #else
  19355. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19356. #endif
  19357. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19358. if ((buffer == NULL) || (buflen < 1)) {
  19359. buflen = 0;
  19360. end = buffer;
  19361. } else {
  19362. *buffer = 0;
  19363. end = buffer + buflen;
  19364. }
  19365. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19366. /* has enough space to append eoobj */
  19367. append_eoobj = buffer;
  19368. end -= sizeof(eoobj) - 1;
  19369. }
  19370. context_info_length += mg_str_append(&buffer, end, "{");
  19371. if (ms) { /* <-- should be always true */
  19372. /* Memory information */
  19373. int blockCount = (int)ms->blockCount;
  19374. int64_t totalMemUsed = ms->totalMemUsed;
  19375. int64_t maxMemUsed = ms->maxMemUsed;
  19376. if (totalMemUsed > maxMemUsed) {
  19377. maxMemUsed = totalMemUsed;
  19378. }
  19379. mg_snprintf(NULL,
  19380. NULL,
  19381. block,
  19382. sizeof(block),
  19383. "%s\"memory\" : {%s"
  19384. "\"blocks\" : %i,%s"
  19385. "\"used\" : %" INT64_FMT ",%s"
  19386. "\"maxUsed\" : %" INT64_FMT "%s"
  19387. "}",
  19388. eol,
  19389. eol,
  19390. blockCount,
  19391. eol,
  19392. totalMemUsed,
  19393. eol,
  19394. maxMemUsed,
  19395. eol);
  19396. context_info_length += mg_str_append(&buffer, end, block);
  19397. }
  19398. if (ctx) {
  19399. /* Declare all variables at begin of the block, to comply
  19400. * with old C standards. */
  19401. char start_time_str[64] = {0};
  19402. char now_str[64] = {0};
  19403. time_t start_time = ctx->start_time;
  19404. time_t now = time(NULL);
  19405. int64_t total_data_read, total_data_written;
  19406. int active_connections = (int)ctx->active_connections;
  19407. int max_active_connections = (int)ctx->max_active_connections;
  19408. int total_connections = (int)ctx->total_connections;
  19409. if (active_connections > max_active_connections) {
  19410. max_active_connections = active_connections;
  19411. }
  19412. if (active_connections > total_connections) {
  19413. total_connections = active_connections;
  19414. }
  19415. /* Connections information */
  19416. mg_snprintf(NULL,
  19417. NULL,
  19418. block,
  19419. sizeof(block),
  19420. ",%s\"connections\" : {%s"
  19421. "\"active\" : %i,%s"
  19422. "\"maxActive\" : %i,%s"
  19423. "\"total\" : %i%s"
  19424. "}",
  19425. eol,
  19426. eol,
  19427. active_connections,
  19428. eol,
  19429. max_active_connections,
  19430. eol,
  19431. total_connections,
  19432. eol);
  19433. context_info_length += mg_str_append(&buffer, end, block);
  19434. /* Queue information */
  19435. #if !defined(ALTERNATIVE_QUEUE)
  19436. mg_snprintf(NULL,
  19437. NULL,
  19438. block,
  19439. sizeof(block),
  19440. ",%s\"queue\" : {%s"
  19441. "\"length\" : %i,%s"
  19442. "\"filled\" : %i,%s"
  19443. "\"maxFilled\" : %i,%s"
  19444. "\"full\" : %s%s"
  19445. "}",
  19446. eol,
  19447. eol,
  19448. ctx->sq_size,
  19449. eol,
  19450. ctx->sq_head - ctx->sq_tail,
  19451. eol,
  19452. ctx->sq_max_fill,
  19453. eol,
  19454. (ctx->sq_blocked ? "true" : "false"),
  19455. eol);
  19456. context_info_length += mg_str_append(&buffer, end, block);
  19457. #endif
  19458. /* Requests information */
  19459. mg_snprintf(NULL,
  19460. NULL,
  19461. block,
  19462. sizeof(block),
  19463. ",%s\"requests\" : {%s"
  19464. "\"total\" : %lu%s"
  19465. "}",
  19466. eol,
  19467. eol,
  19468. (unsigned long)ctx->total_requests,
  19469. eol);
  19470. context_info_length += mg_str_append(&buffer, end, block);
  19471. /* Data information */
  19472. total_data_read =
  19473. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19474. total_data_written =
  19475. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19476. mg_snprintf(NULL,
  19477. NULL,
  19478. block,
  19479. sizeof(block),
  19480. ",%s\"data\" : {%s"
  19481. "\"read\" : %" INT64_FMT ",%s"
  19482. "\"written\" : %" INT64_FMT "%s"
  19483. "}",
  19484. eol,
  19485. eol,
  19486. total_data_read,
  19487. eol,
  19488. total_data_written,
  19489. eol);
  19490. context_info_length += mg_str_append(&buffer, end, block);
  19491. /* Execution time information */
  19492. gmt_time_string(start_time_str,
  19493. sizeof(start_time_str) - 1,
  19494. &start_time);
  19495. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19496. mg_snprintf(NULL,
  19497. NULL,
  19498. block,
  19499. sizeof(block),
  19500. ",%s\"time\" : {%s"
  19501. "\"uptime\" : %.0f,%s"
  19502. "\"start\" : \"%s\",%s"
  19503. "\"now\" : \"%s\"%s"
  19504. "}",
  19505. eol,
  19506. eol,
  19507. difftime(now, start_time),
  19508. eol,
  19509. start_time_str,
  19510. eol,
  19511. now_str,
  19512. eol);
  19513. context_info_length += mg_str_append(&buffer, end, block);
  19514. }
  19515. /* Terminate string */
  19516. if (append_eoobj) {
  19517. strcat(append_eoobj, eoobj);
  19518. }
  19519. context_info_length += sizeof(eoobj) - 1;
  19520. return (int)context_info_length;
  19521. #else
  19522. (void)ctx;
  19523. if ((buffer != NULL) && (buflen > 0)) {
  19524. *buffer = 0;
  19525. }
  19526. return 0;
  19527. #endif
  19528. }
  19529. CIVETWEB_API void
  19530. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19531. {
  19532. /* https://github.com/civetweb/civetweb/issues/727 */
  19533. if (conn != NULL) {
  19534. conn->must_close = 1;
  19535. }
  19536. }
  19537. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19538. /* Get connection information. It can be printed or stored by the caller.
  19539. * Return the size of available information. */
  19540. CIVETWEB_API int
  19541. mg_get_connection_info(const struct mg_context *ctx,
  19542. int idx,
  19543. char *buffer,
  19544. int buflen)
  19545. {
  19546. const struct mg_connection *conn;
  19547. const struct mg_request_info *ri;
  19548. char *end, *append_eoobj = NULL, block[256];
  19549. size_t connection_info_length = 0;
  19550. int state = 0;
  19551. const char *state_str = "unknown";
  19552. #if defined(_WIN32)
  19553. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19554. #else
  19555. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19556. #endif
  19557. if ((buffer == NULL) || (buflen < 1)) {
  19558. buflen = 0;
  19559. end = buffer;
  19560. } else {
  19561. *buffer = 0;
  19562. end = buffer + buflen;
  19563. }
  19564. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19565. /* has enough space to append eoobj */
  19566. append_eoobj = buffer;
  19567. end -= sizeof(eoobj) - 1;
  19568. }
  19569. if ((ctx == NULL) || (idx < 0)) {
  19570. /* Parameter error */
  19571. return 0;
  19572. }
  19573. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19574. /* Out of range */
  19575. return 0;
  19576. }
  19577. /* Take connection [idx]. This connection is not locked in
  19578. * any way, so some other thread might use it. */
  19579. conn = (ctx->worker_connections) + idx;
  19580. /* Initialize output string */
  19581. connection_info_length += mg_str_append(&buffer, end, "{");
  19582. /* Init variables */
  19583. ri = &(conn->request_info);
  19584. #if defined(USE_SERVER_STATS)
  19585. state = conn->conn_state;
  19586. /* State as string */
  19587. switch (state) {
  19588. case 0:
  19589. state_str = "undefined";
  19590. break;
  19591. case 1:
  19592. state_str = "not used";
  19593. break;
  19594. case 2:
  19595. state_str = "init";
  19596. break;
  19597. case 3:
  19598. state_str = "ready";
  19599. break;
  19600. case 4:
  19601. state_str = "processing";
  19602. break;
  19603. case 5:
  19604. state_str = "processed";
  19605. break;
  19606. case 6:
  19607. state_str = "to close";
  19608. break;
  19609. case 7:
  19610. state_str = "closing";
  19611. break;
  19612. case 8:
  19613. state_str = "closed";
  19614. break;
  19615. case 9:
  19616. state_str = "done";
  19617. break;
  19618. }
  19619. #endif
  19620. /* Connection info */
  19621. if ((state >= 3) && (state < 9)) {
  19622. mg_snprintf(NULL,
  19623. NULL,
  19624. block,
  19625. sizeof(block),
  19626. "%s\"connection\" : {%s"
  19627. "\"remote\" : {%s"
  19628. "\"protocol\" : \"%s\",%s"
  19629. "\"addr\" : \"%s\",%s"
  19630. "\"port\" : %u%s"
  19631. "},%s"
  19632. "\"handled_requests\" : %u%s"
  19633. "}",
  19634. eol,
  19635. eol,
  19636. eol,
  19637. get_proto_name(conn),
  19638. eol,
  19639. ri->remote_addr,
  19640. eol,
  19641. ri->remote_port,
  19642. eol,
  19643. eol,
  19644. conn->handled_requests,
  19645. eol);
  19646. connection_info_length += mg_str_append(&buffer, end, block);
  19647. }
  19648. /* Request info */
  19649. if ((state >= 4) && (state < 6)) {
  19650. mg_snprintf(NULL,
  19651. NULL,
  19652. block,
  19653. sizeof(block),
  19654. "%s%s\"request_info\" : {%s"
  19655. "\"method\" : \"%s\",%s"
  19656. "\"uri\" : \"%s\",%s"
  19657. "\"query\" : %s%s%s%s"
  19658. "}",
  19659. (connection_info_length > 1 ? "," : ""),
  19660. eol,
  19661. eol,
  19662. ri->request_method,
  19663. eol,
  19664. ri->request_uri,
  19665. eol,
  19666. ri->query_string ? "\"" : "",
  19667. ri->query_string ? ri->query_string : "null",
  19668. ri->query_string ? "\"" : "",
  19669. eol);
  19670. connection_info_length += mg_str_append(&buffer, end, block);
  19671. }
  19672. /* Execution time information */
  19673. if ((state >= 2) && (state < 9)) {
  19674. char start_time_str[64] = {0};
  19675. char close_time_str[64] = {0};
  19676. time_t start_time = conn->conn_birth_time;
  19677. time_t close_time = 0;
  19678. double time_diff;
  19679. gmt_time_string(start_time_str,
  19680. sizeof(start_time_str) - 1,
  19681. &start_time);
  19682. #if defined(USE_SERVER_STATS)
  19683. close_time = conn->conn_close_time;
  19684. #endif
  19685. if (close_time != 0) {
  19686. time_diff = difftime(close_time, start_time);
  19687. gmt_time_string(close_time_str,
  19688. sizeof(close_time_str) - 1,
  19689. &close_time);
  19690. } else {
  19691. time_t now = time(NULL);
  19692. time_diff = difftime(now, start_time);
  19693. close_time_str[0] = 0; /* or use "now" ? */
  19694. }
  19695. mg_snprintf(NULL,
  19696. NULL,
  19697. block,
  19698. sizeof(block),
  19699. "%s%s\"time\" : {%s"
  19700. "\"uptime\" : %.0f,%s"
  19701. "\"start\" : \"%s\",%s"
  19702. "\"closed\" : \"%s\"%s"
  19703. "}",
  19704. (connection_info_length > 1 ? "," : ""),
  19705. eol,
  19706. eol,
  19707. time_diff,
  19708. eol,
  19709. start_time_str,
  19710. eol,
  19711. close_time_str,
  19712. eol);
  19713. connection_info_length += mg_str_append(&buffer, end, block);
  19714. }
  19715. /* Remote user name */
  19716. if ((ri->remote_user) && (state < 9)) {
  19717. mg_snprintf(NULL,
  19718. NULL,
  19719. block,
  19720. sizeof(block),
  19721. "%s%s\"user\" : {%s"
  19722. "\"name\" : \"%s\",%s"
  19723. "}",
  19724. (connection_info_length > 1 ? "," : ""),
  19725. eol,
  19726. eol,
  19727. ri->remote_user,
  19728. eol);
  19729. connection_info_length += mg_str_append(&buffer, end, block);
  19730. }
  19731. /* Data block */
  19732. if (state >= 3) {
  19733. mg_snprintf(NULL,
  19734. NULL,
  19735. block,
  19736. sizeof(block),
  19737. "%s%s\"data\" : {%s"
  19738. "\"read\" : %" INT64_FMT ",%s"
  19739. "\"written\" : %" INT64_FMT "%s"
  19740. "}",
  19741. (connection_info_length > 1 ? "," : ""),
  19742. eol,
  19743. eol,
  19744. conn->consumed_content,
  19745. eol,
  19746. conn->num_bytes_sent,
  19747. eol);
  19748. connection_info_length += mg_str_append(&buffer, end, block);
  19749. }
  19750. /* State */
  19751. mg_snprintf(NULL,
  19752. NULL,
  19753. block,
  19754. sizeof(block),
  19755. "%s%s\"state\" : \"%s\"",
  19756. (connection_info_length > 1 ? "," : ""),
  19757. eol,
  19758. state_str);
  19759. connection_info_length += mg_str_append(&buffer, end, block);
  19760. /* Terminate string */
  19761. if (append_eoobj) {
  19762. strcat(append_eoobj, eoobj);
  19763. }
  19764. connection_info_length += sizeof(eoobj) - 1;
  19765. return (int)connection_info_length;
  19766. }
  19767. #if 0
  19768. /* Get handler information. Not fully implemented. Is it required? */
  19769. CIVETWEB_API int
  19770. mg_get_handler_info(struct mg_context *ctx,
  19771. char *buffer,
  19772. int buflen)
  19773. {
  19774. int handler_info_len = 0;
  19775. struct mg_handler_info *tmp_rh;
  19776. mg_lock_context(ctx);
  19777. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19778. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19779. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19780. }
  19781. handler_info_len += tmp_rh->uri_len;
  19782. switch (tmp_rh->handler_type) {
  19783. case REQUEST_HANDLER:
  19784. (void)tmp_rh->handler;
  19785. break;
  19786. case WEBSOCKET_HANDLER:
  19787. (void)tmp_rh->connect_handler;
  19788. (void)tmp_rh->ready_handler;
  19789. (void)tmp_rh->data_handler;
  19790. (void)tmp_rh->close_handler;
  19791. break;
  19792. case AUTH_HANDLER:
  19793. (void)tmp_rh->auth_handler;
  19794. break;
  19795. }
  19796. (void)cbdata;
  19797. }
  19798. mg_unlock_context(ctx);
  19799. return handler_info_len;
  19800. }
  19801. #endif
  19802. #endif
  19803. /* Initialize this library. This function does not need to be thread safe.
  19804. */
  19805. CIVETWEB_API unsigned
  19806. mg_init_library(unsigned features)
  19807. {
  19808. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19809. unsigned features_inited = features_to_init;
  19810. if (mg_init_library_called <= 0) {
  19811. /* Not initialized yet */
  19812. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19813. return 0;
  19814. }
  19815. }
  19816. mg_global_lock();
  19817. if (mg_init_library_called <= 0) {
  19818. int i;
  19819. size_t len;
  19820. #if defined(_WIN32)
  19821. int file_mutex_init = 1;
  19822. int wsa = 1;
  19823. #else
  19824. int mutexattr_init = 1;
  19825. #endif
  19826. int failed = 1;
  19827. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19828. if (key_create == 0) {
  19829. #if defined(_WIN32)
  19830. file_mutex_init =
  19831. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19832. if (file_mutex_init == 0) {
  19833. /* Start WinSock */
  19834. WSADATA data;
  19835. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19836. }
  19837. #else
  19838. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19839. if (mutexattr_init == 0) {
  19840. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19841. PTHREAD_MUTEX_RECURSIVE);
  19842. }
  19843. #endif
  19844. }
  19845. if (failed) {
  19846. #if defined(_WIN32)
  19847. if (wsa == 0) {
  19848. (void)WSACleanup();
  19849. }
  19850. if (file_mutex_init == 0) {
  19851. (void)pthread_mutex_destroy(&global_log_file_lock);
  19852. }
  19853. #else
  19854. if (mutexattr_init == 0) {
  19855. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19856. }
  19857. #endif
  19858. if (key_create == 0) {
  19859. (void)pthread_key_delete(sTlsKey);
  19860. }
  19861. mg_global_unlock();
  19862. (void)pthread_mutex_destroy(&global_lock_mutex);
  19863. return 0;
  19864. }
  19865. len = 1;
  19866. for (i = 0; http_methods[i].name != NULL; i++) {
  19867. size_t sl = strlen(http_methods[i].name);
  19868. len += sl;
  19869. if (i > 0) {
  19870. len += 2;
  19871. }
  19872. }
  19873. all_methods = (char *)mg_malloc(len);
  19874. if (!all_methods) {
  19875. /* Must never happen */
  19876. mg_global_unlock();
  19877. (void)pthread_mutex_destroy(&global_lock_mutex);
  19878. return 0;
  19879. }
  19880. all_methods[0] = 0;
  19881. for (i = 0; http_methods[i].name != NULL; i++) {
  19882. if (i > 0) {
  19883. strcat(all_methods, ", ");
  19884. strcat(all_methods, http_methods[i].name);
  19885. } else {
  19886. strcpy(all_methods, http_methods[i].name);
  19887. }
  19888. }
  19889. }
  19890. #if defined(USE_LUA)
  19891. lua_init_optional_libraries();
  19892. #endif
  19893. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19894. || defined(OPENSSL_API_3_0)) \
  19895. && !defined(NO_SSL)
  19896. if (features_to_init & MG_FEATURES_SSL) {
  19897. if (!mg_openssl_initialized) {
  19898. char ebuf[128];
  19899. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19900. mg_openssl_initialized = 1;
  19901. } else {
  19902. (void)ebuf;
  19903. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19904. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19905. }
  19906. } else {
  19907. /* ssl already initialized */
  19908. }
  19909. }
  19910. #endif
  19911. if (mg_init_library_called <= 0) {
  19912. mg_init_library_called = 1;
  19913. } else {
  19914. mg_init_library_called++;
  19915. }
  19916. mg_global_unlock();
  19917. return features_inited;
  19918. }
  19919. /* Un-initialize this library. */
  19920. CIVETWEB_API unsigned
  19921. mg_exit_library(void)
  19922. {
  19923. if (mg_init_library_called <= 0) {
  19924. return 0;
  19925. }
  19926. mg_global_lock();
  19927. mg_init_library_called--;
  19928. if (mg_init_library_called == 0) {
  19929. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19930. if (mg_openssl_initialized) {
  19931. uninitialize_openssl();
  19932. mg_openssl_initialized = 0;
  19933. }
  19934. #endif
  19935. #if defined(_WIN32)
  19936. (void)WSACleanup();
  19937. (void)pthread_mutex_destroy(&global_log_file_lock);
  19938. #else
  19939. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19940. #endif
  19941. (void)pthread_key_delete(sTlsKey);
  19942. #if defined(USE_LUA)
  19943. lua_exit_optional_libraries();
  19944. #endif
  19945. mg_free(all_methods);
  19946. all_methods = NULL;
  19947. mg_global_unlock();
  19948. (void)pthread_mutex_destroy(&global_lock_mutex);
  19949. return 1;
  19950. }
  19951. mg_global_unlock();
  19952. return 1;
  19953. }
  19954. /* End of civetweb.c */