civetweb.c 619 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197
  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(__rtems__)
  170. #include <rtems/version.h>
  171. #endif
  172. #if defined(__ZEPHYR__)
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <poll.h>
  177. #include <pthread.h>
  178. #include <stdio.h>
  179. #include <stdlib.h>
  180. #include <string.h>
  181. #include <sys/socket.h>
  182. #include <time.h>
  183. #include <zephyr/kernel.h>
  184. /* Max worker threads is the max of pthreads minus the main application thread
  185. * and minus the main civetweb thread, thus -2
  186. */
  187. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  188. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  189. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  190. #else
  191. #define ZEPHYR_STACK_SIZE (1024 * 16)
  192. #endif
  193. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  194. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  195. MAX_WORKER_THREADS,
  196. ZEPHYR_STACK_SIZE);
  197. static int zephyr_worker_stack_index;
  198. #endif
  199. #if !defined(CIVETWEB_HEADER_INCLUDED)
  200. /* Include the header file here, so the CivetWeb interface is defined for the
  201. * entire implementation, including the following forward definitions. */
  202. #include "civetweb.h"
  203. #endif
  204. #if !defined(DEBUG_TRACE)
  205. #if defined(DEBUG)
  206. static void DEBUG_TRACE_FUNC(const char *func,
  207. unsigned line,
  208. PRINTF_FORMAT_STRING(const char *fmt),
  209. ...) PRINTF_ARGS(3, 4);
  210. #define DEBUG_TRACE(fmt, ...) \
  211. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  212. #define NEED_DEBUG_TRACE_FUNC
  213. #if !defined(DEBUG_TRACE_STREAM)
  214. #define DEBUG_TRACE_STREAM stdout
  215. #endif
  216. #else
  217. #define DEBUG_TRACE(fmt, ...) \
  218. do { \
  219. } while (0)
  220. #endif /* DEBUG */
  221. #endif /* DEBUG_TRACE */
  222. #if !defined(DEBUG_ASSERT)
  223. #if defined(DEBUG)
  224. #include <stdlib.h>
  225. #define DEBUG_ASSERT(cond) \
  226. do { \
  227. if (!(cond)) { \
  228. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  229. exit(2); /* Exit with error */ \
  230. } \
  231. } while (0)
  232. #else
  233. #define DEBUG_ASSERT(cond)
  234. #endif /* DEBUG */
  235. #endif
  236. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  237. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. __attribute__((no_instrument_function));
  239. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  240. __attribute__((no_instrument_function));
  241. void
  242. __cyg_profile_func_enter(void *this_fn, void *call_site)
  243. {
  244. if ((void *)this_fn != (void *)printf) {
  245. printf("E %p %p\n", this_fn, call_site);
  246. }
  247. }
  248. void
  249. __cyg_profile_func_exit(void *this_fn, void *call_site)
  250. {
  251. if ((void *)this_fn != (void *)printf) {
  252. printf("X %p %p\n", this_fn, call_site);
  253. }
  254. }
  255. #endif
  256. #if !defined(IGNORE_UNUSED_RESULT)
  257. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  258. #endif
  259. #if defined(__GNUC__) || defined(__MINGW32__)
  260. /* GCC unused function attribute seems fundamentally broken.
  261. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  262. * OR UNUSED" for individual functions failed.
  263. * Either the compiler creates an "unused-function" warning if a
  264. * function is not marked with __attribute__((unused)).
  265. * On the other hand, if the function is marked with this attribute,
  266. * but is used, the compiler raises a completely idiotic
  267. * "used-but-marked-unused" warning - and
  268. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  269. * raises error: unknown option after "#pragma GCC diagnostic".
  270. * Disable this warning completely, until the GCC guys sober up
  271. * again.
  272. */
  273. #pragma GCC diagnostic ignored "-Wunused-function"
  274. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  275. #else
  276. #define FUNCTION_MAY_BE_UNUSED
  277. #endif
  278. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  279. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  280. #include <errno.h>
  281. #include <fcntl.h>
  282. #include <signal.h>
  283. #include <stdlib.h>
  284. #include <sys/stat.h>
  285. #include <sys/types.h>
  286. #endif /* !_WIN32_WCE */
  287. #if defined(__clang__)
  288. /* When using -Weverything, clang does not accept it's own headers
  289. * in a release build configuration. Disable what is too much in
  290. * -Weverything. */
  291. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  292. #endif
  293. #if defined(__GNUC__) || defined(__MINGW32__)
  294. /* Who on earth came to the conclusion, using __DATE__ should rise
  295. * an "expansion of date or time macro is not reproducible"
  296. * warning. That's exactly what was intended by using this macro.
  297. * Just disable this nonsense warning. */
  298. /* And disabling them does not work either:
  299. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  300. * #pragma clang diagnostic ignored "-Wdate-time"
  301. * So we just have to disable ALL warnings for some lines
  302. * of code.
  303. * This seems to be a known GCC bug, not resolved since 2012:
  304. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  305. */
  306. #endif
  307. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  308. #if defined(__clang__)
  309. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  310. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  311. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  312. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  313. #endif
  314. #endif
  315. #ifndef CLOCK_MONOTONIC
  316. #define CLOCK_MONOTONIC (1)
  317. #endif
  318. #ifndef CLOCK_REALTIME
  319. #define CLOCK_REALTIME (2)
  320. #endif
  321. #include <mach/clock.h>
  322. #include <mach/mach.h>
  323. #include <mach/mach_time.h>
  324. #include <sys/errno.h>
  325. #include <sys/time.h>
  326. /* clock_gettime is not implemented on OSX prior to 10.12 */
  327. static int
  328. _civet_clock_gettime(int clk_id, struct timespec *t)
  329. {
  330. memset(t, 0, sizeof(*t));
  331. if (clk_id == CLOCK_REALTIME) {
  332. struct timeval now;
  333. int rv = gettimeofday(&now, NULL);
  334. if (rv) {
  335. return rv;
  336. }
  337. t->tv_sec = now.tv_sec;
  338. t->tv_nsec = now.tv_usec * 1000;
  339. return 0;
  340. } else if (clk_id == CLOCK_MONOTONIC) {
  341. static uint64_t clock_start_time = 0;
  342. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  343. uint64_t now = mach_absolute_time();
  344. if (clock_start_time == 0) {
  345. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  346. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  347. /* appease "unused variable" warning for release builds */
  348. (void)mach_status;
  349. clock_start_time = now;
  350. }
  351. now = (uint64_t)((double)(now - clock_start_time)
  352. * (double)timebase_ifo.numer
  353. / (double)timebase_ifo.denom);
  354. t->tv_sec = now / 1000000000;
  355. t->tv_nsec = now % 1000000000;
  356. return 0;
  357. }
  358. return -1; /* EINVAL - Clock ID is unknown */
  359. }
  360. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  361. #if defined(__CLOCK_AVAILABILITY)
  362. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  363. * declared but it may be NULL at runtime. So we need to check before using
  364. * it. */
  365. static int
  366. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  367. {
  368. if (clock_gettime) {
  369. return clock_gettime(clk_id, t);
  370. }
  371. return _civet_clock_gettime(clk_id, t);
  372. }
  373. #define clock_gettime _civet_safe_clock_gettime
  374. #else
  375. #define clock_gettime _civet_clock_gettime
  376. #endif
  377. #endif
  378. #if defined(_WIN32)
  379. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  380. #else
  381. /* Unix might return different error codes indicating to try again.
  382. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  383. * decades ago, but better check both and let the compiler optimize it. */
  384. #define ERROR_TRY_AGAIN(err) \
  385. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  386. #endif
  387. #if defined(USE_ZLIB)
  388. #include "zconf.h"
  389. #include "zlib.h"
  390. #endif
  391. /********************************************************************/
  392. /* CivetWeb configuration defines */
  393. /********************************************************************/
  394. /* Maximum number of threads that can be configured.
  395. * The number of threads actually created depends on the "num_threads"
  396. * configuration parameter, but this is the upper limit. */
  397. #if !defined(MAX_WORKER_THREADS)
  398. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  399. #endif
  400. /* Timeout interval for select/poll calls.
  401. * The timeouts depend on "*_timeout_ms" configuration values, but long
  402. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  403. * This reduces the time required to stop the server. */
  404. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  405. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  406. #endif
  407. /* Do not try to compress files smaller than this limit. */
  408. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  409. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  410. #endif
  411. #if !defined(PASSWORDS_FILE_NAME)
  412. #define PASSWORDS_FILE_NAME ".htpasswd"
  413. #endif
  414. /* Initial buffer size for all CGI environment variables. In case there is
  415. * not enough space, another block is allocated. */
  416. #if !defined(CGI_ENVIRONMENT_SIZE)
  417. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  418. #endif
  419. /* Maximum number of environment variables. */
  420. #if !defined(MAX_CGI_ENVIR_VARS)
  421. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  422. #endif
  423. /* General purpose buffer size. */
  424. #if !defined(MG_BUF_LEN) /* in bytes */
  425. #define MG_BUF_LEN (1024 * 8)
  426. #endif
  427. /********************************************************************/
  428. /* Helper macros */
  429. #if !defined(ARRAY_SIZE)
  430. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  431. #endif
  432. #include <stdint.h>
  433. /* Standard defines */
  434. #if !defined(INT64_MAX)
  435. #define INT64_MAX (9223372036854775807)
  436. #endif
  437. #define SHUTDOWN_RD (0)
  438. #define SHUTDOWN_WR (1)
  439. #define SHUTDOWN_BOTH (2)
  440. mg_static_assert(MAX_WORKER_THREADS >= 1,
  441. "worker threads must be a positive number");
  442. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  443. "size_t data type size check");
  444. #if defined(_WIN32) /* WINDOWS include block */
  445. #include <malloc.h> /* *alloc( */
  446. #include <stdlib.h> /* *alloc( */
  447. #include <time.h> /* struct timespec */
  448. #include <windows.h>
  449. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  450. #include <ws2tcpip.h>
  451. typedef const char *SOCK_OPT_TYPE;
  452. /* For a detailed description of these *_PATH_MAX defines, see
  453. * https://github.com/civetweb/civetweb/issues/937. */
  454. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  455. * null termination, rounded up to the next 4 bytes boundary */
  456. #define UTF8_PATH_MAX (3 * 260)
  457. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  458. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  459. #define UTF16_PATH_MAX (260)
  460. #if !defined(_IN_PORT_T)
  461. #if !defined(in_port_t)
  462. #define in_port_t u_short
  463. #endif
  464. #endif
  465. #if defined(_WIN32_WCE)
  466. #error "WinCE support has ended"
  467. #endif
  468. #include <direct.h>
  469. #include <io.h>
  470. #include <process.h>
  471. #define MAKEUQUAD(lo, hi) \
  472. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  473. #define RATE_DIFF (10000000) /* 100 nsecs */
  474. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  475. #define SYS2UNIX_TIME(lo, hi) \
  476. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  477. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  478. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  479. * Also use _strtoui64 on modern M$ compilers */
  480. #if defined(_MSC_VER)
  481. #if (_MSC_VER < 1300)
  482. #define STRX(x) #x
  483. #define STR(x) STRX(x)
  484. #define __func__ __FILE__ ":" STR(__LINE__)
  485. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  486. #define strtoll(x, y, z) (_atoi64(x))
  487. #else
  488. #define __func__ __FUNCTION__
  489. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  490. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  491. #endif
  492. #endif /* _MSC_VER */
  493. #define ERRNO ((int)(GetLastError()))
  494. #define NO_SOCKLEN_T
  495. #if defined(_WIN64) || defined(__MINGW64__)
  496. #if !defined(SSL_LIB)
  497. #if defined(OPENSSL_API_3_0)
  498. #define SSL_LIB "libssl-3-x64.dll"
  499. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  500. #endif
  501. #if defined(OPENSSL_API_1_1)
  502. #define SSL_LIB "libssl-1_1-x64.dll"
  503. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  504. #endif /* OPENSSL_API_1_1 */
  505. #if defined(OPENSSL_API_1_0)
  506. #define SSL_LIB "ssleay64.dll"
  507. #define CRYPTO_LIB "libeay64.dll"
  508. #endif /* OPENSSL_API_1_0 */
  509. #endif
  510. #else /* defined(_WIN64) || defined(__MINGW64__) */
  511. #if !defined(SSL_LIB)
  512. #if defined(OPENSSL_API_3_0)
  513. #define SSL_LIB "libssl-3.dll"
  514. #define CRYPTO_LIB "libcrypto-3.dll"
  515. #endif
  516. #if defined(OPENSSL_API_1_1)
  517. #define SSL_LIB "libssl-1_1.dll"
  518. #define CRYPTO_LIB "libcrypto-1_1.dll"
  519. #endif /* OPENSSL_API_1_1 */
  520. #if defined(OPENSSL_API_1_0)
  521. #define SSL_LIB "ssleay32.dll"
  522. #define CRYPTO_LIB "libeay32.dll"
  523. #endif /* OPENSSL_API_1_0 */
  524. #endif /* SSL_LIB */
  525. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  526. #define O_NONBLOCK (0)
  527. #if !defined(W_OK)
  528. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  529. #endif
  530. #define _POSIX_
  531. #define INT64_FMT "I64d"
  532. #define UINT64_FMT "I64u"
  533. #define WINCDECL __cdecl
  534. #define vsnprintf_impl _vsnprintf
  535. #define access _access
  536. #define mg_sleep(x) (Sleep(x))
  537. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  538. #if !defined(popen)
  539. #define popen(x, y) (_popen(x, y))
  540. #endif
  541. #if !defined(pclose)
  542. #define pclose(x) (_pclose(x))
  543. #endif
  544. #define close(x) (_close(x))
  545. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  546. #define RTLD_LAZY (0)
  547. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  548. #define fdopen(x, y) (_fdopen((x), (y)))
  549. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  550. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  551. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  552. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  553. #define sleep(x) (Sleep((x)*1000))
  554. #define rmdir(x) (_rmdir(x))
  555. #if defined(_WIN64) || !defined(__MINGW32__)
  556. /* Only MinGW 32 bit is missing this function */
  557. #define timegm(x) (_mkgmtime(x))
  558. #else
  559. time_t timegm(struct tm *tm);
  560. #define NEED_TIMEGM
  561. #endif
  562. #if !defined(fileno)
  563. #define fileno(x) (_fileno(x))
  564. #endif /* !fileno MINGW #defines fileno */
  565. typedef struct {
  566. CRITICAL_SECTION sec; /* Immovable */
  567. } pthread_mutex_t;
  568. typedef DWORD pthread_key_t;
  569. typedef HANDLE pthread_t;
  570. typedef struct {
  571. pthread_mutex_t threadIdSec;
  572. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  573. } pthread_cond_t;
  574. #if !defined(__clockid_t_defined)
  575. typedef DWORD clockid_t;
  576. #endif
  577. #if !defined(CLOCK_MONOTONIC)
  578. #define CLOCK_MONOTONIC (1)
  579. #endif
  580. #if !defined(CLOCK_REALTIME)
  581. #define CLOCK_REALTIME (2)
  582. #endif
  583. #if !defined(CLOCK_THREAD)
  584. #define CLOCK_THREAD (3)
  585. #endif
  586. #if !defined(CLOCK_PROCESS)
  587. #define CLOCK_PROCESS (4)
  588. #endif
  589. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  590. #define _TIMESPEC_DEFINED
  591. #endif
  592. #if !defined(_TIMESPEC_DEFINED)
  593. struct timespec {
  594. time_t tv_sec; /* seconds */
  595. long tv_nsec; /* nanoseconds */
  596. };
  597. #endif
  598. #if !defined(WIN_PTHREADS_TIME_H)
  599. #define MUST_IMPLEMENT_CLOCK_GETTIME
  600. #endif
  601. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  602. #define clock_gettime mg_clock_gettime
  603. static int
  604. clock_gettime(clockid_t clk_id, struct timespec *tp)
  605. {
  606. FILETIME ft;
  607. ULARGE_INTEGER li, li2;
  608. BOOL ok = FALSE;
  609. double d;
  610. static double perfcnt_per_sec = 0.0;
  611. static BOOL initialized = FALSE;
  612. if (!initialized) {
  613. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  614. perfcnt_per_sec = 1.0 / li.QuadPart;
  615. initialized = TRUE;
  616. }
  617. if (tp) {
  618. memset(tp, 0, sizeof(*tp));
  619. if (clk_id == CLOCK_REALTIME) {
  620. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  621. GetSystemTimeAsFileTime(&ft);
  622. li.LowPart = ft.dwLowDateTime;
  623. li.HighPart = ft.dwHighDateTime;
  624. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  625. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  626. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  627. ok = TRUE;
  628. /* END: CLOCK_REALTIME */
  629. } else if (clk_id == CLOCK_MONOTONIC) {
  630. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  631. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  632. d = li.QuadPart * perfcnt_per_sec;
  633. tp->tv_sec = (time_t)d;
  634. d -= (double)tp->tv_sec;
  635. tp->tv_nsec = (long)(d * 1.0E9);
  636. ok = TRUE;
  637. /* END: CLOCK_MONOTONIC */
  638. } else if (clk_id == CLOCK_THREAD) {
  639. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  640. FILETIME t_create, t_exit, t_kernel, t_user;
  641. if (GetThreadTimes(GetCurrentThread(),
  642. &t_create,
  643. &t_exit,
  644. &t_kernel,
  645. &t_user)) {
  646. li.LowPart = t_user.dwLowDateTime;
  647. li.HighPart = t_user.dwHighDateTime;
  648. li2.LowPart = t_kernel.dwLowDateTime;
  649. li2.HighPart = t_kernel.dwHighDateTime;
  650. li.QuadPart += li2.QuadPart;
  651. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  652. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  653. ok = TRUE;
  654. }
  655. /* END: CLOCK_THREAD */
  656. } else if (clk_id == CLOCK_PROCESS) {
  657. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  658. FILETIME t_create, t_exit, t_kernel, t_user;
  659. if (GetProcessTimes(GetCurrentProcess(),
  660. &t_create,
  661. &t_exit,
  662. &t_kernel,
  663. &t_user)) {
  664. li.LowPart = t_user.dwLowDateTime;
  665. li.HighPart = t_user.dwHighDateTime;
  666. li2.LowPart = t_kernel.dwLowDateTime;
  667. li2.HighPart = t_kernel.dwHighDateTime;
  668. li.QuadPart += li2.QuadPart;
  669. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  670. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  671. ok = TRUE;
  672. }
  673. /* END: CLOCK_PROCESS */
  674. } else {
  675. /* BEGIN: unknown clock */
  676. /* ok = FALSE; already set by init */
  677. /* END: unknown clock */
  678. }
  679. }
  680. return ok ? 0 : -1;
  681. }
  682. #endif
  683. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  684. static int pthread_mutex_lock(pthread_mutex_t *);
  685. static int pthread_mutex_unlock(pthread_mutex_t *);
  686. static void path_to_unicode(const struct mg_connection *conn,
  687. const char *path,
  688. wchar_t *wbuf,
  689. size_t wbuf_len);
  690. /* All file operations need to be rewritten to solve #246. */
  691. struct mg_file;
  692. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  693. /* POSIX dirent interface */
  694. struct dirent {
  695. char d_name[UTF8_PATH_MAX];
  696. };
  697. typedef struct DIR {
  698. HANDLE handle;
  699. WIN32_FIND_DATAW info;
  700. struct dirent result;
  701. } DIR;
  702. #if defined(HAVE_POLL)
  703. #define mg_pollfd pollfd
  704. #else
  705. struct mg_pollfd {
  706. SOCKET fd;
  707. short events;
  708. short revents;
  709. };
  710. #endif
  711. /* Mark required libraries */
  712. #if defined(_MSC_VER)
  713. #pragma comment(lib, "Ws2_32.lib")
  714. #endif
  715. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  716. #include <inttypes.h>
  717. /* Linux & co. internally use UTF8 */
  718. #define UTF8_PATH_MAX (PATH_MAX)
  719. typedef const void *SOCK_OPT_TYPE;
  720. #if defined(ANDROID)
  721. typedef unsigned short int in_port_t;
  722. #endif
  723. #if !defined(__ZEPHYR__)
  724. #include <arpa/inet.h>
  725. #include <ctype.h>
  726. #include <dirent.h>
  727. #include <grp.h>
  728. #include <limits.h>
  729. #include <netdb.h>
  730. #include <netinet/in.h>
  731. #include <netinet/tcp.h>
  732. #include <poll.h>
  733. #include <pthread.h>
  734. #include <pwd.h>
  735. #include <stdarg.h>
  736. #include <stddef.h>
  737. #include <stdio.h>
  738. #include <stdlib.h>
  739. #include <string.h>
  740. #include <sys/socket.h>
  741. #include <sys/time.h>
  742. #if !defined(__rtems__)
  743. #include <sys/utsname.h>
  744. #endif
  745. #include <sys/wait.h>
  746. #include <time.h>
  747. #include <unistd.h>
  748. #if defined(USE_X_DOM_SOCKET)
  749. #include <sys/un.h>
  750. #endif
  751. #endif
  752. #define vsnprintf_impl vsnprintf
  753. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  754. #include <dlfcn.h>
  755. #endif
  756. #if defined(__MACH__) && defined(__APPLE__)
  757. #if defined(OPENSSL_API_3_0)
  758. #define SSL_LIB "libssl.3.dylib"
  759. #define CRYPTO_LIB "libcrypto.3.dylib"
  760. #endif
  761. #if defined(OPENSSL_API_1_1)
  762. #define SSL_LIB "libssl.1.1.dylib"
  763. #define CRYPTO_LIB "libcrypto.1.1.dylib"
  764. #endif /* OPENSSL_API_1_1 */
  765. #if defined(OPENSSL_API_1_0)
  766. #define SSL_LIB "libssl.1.0.dylib"
  767. #define CRYPTO_LIB "libcrypto.1.0.dylib"
  768. #endif /* OPENSSL_API_1_0 */
  769. #else
  770. #if !defined(SSL_LIB)
  771. #define SSL_LIB "libssl.so"
  772. #endif
  773. #if !defined(CRYPTO_LIB)
  774. #define CRYPTO_LIB "libcrypto.so"
  775. #endif
  776. #endif
  777. #if !defined(O_BINARY)
  778. #define O_BINARY (0)
  779. #endif /* O_BINARY */
  780. #define closesocket(a) (close(a))
  781. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  782. #define mg_remove(conn, x) (remove(x))
  783. #define mg_sleep(x) (usleep((x)*1000))
  784. #define mg_opendir(conn, x) (opendir(x))
  785. #define mg_closedir(x) (closedir(x))
  786. #define mg_readdir(x) (readdir(x))
  787. #define ERRNO (errno)
  788. #define INVALID_SOCKET (-1)
  789. #define INT64_FMT PRId64
  790. #define UINT64_FMT PRIu64
  791. typedef int SOCKET;
  792. #define WINCDECL
  793. #if defined(__hpux)
  794. /* HPUX 11 does not have monotonic, fall back to realtime */
  795. #if !defined(CLOCK_MONOTONIC)
  796. #define CLOCK_MONOTONIC CLOCK_REALTIME
  797. #endif
  798. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  799. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  800. * the prototypes use int* rather than socklen_t* which matches the
  801. * actual library expectation. When called with the wrong size arg
  802. * accept() returns a zero client inet addr and check_acl() always
  803. * fails. Since socklen_t is widely used below, just force replace
  804. * their typedef with int. - DTL
  805. */
  806. #define socklen_t int
  807. #endif /* hpux */
  808. #define mg_pollfd pollfd
  809. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  810. /* In case our C library is missing "timegm", provide an implementation */
  811. #if defined(NEED_TIMEGM)
  812. static inline int
  813. is_leap(int y)
  814. {
  815. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  816. }
  817. static inline int
  818. count_leap(int y)
  819. {
  820. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  821. }
  822. static time_t
  823. timegm(struct tm *tm)
  824. {
  825. static const unsigned short ydays[] = {
  826. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  827. int year = tm->tm_year + 1900;
  828. int mon = tm->tm_mon;
  829. int mday = tm->tm_mday - 1;
  830. int hour = tm->tm_hour;
  831. int min = tm->tm_min;
  832. int sec = tm->tm_sec;
  833. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  834. || (mday >= ydays[mon + 1] - ydays[mon]
  835. + (mon == 1 && is_leap(year) ? 1 : 0))
  836. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  837. return -1;
  838. time_t res = year - 1970;
  839. res *= 365;
  840. res += mday;
  841. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  842. res += count_leap(year);
  843. res *= 24;
  844. res += hour;
  845. res *= 60;
  846. res += min;
  847. res *= 60;
  848. res += sec;
  849. return res;
  850. }
  851. #endif /* NEED_TIMEGM */
  852. /* va_copy should always be a macro, C99 and C++11 - DTL */
  853. #if !defined(va_copy)
  854. #define va_copy(x, y) ((x) = (y))
  855. #endif
  856. #if defined(_WIN32)
  857. /* Create substitutes for POSIX functions in Win32. */
  858. #if defined(GCC_DIAGNOSTIC)
  859. /* Show no warning in case system functions are not used. */
  860. #pragma GCC diagnostic push
  861. #pragma GCC diagnostic ignored "-Wunused-function"
  862. #endif
  863. static pthread_mutex_t global_log_file_lock;
  864. FUNCTION_MAY_BE_UNUSED
  865. static DWORD
  866. pthread_self(void)
  867. {
  868. return GetCurrentThreadId();
  869. }
  870. FUNCTION_MAY_BE_UNUSED
  871. static int
  872. pthread_key_create(
  873. pthread_key_t *key,
  874. void (*_ignored)(void *) /* destructor not supported for Windows */
  875. )
  876. {
  877. (void)_ignored;
  878. if ((key != 0)) {
  879. *key = TlsAlloc();
  880. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  881. }
  882. return -2;
  883. }
  884. FUNCTION_MAY_BE_UNUSED
  885. static int
  886. pthread_key_delete(pthread_key_t key)
  887. {
  888. return TlsFree(key) ? 0 : 1;
  889. }
  890. FUNCTION_MAY_BE_UNUSED
  891. static int
  892. pthread_setspecific(pthread_key_t key, void *value)
  893. {
  894. return TlsSetValue(key, value) ? 0 : 1;
  895. }
  896. FUNCTION_MAY_BE_UNUSED
  897. static void *
  898. pthread_getspecific(pthread_key_t key)
  899. {
  900. return TlsGetValue(key);
  901. }
  902. #if defined(GCC_DIAGNOSTIC)
  903. /* Enable unused function warning again */
  904. #pragma GCC diagnostic pop
  905. #endif
  906. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  907. #else
  908. static pthread_mutexattr_t pthread_mutex_attr;
  909. #endif /* _WIN32 */
  910. #if defined(GCC_DIAGNOSTIC)
  911. /* Show no warning in case system functions are not used. */
  912. #pragma GCC diagnostic push
  913. #pragma GCC diagnostic ignored "-Wunused-function"
  914. #endif /* defined(GCC_DIAGNOSTIC) */
  915. #if defined(__clang__)
  916. /* Show no warning in case system functions are not used. */
  917. #pragma clang diagnostic push
  918. #pragma clang diagnostic ignored "-Wunused-function"
  919. #endif
  920. static pthread_mutex_t global_lock_mutex;
  921. FUNCTION_MAY_BE_UNUSED
  922. static void
  923. mg_global_lock(void)
  924. {
  925. (void)pthread_mutex_lock(&global_lock_mutex);
  926. }
  927. FUNCTION_MAY_BE_UNUSED
  928. static void
  929. mg_global_unlock(void)
  930. {
  931. (void)pthread_mutex_unlock(&global_lock_mutex);
  932. }
  933. #if defined(_WIN64)
  934. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  935. #elif defined(_WIN32)
  936. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  937. #endif
  938. /* Atomic functions working on ptrdiff_t ("signed size_t").
  939. * Operations: Increment, Decrement, Add, Maximum.
  940. * Up to size_t, they do not an atomic "load" operation.
  941. */
  942. FUNCTION_MAY_BE_UNUSED
  943. static ptrdiff_t
  944. mg_atomic_inc(volatile ptrdiff_t *addr)
  945. {
  946. ptrdiff_t ret;
  947. #if defined(_WIN64) && !defined(NO_ATOMICS)
  948. ret = InterlockedIncrement64(addr);
  949. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  950. #ifdef __cplusplus
  951. /* For C++ the Microsoft Visual Studio compiler can not decide what
  952. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  953. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  954. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  955. ret = InterlockedIncrement((LONG *)addr);
  956. #else
  957. ret = InterlockedIncrement(addr);
  958. #endif
  959. #elif defined(__GNUC__) \
  960. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  961. && !defined(NO_ATOMICS)
  962. ret = __sync_add_and_fetch(addr, 1);
  963. #else
  964. mg_global_lock();
  965. ret = (++(*addr));
  966. mg_global_unlock();
  967. #endif
  968. return ret;
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static ptrdiff_t
  972. mg_atomic_dec(volatile ptrdiff_t *addr)
  973. {
  974. ptrdiff_t ret;
  975. #if defined(_WIN64) && !defined(NO_ATOMICS)
  976. ret = InterlockedDecrement64(addr);
  977. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  978. #ifdef __cplusplus
  979. /* see mg_atomic_inc */
  980. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  981. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  982. ret = InterlockedDecrement((LONG *)addr);
  983. #else
  984. ret = InterlockedDecrement(addr);
  985. #endif
  986. #elif defined(__GNUC__) \
  987. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  988. && !defined(NO_ATOMICS)
  989. ret = __sync_sub_and_fetch(addr, 1);
  990. #else
  991. mg_global_lock();
  992. ret = (--(*addr));
  993. mg_global_unlock();
  994. #endif
  995. return ret;
  996. }
  997. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  998. static ptrdiff_t
  999. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  1000. {
  1001. ptrdiff_t ret;
  1002. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1003. ret = InterlockedAdd64(addr, value);
  1004. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1005. ret = InterlockedExchangeAdd(addr, value) + value;
  1006. #elif defined(__GNUC__) \
  1007. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1008. && !defined(NO_ATOMICS)
  1009. ret = __sync_add_and_fetch(addr, value);
  1010. #else
  1011. mg_global_lock();
  1012. *addr += value;
  1013. ret = (*addr);
  1014. mg_global_unlock();
  1015. #endif
  1016. return ret;
  1017. }
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static ptrdiff_t
  1020. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1021. ptrdiff_t oldval,
  1022. ptrdiff_t newval)
  1023. {
  1024. ptrdiff_t ret;
  1025. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1026. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1027. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1028. ret = InterlockedCompareExchange(addr, newval, oldval);
  1029. #elif defined(__GNUC__) \
  1030. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1031. && !defined(NO_ATOMICS)
  1032. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1033. #else
  1034. mg_global_lock();
  1035. ret = *addr;
  1036. if ((ret != newval) && (ret == oldval)) {
  1037. *addr = newval;
  1038. }
  1039. mg_global_unlock();
  1040. #endif
  1041. return ret;
  1042. }
  1043. static void
  1044. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1045. {
  1046. register ptrdiff_t tmp = *addr;
  1047. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1048. while (tmp < value) {
  1049. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1050. }
  1051. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1052. while (tmp < value) {
  1053. tmp = InterlockedCompareExchange(addr, value, tmp);
  1054. }
  1055. #elif defined(__GNUC__) \
  1056. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1057. && !defined(NO_ATOMICS)
  1058. while (tmp < value) {
  1059. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1060. }
  1061. #else
  1062. mg_global_lock();
  1063. if (*addr < value) {
  1064. *addr = value;
  1065. }
  1066. mg_global_unlock();
  1067. #endif
  1068. }
  1069. static int64_t
  1070. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1071. {
  1072. int64_t ret;
  1073. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1074. ret = InterlockedAdd64(addr, value);
  1075. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1076. ret = InterlockedExchangeAdd64(addr, value) + value;
  1077. #elif defined(__GNUC__) \
  1078. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1079. && !defined(NO_ATOMICS)
  1080. ret = __sync_add_and_fetch(addr, value);
  1081. #else
  1082. mg_global_lock();
  1083. *addr += value;
  1084. ret = (*addr);
  1085. mg_global_unlock();
  1086. #endif
  1087. return ret;
  1088. }
  1089. #endif
  1090. #if defined(GCC_DIAGNOSTIC)
  1091. /* Show no warning in case system functions are not used. */
  1092. #pragma GCC diagnostic pop
  1093. #endif /* defined(GCC_DIAGNOSTIC) */
  1094. #if defined(__clang__)
  1095. /* Show no warning in case system functions are not used. */
  1096. #pragma clang diagnostic pop
  1097. #endif
  1098. #if defined(USE_SERVER_STATS)
  1099. struct mg_memory_stat {
  1100. volatile ptrdiff_t totalMemUsed;
  1101. volatile ptrdiff_t maxMemUsed;
  1102. volatile ptrdiff_t blockCount;
  1103. };
  1104. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1105. static void *
  1106. mg_malloc_ex(size_t size,
  1107. struct mg_context *ctx,
  1108. const char *file,
  1109. unsigned line)
  1110. {
  1111. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1112. void *memory = 0;
  1113. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1114. #if defined(MEMORY_DEBUGGING)
  1115. char mallocStr[256];
  1116. #else
  1117. (void)file;
  1118. (void)line;
  1119. #endif
  1120. if (data) {
  1121. uintptr_t *tmp = (uintptr_t *)data;
  1122. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1123. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1124. mg_atomic_inc(&mstat->blockCount);
  1125. tmp[0] = size;
  1126. tmp[1] = (uintptr_t)mstat;
  1127. memory = (void *)&tmp[2];
  1128. }
  1129. #if defined(MEMORY_DEBUGGING)
  1130. sprintf(mallocStr,
  1131. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1132. memory,
  1133. (unsigned long)size,
  1134. (unsigned long)mstat->totalMemUsed,
  1135. (unsigned long)mstat->blockCount,
  1136. file,
  1137. line);
  1138. DEBUG_TRACE("%s", mallocStr);
  1139. #endif
  1140. return memory;
  1141. }
  1142. static void *
  1143. mg_calloc_ex(size_t count,
  1144. size_t size,
  1145. struct mg_context *ctx,
  1146. const char *file,
  1147. unsigned line)
  1148. {
  1149. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1150. if (data) {
  1151. memset(data, 0, size * count);
  1152. }
  1153. return data;
  1154. }
  1155. static void
  1156. mg_free_ex(void *memory, const char *file, unsigned line)
  1157. {
  1158. #if defined(MEMORY_DEBUGGING)
  1159. char mallocStr[256];
  1160. #else
  1161. (void)file;
  1162. (void)line;
  1163. #endif
  1164. if (memory) {
  1165. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1166. uintptr_t size = ((uintptr_t *)data)[0];
  1167. struct mg_memory_stat *mstat =
  1168. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1169. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1170. mg_atomic_dec(&mstat->blockCount);
  1171. #if defined(MEMORY_DEBUGGING)
  1172. sprintf(mallocStr,
  1173. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1174. memory,
  1175. (unsigned long)size,
  1176. (unsigned long)mstat->totalMemUsed,
  1177. (unsigned long)mstat->blockCount,
  1178. file,
  1179. line);
  1180. DEBUG_TRACE("%s", mallocStr);
  1181. #endif
  1182. free(data);
  1183. }
  1184. }
  1185. static void *
  1186. mg_realloc_ex(void *memory,
  1187. size_t newsize,
  1188. struct mg_context *ctx,
  1189. const char *file,
  1190. unsigned line)
  1191. {
  1192. void *data;
  1193. void *_realloc;
  1194. uintptr_t oldsize;
  1195. #if defined(MEMORY_DEBUGGING)
  1196. char mallocStr[256];
  1197. #else
  1198. (void)file;
  1199. (void)line;
  1200. #endif
  1201. if (newsize) {
  1202. if (memory) {
  1203. /* Reallocate existing block */
  1204. struct mg_memory_stat *mstat;
  1205. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1206. oldsize = ((uintptr_t *)data)[0];
  1207. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1208. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1209. if (_realloc) {
  1210. data = _realloc;
  1211. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1212. #if defined(MEMORY_DEBUGGING)
  1213. sprintf(mallocStr,
  1214. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1215. memory,
  1216. (unsigned long)oldsize,
  1217. (unsigned long)mstat->totalMemUsed,
  1218. (unsigned long)mstat->blockCount,
  1219. file,
  1220. line);
  1221. DEBUG_TRACE("%s", mallocStr);
  1222. #endif
  1223. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1224. #if defined(MEMORY_DEBUGGING)
  1225. sprintf(mallocStr,
  1226. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1227. memory,
  1228. (unsigned long)newsize,
  1229. (unsigned long)mstat->totalMemUsed,
  1230. (unsigned long)mstat->blockCount,
  1231. file,
  1232. line);
  1233. DEBUG_TRACE("%s", mallocStr);
  1234. #endif
  1235. *(uintptr_t *)data = newsize;
  1236. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1237. } else {
  1238. #if defined(MEMORY_DEBUGGING)
  1239. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1240. #endif
  1241. return _realloc;
  1242. }
  1243. } else {
  1244. /* Allocate new block */
  1245. data = mg_malloc_ex(newsize, ctx, file, line);
  1246. }
  1247. } else {
  1248. /* Free existing block */
  1249. data = 0;
  1250. mg_free_ex(memory, file, line);
  1251. }
  1252. return data;
  1253. }
  1254. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1255. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1256. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1257. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1258. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1259. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1260. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1261. #else /* USE_SERVER_STATS */
  1262. static __inline void *
  1263. mg_malloc(size_t a)
  1264. {
  1265. return malloc(a);
  1266. }
  1267. static __inline void *
  1268. mg_calloc(size_t a, size_t b)
  1269. {
  1270. return calloc(a, b);
  1271. }
  1272. static __inline void *
  1273. mg_realloc(void *a, size_t b)
  1274. {
  1275. return realloc(a, b);
  1276. }
  1277. static __inline void
  1278. mg_free(void *a)
  1279. {
  1280. free(a);
  1281. }
  1282. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1283. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1284. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1285. #define mg_free_ctx(a, c) mg_free(a)
  1286. #endif /* USE_SERVER_STATS */
  1287. static void mg_vsnprintf(const struct mg_connection *conn,
  1288. int *truncated,
  1289. char *buf,
  1290. size_t buflen,
  1291. const char *fmt,
  1292. va_list ap);
  1293. static void mg_snprintf(const struct mg_connection *conn,
  1294. int *truncated,
  1295. char *buf,
  1296. size_t buflen,
  1297. PRINTF_FORMAT_STRING(const char *fmt),
  1298. ...) PRINTF_ARGS(5, 6);
  1299. /* This following lines are just meant as a reminder to use the mg-functions
  1300. * for memory management */
  1301. #if defined(malloc)
  1302. #undef malloc
  1303. #endif
  1304. #if defined(calloc)
  1305. #undef calloc
  1306. #endif
  1307. #if defined(realloc)
  1308. #undef realloc
  1309. #endif
  1310. #if defined(free)
  1311. #undef free
  1312. #endif
  1313. #if defined(snprintf)
  1314. #undef snprintf
  1315. #endif
  1316. #if defined(vsnprintf)
  1317. #undef vsnprintf
  1318. #endif
  1319. #if !defined(NDEBUG)
  1320. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1321. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1322. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1323. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1324. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1325. #endif
  1326. #if defined(_WIN32)
  1327. /* vsnprintf must not be used in any system,
  1328. * but this define only works well for Windows. */
  1329. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1330. #endif
  1331. /* mg_init_library counter */
  1332. static int mg_init_library_called = 0;
  1333. #if !defined(NO_SSL)
  1334. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)
  1336. static int mg_openssl_initialized = 0;
  1337. #endif
  1338. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1339. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS) \
  1340. && !defined(USE_GNUTLS)
  1341. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS or USE_GNUTLS"
  1342. #endif
  1343. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1344. #error "Multiple OPENSSL_API versions defined"
  1345. #endif
  1346. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1347. #error "Multiple OPENSSL_API versions defined"
  1348. #endif
  1349. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1350. #error "Multiple OPENSSL_API versions defined"
  1351. #endif
  1352. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1353. || defined(OPENSSL_API_3_0)) \
  1354. && (defined(USE_MBEDTLS) || defined(USE_GNUTLS))
  1355. #error "Multiple SSL libraries defined"
  1356. #endif
  1357. #if defined(USE_MBEDTLS) && defined(USE_GNUTLS)
  1358. #error "Multiple SSL libraries defined"
  1359. #endif
  1360. #endif
  1361. static pthread_key_t sTlsKey; /* Thread local storage index */
  1362. static volatile ptrdiff_t thread_idx_max = 0;
  1363. #if defined(MG_LEGACY_INTERFACE)
  1364. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1365. #endif
  1366. struct mg_workerTLS {
  1367. int is_master;
  1368. unsigned long thread_idx;
  1369. void *user_ptr;
  1370. #if defined(_WIN32)
  1371. HANDLE pthread_cond_helper_mutex;
  1372. struct mg_workerTLS *next_waiting_thread;
  1373. #endif
  1374. const char *alpn_proto;
  1375. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1376. char txtbuf[4];
  1377. #endif
  1378. };
  1379. #if defined(GCC_DIAGNOSTIC)
  1380. /* Show no warning in case system functions are not used. */
  1381. #pragma GCC diagnostic push
  1382. #pragma GCC diagnostic ignored "-Wunused-function"
  1383. #endif /* defined(GCC_DIAGNOSTIC) */
  1384. #if defined(__clang__)
  1385. /* Show no warning in case system functions are not used. */
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunused-function"
  1388. #endif
  1389. /* Get a unique thread ID as unsigned long, independent from the data type
  1390. * of thread IDs defined by the operating system API.
  1391. * If two calls to mg_current_thread_id return the same value, they calls
  1392. * are done from the same thread. If they return different values, they are
  1393. * done from different threads. (Provided this function is used in the same
  1394. * process context and threads are not repeatedly created and deleted, but
  1395. * CivetWeb does not do that).
  1396. * This function must match the signature required for SSL id callbacks:
  1397. * CRYPTO_set_id_callback
  1398. */
  1399. FUNCTION_MAY_BE_UNUSED
  1400. static unsigned long
  1401. mg_current_thread_id(void)
  1402. {
  1403. #if defined(_WIN32)
  1404. return GetCurrentThreadId();
  1405. #else
  1406. #if defined(__clang__)
  1407. #pragma clang diagnostic push
  1408. #pragma clang diagnostic ignored "-Wunreachable-code"
  1409. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1410. * or not, so one of the two conditions will be unreachable by construction.
  1411. * Unfortunately the C standard does not define a way to check this at
  1412. * compile time, since the #if preprocessor conditions can not use the
  1413. * sizeof operator as an argument. */
  1414. #endif
  1415. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1416. /* This is the problematic case for CRYPTO_set_id_callback:
  1417. * The OS pthread_t can not be cast to unsigned long. */
  1418. struct mg_workerTLS *tls =
  1419. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1420. if (tls == NULL) {
  1421. /* SSL called from an unknown thread: Create some thread index.
  1422. */
  1423. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1424. tls->is_master = -2; /* -2 means "3rd party thread" */
  1425. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1426. pthread_setspecific(sTlsKey, tls);
  1427. }
  1428. return tls->thread_idx;
  1429. } else {
  1430. /* pthread_t may be any data type, so a simple cast to unsigned long
  1431. * can rise a warning/error, depending on the platform.
  1432. * Here memcpy is used as an anything-to-anything cast. */
  1433. unsigned long ret = 0;
  1434. pthread_t t = pthread_self();
  1435. memcpy(&ret, &t, sizeof(pthread_t));
  1436. return ret;
  1437. }
  1438. #if defined(__clang__)
  1439. #pragma clang diagnostic pop
  1440. #endif
  1441. #endif
  1442. }
  1443. FUNCTION_MAY_BE_UNUSED
  1444. static uint64_t
  1445. mg_get_current_time_ns(void)
  1446. {
  1447. struct timespec tsnow;
  1448. clock_gettime(CLOCK_REALTIME, &tsnow);
  1449. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1450. }
  1451. #if defined(GCC_DIAGNOSTIC)
  1452. /* Show no warning in case system functions are not used. */
  1453. #pragma GCC diagnostic pop
  1454. #endif /* defined(GCC_DIAGNOSTIC) */
  1455. #if defined(__clang__)
  1456. /* Show no warning in case system functions are not used. */
  1457. #pragma clang diagnostic pop
  1458. #endif
  1459. #if defined(NEED_DEBUG_TRACE_FUNC)
  1460. static void
  1461. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1462. {
  1463. va_list args;
  1464. struct timespec tsnow;
  1465. /* Get some operating system independent thread id */
  1466. unsigned long thread_id = mg_current_thread_id();
  1467. clock_gettime(CLOCK_REALTIME, &tsnow);
  1468. flockfile(DEBUG_TRACE_STREAM);
  1469. fprintf(DEBUG_TRACE_STREAM,
  1470. "*** %lu.%09lu %lu %s:%u: ",
  1471. (unsigned long)tsnow.tv_sec,
  1472. (unsigned long)tsnow.tv_nsec,
  1473. thread_id,
  1474. func,
  1475. line);
  1476. va_start(args, fmt);
  1477. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1478. va_end(args);
  1479. putc('\n', DEBUG_TRACE_STREAM);
  1480. fflush(DEBUG_TRACE_STREAM);
  1481. funlockfile(DEBUG_TRACE_STREAM);
  1482. }
  1483. #endif /* NEED_DEBUG_TRACE_FUNC */
  1484. #define MD5_STATIC static
  1485. #include "md5.inl"
  1486. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1487. #if defined(NO_SOCKLEN_T)
  1488. typedef int socklen_t;
  1489. #endif /* NO_SOCKLEN_T */
  1490. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1491. #if !defined(MSG_NOSIGNAL)
  1492. #define MSG_NOSIGNAL (0)
  1493. #endif
  1494. /* SSL: mbedTLS vs. GnuTLS vs. no-ssl vs. OpenSSL */
  1495. #if defined(USE_MBEDTLS)
  1496. /* mbedTLS */
  1497. #include "mod_mbedtls.inl"
  1498. #elif defined(USE_GNUTLS)
  1499. /* GnuTLS */
  1500. #include "mod_gnutls.inl"
  1501. #elif defined(NO_SSL)
  1502. /* no SSL */
  1503. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1504. typedef struct SSL_CTX SSL_CTX;
  1505. #elif defined(NO_SSL_DL)
  1506. /* OpenSSL without dynamic loading */
  1507. #include <openssl/bn.h>
  1508. #include <openssl/conf.h>
  1509. #include <openssl/crypto.h>
  1510. #include <openssl/dh.h>
  1511. #include <openssl/engine.h>
  1512. #include <openssl/err.h>
  1513. #include <openssl/opensslv.h>
  1514. #include <openssl/pem.h>
  1515. #include <openssl/ssl.h>
  1516. #include <openssl/tls1.h>
  1517. #include <openssl/x509.h>
  1518. #if defined(WOLFSSL_VERSION)
  1519. /* Additional defines for WolfSSL, see
  1520. * https://github.com/civetweb/civetweb/issues/583 */
  1521. #include "wolfssl_extras.inl"
  1522. #endif
  1523. #if defined(OPENSSL_IS_BORINGSSL)
  1524. /* From boringssl/src/include/openssl/mem.h:
  1525. *
  1526. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1527. * However, that was written in a time before Valgrind and ASAN. Since we now
  1528. * have those tools, the OpenSSL allocation functions are simply macros around
  1529. * the standard memory functions.
  1530. *
  1531. * #define OPENSSL_free free */
  1532. #define free free
  1533. // disable for boringssl
  1534. #define CONF_modules_unload(a) ((void)0)
  1535. #define ENGINE_cleanup() ((void)0)
  1536. #endif
  1537. /* If OpenSSL headers are included, automatically select the API version */
  1538. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1539. #if !defined(OPENSSL_API_3_0)
  1540. #define OPENSSL_API_3_0
  1541. #endif
  1542. #define OPENSSL_REMOVE_THREAD_STATE()
  1543. #else
  1544. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1545. #if !defined(OPENSSL_API_1_1)
  1546. #define OPENSSL_API_1_1
  1547. #endif
  1548. #define OPENSSL_REMOVE_THREAD_STATE()
  1549. #else
  1550. #if !defined(OPENSSL_API_1_0)
  1551. #define OPENSSL_API_1_0
  1552. #endif
  1553. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1554. #endif
  1555. #endif
  1556. #else
  1557. /* SSL loaded dynamically from DLL / shared object */
  1558. /* Add all prototypes here, to be independent from OpenSSL source
  1559. * installation. */
  1560. #include "openssl_dl.inl"
  1561. #endif /* Various SSL bindings */
  1562. #if !defined(NO_CACHING)
  1563. static const char month_names[][4] = {"Jan",
  1564. "Feb",
  1565. "Mar",
  1566. "Apr",
  1567. "May",
  1568. "Jun",
  1569. "Jul",
  1570. "Aug",
  1571. "Sep",
  1572. "Oct",
  1573. "Nov",
  1574. "Dec"};
  1575. #endif /* !NO_CACHING */
  1576. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1577. * the union u. */
  1578. union usa {
  1579. struct sockaddr sa;
  1580. struct sockaddr_in sin;
  1581. #if defined(USE_IPV6)
  1582. struct sockaddr_in6 sin6;
  1583. #endif
  1584. #if defined(USE_X_DOM_SOCKET)
  1585. struct sockaddr_un sun;
  1586. #endif
  1587. };
  1588. #if defined(USE_X_DOM_SOCKET)
  1589. static unsigned short
  1590. USA_IN_PORT_UNSAFE(union usa *s)
  1591. {
  1592. if (s->sa.sa_family == AF_INET)
  1593. return s->sin.sin_port;
  1594. #if defined(USE_IPV6)
  1595. if (s->sa.sa_family == AF_INET6)
  1596. return s->sin6.sin6_port;
  1597. #endif
  1598. return 0;
  1599. }
  1600. #endif
  1601. #if defined(USE_IPV6)
  1602. #define USA_IN_PORT_UNSAFE(s) \
  1603. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1604. #else
  1605. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1606. #endif
  1607. /* Describes a string (chunk of memory). */
  1608. struct vec {
  1609. const char *ptr;
  1610. size_t len;
  1611. };
  1612. struct mg_file_stat {
  1613. /* File properties filled by mg_stat: */
  1614. uint64_t size;
  1615. time_t last_modified;
  1616. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1617. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1618. * case we need a "Content-Eencoding: gzip" header */
  1619. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1620. };
  1621. struct mg_file_access {
  1622. /* File properties filled by mg_fopen: */
  1623. FILE *fp;
  1624. };
  1625. struct mg_file {
  1626. struct mg_file_stat stat;
  1627. struct mg_file_access access;
  1628. };
  1629. #define STRUCT_FILE_INITIALIZER \
  1630. { \
  1631. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1632. { \
  1633. (FILE *)NULL \
  1634. } \
  1635. }
  1636. /* Describes listening socket, or socket which was accept()-ed by the master
  1637. * thread and queued for future handling by the worker thread. */
  1638. struct socket {
  1639. SOCKET sock; /* Listening socket */
  1640. union usa lsa; /* Local socket address */
  1641. union usa rsa; /* Remote socket address */
  1642. unsigned char is_ssl; /* Is port SSL-ed */
  1643. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1644. * port */
  1645. unsigned char
  1646. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1647. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1648. };
  1649. /* Enum const for all options must be in sync with
  1650. * static struct mg_option config_options[]
  1651. * This is tested in the unit test (test/private.c)
  1652. * "Private Config Options"
  1653. */
  1654. enum {
  1655. /* Once for each server */
  1656. LISTENING_PORTS,
  1657. NUM_THREADS,
  1658. PRESPAWN_THREADS,
  1659. RUN_AS_USER,
  1660. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1661. * socket option typedef TCP_NODELAY. */
  1662. MAX_REQUEST_SIZE,
  1663. LINGER_TIMEOUT,
  1664. CONNECTION_QUEUE_SIZE,
  1665. LISTEN_BACKLOG_SIZE,
  1666. #if defined(__linux__)
  1667. ALLOW_SENDFILE_CALL,
  1668. #endif
  1669. #if defined(_WIN32)
  1670. CASE_SENSITIVE_FILES,
  1671. #endif
  1672. THROTTLE,
  1673. ENABLE_KEEP_ALIVE,
  1674. REQUEST_TIMEOUT,
  1675. KEEP_ALIVE_TIMEOUT,
  1676. #if defined(USE_WEBSOCKET)
  1677. WEBSOCKET_TIMEOUT,
  1678. ENABLE_WEBSOCKET_PING_PONG,
  1679. #endif
  1680. DECODE_URL,
  1681. DECODE_QUERY_STRING,
  1682. #if defined(USE_LUA)
  1683. LUA_BACKGROUND_SCRIPT,
  1684. LUA_BACKGROUND_SCRIPT_PARAMS,
  1685. #endif
  1686. #if defined(USE_HTTP2)
  1687. ENABLE_HTTP2,
  1688. #endif
  1689. /* Once for each domain */
  1690. DOCUMENT_ROOT,
  1691. FALLBACK_DOCUMENT_ROOT,
  1692. ACCESS_LOG_FILE,
  1693. ERROR_LOG_FILE,
  1694. CGI_EXTENSIONS,
  1695. CGI_ENVIRONMENT,
  1696. CGI_INTERPRETER,
  1697. CGI_INTERPRETER_ARGS,
  1698. #if defined(USE_TIMERS)
  1699. CGI_TIMEOUT,
  1700. #endif
  1701. CGI_BUFFERING,
  1702. CGI2_EXTENSIONS,
  1703. CGI2_ENVIRONMENT,
  1704. CGI2_INTERPRETER,
  1705. CGI2_INTERPRETER_ARGS,
  1706. #if defined(USE_TIMERS)
  1707. CGI2_TIMEOUT,
  1708. #endif
  1709. CGI2_BUFFERING,
  1710. #if defined(USE_4_CGI)
  1711. CGI3_EXTENSIONS,
  1712. CGI3_ENVIRONMENT,
  1713. CGI3_INTERPRETER,
  1714. CGI3_INTERPRETER_ARGS,
  1715. #if defined(USE_TIMERS)
  1716. CGI3_TIMEOUT,
  1717. #endif
  1718. CGI3_BUFFERING,
  1719. CGI4_EXTENSIONS,
  1720. CGI4_ENVIRONMENT,
  1721. CGI4_INTERPRETER,
  1722. CGI4_INTERPRETER_ARGS,
  1723. #if defined(USE_TIMERS)
  1724. CGI4_TIMEOUT,
  1725. #endif
  1726. CGI4_BUFFERING,
  1727. #endif
  1728. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1729. PROTECT_URI,
  1730. AUTHENTICATION_DOMAIN,
  1731. ENABLE_AUTH_DOMAIN_CHECK,
  1732. SSI_EXTENSIONS,
  1733. ENABLE_DIRECTORY_LISTING,
  1734. ENABLE_WEBDAV,
  1735. GLOBAL_PASSWORDS_FILE,
  1736. INDEX_FILES,
  1737. ACCESS_CONTROL_LIST,
  1738. EXTRA_MIME_TYPES,
  1739. SSL_CERTIFICATE,
  1740. SSL_CERTIFICATE_CHAIN,
  1741. URL_REWRITE_PATTERN,
  1742. HIDE_FILES,
  1743. SSL_DO_VERIFY_PEER,
  1744. SSL_CACHE_TIMEOUT,
  1745. SSL_CA_PATH,
  1746. SSL_CA_FILE,
  1747. SSL_VERIFY_DEPTH,
  1748. SSL_DEFAULT_VERIFY_PATHS,
  1749. SSL_CIPHER_LIST,
  1750. SSL_PROTOCOL_VERSION,
  1751. SSL_SHORT_TRUST,
  1752. #if defined(USE_LUA)
  1753. LUA_PRELOAD_FILE,
  1754. LUA_SCRIPT_EXTENSIONS,
  1755. LUA_SERVER_PAGE_EXTENSIONS,
  1756. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1757. LUA_DEBUG_PARAMS,
  1758. #endif
  1759. #endif
  1760. #if defined(USE_DUKTAPE)
  1761. DUKTAPE_SCRIPT_EXTENSIONS,
  1762. #endif
  1763. #if defined(USE_WEBSOCKET)
  1764. WEBSOCKET_ROOT,
  1765. FALLBACK_WEBSOCKET_ROOT,
  1766. #endif
  1767. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1768. LUA_WEBSOCKET_EXTENSIONS,
  1769. #endif
  1770. ACCESS_CONTROL_ALLOW_ORIGIN,
  1771. ACCESS_CONTROL_ALLOW_METHODS,
  1772. ACCESS_CONTROL_ALLOW_HEADERS,
  1773. ACCESS_CONTROL_EXPOSE_HEADERS,
  1774. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1775. ERROR_PAGES,
  1776. #if !defined(NO_CACHING)
  1777. STATIC_FILE_MAX_AGE,
  1778. STATIC_FILE_CACHE_CONTROL,
  1779. #endif
  1780. #if !defined(NO_SSL)
  1781. STRICT_HTTPS_MAX_AGE,
  1782. #endif
  1783. ADDITIONAL_HEADER,
  1784. ALLOW_INDEX_SCRIPT_SUB_RES,
  1785. NUM_OPTIONS
  1786. };
  1787. /* Config option name, config types, default value.
  1788. * Must be in the same order as the enum const above.
  1789. */
  1790. static const struct mg_option config_options[] = {
  1791. /* Once for each server */
  1792. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1793. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1794. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1795. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1796. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1797. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1798. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1799. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1800. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1801. #if defined(__linux__)
  1802. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1803. #endif
  1804. #if defined(_WIN32)
  1805. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1806. #endif
  1807. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1808. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1809. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1810. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1811. #if defined(USE_WEBSOCKET)
  1812. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1813. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1814. #endif
  1815. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1816. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1817. #if defined(USE_LUA)
  1818. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1819. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1820. #endif
  1821. #if defined(USE_HTTP2)
  1822. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1823. #endif
  1824. /* Once for each domain */
  1825. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1826. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1827. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1828. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1829. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1830. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1831. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1832. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1833. #if defined(USE_TIMERS)
  1834. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1835. #endif
  1836. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1837. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1838. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1839. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1841. #if defined(USE_TIMERS)
  1842. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1843. #endif
  1844. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1845. #if defined(USE_4_CGI)
  1846. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1847. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1848. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1849. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1850. #if defined(USE_TIMERS)
  1851. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1852. #endif
  1853. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1854. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1855. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1856. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1857. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1858. #if defined(USE_TIMERS)
  1859. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1860. #endif
  1861. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1862. #endif
  1863. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1864. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1865. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1866. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1867. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1868. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1869. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1870. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1871. {"index_files",
  1872. MG_CONFIG_TYPE_STRING_LIST,
  1873. #if defined(USE_LUA)
  1874. "index.xhtml,index.html,index.htm,"
  1875. "index.lp,index.lsp,index.lua,index.cgi,"
  1876. "index.shtml,index.php"},
  1877. #else
  1878. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1879. #endif
  1880. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1881. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1882. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1883. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1884. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1885. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1886. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1887. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1888. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1890. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1891. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1892. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1893. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1894. * as a minimum in 2020 */
  1895. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1896. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1897. #if defined(USE_LUA)
  1898. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1899. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1900. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1901. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1902. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1903. #endif
  1904. #endif
  1905. #if defined(USE_DUKTAPE)
  1906. /* The support for duktape is still in alpha version state.
  1907. * The name of this config option might change. */
  1908. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1909. #endif
  1910. #if defined(USE_WEBSOCKET)
  1911. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1912. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1913. #endif
  1914. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1915. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1916. #endif
  1917. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1918. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1919. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1920. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1921. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1922. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1923. #if !defined(NO_CACHING)
  1924. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1925. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1926. #endif
  1927. #if !defined(NO_SSL)
  1928. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1929. #endif
  1930. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1931. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1932. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1933. /* Check if the config_options and the corresponding enum have compatible
  1934. * sizes. */
  1935. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1936. == (NUM_OPTIONS + 1),
  1937. "config_options and enum not sync");
  1938. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1939. struct mg_handler_info {
  1940. /* Name/Pattern of the URI. */
  1941. char *uri;
  1942. size_t uri_len;
  1943. /* handler type */
  1944. int handler_type;
  1945. /* Handler for http/https or requests. */
  1946. mg_request_handler handler;
  1947. unsigned int refcount;
  1948. int removing;
  1949. /* Handler for ws/wss (websocket) requests. */
  1950. mg_websocket_connect_handler connect_handler;
  1951. mg_websocket_ready_handler ready_handler;
  1952. mg_websocket_data_handler data_handler;
  1953. mg_websocket_close_handler close_handler;
  1954. /* accepted subprotocols for ws/wss requests. */
  1955. struct mg_websocket_subprotocols *subprotocols;
  1956. /* Handler for authorization requests */
  1957. mg_authorization_handler auth_handler;
  1958. /* User supplied argument for the handler function. */
  1959. void *cbdata;
  1960. /* next handler in a linked list */
  1961. struct mg_handler_info *next;
  1962. };
  1963. enum {
  1964. CONTEXT_INVALID,
  1965. CONTEXT_SERVER,
  1966. CONTEXT_HTTP_CLIENT,
  1967. CONTEXT_WS_CLIENT
  1968. };
  1969. struct mg_domain_context {
  1970. SSL_CTX *ssl_ctx; /* SSL context */
  1971. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1972. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1973. int64_t ssl_cert_last_mtime;
  1974. /* Server nonce */
  1975. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1976. unsigned long nonce_count; /* Used nonces, used for authentication */
  1977. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1978. /* linked list of shared lua websockets */
  1979. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1980. #endif
  1981. /* Linked list of domains */
  1982. struct mg_domain_context *next;
  1983. };
  1984. /* Stop flag can be "volatile" or require a lock.
  1985. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1986. * states a read operation for int is always atomic. */
  1987. #if defined(STOP_FLAG_NEEDS_LOCK)
  1988. typedef ptrdiff_t volatile stop_flag_t;
  1989. static int
  1990. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1991. {
  1992. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1993. return (sf == 0);
  1994. }
  1995. static int
  1996. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1997. {
  1998. stop_flag_t sf = mg_atomic_add(f, 0);
  1999. return (sf == 2);
  2000. }
  2001. static void
  2002. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2003. {
  2004. stop_flag_t sf = 0;
  2005. do {
  2006. sf = mg_atomic_compare_and_swap(f,
  2007. __atomic_load_n(f, __ATOMIC_SEQ_CST),
  2008. v);
  2009. } while (sf != v);
  2010. }
  2011. #else /* STOP_FLAG_NEEDS_LOCK */
  2012. typedef int volatile stop_flag_t;
  2013. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2014. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2015. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2016. #endif /* STOP_FLAG_NEEDS_LOCK */
  2017. #if !defined(NUM_WEBDAV_LOCKS)
  2018. #define NUM_WEBDAV_LOCKS 10
  2019. #endif
  2020. #if !defined(LOCK_DURATION_S)
  2021. #define LOCK_DURATION_S 60
  2022. #endif
  2023. struct twebdav_lock {
  2024. uint64_t locktime;
  2025. char token[33];
  2026. char path[UTF8_PATH_MAX * 2];
  2027. char user[UTF8_PATH_MAX * 2];
  2028. };
  2029. struct mg_context {
  2030. /* Part 1 - Physical context:
  2031. * This holds threads, ports, timeouts, ...
  2032. * set for the entire server, independent from the
  2033. * addressed hostname.
  2034. */
  2035. /* Connection related */
  2036. int context_type; /* See CONTEXT_* above */
  2037. struct socket *listening_sockets;
  2038. struct mg_pollfd *listening_socket_fds;
  2039. unsigned int num_listening_sockets;
  2040. struct mg_connection *worker_connections; /* The connection struct, pre-
  2041. * allocated for each worker */
  2042. #if defined(USE_SERVER_STATS)
  2043. volatile ptrdiff_t active_connections;
  2044. volatile ptrdiff_t max_active_connections;
  2045. volatile ptrdiff_t total_connections;
  2046. volatile ptrdiff_t total_requests;
  2047. volatile int64_t total_data_read;
  2048. volatile int64_t total_data_written;
  2049. #endif
  2050. /* Thread related */
  2051. stop_flag_t stop_flag; /* Should we stop event loop */
  2052. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2053. pthread_t masterthreadid; /* The master thread ID */
  2054. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2055. allowed to create, total */
  2056. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2057. exist (modified by master thread) */
  2058. unsigned int
  2059. idle_worker_thread_count; /* How many worker-threads are currently
  2060. sitting around with nothing to do */
  2061. /* Access to this value MUST be synchronized by thread_mutex */
  2062. pthread_t *worker_threadids; /* The worker thread IDs */
  2063. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2064. /* Connection to thread dispatching */
  2065. #if defined(ALTERNATIVE_QUEUE)
  2066. struct socket *client_socks;
  2067. void **client_wait_events;
  2068. #else
  2069. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2070. worker thread */
  2071. volatile int sq_head; /* Head of the socket queue */
  2072. volatile int sq_tail; /* Tail of the socket queue */
  2073. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2074. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2075. volatile int sq_blocked; /* Status information: sq is full */
  2076. int sq_size; /* No of elements in socket queue */
  2077. #if defined(USE_SERVER_STATS)
  2078. int sq_max_fill;
  2079. #endif /* USE_SERVER_STATS */
  2080. #endif /* ALTERNATIVE_QUEUE */
  2081. /* Memory related */
  2082. unsigned int max_request_size; /* The max request size */
  2083. #if defined(USE_SERVER_STATS)
  2084. struct mg_memory_stat ctx_memory;
  2085. #endif
  2086. /* WebDAV lock structures */
  2087. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2088. /* Operating system related */
  2089. char *systemName; /* What operating system is running */
  2090. time_t start_time; /* Server start time, used for authentication
  2091. * and for diagnstics. */
  2092. #if defined(USE_TIMERS)
  2093. struct ttimers *timers;
  2094. #endif
  2095. /* Lua specific: Background operations and shared websockets */
  2096. #if defined(USE_LUA)
  2097. void *lua_background_state; /* lua_State (here as void *) */
  2098. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2099. int lua_bg_log_available; /* Use Lua background state for access log */
  2100. #endif
  2101. int user_shutdown_notification_socket; /* mg_stop() will close this
  2102. socket... */
  2103. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2104. to return immediately */
  2105. /* Server nonce */
  2106. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2107. * ssl_cert_last_mtime, nonce_count, and
  2108. * next (linked list) */
  2109. /* Server callbacks */
  2110. struct mg_callbacks callbacks; /* User-defined callback function */
  2111. void *user_data; /* User-defined data */
  2112. /* Part 2 - Logical domain:
  2113. * This holds hostname, TLS certificate, document root, ...
  2114. * set for a domain hosted at the server.
  2115. * There may be multiple domains hosted at one physical server.
  2116. * The default domain "dd" is the first element of a list of
  2117. * domains.
  2118. */
  2119. struct mg_domain_context dd; /* default domain */
  2120. };
  2121. #if defined(USE_SERVER_STATS)
  2122. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2123. static struct mg_memory_stat *
  2124. get_memory_stat(struct mg_context *ctx)
  2125. {
  2126. if (ctx) {
  2127. return &(ctx->ctx_memory);
  2128. }
  2129. return &mg_common_memory;
  2130. }
  2131. #endif
  2132. enum {
  2133. CONNECTION_TYPE_INVALID = 0,
  2134. CONNECTION_TYPE_REQUEST = 1,
  2135. CONNECTION_TYPE_RESPONSE = 2
  2136. };
  2137. enum {
  2138. PROTOCOL_TYPE_HTTP1 = 0,
  2139. PROTOCOL_TYPE_WEBSOCKET = 1,
  2140. PROTOCOL_TYPE_HTTP2 = 2
  2141. };
  2142. #if defined(USE_HTTP2)
  2143. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2144. #define HTTP2_DYN_TABLE_SIZE (256)
  2145. #endif
  2146. struct mg_http2_connection {
  2147. uint32_t stream_id;
  2148. uint32_t dyn_table_size;
  2149. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2150. };
  2151. #endif
  2152. struct mg_connection {
  2153. int connection_type; /* see CONNECTION_TYPE_* above */
  2154. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2155. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2156. fully sent */
  2157. #if defined(USE_HTTP2)
  2158. struct mg_http2_connection http2;
  2159. #endif
  2160. struct mg_request_info request_info;
  2161. struct mg_response_info response_info;
  2162. struct mg_context *phys_ctx;
  2163. struct mg_domain_context *dom_ctx;
  2164. #if defined(USE_SERVER_STATS)
  2165. int conn_state; /* 0 = undef, numerical value may change in different
  2166. * versions. For the current definition, see
  2167. * mg_get_connection_info_impl */
  2168. #endif
  2169. SSL *ssl; /* SSL descriptor */
  2170. struct socket client; /* Connected client */
  2171. time_t conn_birth_time; /* Time (wall clock) when connection was
  2172. * established */
  2173. #if defined(USE_SERVER_STATS)
  2174. time_t conn_close_time; /* Time (wall clock) when connection was
  2175. * closed (or 0 if still open) */
  2176. double processing_time; /* Processing time for one request. */
  2177. #endif
  2178. struct timespec req_time; /* Time (since system start) when the request
  2179. * was received */
  2180. int64_t num_bytes_sent; /* Total bytes sent to client */
  2181. int64_t content_len; /* How many bytes of content can be read
  2182. * !is_chunked: Content-Length header value
  2183. * or -1 (until connection closed,
  2184. * not allowed for a request)
  2185. * is_chunked: >= 0, appended gradually
  2186. */
  2187. int64_t consumed_content; /* How many bytes of content have been read */
  2188. int is_chunked; /* Transfer-Encoding is chunked:
  2189. * 0 = not chunked,
  2190. * 1 = chunked, not yet, or some data read,
  2191. * 2 = chunked, has error,
  2192. * 3 = chunked, all data read except trailer,
  2193. * 4 = chunked, all data read
  2194. */
  2195. char *buf; /* Buffer for received data */
  2196. char *path_info; /* PATH_INFO part of the URL */
  2197. int must_close; /* 1 if connection must be closed */
  2198. int accept_gzip; /* 1 if gzip encoding is accepted */
  2199. int in_error_handler; /* 1 if in handler for user defined error
  2200. * pages */
  2201. #if defined(USE_WEBSOCKET)
  2202. int in_websocket_handling; /* 1 if in read_websocket */
  2203. #endif
  2204. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2205. && defined(MG_EXPERIMENTAL_INTERFACES)
  2206. /* Parameters for websocket data compression according to rfc7692 */
  2207. int websocket_deflate_server_max_windows_bits;
  2208. int websocket_deflate_client_max_windows_bits;
  2209. int websocket_deflate_server_no_context_takeover;
  2210. int websocket_deflate_client_no_context_takeover;
  2211. int websocket_deflate_initialized;
  2212. int websocket_deflate_flush;
  2213. z_stream websocket_deflate_state;
  2214. z_stream websocket_inflate_state;
  2215. #endif
  2216. int handled_requests; /* Number of requests handled by this connection
  2217. */
  2218. int buf_size; /* Buffer size */
  2219. int request_len; /* Size of the request + headers in a buffer */
  2220. int data_len; /* Total size of data in a buffer */
  2221. int status_code; /* HTTP reply status code, e.g. 200 */
  2222. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2223. * throttle */
  2224. time_t last_throttle_time; /* Last time throttled data was sent */
  2225. int last_throttle_bytes; /* Bytes sent this second */
  2226. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2227. * atomic transmissions for websockets */
  2228. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2229. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2230. #endif
  2231. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2232. * for quick access */
  2233. };
  2234. /* Directory entry */
  2235. struct de {
  2236. char *file_name;
  2237. struct mg_file_stat file;
  2238. };
  2239. #define mg_cry_internal(conn, fmt, ...) \
  2240. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2241. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2242. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2243. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2244. struct mg_context *ctx,
  2245. const char *func,
  2246. unsigned line,
  2247. const char *fmt,
  2248. ...) PRINTF_ARGS(5, 6);
  2249. #if !defined(NO_THREAD_NAME)
  2250. #if defined(_WIN32) && defined(_MSC_VER)
  2251. /* Set the thread name for debugging purposes in Visual Studio
  2252. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2253. */
  2254. #pragma pack(push, 8)
  2255. typedef struct tagTHREADNAME_INFO {
  2256. DWORD dwType; /* Must be 0x1000. */
  2257. LPCSTR szName; /* Pointer to name (in user addr space). */
  2258. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2259. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2260. } THREADNAME_INFO;
  2261. #pragma pack(pop)
  2262. #elif defined(__linux__)
  2263. #include <sys/prctl.h>
  2264. #include <sys/sendfile.h>
  2265. #if defined(ALTERNATIVE_QUEUE)
  2266. #include <sys/eventfd.h>
  2267. #endif /* ALTERNATIVE_QUEUE */
  2268. #if defined(ALTERNATIVE_QUEUE)
  2269. static void *
  2270. event_create(void)
  2271. {
  2272. int evhdl = eventfd(0, EFD_CLOEXEC);
  2273. int *ret;
  2274. if (evhdl == -1) {
  2275. /* Linux uses -1 on error, Windows NULL. */
  2276. /* However, Linux does not return 0 on success either. */
  2277. return 0;
  2278. }
  2279. ret = (int *)mg_malloc(sizeof(int));
  2280. if (ret) {
  2281. *ret = evhdl;
  2282. } else {
  2283. (void)close(evhdl);
  2284. }
  2285. return (void *)ret;
  2286. }
  2287. static int
  2288. event_wait(void *eventhdl)
  2289. {
  2290. uint64_t u;
  2291. int evhdl, s;
  2292. if (!eventhdl) {
  2293. /* error */
  2294. return 0;
  2295. }
  2296. evhdl = *(int *)eventhdl;
  2297. s = (int)read(evhdl, &u, sizeof(u));
  2298. if (s != sizeof(u)) {
  2299. /* error */
  2300. return 0;
  2301. }
  2302. (void)u; /* the value is not required */
  2303. return 1;
  2304. }
  2305. static int
  2306. event_signal(void *eventhdl)
  2307. {
  2308. uint64_t u = 1;
  2309. int evhdl, s;
  2310. if (!eventhdl) {
  2311. /* error */
  2312. return 0;
  2313. }
  2314. evhdl = *(int *)eventhdl;
  2315. s = (int)write(evhdl, &u, sizeof(u));
  2316. if (s != sizeof(u)) {
  2317. /* error */
  2318. return 0;
  2319. }
  2320. return 1;
  2321. }
  2322. static void
  2323. event_destroy(void *eventhdl)
  2324. {
  2325. int evhdl;
  2326. if (!eventhdl) {
  2327. /* error */
  2328. return;
  2329. }
  2330. evhdl = *(int *)eventhdl;
  2331. close(evhdl);
  2332. mg_free(eventhdl);
  2333. }
  2334. #endif
  2335. #endif
  2336. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2337. struct posix_event {
  2338. pthread_mutex_t mutex;
  2339. pthread_cond_t cond;
  2340. int signaled;
  2341. };
  2342. static void *
  2343. event_create(void)
  2344. {
  2345. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2346. if (ret == 0) {
  2347. /* out of memory */
  2348. return 0;
  2349. }
  2350. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2351. /* pthread mutex not available */
  2352. mg_free(ret);
  2353. return 0;
  2354. }
  2355. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2356. /* pthread cond not available */
  2357. pthread_mutex_destroy(&(ret->mutex));
  2358. mg_free(ret);
  2359. return 0;
  2360. }
  2361. ret->signaled = 0;
  2362. return (void *)ret;
  2363. }
  2364. static int
  2365. event_wait(void *eventhdl)
  2366. {
  2367. struct posix_event *ev = (struct posix_event *)eventhdl;
  2368. pthread_mutex_lock(&(ev->mutex));
  2369. while (!ev->signaled) {
  2370. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2371. }
  2372. ev->signaled = 0;
  2373. pthread_mutex_unlock(&(ev->mutex));
  2374. return 1;
  2375. }
  2376. static int
  2377. event_signal(void *eventhdl)
  2378. {
  2379. struct posix_event *ev = (struct posix_event *)eventhdl;
  2380. pthread_mutex_lock(&(ev->mutex));
  2381. pthread_cond_signal(&(ev->cond));
  2382. ev->signaled = 1;
  2383. pthread_mutex_unlock(&(ev->mutex));
  2384. return 1;
  2385. }
  2386. static void
  2387. event_destroy(void *eventhdl)
  2388. {
  2389. struct posix_event *ev = (struct posix_event *)eventhdl;
  2390. pthread_cond_destroy(&(ev->cond));
  2391. pthread_mutex_destroy(&(ev->mutex));
  2392. mg_free(ev);
  2393. }
  2394. #endif
  2395. static void
  2396. mg_set_thread_name(const char *name)
  2397. {
  2398. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2399. mg_snprintf(
  2400. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2401. #if defined(_WIN32)
  2402. #if defined(_MSC_VER)
  2403. /* Windows and Visual Studio Compiler */
  2404. __try {
  2405. THREADNAME_INFO info;
  2406. info.dwType = 0x1000;
  2407. info.szName = threadName;
  2408. info.dwThreadID = ~0U;
  2409. info.dwFlags = 0;
  2410. RaiseException(0x406D1388,
  2411. 0,
  2412. sizeof(info) / sizeof(ULONG_PTR),
  2413. (ULONG_PTR *)&info);
  2414. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2415. }
  2416. #elif defined(__MINGW32__)
  2417. /* No option known to set thread name for MinGW known */
  2418. #endif
  2419. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2420. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2421. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2422. #if defined(__MACH__) && defined(__APPLE__)
  2423. /* OS X only current thread name can be changed */
  2424. (void)pthread_setname_np(threadName);
  2425. #else
  2426. (void)pthread_setname_np(pthread_self(), threadName);
  2427. #endif
  2428. #elif defined(__linux__)
  2429. /* On Linux we can use the prctl function.
  2430. * When building for Linux Standard Base (LSB) use
  2431. * NO_THREAD_NAME. However, thread names are a big
  2432. * help for debugging, so the stadard is to set them.
  2433. */
  2434. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2435. #endif
  2436. }
  2437. #else /* !defined(NO_THREAD_NAME) */
  2438. static void
  2439. mg_set_thread_name(const char *threadName)
  2440. {
  2441. }
  2442. #endif
  2443. CIVETWEB_API const struct mg_option *
  2444. mg_get_valid_options(void)
  2445. {
  2446. return config_options;
  2447. }
  2448. /* Do not open file (unused) */
  2449. #define MG_FOPEN_MODE_NONE (0)
  2450. /* Open file for read only access */
  2451. #define MG_FOPEN_MODE_READ (1)
  2452. /* Open file for writing, create and overwrite */
  2453. #define MG_FOPEN_MODE_WRITE (2)
  2454. /* Open file for writing, create and append */
  2455. #define MG_FOPEN_MODE_APPEND (4)
  2456. static int
  2457. is_file_opened(const struct mg_file_access *fileacc)
  2458. {
  2459. if (!fileacc) {
  2460. return 0;
  2461. }
  2462. return (fileacc->fp != NULL);
  2463. }
  2464. #if !defined(NO_FILESYSTEMS)
  2465. static int mg_stat(const struct mg_connection *conn,
  2466. const char *path,
  2467. struct mg_file_stat *filep);
  2468. /* Reject files with special characters (for Windows) */
  2469. static int
  2470. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2471. {
  2472. const uint8_t *c = (const uint8_t *)path;
  2473. (void)conn; /* not used */
  2474. if ((c == NULL) || (c[0] == 0)) {
  2475. /* Null pointer or empty path --> suspicious */
  2476. return 1;
  2477. }
  2478. #if defined(_WIN32)
  2479. while (*c) {
  2480. if (*c < 32) {
  2481. /* Control character */
  2482. return 1;
  2483. }
  2484. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2485. /* stdin/stdout redirection character */
  2486. return 1;
  2487. }
  2488. if ((*c == '*') || (*c == '?')) {
  2489. /* Wildcard character */
  2490. return 1;
  2491. }
  2492. if (*c == '"') {
  2493. /* Windows quotation */
  2494. return 1;
  2495. }
  2496. c++;
  2497. }
  2498. #endif
  2499. /* Nothing suspicious found */
  2500. return 0;
  2501. }
  2502. /* mg_fopen will open a file either in memory or on the disk.
  2503. * The input parameter path is a string in UTF-8 encoding.
  2504. * The input parameter mode is MG_FOPEN_MODE_*
  2505. * On success, fp will be set in the output struct mg_file.
  2506. * All status members will also be set.
  2507. * The function returns 1 on success, 0 on error. */
  2508. static int
  2509. mg_fopen(const struct mg_connection *conn,
  2510. const char *path,
  2511. int mode,
  2512. struct mg_file *filep)
  2513. {
  2514. int found;
  2515. if (!filep) {
  2516. return 0;
  2517. }
  2518. filep->access.fp = NULL;
  2519. if (mg_path_suspicious(conn, path)) {
  2520. return 0;
  2521. }
  2522. /* filep is initialized in mg_stat: all fields with memset to,
  2523. * some fields like size and modification date with values */
  2524. found = mg_stat(conn, path, &(filep->stat));
  2525. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2526. /* file does not exist and will not be created */
  2527. return 0;
  2528. }
  2529. #if defined(_WIN32)
  2530. {
  2531. wchar_t wbuf[UTF16_PATH_MAX];
  2532. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2533. switch (mode) {
  2534. case MG_FOPEN_MODE_READ:
  2535. filep->access.fp = _wfopen(wbuf, L"rb");
  2536. break;
  2537. case MG_FOPEN_MODE_WRITE:
  2538. filep->access.fp = _wfopen(wbuf, L"wb");
  2539. break;
  2540. case MG_FOPEN_MODE_APPEND:
  2541. filep->access.fp = _wfopen(wbuf, L"ab");
  2542. break;
  2543. }
  2544. }
  2545. #else
  2546. /* Linux et al already use unicode. No need to convert. */
  2547. switch (mode) {
  2548. case MG_FOPEN_MODE_READ:
  2549. filep->access.fp = fopen(path, "r");
  2550. break;
  2551. case MG_FOPEN_MODE_WRITE:
  2552. filep->access.fp = fopen(path, "w");
  2553. break;
  2554. case MG_FOPEN_MODE_APPEND:
  2555. filep->access.fp = fopen(path, "a");
  2556. break;
  2557. }
  2558. #endif
  2559. if (!found) {
  2560. /* File did not exist before fopen was called.
  2561. * Maybe it has been created now. Get stat info
  2562. * like creation time now. */
  2563. found = mg_stat(conn, path, &(filep->stat));
  2564. (void)found;
  2565. }
  2566. /* return OK if file is opened */
  2567. return (filep->access.fp != NULL);
  2568. }
  2569. /* return 0 on success, just like fclose */
  2570. static int
  2571. mg_fclose(struct mg_file_access *fileacc)
  2572. {
  2573. int ret = -1;
  2574. if (fileacc != NULL) {
  2575. if (fileacc->fp != NULL) {
  2576. ret = fclose(fileacc->fp);
  2577. }
  2578. /* reset all members of fileacc */
  2579. memset(fileacc, 0, sizeof(*fileacc));
  2580. }
  2581. return ret;
  2582. }
  2583. #endif /* NO_FILESYSTEMS */
  2584. static void
  2585. mg_strlcpy(char *dst, const char *src, size_t n)
  2586. {
  2587. for (; *src != '\0' && n > 1; n--) {
  2588. *dst++ = *src++;
  2589. }
  2590. *dst = '\0';
  2591. }
  2592. static int
  2593. lowercase(const char *s)
  2594. {
  2595. return tolower((unsigned char)*s);
  2596. }
  2597. CIVETWEB_API int
  2598. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2599. {
  2600. int diff = 0;
  2601. if (len > 0) {
  2602. do {
  2603. diff = lowercase(s1++) - lowercase(s2++);
  2604. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2605. }
  2606. return diff;
  2607. }
  2608. CIVETWEB_API int
  2609. mg_strcasecmp(const char *s1, const char *s2)
  2610. {
  2611. int diff;
  2612. do {
  2613. diff = lowercase(s1++) - lowercase(s2++);
  2614. } while (diff == 0 && s1[-1] != '\0');
  2615. return diff;
  2616. }
  2617. static char *
  2618. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2619. {
  2620. char *p;
  2621. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2622. * defined */
  2623. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2624. mg_strlcpy(p, ptr, len + 1);
  2625. }
  2626. return p;
  2627. }
  2628. static char *
  2629. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2630. {
  2631. return mg_strndup_ctx(str, strlen(str), ctx);
  2632. }
  2633. static char *
  2634. mg_strdup(const char *str)
  2635. {
  2636. return mg_strndup_ctx(str, strlen(str), NULL);
  2637. }
  2638. static const char *
  2639. mg_strcasestr(const char *big_str, const char *small_str)
  2640. {
  2641. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2642. if (big_len >= small_len) {
  2643. for (i = 0; i <= (big_len - small_len); i++) {
  2644. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2645. return big_str + i;
  2646. }
  2647. }
  2648. }
  2649. return NULL;
  2650. }
  2651. /* Return null terminated string of given maximum length.
  2652. * Report errors if length is exceeded. */
  2653. static void
  2654. mg_vsnprintf(const struct mg_connection *conn,
  2655. int *truncated,
  2656. char *buf,
  2657. size_t buflen,
  2658. const char *fmt,
  2659. va_list ap)
  2660. {
  2661. int n, ok;
  2662. if (buflen == 0) {
  2663. if (truncated) {
  2664. *truncated = 1;
  2665. }
  2666. return;
  2667. }
  2668. #if defined(__clang__)
  2669. #pragma clang diagnostic push
  2670. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2671. /* Using fmt as a non-literal is intended here, since it is mostly called
  2672. * indirectly by mg_snprintf */
  2673. #endif
  2674. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2675. ok = (n >= 0) && ((size_t)n < buflen);
  2676. #if defined(__clang__)
  2677. #pragma clang diagnostic pop
  2678. #endif
  2679. if (ok) {
  2680. if (truncated) {
  2681. *truncated = 0;
  2682. }
  2683. } else {
  2684. if (truncated) {
  2685. *truncated = 1;
  2686. }
  2687. mg_cry_internal(conn,
  2688. "truncating vsnprintf buffer: [%.*s]",
  2689. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2690. buf);
  2691. n = (int)buflen - 1;
  2692. }
  2693. buf[n] = '\0';
  2694. }
  2695. static void
  2696. mg_snprintf(const struct mg_connection *conn,
  2697. int *truncated,
  2698. char *buf,
  2699. size_t buflen,
  2700. const char *fmt,
  2701. ...)
  2702. {
  2703. va_list ap;
  2704. va_start(ap, fmt);
  2705. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2706. va_end(ap);
  2707. }
  2708. static int
  2709. get_option_index(const char *name)
  2710. {
  2711. int i;
  2712. for (i = 0; config_options[i].name != NULL; i++) {
  2713. if (strcmp(config_options[i].name, name) == 0) {
  2714. return i;
  2715. }
  2716. }
  2717. return -1;
  2718. }
  2719. CIVETWEB_API const char *
  2720. mg_get_option(const struct mg_context *ctx, const char *name)
  2721. {
  2722. int i;
  2723. if ((i = get_option_index(name)) == -1) {
  2724. return NULL;
  2725. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2726. return "";
  2727. } else {
  2728. return ctx->dd.config[i];
  2729. }
  2730. }
  2731. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2732. CIVETWEB_API struct mg_context *
  2733. mg_get_context(const struct mg_connection *conn)
  2734. {
  2735. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2736. }
  2737. CIVETWEB_API void *
  2738. mg_get_user_data(const struct mg_context *ctx)
  2739. {
  2740. return (ctx == NULL) ? NULL : ctx->user_data;
  2741. }
  2742. CIVETWEB_API void *
  2743. mg_get_user_context_data(const struct mg_connection *conn)
  2744. {
  2745. return mg_get_user_data(mg_get_context(conn));
  2746. }
  2747. CIVETWEB_API void *
  2748. mg_get_thread_pointer(const struct mg_connection *conn)
  2749. {
  2750. /* both methods should return the same pointer */
  2751. if (conn) {
  2752. /* quick access, in case conn is known */
  2753. return conn->tls_user_ptr;
  2754. } else {
  2755. /* otherwise get pointer from thread local storage (TLS) */
  2756. struct mg_workerTLS *tls =
  2757. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2758. return tls->user_ptr;
  2759. }
  2760. }
  2761. CIVETWEB_API void
  2762. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2763. {
  2764. if (const_conn != NULL) {
  2765. /* Const cast, since "const struct mg_connection *" does not mean
  2766. * the connection object is not modified. Here "const" is used,
  2767. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2768. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2769. conn->request_info.conn_data = data;
  2770. }
  2771. }
  2772. CIVETWEB_API void *
  2773. mg_get_user_connection_data(const struct mg_connection *conn)
  2774. {
  2775. if (conn != NULL) {
  2776. return conn->request_info.conn_data;
  2777. }
  2778. return NULL;
  2779. }
  2780. CIVETWEB_API int
  2781. mg_get_server_ports(const struct mg_context *ctx,
  2782. int size,
  2783. struct mg_server_port *ports)
  2784. {
  2785. int i, cnt = 0;
  2786. if (size <= 0) {
  2787. return -1;
  2788. }
  2789. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2790. if (!ctx) {
  2791. return -1;
  2792. }
  2793. if (!ctx->listening_sockets) {
  2794. return -1;
  2795. }
  2796. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2797. ports[cnt].port =
  2798. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2799. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2800. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2801. ports[cnt].is_optional = ctx->listening_sockets[i].is_optional;
  2802. ports[cnt].is_bound = ctx->listening_sockets[i].sock != INVALID_SOCKET;
  2803. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2804. /* IPv4 */
  2805. ports[cnt].protocol = 1;
  2806. cnt++;
  2807. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2808. /* IPv6 */
  2809. ports[cnt].protocol = 3;
  2810. cnt++;
  2811. }
  2812. }
  2813. return cnt;
  2814. }
  2815. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2816. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2817. #endif
  2818. static void
  2819. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2820. {
  2821. buf[0] = '\0';
  2822. if (!usa) {
  2823. return;
  2824. }
  2825. if (usa->sa.sa_family == AF_INET) {
  2826. getnameinfo(&usa->sa,
  2827. sizeof(usa->sin),
  2828. buf,
  2829. (unsigned)len,
  2830. NULL,
  2831. 0,
  2832. NI_NUMERICHOST);
  2833. }
  2834. #if defined(USE_IPV6)
  2835. else if (usa->sa.sa_family == AF_INET6) {
  2836. getnameinfo(&usa->sa,
  2837. sizeof(usa->sin6),
  2838. buf,
  2839. (unsigned)len,
  2840. NULL,
  2841. 0,
  2842. NI_NUMERICHOST);
  2843. }
  2844. #endif
  2845. #if defined(USE_X_DOM_SOCKET)
  2846. else if (usa->sa.sa_family == AF_UNIX) {
  2847. /* TODO: Define a remote address for unix domain sockets.
  2848. * This code will always return "localhost", identical to http+tcp:
  2849. getnameinfo(&usa->sa,
  2850. sizeof(usa->sun),
  2851. buf,
  2852. (unsigned)len,
  2853. NULL,
  2854. 0,
  2855. NI_NUMERICHOST);
  2856. */
  2857. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2858. }
  2859. #endif
  2860. }
  2861. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2862. * included in all responses other than 100, 101, 5xx. */
  2863. static void
  2864. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2865. {
  2866. #if !defined(REENTRANT_TIME)
  2867. struct tm *tm;
  2868. tm = ((t != NULL) ? gmtime(t) : NULL);
  2869. if (tm != NULL) {
  2870. #else
  2871. struct tm _tm;
  2872. struct tm *tm = &_tm;
  2873. if (t != NULL) {
  2874. gmtime_r(t, tm);
  2875. #endif
  2876. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2877. } else {
  2878. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2879. }
  2880. }
  2881. /* difftime for struct timespec. Return value is in seconds. */
  2882. static double
  2883. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2884. {
  2885. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2886. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2887. }
  2888. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2889. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2890. const char *func,
  2891. unsigned line,
  2892. const char *fmt,
  2893. va_list ap);
  2894. #include "external_mg_cry_internal_impl.inl"
  2895. #elif !defined(NO_FILESYSTEMS)
  2896. /* Print error message to the opened error log stream. */
  2897. static void
  2898. mg_cry_internal_impl(const struct mg_connection *conn,
  2899. const char *func,
  2900. unsigned line,
  2901. const char *fmt,
  2902. va_list ap)
  2903. {
  2904. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2905. struct mg_file fi;
  2906. time_t timestamp;
  2907. /* Unused, in the RELEASE build */
  2908. (void)func;
  2909. (void)line;
  2910. #if defined(GCC_DIAGNOSTIC)
  2911. #pragma GCC diagnostic push
  2912. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2913. #endif
  2914. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2915. #if defined(GCC_DIAGNOSTIC)
  2916. #pragma GCC diagnostic pop
  2917. #endif
  2918. buf[sizeof(buf) - 1] = 0;
  2919. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2920. if (!conn) {
  2921. puts(buf);
  2922. return;
  2923. }
  2924. /* Do not lock when getting the callback value, here and below.
  2925. * I suppose this is fine, since function cannot disappear in the
  2926. * same way string option can. */
  2927. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2928. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2929. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2930. if (mg_fopen(conn,
  2931. conn->dom_ctx->config[ERROR_LOG_FILE],
  2932. MG_FOPEN_MODE_APPEND,
  2933. &fi)
  2934. == 0) {
  2935. fi.access.fp = NULL;
  2936. }
  2937. } else {
  2938. fi.access.fp = NULL;
  2939. }
  2940. if (fi.access.fp != NULL) {
  2941. flockfile(fi.access.fp);
  2942. timestamp = time(NULL);
  2943. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2944. fprintf(fi.access.fp,
  2945. "[%010lu] [error] [client %s] ",
  2946. (unsigned long)timestamp,
  2947. src_addr);
  2948. if (conn->request_info.request_method != NULL) {
  2949. fprintf(fi.access.fp,
  2950. "%s %s: ",
  2951. conn->request_info.request_method,
  2952. conn->request_info.request_uri
  2953. ? conn->request_info.request_uri
  2954. : "");
  2955. }
  2956. fprintf(fi.access.fp, "%s", buf);
  2957. fputc('\n', fi.access.fp);
  2958. fflush(fi.access.fp);
  2959. funlockfile(fi.access.fp);
  2960. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2961. * mg_cry here anyway ;-) */
  2962. }
  2963. }
  2964. }
  2965. #else
  2966. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2967. #endif /* Externally provided function */
  2968. /* Construct fake connection structure. Used for logging, if connection
  2969. * is not applicable at the moment of logging. */
  2970. static struct mg_connection *
  2971. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2972. {
  2973. static const struct mg_connection conn_zero = {0};
  2974. *fc = conn_zero;
  2975. fc->phys_ctx = ctx;
  2976. fc->dom_ctx = &(ctx->dd);
  2977. return fc;
  2978. }
  2979. static void
  2980. mg_cry_internal_wrap(const struct mg_connection *conn,
  2981. struct mg_context *ctx,
  2982. const char *func,
  2983. unsigned line,
  2984. const char *fmt,
  2985. ...)
  2986. {
  2987. va_list ap;
  2988. va_start(ap, fmt);
  2989. if (!conn && ctx) {
  2990. struct mg_connection fc;
  2991. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2992. } else {
  2993. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2994. }
  2995. va_end(ap);
  2996. }
  2997. CIVETWEB_API void
  2998. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2999. {
  3000. va_list ap;
  3001. va_start(ap, fmt);
  3002. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3003. va_end(ap);
  3004. }
  3005. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3006. CIVETWEB_API const char *
  3007. mg_version(void)
  3008. {
  3009. return CIVETWEB_VERSION;
  3010. }
  3011. CIVETWEB_API const struct mg_request_info *
  3012. mg_get_request_info(const struct mg_connection *conn)
  3013. {
  3014. if (!conn) {
  3015. return NULL;
  3016. }
  3017. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3018. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3019. char txt[16];
  3020. struct mg_workerTLS *tls =
  3021. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3022. sprintf(txt, "%03i", conn->response_info.status_code);
  3023. if (strlen(txt) == 3) {
  3024. memcpy(tls->txtbuf, txt, 4);
  3025. } else {
  3026. strcpy(tls->txtbuf, "ERR");
  3027. }
  3028. ((struct mg_connection *)conn)->request_info.local_uri =
  3029. tls->txtbuf; /* use thread safe buffer */
  3030. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3031. tls->txtbuf; /* use the same thread safe buffer */
  3032. ((struct mg_connection *)conn)->request_info.request_uri =
  3033. tls->txtbuf; /* use the same thread safe buffer */
  3034. ((struct mg_connection *)conn)->request_info.num_headers =
  3035. conn->response_info.num_headers;
  3036. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3037. conn->response_info.http_headers,
  3038. sizeof(conn->response_info.http_headers));
  3039. } else
  3040. #endif
  3041. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3042. return NULL;
  3043. }
  3044. return &conn->request_info;
  3045. }
  3046. CIVETWEB_API const struct mg_response_info *
  3047. mg_get_response_info(const struct mg_connection *conn)
  3048. {
  3049. if (!conn) {
  3050. return NULL;
  3051. }
  3052. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3053. return NULL;
  3054. }
  3055. return &conn->response_info;
  3056. }
  3057. static const char *
  3058. get_proto_name(const struct mg_connection *conn)
  3059. {
  3060. #if defined(__clang__)
  3061. #pragma clang diagnostic push
  3062. #pragma clang diagnostic ignored "-Wunreachable-code"
  3063. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3064. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3065. * unreachable, but splitting into four different #ifdef clauses here is
  3066. * more complicated.
  3067. */
  3068. #endif
  3069. const struct mg_request_info *ri = &conn->request_info;
  3070. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3071. ? (ri->is_ssl ? "wss" : "ws")
  3072. : (ri->is_ssl ? "https" : "http"));
  3073. return proto;
  3074. #if defined(__clang__)
  3075. #pragma clang diagnostic pop
  3076. #endif
  3077. }
  3078. static int
  3079. mg_construct_local_link(const struct mg_connection *conn,
  3080. char *buf,
  3081. size_t buflen,
  3082. const char *define_proto,
  3083. int define_port,
  3084. const char *define_uri)
  3085. {
  3086. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3087. return -1;
  3088. } else {
  3089. int i, j;
  3090. int truncated = 0;
  3091. const struct mg_request_info *ri = &conn->request_info;
  3092. const char *proto =
  3093. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3094. const char *uri =
  3095. (define_uri != NULL)
  3096. ? define_uri
  3097. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3098. int port = (define_port > 0) ? define_port : ri->server_port;
  3099. int default_port = 80;
  3100. char *uri_encoded;
  3101. size_t uri_encoded_len;
  3102. if (uri == NULL) {
  3103. return -1;
  3104. }
  3105. uri_encoded_len = strlen(uri) * 3 + 1;
  3106. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3107. if (uri_encoded == NULL) {
  3108. return -1;
  3109. }
  3110. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3111. /* Directory separator should be preserved. */
  3112. for (i = j = 0; uri_encoded[i]; j++) {
  3113. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3114. uri_encoded[j] = '/';
  3115. i += 3;
  3116. } else {
  3117. uri_encoded[j] = uri_encoded[i++];
  3118. }
  3119. }
  3120. uri_encoded[j] = '\0';
  3121. #if defined(USE_X_DOM_SOCKET)
  3122. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3123. /* TODO: Define and document a link for UNIX domain sockets. */
  3124. /* There seems to be no official standard for this.
  3125. * Common uses seem to be "httpunix://", "http.unix://" or
  3126. * "http+unix://" as a protocol definition string, followed by
  3127. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3128. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3129. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3130. * "" (completely skipping the server name part). In any case, the
  3131. * last part is the server local path. */
  3132. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3133. mg_snprintf(conn,
  3134. &truncated,
  3135. buf,
  3136. buflen,
  3137. "%s.unix://%s%s",
  3138. proto,
  3139. server_name,
  3140. ri->local_uri);
  3141. default_port = 0;
  3142. mg_free(uri_encoded);
  3143. return 0;
  3144. }
  3145. #endif
  3146. if (define_proto) {
  3147. /* If we got a protocol name, use the default port accordingly. */
  3148. if ((0 == strcmp(define_proto, "https"))
  3149. || (0 == strcmp(define_proto, "wss"))) {
  3150. default_port = 443;
  3151. }
  3152. } else if (ri->is_ssl) {
  3153. /* If we did not get a protocol name, use TLS as default if it is
  3154. * already used. */
  3155. default_port = 443;
  3156. }
  3157. {
  3158. #if defined(USE_IPV6)
  3159. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3160. #endif
  3161. int auth_domain_check_enabled =
  3162. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3163. && (!mg_strcasecmp(
  3164. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3165. const char *server_domain =
  3166. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3167. char portstr[16];
  3168. char server_ip[48];
  3169. if (port != default_port) {
  3170. sprintf(portstr, ":%u", (unsigned)port);
  3171. } else {
  3172. portstr[0] = 0;
  3173. }
  3174. if (!auth_domain_check_enabled || !server_domain) {
  3175. sockaddr_to_string(server_ip,
  3176. sizeof(server_ip),
  3177. &conn->client.lsa);
  3178. server_domain = server_ip;
  3179. }
  3180. mg_snprintf(conn,
  3181. &truncated,
  3182. buf,
  3183. buflen,
  3184. #if defined(USE_IPV6)
  3185. "%s://%s%s%s%s%s",
  3186. proto,
  3187. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3188. server_domain,
  3189. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3190. #else
  3191. "%s://%s%s%s",
  3192. proto,
  3193. server_domain,
  3194. #endif
  3195. portstr,
  3196. uri_encoded);
  3197. mg_free(uri_encoded);
  3198. if (truncated) {
  3199. return -1;
  3200. }
  3201. return 0;
  3202. }
  3203. }
  3204. }
  3205. CIVETWEB_API int
  3206. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3207. {
  3208. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3209. }
  3210. /* Skip the characters until one of the delimiters characters found.
  3211. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3212. * Advance pointer to buffer to the next word. Return found 0-terminated
  3213. * word.
  3214. * Delimiters can be quoted with quotechar. */
  3215. static char *
  3216. skip_quoted(char **buf,
  3217. const char *delimiters,
  3218. const char *whitespace,
  3219. char quotechar)
  3220. {
  3221. char *p, *begin_word, *end_word, *end_whitespace;
  3222. begin_word = *buf;
  3223. end_word = begin_word + strcspn(begin_word, delimiters);
  3224. /* Check for quotechar */
  3225. if (end_word > begin_word) {
  3226. p = end_word - 1;
  3227. while (*p == quotechar) {
  3228. /* While the delimiter is quoted, look for the next delimiter. */
  3229. /* This happens, e.g., in calls from parse_auth_header,
  3230. * if the user name contains a " character. */
  3231. /* If there is anything beyond end_word, copy it. */
  3232. if (*end_word != '\0') {
  3233. size_t end_off = strcspn(end_word + 1, delimiters);
  3234. memmove(p, end_word, end_off + 1);
  3235. p += end_off; /* p must correspond to end_word - 1 */
  3236. end_word += end_off + 1;
  3237. } else {
  3238. *p = '\0';
  3239. break;
  3240. }
  3241. }
  3242. for (p++; p < end_word; p++) {
  3243. *p = '\0';
  3244. }
  3245. }
  3246. if (*end_word == '\0') {
  3247. *buf = end_word;
  3248. } else {
  3249. #if defined(GCC_DIAGNOSTIC)
  3250. /* Disable spurious conversion warning for GCC */
  3251. #pragma GCC diagnostic push
  3252. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3253. #endif /* defined(GCC_DIAGNOSTIC) */
  3254. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3255. #if defined(GCC_DIAGNOSTIC)
  3256. #pragma GCC diagnostic pop
  3257. #endif /* defined(GCC_DIAGNOSTIC) */
  3258. for (p = end_word; p < end_whitespace; p++) {
  3259. *p = '\0';
  3260. }
  3261. *buf = end_whitespace;
  3262. }
  3263. return begin_word;
  3264. }
  3265. /* Return HTTP header value, or NULL if not found. */
  3266. static const char *
  3267. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3268. {
  3269. int i;
  3270. for (i = 0; i < num_hdr; i++) {
  3271. if (!mg_strcasecmp(name, hdr[i].name)) {
  3272. return hdr[i].value;
  3273. }
  3274. }
  3275. return NULL;
  3276. }
  3277. /* Retrieve requested HTTP header multiple values, and return the number of
  3278. * found occurrences */
  3279. static int
  3280. get_req_headers(const struct mg_request_info *ri,
  3281. const char *name,
  3282. const char **output,
  3283. int output_max_size)
  3284. {
  3285. int i;
  3286. int cnt = 0;
  3287. if (ri) {
  3288. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3289. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3290. output[cnt++] = ri->http_headers[i].value;
  3291. }
  3292. }
  3293. }
  3294. return cnt;
  3295. }
  3296. CIVETWEB_API const char *
  3297. mg_get_header(const struct mg_connection *conn, const char *name)
  3298. {
  3299. if (!conn) {
  3300. return NULL;
  3301. }
  3302. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3303. return get_header(conn->request_info.http_headers,
  3304. conn->request_info.num_headers,
  3305. name);
  3306. }
  3307. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3308. return get_header(conn->response_info.http_headers,
  3309. conn->response_info.num_headers,
  3310. name);
  3311. }
  3312. return NULL;
  3313. }
  3314. static const char *
  3315. get_http_version(const struct mg_connection *conn)
  3316. {
  3317. if (!conn) {
  3318. return NULL;
  3319. }
  3320. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3321. return conn->request_info.http_version;
  3322. }
  3323. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3324. return conn->response_info.http_version;
  3325. }
  3326. return NULL;
  3327. }
  3328. /* A helper function for traversing a comma separated list of values.
  3329. * It returns a list pointer shifted to the next value, or NULL if the end
  3330. * of the list found.
  3331. * Value is stored in val vector. If value has form "x=y", then eq_val
  3332. * vector is initialized to point to the "y" part, and val vector length
  3333. * is adjusted to point only to "x". */
  3334. static const char *
  3335. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3336. {
  3337. int end;
  3338. reparse:
  3339. if (val == NULL || list == NULL || *list == '\0') {
  3340. /* End of the list */
  3341. return NULL;
  3342. }
  3343. /* Skip over leading LWS */
  3344. while (*list == ' ' || *list == '\t')
  3345. list++;
  3346. val->ptr = list;
  3347. if ((list = strchr(val->ptr, ',')) != NULL) {
  3348. /* Comma found. Store length and shift the list ptr */
  3349. val->len = ((size_t)(list - val->ptr));
  3350. list++;
  3351. } else {
  3352. /* This value is the last one */
  3353. list = val->ptr + strlen(val->ptr);
  3354. val->len = ((size_t)(list - val->ptr));
  3355. }
  3356. /* Adjust length for trailing LWS */
  3357. end = (int)val->len - 1;
  3358. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3359. end--;
  3360. val->len = (size_t)(end) + (size_t)(1);
  3361. if (val->len == 0) {
  3362. /* Ignore any empty entries. */
  3363. goto reparse;
  3364. }
  3365. if (eq_val != NULL) {
  3366. /* Value has form "x=y", adjust pointers and lengths
  3367. * so that val points to "x", and eq_val points to "y". */
  3368. eq_val->len = 0;
  3369. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3370. if (eq_val->ptr != NULL) {
  3371. eq_val->ptr++; /* Skip over '=' character */
  3372. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3373. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3374. }
  3375. }
  3376. return list;
  3377. }
  3378. /* A helper function for checking if a comma separated list of values
  3379. * contains
  3380. * the given option (case insensitvely).
  3381. * 'header' can be NULL, in which case false is returned. */
  3382. static int
  3383. header_has_option(const char *header, const char *option)
  3384. {
  3385. struct vec opt_vec;
  3386. struct vec eq_vec;
  3387. DEBUG_ASSERT(option != NULL);
  3388. DEBUG_ASSERT(option[0] != '\0');
  3389. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3390. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3391. return 1;
  3392. }
  3393. return 0;
  3394. }
  3395. /* Sorting function implemented in a separate file */
  3396. #include "sort.inl"
  3397. /* Pattern matching has been reimplemented in a new file */
  3398. #include "match.inl"
  3399. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3400. * This function must tolerate situations when connection info is not
  3401. * set up, for example if request parsing failed. */
  3402. static int
  3403. should_keep_alive(const struct mg_connection *conn)
  3404. {
  3405. const char *http_version;
  3406. const char *header;
  3407. /* First satisfy needs of the server */
  3408. if ((conn == NULL) || conn->must_close) {
  3409. /* Close, if civetweb framework needs to close */
  3410. return 0;
  3411. }
  3412. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3413. /* Close, if keep alive is not enabled */
  3414. return 0;
  3415. }
  3416. /* Check explicit wish of the client */
  3417. header = mg_get_header(conn, "Connection");
  3418. if (header) {
  3419. /* If there is a connection header from the client, obey */
  3420. if (header_has_option(header, "keep-alive")) {
  3421. return 1;
  3422. }
  3423. return 0;
  3424. }
  3425. /* Use default of the standard */
  3426. http_version = get_http_version(conn);
  3427. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3428. /* HTTP 1.1 default is keep alive */
  3429. return 1;
  3430. }
  3431. /* HTTP 1.0 (and earlier) default is to close the connection */
  3432. return 0;
  3433. }
  3434. static int
  3435. should_decode_url(const struct mg_connection *conn)
  3436. {
  3437. if (!conn || !conn->dom_ctx) {
  3438. return 0;
  3439. }
  3440. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3441. }
  3442. static int
  3443. should_decode_query_string(const struct mg_connection *conn)
  3444. {
  3445. if (!conn || !conn->dom_ctx) {
  3446. return 0;
  3447. }
  3448. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3449. == 0);
  3450. }
  3451. static const char *
  3452. suggest_connection_header(const struct mg_connection *conn)
  3453. {
  3454. return should_keep_alive(conn) ? "keep-alive" : "close";
  3455. }
  3456. #include "response.inl"
  3457. static void
  3458. send_no_cache_header(struct mg_connection *conn)
  3459. {
  3460. /* Send all current and obsolete cache opt-out directives. */
  3461. mg_response_header_add(conn,
  3462. "Cache-Control",
  3463. "no-cache, no-store, "
  3464. "must-revalidate, private, max-age=0",
  3465. -1);
  3466. mg_response_header_add(conn, "Expires", "0", -1);
  3467. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3468. /* Obsolete, but still send it for HTTP/1.0 */
  3469. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3470. }
  3471. }
  3472. static void
  3473. send_static_cache_header(struct mg_connection *conn)
  3474. {
  3475. #if !defined(NO_CACHING)
  3476. int max_age;
  3477. char val[64];
  3478. const char *cache_control =
  3479. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3480. /* If there is a full cache-control option configured,0 use it */
  3481. if (cache_control != NULL) {
  3482. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3483. return;
  3484. }
  3485. /* Read the server config to check how long a file may be cached.
  3486. * The configuration is in seconds. */
  3487. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3488. if (max_age <= 0) {
  3489. /* 0 means "do not cache". All values <0 are reserved
  3490. * and may be used differently in the future. */
  3491. /* If a file should not be cached, do not only send
  3492. * max-age=0, but also pragmas and Expires headers. */
  3493. send_no_cache_header(conn);
  3494. return;
  3495. }
  3496. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3497. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3498. /* See also https://www.mnot.net/cache_docs/ */
  3499. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3500. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3501. * leap
  3502. * year to 31622400 seconds. For the moment, we just send whatever has
  3503. * been configured, still the behavior for >1 year should be considered
  3504. * as undefined. */
  3505. mg_snprintf(
  3506. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3507. mg_response_header_add(conn, "Cache-Control", val, -1);
  3508. #else /* NO_CACHING */
  3509. send_no_cache_header(conn);
  3510. #endif /* !NO_CACHING */
  3511. }
  3512. static void
  3513. send_additional_header(struct mg_connection *conn)
  3514. {
  3515. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3516. #if !defined(NO_SSL)
  3517. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3518. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3519. if (max_age >= 0) {
  3520. char val[64];
  3521. mg_snprintf(conn,
  3522. NULL,
  3523. val,
  3524. sizeof(val),
  3525. "max-age=%lu",
  3526. (unsigned long)max_age);
  3527. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3528. }
  3529. }
  3530. #endif
  3531. // Content-Security-Policy
  3532. if (header && header[0]) {
  3533. mg_response_header_add_lines(conn, header);
  3534. }
  3535. }
  3536. static void
  3537. send_cors_header(struct mg_connection *conn)
  3538. {
  3539. const char *origin_hdr = mg_get_header(conn, "Origin");
  3540. const char *cors_orig_cfg =
  3541. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3542. const char *cors_cred_cfg =
  3543. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3544. const char *cors_hdr_cfg =
  3545. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3546. const char *cors_exphdr_cfg =
  3547. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3548. const char *cors_meth_cfg =
  3549. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3550. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3551. /* Cross-origin resource sharing (CORS), see
  3552. * http://www.html5rocks.com/en/tutorials/cors/,
  3553. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3554. * CORS preflight is not supported for files. */
  3555. mg_response_header_add(conn,
  3556. "Access-Control-Allow-Origin",
  3557. cors_orig_cfg,
  3558. -1);
  3559. }
  3560. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3561. /* Cross-origin resource sharing (CORS), see
  3562. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3563. */
  3564. mg_response_header_add(conn,
  3565. "Access-Control-Allow-Credentials",
  3566. cors_cred_cfg,
  3567. -1);
  3568. }
  3569. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3570. mg_response_header_add(conn,
  3571. "Access-Control-Allow-Headers",
  3572. cors_hdr_cfg,
  3573. -1);
  3574. }
  3575. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3576. mg_response_header_add(conn,
  3577. "Access-Control-Expose-Headers",
  3578. cors_exphdr_cfg,
  3579. -1);
  3580. }
  3581. if (cors_meth_cfg && *cors_meth_cfg) {
  3582. mg_response_header_add(conn,
  3583. "Access-Control-Allow-Methods",
  3584. cors_meth_cfg,
  3585. -1);
  3586. }
  3587. }
  3588. #if !defined(NO_FILESYSTEMS)
  3589. static void handle_file_based_request(struct mg_connection *conn,
  3590. const char *path,
  3591. struct mg_file *filep);
  3592. #endif /* NO_FILESYSTEMS */
  3593. CIVETWEB_API const char *
  3594. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3595. {
  3596. /* See IANA HTTP status code assignment:
  3597. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3598. */
  3599. switch (response_code) {
  3600. /* RFC2616 Section 10.1 - Informational 1xx */
  3601. case 100:
  3602. return "Continue"; /* RFC2616 Section 10.1.1 */
  3603. case 101:
  3604. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3605. case 102:
  3606. return "Processing"; /* RFC2518 Section 10.1 */
  3607. /* RFC2616 Section 10.2 - Successful 2xx */
  3608. case 200:
  3609. return "OK"; /* RFC2616 Section 10.2.1 */
  3610. case 201:
  3611. return "Created"; /* RFC2616 Section 10.2.2 */
  3612. case 202:
  3613. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3614. case 203:
  3615. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3616. case 204:
  3617. return "No Content"; /* RFC2616 Section 10.2.5 */
  3618. case 205:
  3619. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3620. case 206:
  3621. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3622. case 207:
  3623. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3624. */
  3625. case 208:
  3626. return "Already Reported"; /* RFC5842 Section 7.1 */
  3627. case 226:
  3628. return "IM used"; /* RFC3229 Section 10.4.1 */
  3629. /* RFC2616 Section 10.3 - Redirection 3xx */
  3630. case 300:
  3631. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3632. case 301:
  3633. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3634. case 302:
  3635. return "Found"; /* RFC2616 Section 10.3.3 */
  3636. case 303:
  3637. return "See Other"; /* RFC2616 Section 10.3.4 */
  3638. case 304:
  3639. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3640. case 305:
  3641. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3642. case 307:
  3643. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3644. case 308:
  3645. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3646. /* RFC2616 Section 10.4 - Client Error 4xx */
  3647. case 400:
  3648. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3649. case 401:
  3650. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3651. case 402:
  3652. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3653. case 403:
  3654. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3655. case 404:
  3656. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3657. case 405:
  3658. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3659. case 406:
  3660. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3661. case 407:
  3662. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3663. case 408:
  3664. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3665. case 409:
  3666. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3667. case 410:
  3668. return "Gone"; /* RFC2616 Section 10.4.11 */
  3669. case 411:
  3670. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3671. case 412:
  3672. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3673. case 413:
  3674. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3675. case 414:
  3676. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3677. case 415:
  3678. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3679. case 416:
  3680. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3681. */
  3682. case 417:
  3683. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3684. case 421:
  3685. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3686. case 422:
  3687. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3688. * Section 11.2 */
  3689. case 423:
  3690. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3691. case 424:
  3692. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3693. * Section 11.4 */
  3694. case 426:
  3695. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3696. case 428:
  3697. return "Precondition Required"; /* RFC 6585, Section 3 */
  3698. case 429:
  3699. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3700. case 431:
  3701. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3702. case 451:
  3703. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3704. * Section 3 */
  3705. /* RFC2616 Section 10.5 - Server Error 5xx */
  3706. case 500:
  3707. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3708. case 501:
  3709. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3710. case 502:
  3711. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3712. case 503:
  3713. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3714. case 504:
  3715. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3716. case 505:
  3717. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3718. case 506:
  3719. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3720. case 507:
  3721. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3722. * Section 11.5 */
  3723. case 508:
  3724. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3725. case 510:
  3726. return "Not Extended"; /* RFC 2774, Section 7 */
  3727. case 511:
  3728. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3729. /* Other status codes, not shown in the IANA HTTP status code
  3730. * assignment.
  3731. * E.g., "de facto" standards due to common use, ... */
  3732. case 418:
  3733. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3734. case 419:
  3735. return "Authentication Timeout"; /* common use */
  3736. case 420:
  3737. return "Enhance Your Calm"; /* common use */
  3738. case 440:
  3739. return "Login Timeout"; /* common use */
  3740. case 509:
  3741. return "Bandwidth Limit Exceeded"; /* common use */
  3742. default:
  3743. /* This error code is unknown. This should not happen. */
  3744. if (conn) {
  3745. mg_cry_internal(conn,
  3746. "Unknown HTTP response code: %u",
  3747. response_code);
  3748. }
  3749. /* Return at least a category according to RFC 2616 Section 10. */
  3750. if (response_code >= 100 && response_code < 200) {
  3751. /* Unknown informational status code */
  3752. return "Information";
  3753. }
  3754. if (response_code >= 200 && response_code < 300) {
  3755. /* Unknown success code */
  3756. return "Success";
  3757. }
  3758. if (response_code >= 300 && response_code < 400) {
  3759. /* Unknown redirection code */
  3760. return "Redirection";
  3761. }
  3762. if (response_code >= 400 && response_code < 500) {
  3763. /* Unknown request error code */
  3764. return "Client Error";
  3765. }
  3766. if (response_code >= 500 && response_code < 600) {
  3767. /* Unknown server error code */
  3768. return "Server Error";
  3769. }
  3770. /* Response code not even within reasonable range */
  3771. return "";
  3772. }
  3773. }
  3774. static int
  3775. mg_send_http_error_impl(struct mg_connection *conn,
  3776. int status,
  3777. const char *fmt,
  3778. va_list args)
  3779. {
  3780. char errmsg_buf[MG_BUF_LEN];
  3781. va_list ap;
  3782. int has_body;
  3783. #if !defined(NO_FILESYSTEMS)
  3784. char path_buf[UTF8_PATH_MAX];
  3785. int len, i, page_handler_found, scope, truncated;
  3786. const char *error_handler = NULL;
  3787. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3788. const char *error_page_file_ext, *tstr;
  3789. #endif /* NO_FILESYSTEMS */
  3790. int handled_by_callback = 0;
  3791. if ((conn == NULL) || (fmt == NULL)) {
  3792. return -2;
  3793. }
  3794. /* Set status (for log) */
  3795. conn->status_code = status;
  3796. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3797. has_body = ((status > 199) && (status != 204) && (status != 304));
  3798. /* Prepare message in buf, if required */
  3799. if (has_body
  3800. || (!conn->in_error_handler
  3801. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3802. /* Store error message in errmsg_buf */
  3803. va_copy(ap, args);
  3804. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3805. va_end(ap);
  3806. /* In a debug build, print all html errors */
  3807. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3808. }
  3809. /* If there is a http_error callback, call it.
  3810. * But don't do it recursively, if callback calls mg_send_http_error again.
  3811. */
  3812. if (!conn->in_error_handler
  3813. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3814. /* Mark in_error_handler to avoid recursion and call user callback. */
  3815. conn->in_error_handler = 1;
  3816. handled_by_callback =
  3817. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3818. == 0);
  3819. conn->in_error_handler = 0;
  3820. }
  3821. if (!handled_by_callback) {
  3822. /* Check for recursion */
  3823. if (conn->in_error_handler) {
  3824. DEBUG_TRACE(
  3825. "Recursion when handling error %u - fall back to default",
  3826. status);
  3827. #if !defined(NO_FILESYSTEMS)
  3828. } else {
  3829. /* Send user defined error pages, if defined */
  3830. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3831. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3832. page_handler_found = 0;
  3833. if (error_handler != NULL) {
  3834. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3835. switch (scope) {
  3836. case 1: /* Handler for specific error, e.g. 404 error */
  3837. mg_snprintf(conn,
  3838. &truncated,
  3839. path_buf,
  3840. sizeof(path_buf) - 32,
  3841. "%serror%03u.",
  3842. error_handler,
  3843. status);
  3844. break;
  3845. case 2: /* Handler for error group, e.g., 5xx error
  3846. * handler
  3847. * for all server errors (500-599) */
  3848. mg_snprintf(conn,
  3849. &truncated,
  3850. path_buf,
  3851. sizeof(path_buf) - 32,
  3852. "%serror%01uxx.",
  3853. error_handler,
  3854. status / 100);
  3855. break;
  3856. default: /* Handler for all errors */
  3857. mg_snprintf(conn,
  3858. &truncated,
  3859. path_buf,
  3860. sizeof(path_buf) - 32,
  3861. "%serror.",
  3862. error_handler);
  3863. break;
  3864. }
  3865. /* String truncation in buf may only occur if
  3866. * error_handler is too long. This string is
  3867. * from the config, not from a client. */
  3868. (void)truncated;
  3869. /* The following code is redundant, but it should avoid
  3870. * false positives in static source code analyzers and
  3871. * vulnerability scanners.
  3872. */
  3873. path_buf[sizeof(path_buf) - 32] = 0;
  3874. len = (int)strlen(path_buf);
  3875. if (len > (int)sizeof(path_buf) - 32) {
  3876. len = (int)sizeof(path_buf) - 32;
  3877. }
  3878. /* Start with the file extension from the configuration. */
  3879. tstr = strchr(error_page_file_ext, '.');
  3880. while (tstr) {
  3881. for (i = 1;
  3882. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3883. i++) {
  3884. /* buffer overrun is not possible here, since
  3885. * (i < 32) && (len < sizeof(path_buf) - 32)
  3886. * ==> (i + len) < sizeof(path_buf) */
  3887. path_buf[len + i - 1] = tstr[i];
  3888. }
  3889. /* buffer overrun is not possible here, since
  3890. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3891. * ==> (i + len) <= sizeof(path_buf) */
  3892. path_buf[len + i - 1] = 0;
  3893. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3894. DEBUG_TRACE("Check error page %s - found",
  3895. path_buf);
  3896. page_handler_found = 1;
  3897. break;
  3898. }
  3899. DEBUG_TRACE("Check error page %s - not found",
  3900. path_buf);
  3901. /* Continue with the next file extension from the
  3902. * configuration (if there is a next one). */
  3903. tstr = strchr(tstr + i, '.');
  3904. }
  3905. }
  3906. }
  3907. if (page_handler_found) {
  3908. conn->in_error_handler = 1;
  3909. handle_file_based_request(conn, path_buf, &error_page_file);
  3910. conn->in_error_handler = 0;
  3911. return 0;
  3912. }
  3913. #endif /* NO_FILESYSTEMS */
  3914. }
  3915. /* No custom error page. Send default error page. */
  3916. conn->must_close = 1;
  3917. mg_response_header_start(conn, status);
  3918. send_no_cache_header(conn);
  3919. send_additional_header(conn);
  3920. send_cors_header(conn);
  3921. if (has_body) {
  3922. mg_response_header_add(conn,
  3923. "Content-Type",
  3924. "text/plain; charset=utf-8",
  3925. -1);
  3926. }
  3927. mg_response_header_send(conn);
  3928. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3929. if (has_body) {
  3930. /* For other errors, send a generic error message. */
  3931. const char *status_text = mg_get_response_code_text(conn, status);
  3932. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3933. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3934. } else {
  3935. /* No body allowed. Close the connection. */
  3936. DEBUG_TRACE("Error %i", status);
  3937. }
  3938. }
  3939. return 0;
  3940. }
  3941. CIVETWEB_API int
  3942. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3943. {
  3944. va_list ap;
  3945. int ret;
  3946. va_start(ap, fmt);
  3947. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3948. va_end(ap);
  3949. return ret;
  3950. }
  3951. CIVETWEB_API int
  3952. mg_send_http_ok(struct mg_connection *conn,
  3953. const char *mime_type,
  3954. long long content_length)
  3955. {
  3956. if ((mime_type == NULL) || (*mime_type == 0)) {
  3957. /* No content type defined: default to text/html */
  3958. mime_type = "text/html";
  3959. }
  3960. mg_response_header_start(conn, 200);
  3961. send_no_cache_header(conn);
  3962. send_additional_header(conn);
  3963. send_cors_header(conn);
  3964. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3965. if (content_length < 0) {
  3966. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3967. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3968. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3969. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3970. }
  3971. } else {
  3972. char len[32];
  3973. int trunc = 0;
  3974. mg_snprintf(conn,
  3975. &trunc,
  3976. len,
  3977. sizeof(len),
  3978. "%" UINT64_FMT,
  3979. (uint64_t)content_length);
  3980. if (!trunc) {
  3981. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3982. * !trunc is always true */
  3983. mg_response_header_add(conn, "Content-Length", len, -1);
  3984. }
  3985. }
  3986. mg_response_header_send(conn);
  3987. return 0;
  3988. }
  3989. CIVETWEB_API int
  3990. mg_send_http_redirect(struct mg_connection *conn,
  3991. const char *target_url,
  3992. int redirect_code)
  3993. {
  3994. /* Send a 30x redirect response.
  3995. *
  3996. * Redirect types (status codes):
  3997. *
  3998. * Status | Perm/Temp | Method | Version
  3999. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4000. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4001. * 303 | temporary | always use GET | HTTP/1.1
  4002. * 307 | temporary | always keep method | HTTP/1.1
  4003. * 308 | permanent | always keep method | HTTP/1.1
  4004. */
  4005. #if defined(MG_SEND_REDIRECT_BODY)
  4006. char redirect_body[MG_BUF_LEN];
  4007. size_t content_len = 0;
  4008. char content_len_text[32];
  4009. #endif
  4010. /* In case redirect_code=0, use 307. */
  4011. if (redirect_code == 0) {
  4012. redirect_code = 307;
  4013. }
  4014. /* In case redirect_code is none of the above, return error. */
  4015. if ((redirect_code != 301) && (redirect_code != 302)
  4016. && (redirect_code != 303) && (redirect_code != 307)
  4017. && (redirect_code != 308)) {
  4018. /* Parameter error */
  4019. return -2;
  4020. }
  4021. /* If target_url is not defined, redirect to "/". */
  4022. if ((target_url == NULL) || (*target_url == 0)) {
  4023. target_url = "/";
  4024. }
  4025. #if defined(MG_SEND_REDIRECT_BODY)
  4026. /* TODO: condition name? */
  4027. /* Prepare a response body with a hyperlink.
  4028. *
  4029. * According to RFC2616 (and RFC1945 before):
  4030. * Unless the request method was HEAD, the entity of the
  4031. * response SHOULD contain a short hypertext note with a hyperlink to
  4032. * the new URI(s).
  4033. *
  4034. * However, this response body is not useful in M2M communication.
  4035. * Probably the original reason in the RFC was, clients not supporting
  4036. * a 30x HTTP redirect could still show the HTML page and let the user
  4037. * press the link. Since current browsers support 30x HTTP, the additional
  4038. * HTML body does not seem to make sense anymore.
  4039. *
  4040. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4041. * but it only notes:
  4042. * The server's response payload usually contains a short
  4043. * hypertext note with a hyperlink to the new URI(s).
  4044. *
  4045. * Deactivated by default. If you need the 30x body, set the define.
  4046. */
  4047. mg_snprintf(
  4048. conn,
  4049. NULL /* ignore truncation */,
  4050. redirect_body,
  4051. sizeof(redirect_body),
  4052. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4053. redirect_text,
  4054. target_url,
  4055. target_url);
  4056. content_len = strlen(reply);
  4057. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4058. #endif
  4059. /* Send all required headers */
  4060. mg_response_header_start(conn, redirect_code);
  4061. mg_response_header_add(conn, "Location", target_url, -1);
  4062. if ((redirect_code == 301) || (redirect_code == 308)) {
  4063. /* Permanent redirect */
  4064. send_static_cache_header(conn);
  4065. } else {
  4066. /* Temporary redirect */
  4067. send_no_cache_header(conn);
  4068. }
  4069. send_additional_header(conn);
  4070. send_cors_header(conn);
  4071. #if defined(MG_SEND_REDIRECT_BODY)
  4072. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4073. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4074. #else
  4075. mg_response_header_add(conn, "Content-Length", "0", 1);
  4076. #endif
  4077. mg_response_header_send(conn);
  4078. #if defined(MG_SEND_REDIRECT_BODY)
  4079. /* Send response body */
  4080. /* ... unless it is a HEAD request */
  4081. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4082. ret = mg_write(conn, redirect_body, content_len);
  4083. }
  4084. #endif
  4085. return 1;
  4086. }
  4087. #if defined(_WIN32)
  4088. /* Create substitutes for POSIX functions in Win32. */
  4089. #if defined(GCC_DIAGNOSTIC)
  4090. /* Show no warning in case system functions are not used. */
  4091. #pragma GCC diagnostic push
  4092. #pragma GCC diagnostic ignored "-Wunused-function"
  4093. #endif
  4094. static int
  4095. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4096. {
  4097. (void)unused;
  4098. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4099. InitializeCriticalSection(&mutex->sec);
  4100. return 0;
  4101. }
  4102. static int
  4103. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4104. {
  4105. DeleteCriticalSection(&mutex->sec);
  4106. return 0;
  4107. }
  4108. static int
  4109. pthread_mutex_lock(pthread_mutex_t *mutex)
  4110. {
  4111. EnterCriticalSection(&mutex->sec);
  4112. return 0;
  4113. }
  4114. static int
  4115. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4116. {
  4117. LeaveCriticalSection(&mutex->sec);
  4118. return 0;
  4119. }
  4120. FUNCTION_MAY_BE_UNUSED
  4121. static int
  4122. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4123. {
  4124. (void)unused;
  4125. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4126. cv->waiting_thread = NULL;
  4127. return 0;
  4128. }
  4129. FUNCTION_MAY_BE_UNUSED
  4130. static int
  4131. pthread_cond_timedwait(pthread_cond_t *cv,
  4132. pthread_mutex_t *mutex,
  4133. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4134. {
  4135. struct mg_workerTLS **ptls,
  4136. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4137. int ok;
  4138. uint64_t nsnow, nswaitabs;
  4139. int64_t nswaitrel;
  4140. DWORD mswaitrel;
  4141. pthread_mutex_lock(&cv->threadIdSec);
  4142. /* Add this thread to cv's waiting list */
  4143. ptls = &cv->waiting_thread;
  4144. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4145. ;
  4146. tls->next_waiting_thread = NULL;
  4147. *ptls = tls;
  4148. pthread_mutex_unlock(&cv->threadIdSec);
  4149. if (abstime) {
  4150. nsnow = mg_get_current_time_ns();
  4151. nswaitabs =
  4152. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4153. nswaitrel = nswaitabs - nsnow;
  4154. if (nswaitrel < 0) {
  4155. nswaitrel = 0;
  4156. }
  4157. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4158. } else {
  4159. mswaitrel = (DWORD)INFINITE;
  4160. }
  4161. pthread_mutex_unlock(mutex);
  4162. ok = (WAIT_OBJECT_0
  4163. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4164. if (!ok) {
  4165. ok = 1;
  4166. pthread_mutex_lock(&cv->threadIdSec);
  4167. ptls = &cv->waiting_thread;
  4168. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4169. if (*ptls == tls) {
  4170. *ptls = tls->next_waiting_thread;
  4171. ok = 0;
  4172. break;
  4173. }
  4174. }
  4175. pthread_mutex_unlock(&cv->threadIdSec);
  4176. if (ok) {
  4177. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4178. (DWORD)INFINITE);
  4179. }
  4180. }
  4181. /* This thread has been removed from cv's waiting list */
  4182. pthread_mutex_lock(mutex);
  4183. return ok ? 0 : -1;
  4184. }
  4185. FUNCTION_MAY_BE_UNUSED
  4186. static int
  4187. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4188. {
  4189. return pthread_cond_timedwait(cv, mutex, NULL);
  4190. }
  4191. FUNCTION_MAY_BE_UNUSED
  4192. static int
  4193. pthread_cond_signal(pthread_cond_t *cv)
  4194. {
  4195. HANDLE wkup = NULL;
  4196. BOOL ok = FALSE;
  4197. pthread_mutex_lock(&cv->threadIdSec);
  4198. if (cv->waiting_thread) {
  4199. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4200. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4201. ok = SetEvent(wkup);
  4202. DEBUG_ASSERT(ok);
  4203. }
  4204. pthread_mutex_unlock(&cv->threadIdSec);
  4205. return ok ? 0 : 1;
  4206. }
  4207. FUNCTION_MAY_BE_UNUSED
  4208. static int
  4209. pthread_cond_broadcast(pthread_cond_t *cv)
  4210. {
  4211. pthread_mutex_lock(&cv->threadIdSec);
  4212. while (cv->waiting_thread) {
  4213. pthread_cond_signal(cv);
  4214. }
  4215. pthread_mutex_unlock(&cv->threadIdSec);
  4216. return 0;
  4217. }
  4218. FUNCTION_MAY_BE_UNUSED
  4219. static int
  4220. pthread_cond_destroy(pthread_cond_t *cv)
  4221. {
  4222. pthread_mutex_lock(&cv->threadIdSec);
  4223. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4224. pthread_mutex_unlock(&cv->threadIdSec);
  4225. pthread_mutex_destroy(&cv->threadIdSec);
  4226. return 0;
  4227. }
  4228. #if defined(ALTERNATIVE_QUEUE)
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static void *
  4231. event_create(void)
  4232. {
  4233. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static int
  4237. event_wait(void *eventhdl)
  4238. {
  4239. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4240. return (res == WAIT_OBJECT_0);
  4241. }
  4242. FUNCTION_MAY_BE_UNUSED
  4243. static int
  4244. event_signal(void *eventhdl)
  4245. {
  4246. return (int)SetEvent((HANDLE)eventhdl);
  4247. }
  4248. FUNCTION_MAY_BE_UNUSED
  4249. static void
  4250. event_destroy(void *eventhdl)
  4251. {
  4252. CloseHandle((HANDLE)eventhdl);
  4253. }
  4254. #endif
  4255. #if defined(GCC_DIAGNOSTIC)
  4256. /* Enable unused function warning again */
  4257. #pragma GCC diagnostic pop
  4258. #endif
  4259. /* For Windows, change all slashes to backslashes in path names. */
  4260. static void
  4261. change_slashes_to_backslashes(char *path)
  4262. {
  4263. int i;
  4264. for (i = 0; path[i] != '\0'; i++) {
  4265. if (path[i] == '/') {
  4266. path[i] = '\\';
  4267. }
  4268. /* remove double backslash (check i > 0 to preserve UNC paths,
  4269. * like \\server\file.txt) */
  4270. if ((i > 0) && (path[i] == '\\')) {
  4271. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4272. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4273. }
  4274. }
  4275. }
  4276. }
  4277. static int
  4278. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4279. {
  4280. int diff;
  4281. do {
  4282. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4283. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4284. s1++;
  4285. s2++;
  4286. } while ((diff == 0) && (s1[-1] != L'\0'));
  4287. return diff;
  4288. }
  4289. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4290. * wbuf and wbuf_len is a target buffer and its length. */
  4291. static void
  4292. path_to_unicode(const struct mg_connection *conn,
  4293. const char *path,
  4294. wchar_t *wbuf,
  4295. size_t wbuf_len)
  4296. {
  4297. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4298. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4299. DWORD long_len, err;
  4300. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4301. mg_strlcpy(buf, path, sizeof(buf));
  4302. change_slashes_to_backslashes(buf);
  4303. /* Convert to Unicode and back. If doubly-converted string does not
  4304. * match the original, something is fishy, reject. */
  4305. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4306. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4307. WideCharToMultiByte(
  4308. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4309. if (strcmp(buf, buf2) != 0) {
  4310. wbuf[0] = L'\0';
  4311. }
  4312. /* Windows file systems are not case sensitive, but you can still use
  4313. * uppercase and lowercase letters (on all modern file systems).
  4314. * The server can check if the URI uses the same upper/lowercase
  4315. * letters an the file system, effectively making Windows servers
  4316. * case sensitive (like Linux servers are). It is still not possible
  4317. * to use two files with the same name in different cases on Windows
  4318. * (like /a and /A) - this would be possible in Linux.
  4319. * As a default, Windows is not case sensitive, but the case sensitive
  4320. * file name check can be activated by an additional configuration. */
  4321. if (conn) {
  4322. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4323. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4324. "yes")) {
  4325. /* Use case sensitive compare function */
  4326. fcompare = wcscmp;
  4327. }
  4328. }
  4329. (void)conn; /* conn is currently unused */
  4330. /* Only accept a full file path, not a Windows short (8.3) path. */
  4331. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4332. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4333. if (long_len == 0) {
  4334. err = GetLastError();
  4335. if (err == ERROR_FILE_NOT_FOUND) {
  4336. /* File does not exist. This is not always a problem here. */
  4337. return;
  4338. }
  4339. }
  4340. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4341. /* Short name is used. */
  4342. wbuf[0] = L'\0';
  4343. }
  4344. }
  4345. #if !defined(NO_FILESYSTEMS)
  4346. /* Get file information, return 1 if file exists, 0 if not */
  4347. static int
  4348. mg_stat(const struct mg_connection *conn,
  4349. const char *path,
  4350. struct mg_file_stat *filep)
  4351. {
  4352. wchar_t wbuf[UTF16_PATH_MAX];
  4353. WIN32_FILE_ATTRIBUTE_DATA info;
  4354. time_t creation_time;
  4355. size_t len;
  4356. if (!filep) {
  4357. return 0;
  4358. }
  4359. memset(filep, 0, sizeof(*filep));
  4360. if (mg_path_suspicious(conn, path)) {
  4361. return 0;
  4362. }
  4363. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4364. /* Windows happily opens files with some garbage at the end of file name.
  4365. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4366. * "a.cgi", despite one would expect an error back. */
  4367. len = strlen(path);
  4368. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4369. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4370. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4371. filep->last_modified =
  4372. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4373. info.ftLastWriteTime.dwHighDateTime);
  4374. /* On Windows, the file creation time can be higher than the
  4375. * modification time, e.g. when a file is copied.
  4376. * Since the Last-Modified timestamp is used for caching
  4377. * it should be based on the most recent timestamp. */
  4378. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4379. info.ftCreationTime.dwHighDateTime);
  4380. if (creation_time > filep->last_modified) {
  4381. filep->last_modified = creation_time;
  4382. }
  4383. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4384. return 1;
  4385. }
  4386. return 0;
  4387. }
  4388. #endif
  4389. static int
  4390. mg_remove(const struct mg_connection *conn, const char *path)
  4391. {
  4392. wchar_t wbuf[UTF16_PATH_MAX];
  4393. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4394. return DeleteFileW(wbuf) ? 0 : -1;
  4395. }
  4396. static int
  4397. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4398. {
  4399. wchar_t wbuf[UTF16_PATH_MAX];
  4400. (void)mode;
  4401. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4402. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4403. }
  4404. /* Create substitutes for POSIX functions in Win32. */
  4405. #if defined(GCC_DIAGNOSTIC)
  4406. /* Show no warning in case system functions are not used. */
  4407. #pragma GCC diagnostic push
  4408. #pragma GCC diagnostic ignored "-Wunused-function"
  4409. #endif
  4410. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4411. FUNCTION_MAY_BE_UNUSED
  4412. static DIR *
  4413. mg_opendir(const struct mg_connection *conn, const char *name)
  4414. {
  4415. DIR *dir = NULL;
  4416. wchar_t wpath[UTF16_PATH_MAX];
  4417. DWORD attrs;
  4418. if (name == NULL) {
  4419. SetLastError(ERROR_BAD_ARGUMENTS);
  4420. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4421. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4422. } else {
  4423. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4424. attrs = GetFileAttributesW(wpath);
  4425. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4426. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4427. (void)wcscat(wpath, L"\\*");
  4428. dir->handle = FindFirstFileW(wpath, &dir->info);
  4429. dir->result.d_name[0] = '\0';
  4430. } else {
  4431. mg_free(dir);
  4432. dir = NULL;
  4433. }
  4434. }
  4435. return dir;
  4436. }
  4437. FUNCTION_MAY_BE_UNUSED
  4438. static int
  4439. mg_closedir(DIR *dir)
  4440. {
  4441. int result = 0;
  4442. if (dir != NULL) {
  4443. if (dir->handle != INVALID_HANDLE_VALUE)
  4444. result = FindClose(dir->handle) ? 0 : -1;
  4445. mg_free(dir);
  4446. } else {
  4447. result = -1;
  4448. SetLastError(ERROR_BAD_ARGUMENTS);
  4449. }
  4450. return result;
  4451. }
  4452. FUNCTION_MAY_BE_UNUSED
  4453. static struct dirent *
  4454. mg_readdir(DIR *dir)
  4455. {
  4456. struct dirent *result = 0;
  4457. if (dir) {
  4458. if (dir->handle != INVALID_HANDLE_VALUE) {
  4459. result = &dir->result;
  4460. (void)WideCharToMultiByte(CP_UTF8,
  4461. 0,
  4462. dir->info.cFileName,
  4463. -1,
  4464. result->d_name,
  4465. sizeof(result->d_name),
  4466. NULL,
  4467. NULL);
  4468. if (!FindNextFileW(dir->handle, &dir->info)) {
  4469. (void)FindClose(dir->handle);
  4470. dir->handle = INVALID_HANDLE_VALUE;
  4471. }
  4472. } else {
  4473. SetLastError(ERROR_FILE_NOT_FOUND);
  4474. }
  4475. } else {
  4476. SetLastError(ERROR_BAD_ARGUMENTS);
  4477. }
  4478. return result;
  4479. }
  4480. #if !defined(HAVE_POLL)
  4481. #undef POLLIN
  4482. #undef POLLPRI
  4483. #undef POLLOUT
  4484. #undef POLLERR
  4485. #define POLLIN (1) /* Data ready - read will not block. */
  4486. #define POLLPRI (2) /* Priority data ready. */
  4487. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4488. #define POLLERR (8) /* Error event */
  4489. FUNCTION_MAY_BE_UNUSED
  4490. static int
  4491. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4492. {
  4493. struct timeval tv;
  4494. fd_set rset;
  4495. fd_set wset;
  4496. fd_set eset;
  4497. unsigned int i;
  4498. int result;
  4499. SOCKET maxfd = 0;
  4500. memset(&tv, 0, sizeof(tv));
  4501. tv.tv_sec = milliseconds / 1000;
  4502. tv.tv_usec = (milliseconds % 1000) * 1000;
  4503. FD_ZERO(&rset);
  4504. FD_ZERO(&wset);
  4505. FD_ZERO(&eset);
  4506. for (i = 0; i < n; i++) {
  4507. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4508. if (pfd[i].events & POLLIN) {
  4509. FD_SET(pfd[i].fd, &rset);
  4510. }
  4511. if (pfd[i].events & POLLOUT) {
  4512. FD_SET(pfd[i].fd, &wset);
  4513. }
  4514. /* Check for errors for any FD in the set */
  4515. FD_SET(pfd[i].fd, &eset);
  4516. }
  4517. pfd[i].revents = 0;
  4518. if (pfd[i].fd > maxfd) {
  4519. maxfd = pfd[i].fd;
  4520. }
  4521. }
  4522. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4523. for (i = 0; i < n; i++) {
  4524. if (FD_ISSET(pfd[i].fd, &rset)) {
  4525. pfd[i].revents |= POLLIN;
  4526. }
  4527. if (FD_ISSET(pfd[i].fd, &wset)) {
  4528. pfd[i].revents |= POLLOUT;
  4529. }
  4530. if (FD_ISSET(pfd[i].fd, &eset)) {
  4531. pfd[i].revents |= POLLERR;
  4532. }
  4533. }
  4534. }
  4535. /* We should subtract the time used in select from remaining
  4536. * "milliseconds", in particular if called from mg_poll with a
  4537. * timeout quantum.
  4538. * Unfortunately, the remaining time is not stored in "tv" in all
  4539. * implementations, so the result in "tv" must be considered undefined.
  4540. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4541. return result;
  4542. }
  4543. #endif /* HAVE_POLL */
  4544. #if defined(GCC_DIAGNOSTIC)
  4545. /* Enable unused function warning again */
  4546. #pragma GCC diagnostic pop
  4547. #endif
  4548. static void
  4549. set_close_on_exec(SOCKET sock,
  4550. const struct mg_connection *conn /* may be null */,
  4551. struct mg_context *ctx /* may be null */)
  4552. {
  4553. (void)conn; /* Unused. */
  4554. (void)ctx;
  4555. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4556. }
  4557. CIVETWEB_API int
  4558. mg_start_thread(mg_thread_func_t f, void *p)
  4559. {
  4560. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4561. /* Compile-time option to control stack size, e.g.
  4562. * -DUSE_STACK_SIZE=16384
  4563. */
  4564. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4565. == ((uintptr_t)(-1L)))
  4566. ? -1
  4567. : 0);
  4568. #else
  4569. return (
  4570. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4571. ? -1
  4572. : 0);
  4573. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4574. }
  4575. /* Start a thread storing the thread context. */
  4576. static int
  4577. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4578. void *p,
  4579. pthread_t *threadidptr)
  4580. {
  4581. uintptr_t uip;
  4582. HANDLE threadhandle;
  4583. int result = -1;
  4584. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4585. threadhandle = (HANDLE)uip;
  4586. if ((uip != 0) && (threadidptr != NULL)) {
  4587. *threadidptr = threadhandle;
  4588. result = 0;
  4589. }
  4590. return result;
  4591. }
  4592. /* Wait for a thread to finish. */
  4593. static int
  4594. mg_join_thread(pthread_t threadid)
  4595. {
  4596. int result;
  4597. DWORD dwevent;
  4598. result = -1;
  4599. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4600. if (dwevent == WAIT_FAILED) {
  4601. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4602. } else {
  4603. if (dwevent == WAIT_OBJECT_0) {
  4604. CloseHandle(threadid);
  4605. result = 0;
  4606. }
  4607. }
  4608. return result;
  4609. }
  4610. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4611. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4612. /* Create substitutes for POSIX functions in Win32. */
  4613. #if defined(GCC_DIAGNOSTIC)
  4614. /* Show no warning in case system functions are not used. */
  4615. #pragma GCC diagnostic push
  4616. #pragma GCC diagnostic ignored "-Wunused-function"
  4617. #endif
  4618. FUNCTION_MAY_BE_UNUSED
  4619. static HANDLE
  4620. dlopen(const char *dll_name, int flags)
  4621. {
  4622. wchar_t wbuf[UTF16_PATH_MAX];
  4623. (void)flags;
  4624. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4625. return LoadLibraryW(wbuf);
  4626. }
  4627. FUNCTION_MAY_BE_UNUSED
  4628. static int
  4629. dlclose(void *handle)
  4630. {
  4631. int result;
  4632. if (FreeLibrary((HMODULE)handle) != 0) {
  4633. result = 0;
  4634. } else {
  4635. result = -1;
  4636. }
  4637. return result;
  4638. }
  4639. #if defined(GCC_DIAGNOSTIC)
  4640. /* Enable unused function warning again */
  4641. #pragma GCC diagnostic pop
  4642. #endif
  4643. #endif
  4644. #if !defined(NO_CGI)
  4645. #define SIGKILL (0)
  4646. static int
  4647. kill(pid_t pid, int sig_num)
  4648. {
  4649. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4650. (void)CloseHandle((HANDLE)pid);
  4651. return 0;
  4652. }
  4653. #if !defined(WNOHANG)
  4654. #define WNOHANG (1)
  4655. #endif
  4656. static pid_t
  4657. waitpid(pid_t pid, int *status, int flags)
  4658. {
  4659. DWORD timeout = INFINITE;
  4660. DWORD waitres;
  4661. (void)status; /* Currently not used by any client here */
  4662. if ((flags | WNOHANG) == WNOHANG) {
  4663. timeout = 0;
  4664. }
  4665. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4666. if (waitres == WAIT_OBJECT_0) {
  4667. return pid;
  4668. }
  4669. if (waitres == WAIT_TIMEOUT) {
  4670. return 0;
  4671. }
  4672. return (pid_t)-1;
  4673. }
  4674. static void
  4675. trim_trailing_whitespaces(char *s)
  4676. {
  4677. char *e = s + strlen(s);
  4678. while ((e > s) && isspace((unsigned char)e[-1])) {
  4679. *(--e) = '\0';
  4680. }
  4681. }
  4682. static pid_t
  4683. spawn_process(struct mg_connection *conn,
  4684. const char *prog,
  4685. char *envblk,
  4686. char *envp[],
  4687. int fdin[2],
  4688. int fdout[2],
  4689. int fderr[2],
  4690. const char *dir,
  4691. int cgi_config_idx)
  4692. {
  4693. HANDLE me;
  4694. char *interp;
  4695. char *interp_arg = 0;
  4696. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4697. int truncated;
  4698. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4699. STARTUPINFOA si;
  4700. PROCESS_INFORMATION pi = {0};
  4701. (void)envp;
  4702. memset(&si, 0, sizeof(si));
  4703. si.cb = sizeof(si);
  4704. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4705. si.wShowWindow = SW_HIDE;
  4706. me = GetCurrentProcess();
  4707. DuplicateHandle(me,
  4708. (HANDLE)_get_osfhandle(fdin[0]),
  4709. me,
  4710. &si.hStdInput,
  4711. 0,
  4712. TRUE,
  4713. DUPLICATE_SAME_ACCESS);
  4714. DuplicateHandle(me,
  4715. (HANDLE)_get_osfhandle(fdout[1]),
  4716. me,
  4717. &si.hStdOutput,
  4718. 0,
  4719. TRUE,
  4720. DUPLICATE_SAME_ACCESS);
  4721. DuplicateHandle(me,
  4722. (HANDLE)_get_osfhandle(fderr[1]),
  4723. me,
  4724. &si.hStdError,
  4725. 0,
  4726. TRUE,
  4727. DUPLICATE_SAME_ACCESS);
  4728. /* Mark handles that should not be inherited. See
  4729. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4730. */
  4731. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4732. HANDLE_FLAG_INHERIT,
  4733. 0);
  4734. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4735. HANDLE_FLAG_INHERIT,
  4736. 0);
  4737. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4738. HANDLE_FLAG_INHERIT,
  4739. 0);
  4740. /* First check, if there is a CGI interpreter configured for all CGI
  4741. * scripts. */
  4742. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4743. if (interp != NULL) {
  4744. /* If there is a configured interpreter, check for additional arguments
  4745. */
  4746. interp_arg =
  4747. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4748. } else {
  4749. /* Otherwise, the interpreter must be stated in the first line of the
  4750. * CGI script file, after a #! (shebang) mark. */
  4751. buf[0] = buf[1] = '\0';
  4752. /* Get the full script path */
  4753. mg_snprintf(
  4754. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4755. if (truncated) {
  4756. pi.hProcess = (pid_t)-1;
  4757. goto spawn_cleanup;
  4758. }
  4759. /* Open the script file, to read the first line */
  4760. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4761. /* Read the first line of the script into the buffer */
  4762. mg_fgets(buf, sizeof(buf), &file);
  4763. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4764. buf[sizeof(buf) - 1] = '\0';
  4765. }
  4766. if ((buf[0] == '#') && (buf[1] == '!')) {
  4767. trim_trailing_whitespaces(buf + 2);
  4768. } else {
  4769. buf[2] = '\0';
  4770. }
  4771. interp = buf + 2;
  4772. }
  4773. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4774. if (interp[0] != '\0') {
  4775. /* This is an interpreted script file. We must call the interpreter. */
  4776. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4777. mg_snprintf(conn,
  4778. &truncated,
  4779. cmdline,
  4780. sizeof(cmdline),
  4781. "\"%s\" %s \"%s\\%s\"",
  4782. interp,
  4783. interp_arg,
  4784. full_dir,
  4785. prog);
  4786. } else {
  4787. mg_snprintf(conn,
  4788. &truncated,
  4789. cmdline,
  4790. sizeof(cmdline),
  4791. "\"%s\" \"%s\\%s\"",
  4792. interp,
  4793. full_dir,
  4794. prog);
  4795. }
  4796. } else {
  4797. /* This is (probably) a compiled program. We call it directly. */
  4798. mg_snprintf(conn,
  4799. &truncated,
  4800. cmdline,
  4801. sizeof(cmdline),
  4802. "\"%s\\%s\"",
  4803. full_dir,
  4804. prog);
  4805. }
  4806. if (truncated) {
  4807. pi.hProcess = (pid_t)-1;
  4808. goto spawn_cleanup;
  4809. }
  4810. DEBUG_TRACE("Running [%s]", cmdline);
  4811. if (CreateProcessA(NULL,
  4812. cmdline,
  4813. NULL,
  4814. NULL,
  4815. TRUE,
  4816. CREATE_NEW_PROCESS_GROUP,
  4817. envblk,
  4818. NULL,
  4819. &si,
  4820. &pi)
  4821. == 0) {
  4822. mg_cry_internal(
  4823. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4824. pi.hProcess = (pid_t)-1;
  4825. /* goto spawn_cleanup; */
  4826. }
  4827. spawn_cleanup:
  4828. (void)CloseHandle(si.hStdOutput);
  4829. (void)CloseHandle(si.hStdError);
  4830. (void)CloseHandle(si.hStdInput);
  4831. if (pi.hThread != NULL) {
  4832. (void)CloseHandle(pi.hThread);
  4833. }
  4834. return (pid_t)pi.hProcess;
  4835. }
  4836. #endif /* !NO_CGI */
  4837. static int
  4838. set_blocking_mode(SOCKET sock)
  4839. {
  4840. unsigned long non_blocking = 0;
  4841. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4842. }
  4843. static int
  4844. set_non_blocking_mode(SOCKET sock)
  4845. {
  4846. unsigned long non_blocking = 1;
  4847. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4848. }
  4849. #else
  4850. #if !defined(NO_FILESYSTEMS)
  4851. static int
  4852. mg_stat(const struct mg_connection *conn,
  4853. const char *path,
  4854. struct mg_file_stat *filep)
  4855. {
  4856. struct stat st;
  4857. if (!filep) {
  4858. return 0;
  4859. }
  4860. memset(filep, 0, sizeof(*filep));
  4861. if (mg_path_suspicious(conn, path)) {
  4862. return 0;
  4863. }
  4864. if (0 == stat(path, &st)) {
  4865. filep->size = (uint64_t)(st.st_size);
  4866. filep->last_modified = st.st_mtime;
  4867. filep->is_directory = S_ISDIR(st.st_mode);
  4868. return 1;
  4869. }
  4870. return 0;
  4871. }
  4872. #endif /* NO_FILESYSTEMS */
  4873. static void
  4874. set_close_on_exec(int fd,
  4875. const struct mg_connection *conn /* may be null */,
  4876. struct mg_context *ctx /* may be null */)
  4877. {
  4878. #if defined(__ZEPHYR__)
  4879. (void)fd;
  4880. (void)conn;
  4881. (void)ctx;
  4882. #else
  4883. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4884. if (conn || ctx) {
  4885. struct mg_connection fc;
  4886. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4887. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4888. __func__,
  4889. strerror(ERRNO));
  4890. }
  4891. }
  4892. #endif
  4893. }
  4894. CIVETWEB_API int
  4895. mg_start_thread(mg_thread_func_t func, void *param)
  4896. {
  4897. pthread_t thread_id;
  4898. pthread_attr_t attr;
  4899. int result;
  4900. (void)pthread_attr_init(&attr);
  4901. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4902. #if defined(__ZEPHYR__)
  4903. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4904. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4905. /* Compile-time option to control stack size,
  4906. * e.g. -DUSE_STACK_SIZE=16384 */
  4907. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4908. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4909. result = pthread_create(&thread_id, &attr, func, param);
  4910. pthread_attr_destroy(&attr);
  4911. return result;
  4912. }
  4913. /* Start a thread storing the thread context. */
  4914. static int
  4915. mg_start_thread_with_id(mg_thread_func_t func,
  4916. void *param,
  4917. pthread_t *threadidptr)
  4918. {
  4919. pthread_t thread_id;
  4920. pthread_attr_t attr;
  4921. int result;
  4922. (void)pthread_attr_init(&attr);
  4923. #if defined(__ZEPHYR__)
  4924. pthread_attr_setstack(&attr,
  4925. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4926. ZEPHYR_STACK_SIZE);
  4927. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4928. /* Compile-time option to control stack size,
  4929. * e.g. -DUSE_STACK_SIZE=16384 */
  4930. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4931. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4932. result = pthread_create(&thread_id, &attr, func, param);
  4933. pthread_attr_destroy(&attr);
  4934. if ((result == 0) && (threadidptr != NULL)) {
  4935. *threadidptr = thread_id;
  4936. }
  4937. return result;
  4938. }
  4939. /* Wait for a thread to finish. */
  4940. static int
  4941. mg_join_thread(pthread_t threadid)
  4942. {
  4943. int result;
  4944. result = pthread_join(threadid, NULL);
  4945. return result;
  4946. }
  4947. #if !defined(NO_CGI)
  4948. static pid_t
  4949. spawn_process(struct mg_connection *conn,
  4950. const char *prog,
  4951. char *envblk,
  4952. char *envp[],
  4953. int fdin[2],
  4954. int fdout[2],
  4955. int fderr[2],
  4956. const char *dir,
  4957. int cgi_config_idx)
  4958. {
  4959. pid_t pid;
  4960. const char *interp;
  4961. (void)envblk;
  4962. if ((pid = fork()) == -1) {
  4963. /* Parent */
  4964. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4965. } else if (pid != 0) {
  4966. /* Make sure children close parent-side descriptors.
  4967. * The caller will close the child-side immediately. */
  4968. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4969. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4970. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4971. } else {
  4972. /* Child */
  4973. if (chdir(dir) != 0) {
  4974. mg_cry_internal(
  4975. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4976. } else if (dup2(fdin[0], 0) == -1) {
  4977. mg_cry_internal(conn,
  4978. "%s: dup2(%d, 0): %s",
  4979. __func__,
  4980. fdin[0],
  4981. strerror(ERRNO));
  4982. } else if (dup2(fdout[1], 1) == -1) {
  4983. mg_cry_internal(conn,
  4984. "%s: dup2(%d, 1): %s",
  4985. __func__,
  4986. fdout[1],
  4987. strerror(ERRNO));
  4988. } else if (dup2(fderr[1], 2) == -1) {
  4989. mg_cry_internal(conn,
  4990. "%s: dup2(%d, 2): %s",
  4991. __func__,
  4992. fderr[1],
  4993. strerror(ERRNO));
  4994. } else {
  4995. struct sigaction sa;
  4996. /* Keep stderr and stdout in two different pipes.
  4997. * Stdout will be sent back to the client,
  4998. * stderr should go into a server error log. */
  4999. (void)close(fdin[0]);
  5000. (void)close(fdout[1]);
  5001. (void)close(fderr[1]);
  5002. /* Close write end fdin and read end fdout and fderr */
  5003. (void)close(fdin[1]);
  5004. (void)close(fdout[0]);
  5005. (void)close(fderr[0]);
  5006. /* After exec, all signal handlers are restored to their default
  5007. * values, with one exception of SIGCHLD. According to
  5008. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5009. * will leave unchanged after exec if it was set to be ignored.
  5010. * Restore it to default action. */
  5011. memset(&sa, 0, sizeof(sa));
  5012. sa.sa_handler = SIG_DFL;
  5013. sigaction(SIGCHLD, &sa, NULL);
  5014. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5015. if (interp == NULL) {
  5016. /* no interpreter configured, call the program directly */
  5017. (void)execle(prog, prog, NULL, envp);
  5018. mg_cry_internal(conn,
  5019. "%s: execle(%s): %s",
  5020. __func__,
  5021. prog,
  5022. strerror(ERRNO));
  5023. } else {
  5024. /* call the configured interpreter */
  5025. const char *interp_args =
  5026. conn->dom_ctx
  5027. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5028. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5029. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5030. } else {
  5031. (void)execle(interp, interp, prog, NULL, envp);
  5032. }
  5033. mg_cry_internal(conn,
  5034. "%s: execle(%s %s): %s",
  5035. __func__,
  5036. interp,
  5037. prog,
  5038. strerror(ERRNO));
  5039. }
  5040. }
  5041. exit(EXIT_FAILURE);
  5042. }
  5043. return pid;
  5044. }
  5045. #endif /* !NO_CGI */
  5046. static int
  5047. set_non_blocking_mode(SOCKET sock)
  5048. {
  5049. int flags = fcntl(sock, F_GETFL, 0);
  5050. if (flags < 0) {
  5051. return -1;
  5052. }
  5053. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5054. return -1;
  5055. }
  5056. return 0;
  5057. }
  5058. static int
  5059. set_blocking_mode(SOCKET sock)
  5060. {
  5061. int flags = fcntl(sock, F_GETFL, 0);
  5062. if (flags < 0) {
  5063. return -1;
  5064. }
  5065. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5066. return -1;
  5067. }
  5068. return 0;
  5069. }
  5070. #endif /* _WIN32 / else */
  5071. /* End of initial operating system specific define block. */
  5072. /* Get a random number (independent of C rand function) */
  5073. static uint64_t
  5074. get_random(void)
  5075. {
  5076. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5077. static uint64_t lcg = 0; /* Linear congruential generator */
  5078. uint64_t now = mg_get_current_time_ns();
  5079. if (lfsr == 0) {
  5080. /* lfsr will be only 0 if has not been initialized,
  5081. * so this code is called only once. */
  5082. lfsr = mg_get_current_time_ns();
  5083. lcg = mg_get_current_time_ns();
  5084. } else {
  5085. /* Get the next step of both random number generators. */
  5086. lfsr = (lfsr >> 1)
  5087. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5088. << 63);
  5089. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5090. }
  5091. /* Combining two pseudo-random number generators and a high resolution
  5092. * part
  5093. * of the current server time will make it hard (impossible?) to guess
  5094. * the
  5095. * next number. */
  5096. return (lfsr ^ lcg ^ now);
  5097. }
  5098. static int
  5099. mg_poll(struct mg_pollfd *pfd,
  5100. unsigned int n,
  5101. int milliseconds,
  5102. const stop_flag_t *stop_flag)
  5103. {
  5104. /* Call poll, but only for a maximum time of a few seconds.
  5105. * This will allow to stop the server after some seconds, instead
  5106. * of having to wait for a long socket timeout. */
  5107. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5108. int check_pollerr = 0;
  5109. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5110. /* If we wait for only one file descriptor, wait on error as well */
  5111. pfd[0].events |= POLLERR;
  5112. check_pollerr = 1;
  5113. }
  5114. do {
  5115. int result;
  5116. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5117. /* Shut down signal */
  5118. return -2;
  5119. }
  5120. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5121. ms_now = milliseconds;
  5122. }
  5123. result = poll(pfd, n, ms_now);
  5124. if (result != 0) {
  5125. int err = ERRNO;
  5126. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5127. /* Poll returned either success (1) or error (-1).
  5128. * Forward both to the caller. */
  5129. if ((check_pollerr)
  5130. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5131. == POLLERR)) {
  5132. /* One and only file descriptor returned error */
  5133. return -1;
  5134. }
  5135. return result;
  5136. }
  5137. }
  5138. /* Poll returned timeout (0). */
  5139. if (milliseconds > 0) {
  5140. milliseconds -= ms_now;
  5141. }
  5142. } while (milliseconds > 0);
  5143. /* timeout: return 0 */
  5144. return 0;
  5145. }
  5146. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5147. * descriptor.
  5148. * Return value:
  5149. * >=0 .. number of bytes successfully written
  5150. * -1 .. timeout
  5151. * -2 .. error
  5152. */
  5153. static int
  5154. push_inner(struct mg_context *ctx,
  5155. FILE *fp,
  5156. SOCKET sock,
  5157. SSL *ssl,
  5158. const char *buf,
  5159. int len,
  5160. double timeout)
  5161. {
  5162. uint64_t start = 0, now = 0, timeout_ns = 0;
  5163. int n, err;
  5164. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5165. #if defined(_WIN32)
  5166. typedef int len_t;
  5167. #else
  5168. typedef size_t len_t;
  5169. #endif
  5170. if (timeout > 0) {
  5171. now = mg_get_current_time_ns();
  5172. start = now;
  5173. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5174. }
  5175. if (ctx == NULL) {
  5176. return -2;
  5177. }
  5178. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5179. if (ssl) {
  5180. return -2;
  5181. }
  5182. #endif
  5183. /* Try to read until it succeeds, fails, times out, or the server
  5184. * shuts down. */
  5185. for (;;) {
  5186. #if defined(USE_MBEDTLS)
  5187. if (ssl != NULL) {
  5188. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5189. if (n <= 0) {
  5190. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5191. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5192. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5193. n = 0;
  5194. } else {
  5195. fprintf(stderr, "SSL write failed, error %d\n", n);
  5196. return -2;
  5197. }
  5198. } else {
  5199. err = 0;
  5200. }
  5201. } else
  5202. #elif defined(USE_GNUTLS)
  5203. if (ssl != NULL) {
  5204. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t)len);
  5205. if (n < 0) {
  5206. fprintf(stderr,
  5207. "SSL write failed (%d): %s",
  5208. n,
  5209. gnutls_strerror(n));
  5210. return -2;
  5211. } else {
  5212. err = 0;
  5213. }
  5214. } else
  5215. #elif !defined(NO_SSL)
  5216. if (ssl != NULL) {
  5217. ERR_clear_error();
  5218. n = SSL_write(ssl, buf, len);
  5219. if (n <= 0) {
  5220. err = SSL_get_error(ssl, n);
  5221. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5222. err = ERRNO;
  5223. } else if ((err == SSL_ERROR_WANT_READ)
  5224. || (err == SSL_ERROR_WANT_WRITE)) {
  5225. n = 0;
  5226. } else {
  5227. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5228. ERR_clear_error();
  5229. return -2;
  5230. }
  5231. ERR_clear_error();
  5232. } else {
  5233. err = 0;
  5234. }
  5235. } else
  5236. #endif
  5237. if (fp != NULL) {
  5238. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5239. if (ferror(fp)) {
  5240. n = -1;
  5241. err = ERRNO;
  5242. } else {
  5243. err = 0;
  5244. }
  5245. } else {
  5246. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5247. err = (n < 0) ? ERRNO : 0;
  5248. if (ERROR_TRY_AGAIN(err)) {
  5249. err = 0;
  5250. n = 0;
  5251. }
  5252. if (n < 0) {
  5253. /* shutdown of the socket at client side */
  5254. return -2;
  5255. }
  5256. }
  5257. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5258. return -2;
  5259. }
  5260. if ((n > 0) || ((n == 0) && (len == 0))) {
  5261. /* some data has been read, or no data was requested */
  5262. return n;
  5263. }
  5264. if (n < 0) {
  5265. /* socket error - check errno */
  5266. DEBUG_TRACE("send() failed, error %d", err);
  5267. /* TODO (mid): error handling depending on the error code.
  5268. * These codes are different between Windows and Linux.
  5269. * Currently there is no problem with failing send calls,
  5270. * if there is a reproducible situation, it should be
  5271. * investigated in detail.
  5272. */
  5273. return -2;
  5274. }
  5275. /* Only in case n=0 (timeout), repeat calling the write function */
  5276. /* If send failed, wait before retry */
  5277. if (fp != NULL) {
  5278. /* For files, just wait a fixed time.
  5279. * Maybe it helps, maybe not. */
  5280. mg_sleep(5);
  5281. } else {
  5282. /* For sockets, wait for the socket using poll */
  5283. struct mg_pollfd pfd[2];
  5284. int pollres;
  5285. unsigned int num_sock = 1;
  5286. pfd[0].fd = sock;
  5287. pfd[0].events = POLLOUT;
  5288. if (ctx->context_type == CONTEXT_SERVER) {
  5289. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5290. pfd[num_sock].events = POLLIN;
  5291. num_sock++;
  5292. }
  5293. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5294. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5295. return -2;
  5296. }
  5297. if (pollres > 0) {
  5298. continue;
  5299. }
  5300. }
  5301. if (timeout > 0) {
  5302. now = mg_get_current_time_ns();
  5303. if ((now - start) > timeout_ns) {
  5304. /* Timeout */
  5305. break;
  5306. }
  5307. }
  5308. }
  5309. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5310. used */
  5311. return -1;
  5312. }
  5313. static int
  5314. push_all(struct mg_context *ctx,
  5315. FILE *fp,
  5316. SOCKET sock,
  5317. SSL *ssl,
  5318. const char *buf,
  5319. int len)
  5320. {
  5321. double timeout = -1.0;
  5322. int n, nwritten = 0;
  5323. if (ctx == NULL) {
  5324. return -1;
  5325. }
  5326. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5327. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5328. }
  5329. if (timeout <= 0.0) {
  5330. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5331. / 1000.0;
  5332. }
  5333. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5334. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5335. if (n < 0) {
  5336. if (nwritten == 0) {
  5337. nwritten = -1; /* Propagate the error */
  5338. }
  5339. break;
  5340. } else if (n == 0) {
  5341. break; /* No more data to write */
  5342. } else {
  5343. nwritten += n;
  5344. len -= n;
  5345. }
  5346. }
  5347. return nwritten;
  5348. }
  5349. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5350. * Return value:
  5351. * >=0 .. number of bytes successfully read
  5352. * -1 .. timeout
  5353. * -2 .. error
  5354. */
  5355. static int
  5356. pull_inner(FILE *fp,
  5357. struct mg_connection *conn,
  5358. char *buf,
  5359. int len,
  5360. double timeout)
  5361. {
  5362. int nread, err = 0;
  5363. #if defined(_WIN32)
  5364. typedef int len_t;
  5365. #else
  5366. typedef size_t len_t;
  5367. #endif
  5368. /* We need an additional wait loop around this, because in some cases
  5369. * with TLSwe may get data from the socket but not from SSL_read.
  5370. * In this case we need to repeat at least once.
  5371. */
  5372. if (fp != NULL) {
  5373. /* Use read() instead of fread(), because if we're reading from the
  5374. * CGI pipe, fread() may block until IO buffer is filled up. We
  5375. * cannot afford to block and must pass all read bytes immediately
  5376. * to the client. */
  5377. nread = (int)read(fileno(fp), buf, (size_t)len);
  5378. err = (nread < 0) ? ERRNO : 0;
  5379. if ((nread == 0) && (len > 0)) {
  5380. /* Should get data, but got EOL */
  5381. return -2;
  5382. }
  5383. #if defined(USE_MBEDTLS)
  5384. } else if (conn->ssl != NULL) {
  5385. struct mg_pollfd pfd[2];
  5386. int to_read;
  5387. int pollres;
  5388. unsigned int num_sock = 1;
  5389. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5390. if (to_read > 0) {
  5391. /* We already know there is no more data buffered in conn->buf
  5392. * but there is more available in the SSL layer. So don't poll
  5393. * conn->client.sock yet. */
  5394. pollres = 1;
  5395. if (to_read > len)
  5396. to_read = len;
  5397. } else {
  5398. pfd[0].fd = conn->client.sock;
  5399. pfd[0].events = POLLIN;
  5400. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5401. pfd[num_sock].fd =
  5402. conn->phys_ctx->thread_shutdown_notification_socket;
  5403. pfd[num_sock].events = POLLIN;
  5404. num_sock++;
  5405. }
  5406. to_read = len;
  5407. pollres = mg_poll(pfd,
  5408. num_sock,
  5409. (int)(timeout * 1000.0),
  5410. &(conn->phys_ctx->stop_flag));
  5411. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5412. return -2;
  5413. }
  5414. }
  5415. if (pollres > 0) {
  5416. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5417. if (nread <= 0) {
  5418. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5419. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5420. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5421. nread = 0;
  5422. } else {
  5423. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5424. return -2;
  5425. }
  5426. } else {
  5427. err = 0;
  5428. }
  5429. } else if (pollres < 0) {
  5430. /* Error */
  5431. return -2;
  5432. } else {
  5433. /* pollres = 0 means timeout */
  5434. nread = 0;
  5435. }
  5436. #elif defined(USE_GNUTLS)
  5437. } else if (conn->ssl != NULL) {
  5438. struct mg_pollfd pfd[2];
  5439. size_t to_read;
  5440. int pollres;
  5441. unsigned int num_sock = 1;
  5442. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5443. if (to_read > 0) {
  5444. /* We already know there is no more data buffered in conn->buf
  5445. * but there is more available in the SSL layer. So don't poll
  5446. * conn->client.sock yet. */
  5447. pollres = 1;
  5448. if (to_read > (size_t)len)
  5449. to_read = (size_t)len;
  5450. } else {
  5451. pfd[0].fd = conn->client.sock;
  5452. pfd[0].events = POLLIN;
  5453. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5454. pfd[num_sock].fd =
  5455. conn->phys_ctx->thread_shutdown_notification_socket;
  5456. pfd[num_sock].events = POLLIN;
  5457. num_sock++;
  5458. }
  5459. to_read = (size_t)len;
  5460. pollres = mg_poll(pfd,
  5461. num_sock,
  5462. (int)(timeout * 1000.0),
  5463. &(conn->phys_ctx->stop_flag));
  5464. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5465. return -2;
  5466. }
  5467. }
  5468. if (pollres > 0) {
  5469. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5470. if (nread < 0) {
  5471. fprintf(stderr,
  5472. "SSL read failed (%d): %s",
  5473. nread,
  5474. gnutls_strerror(nread));
  5475. return -2;
  5476. } else {
  5477. err = 0;
  5478. }
  5479. } else if (pollres < 0) {
  5480. /* Error */
  5481. return -2;
  5482. } else {
  5483. /* pollres = 0 means timeout */
  5484. nread = 0;
  5485. }
  5486. #elif !defined(NO_SSL)
  5487. } else if (conn->ssl != NULL) {
  5488. int ssl_pending;
  5489. struct mg_pollfd pfd[2];
  5490. int pollres;
  5491. unsigned int num_sock = 1;
  5492. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5493. /* We already know there is no more data buffered in conn->buf
  5494. * but there is more available in the SSL layer. So don't poll
  5495. * conn->client.sock yet. */
  5496. if (ssl_pending > len) {
  5497. ssl_pending = len;
  5498. }
  5499. pollres = 1;
  5500. } else {
  5501. pfd[0].fd = conn->client.sock;
  5502. pfd[0].events = POLLIN;
  5503. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5504. pfd[num_sock].fd =
  5505. conn->phys_ctx->thread_shutdown_notification_socket;
  5506. pfd[num_sock].events = POLLIN;
  5507. num_sock++;
  5508. }
  5509. pollres = mg_poll(pfd,
  5510. num_sock,
  5511. (int)(timeout * 1000.0),
  5512. &(conn->phys_ctx->stop_flag));
  5513. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5514. return -2;
  5515. }
  5516. }
  5517. if (pollres > 0) {
  5518. ERR_clear_error();
  5519. nread =
  5520. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5521. if (nread <= 0) {
  5522. err = SSL_get_error(conn->ssl, nread);
  5523. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5524. err = ERRNO;
  5525. } else if ((err == SSL_ERROR_WANT_READ)
  5526. || (err == SSL_ERROR_WANT_WRITE)) {
  5527. nread = 0;
  5528. } else {
  5529. /* All errors should return -2 */
  5530. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5531. ERR_clear_error();
  5532. return -2;
  5533. }
  5534. ERR_clear_error();
  5535. } else {
  5536. err = 0;
  5537. }
  5538. } else if (pollres < 0) {
  5539. /* Error */
  5540. return -2;
  5541. } else {
  5542. /* pollres = 0 means timeout */
  5543. nread = 0;
  5544. }
  5545. #endif
  5546. } else {
  5547. struct mg_pollfd pfd[2];
  5548. int pollres;
  5549. unsigned int num_sock = 1;
  5550. pfd[0].fd = conn->client.sock;
  5551. pfd[0].events = POLLIN;
  5552. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5553. pfd[num_sock].fd =
  5554. conn->phys_ctx->thread_shutdown_notification_socket;
  5555. pfd[num_sock].events = POLLIN;
  5556. num_sock++;
  5557. }
  5558. pollres = mg_poll(pfd,
  5559. num_sock,
  5560. (int)(timeout * 1000.0),
  5561. &(conn->phys_ctx->stop_flag));
  5562. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5563. return -2;
  5564. }
  5565. if (pollres > 0) {
  5566. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5567. err = (nread < 0) ? ERRNO : 0;
  5568. if (nread <= 0) {
  5569. /* shutdown of the socket at client side */
  5570. return -2;
  5571. }
  5572. } else if (pollres < 0) {
  5573. /* error calling poll */
  5574. return -2;
  5575. } else {
  5576. /* pollres = 0 means timeout */
  5577. nread = 0;
  5578. }
  5579. }
  5580. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5581. return -2;
  5582. }
  5583. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5584. /* some data has been read, or no data was requested */
  5585. return nread;
  5586. }
  5587. if (nread < 0) {
  5588. /* socket error - check errno */
  5589. #if defined(_WIN32)
  5590. if (err == WSAEWOULDBLOCK) {
  5591. /* TODO (low): check if this is still required */
  5592. /* standard case if called from close_socket_gracefully */
  5593. return -2;
  5594. } else if (err == WSAETIMEDOUT) {
  5595. /* TODO (low): check if this is still required */
  5596. /* timeout is handled by the while loop */
  5597. return 0;
  5598. } else if (err == WSAECONNABORTED) {
  5599. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5600. return -2;
  5601. } else {
  5602. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5603. return -2;
  5604. }
  5605. #else
  5606. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5607. * if the timeout is reached and if the socket was set to non-
  5608. * blocking in close_socket_gracefully, so we can not distinguish
  5609. * here. We have to wait for the timeout in both cases for now.
  5610. */
  5611. if (ERROR_TRY_AGAIN(err)) {
  5612. /* TODO (low): check if this is still required */
  5613. /* EAGAIN/EWOULDBLOCK:
  5614. * standard case if called from close_socket_gracefully
  5615. * => should return -1 */
  5616. /* or timeout occurred
  5617. * => the code must stay in the while loop */
  5618. /* EINTR can be generated on a socket with a timeout set even
  5619. * when SA_RESTART is effective for all relevant signals
  5620. * (see signal(7)).
  5621. * => stay in the while loop */
  5622. } else {
  5623. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5624. return -2;
  5625. }
  5626. #endif
  5627. }
  5628. /* Timeout occurred, but no data available. */
  5629. return -1;
  5630. }
  5631. static int
  5632. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5633. {
  5634. int n, nread = 0;
  5635. double timeout = -1.0;
  5636. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5637. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5638. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5639. }
  5640. if (timeout <= 0.0) {
  5641. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5642. / 1000.0;
  5643. }
  5644. start_time = mg_get_current_time_ns();
  5645. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5646. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5647. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5648. if (n == -2) {
  5649. if (nread == 0) {
  5650. nread = -1; /* Propagate the error */
  5651. }
  5652. break;
  5653. } else if (n == -1) {
  5654. /* timeout */
  5655. if (timeout >= 0.0) {
  5656. now = mg_get_current_time_ns();
  5657. if ((now - start_time) <= timeout_ns) {
  5658. continue;
  5659. }
  5660. }
  5661. break;
  5662. } else if (n == 0) {
  5663. break; /* No more data to read */
  5664. } else {
  5665. nread += n;
  5666. len -= n;
  5667. }
  5668. }
  5669. return nread;
  5670. }
  5671. static void
  5672. discard_unread_request_data(struct mg_connection *conn)
  5673. {
  5674. char buf[MG_BUF_LEN];
  5675. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5676. ;
  5677. }
  5678. static int
  5679. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5680. {
  5681. int64_t content_len, n, buffered_len, nread;
  5682. int64_t len64 =
  5683. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5684. * int, we may not read more
  5685. * bytes */
  5686. const char *body;
  5687. if (conn == NULL) {
  5688. return 0;
  5689. }
  5690. /* If Content-Length is not set for a response with body data,
  5691. * we do not know in advance how much data should be read. */
  5692. content_len = conn->content_len;
  5693. if (content_len < 0) {
  5694. /* The body data is completed when the connection is closed. */
  5695. content_len = INT64_MAX;
  5696. }
  5697. nread = 0;
  5698. if (conn->consumed_content < content_len) {
  5699. /* Adjust number of bytes to read. */
  5700. int64_t left_to_read = content_len - conn->consumed_content;
  5701. if (left_to_read < len64) {
  5702. /* Do not read more than the total content length of the
  5703. * request.
  5704. */
  5705. len64 = left_to_read;
  5706. }
  5707. /* Return buffered data */
  5708. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5709. - conn->consumed_content;
  5710. if (buffered_len > 0) {
  5711. if (len64 < buffered_len) {
  5712. buffered_len = len64;
  5713. }
  5714. body = conn->buf + conn->request_len + conn->consumed_content;
  5715. memcpy(buf, body, (size_t)buffered_len);
  5716. len64 -= buffered_len;
  5717. conn->consumed_content += buffered_len;
  5718. nread += buffered_len;
  5719. buf = (char *)buf + buffered_len;
  5720. }
  5721. /* We have returned all buffered data. Read new data from the remote
  5722. * socket.
  5723. */
  5724. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5725. conn->consumed_content += n;
  5726. nread += n;
  5727. } else {
  5728. nread = ((nread > 0) ? nread : n);
  5729. }
  5730. }
  5731. return (int)nread;
  5732. }
  5733. /* Forward declarations */
  5734. static void handle_request(struct mg_connection *);
  5735. static void log_access(const struct mg_connection *);
  5736. /* Handle request, update statistics and call access log */
  5737. static void
  5738. handle_request_stat_log(struct mg_connection *conn)
  5739. {
  5740. #if defined(USE_SERVER_STATS)
  5741. struct timespec tnow;
  5742. conn->conn_state = 4; /* processing */
  5743. #endif
  5744. handle_request(conn);
  5745. #if defined(USE_SERVER_STATS)
  5746. conn->conn_state = 5; /* processed */
  5747. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5748. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5749. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5750. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5751. conn->num_bytes_sent);
  5752. #endif
  5753. DEBUG_TRACE("%s", "handle_request done");
  5754. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5755. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5756. DEBUG_TRACE("%s", "end_request callback done");
  5757. }
  5758. log_access(conn);
  5759. }
  5760. #if defined(USE_HTTP2)
  5761. #if defined(NO_SSL)
  5762. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5763. #endif
  5764. #define USE_ALPN
  5765. #include "http2.inl"
  5766. /* Not supported with HTTP/2 */
  5767. #define HTTP1_only \
  5768. { \
  5769. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5770. http2_must_use_http1(conn); \
  5771. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5772. return; \
  5773. } \
  5774. }
  5775. #else
  5776. #define HTTP1_only
  5777. #endif
  5778. CIVETWEB_API int
  5779. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5780. {
  5781. if (len > INT_MAX) {
  5782. len = INT_MAX;
  5783. }
  5784. if (conn == NULL) {
  5785. return 0;
  5786. }
  5787. if (conn->is_chunked) {
  5788. size_t all_read = 0;
  5789. while (len > 0) {
  5790. if (conn->is_chunked >= 3) {
  5791. /* No more data left to read */
  5792. return 0;
  5793. }
  5794. if (conn->is_chunked != 1) {
  5795. /* Has error */
  5796. return -1;
  5797. }
  5798. if (conn->consumed_content != conn->content_len) {
  5799. /* copy from the current chunk */
  5800. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5801. if (read_ret < 1) {
  5802. /* read error */
  5803. conn->is_chunked = 2;
  5804. return -1;
  5805. }
  5806. all_read += (size_t)read_ret;
  5807. len -= (size_t)read_ret;
  5808. if (conn->consumed_content == conn->content_len) {
  5809. /* Add data bytes in the current chunk have been read,
  5810. * so we are expecting \r\n now. */
  5811. char x[2];
  5812. conn->content_len += 2;
  5813. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5814. || (x[1] != '\n')) {
  5815. /* Protocol violation */
  5816. conn->is_chunked = 2;
  5817. return -1;
  5818. }
  5819. }
  5820. } else {
  5821. /* fetch a new chunk */
  5822. size_t i;
  5823. char lenbuf[64];
  5824. char *end = NULL;
  5825. unsigned long chunkSize = 0;
  5826. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5827. conn->content_len++;
  5828. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5829. lenbuf[i] = 0;
  5830. }
  5831. if ((i > 0) && (lenbuf[i] == ';')) {
  5832. // chunk extension --> skip chars until next CR
  5833. //
  5834. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5835. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5836. //
  5837. // chunk = chunk-size [ chunk-extension ] CRLF
  5838. // chunk-data CRLF
  5839. // ...
  5840. // chunk-extension= *( ";" chunk-ext-name [ "="
  5841. // chunk-ext-val ] )
  5842. do
  5843. ++conn->content_len;
  5844. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5845. && lenbuf[i] != '\r');
  5846. }
  5847. if ((i > 0) && (lenbuf[i] == '\r')
  5848. && (lenbuf[i - 1] != '\r')) {
  5849. continue;
  5850. }
  5851. if ((i > 1) && (lenbuf[i] == '\n')
  5852. && (lenbuf[i - 1] == '\r')) {
  5853. lenbuf[i + 1] = 0;
  5854. chunkSize = strtoul(lenbuf, &end, 16);
  5855. if (chunkSize == 0) {
  5856. /* regular end of content */
  5857. conn->is_chunked = 3;
  5858. }
  5859. break;
  5860. }
  5861. if (!isxdigit((unsigned char)lenbuf[i])) {
  5862. /* illegal character for chunk length */
  5863. conn->is_chunked = 2;
  5864. return -1;
  5865. }
  5866. }
  5867. if ((end == NULL) || (*end != '\r')) {
  5868. /* chunksize not set correctly */
  5869. conn->is_chunked = 2;
  5870. return -1;
  5871. }
  5872. if (conn->is_chunked == 3) {
  5873. /* try discarding trailer for keep-alive */
  5874. // We found the last chunk (length 0) including the
  5875. // CRLF that terminates that chunk. Now follows a possibly
  5876. // empty trailer and a final CRLF.
  5877. //
  5878. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5879. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5880. //
  5881. // Chunked-Body = *chunk
  5882. // last-chunk
  5883. // trailer
  5884. // CRLF
  5885. // ...
  5886. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5887. // ...
  5888. // trailer = *(entity-header CRLF)
  5889. int crlf_count = 2; // one CRLF already determined
  5890. while (crlf_count < 4 && conn->is_chunked == 3) {
  5891. ++conn->content_len;
  5892. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5893. if ((crlf_count == 0 || crlf_count == 2)) {
  5894. if (lenbuf[0] == '\r')
  5895. ++crlf_count;
  5896. else
  5897. crlf_count = 0;
  5898. } else {
  5899. // previous character was a CR
  5900. // --> next character must be LF
  5901. if (lenbuf[0] == '\n')
  5902. ++crlf_count;
  5903. else
  5904. conn->is_chunked = 2;
  5905. }
  5906. } else
  5907. // premature end of trailer
  5908. conn->is_chunked = 2;
  5909. }
  5910. if (conn->is_chunked == 2)
  5911. return -1;
  5912. else
  5913. conn->is_chunked = 4;
  5914. break;
  5915. }
  5916. /* append a new chunk */
  5917. conn->content_len += (int64_t)chunkSize;
  5918. }
  5919. }
  5920. return (int)all_read;
  5921. }
  5922. return mg_read_inner(conn, buf, len);
  5923. }
  5924. CIVETWEB_API int
  5925. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5926. {
  5927. time_t now;
  5928. int n, total, allowed;
  5929. if (conn == NULL) {
  5930. return 0;
  5931. }
  5932. if (len > INT_MAX) {
  5933. return -1;
  5934. }
  5935. /* Mark connection as "data sent" */
  5936. conn->request_state = 10;
  5937. #if defined(USE_HTTP2)
  5938. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5939. http2_data_frame_head(conn, len, 0);
  5940. }
  5941. #endif
  5942. if (conn->throttle > 0) {
  5943. if ((now = time(NULL)) != conn->last_throttle_time) {
  5944. conn->last_throttle_time = now;
  5945. conn->last_throttle_bytes = 0;
  5946. }
  5947. allowed = conn->throttle - conn->last_throttle_bytes;
  5948. if (allowed > (int)len) {
  5949. allowed = (int)len;
  5950. }
  5951. total = push_all(conn->phys_ctx,
  5952. NULL,
  5953. conn->client.sock,
  5954. conn->ssl,
  5955. (const char *)buf,
  5956. allowed);
  5957. if (total == allowed) {
  5958. buf = (const char *)buf + total;
  5959. conn->last_throttle_bytes += total;
  5960. while ((total < (int)len)
  5961. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5962. allowed = (conn->throttle > ((int)len - total))
  5963. ? (int)len - total
  5964. : conn->throttle;
  5965. n = push_all(conn->phys_ctx,
  5966. NULL,
  5967. conn->client.sock,
  5968. conn->ssl,
  5969. (const char *)buf,
  5970. allowed);
  5971. if (n != allowed) {
  5972. break;
  5973. }
  5974. sleep(1);
  5975. conn->last_throttle_bytes = allowed;
  5976. conn->last_throttle_time = time(NULL);
  5977. buf = (const char *)buf + n;
  5978. total += n;
  5979. }
  5980. }
  5981. } else {
  5982. total = push_all(conn->phys_ctx,
  5983. NULL,
  5984. conn->client.sock,
  5985. conn->ssl,
  5986. (const char *)buf,
  5987. (int)len);
  5988. }
  5989. if (total > 0) {
  5990. conn->num_bytes_sent += total;
  5991. }
  5992. return total;
  5993. }
  5994. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5995. CIVETWEB_API int
  5996. mg_send_chunk(struct mg_connection *conn,
  5997. const char *chunk,
  5998. unsigned int chunk_len)
  5999. {
  6000. char lenbuf[16];
  6001. size_t lenbuf_len;
  6002. int ret;
  6003. int t;
  6004. /* First store the length information in a text buffer. */
  6005. sprintf(lenbuf, "%x\r\n", chunk_len);
  6006. lenbuf_len = strlen(lenbuf);
  6007. /* Then send length information, chunk and terminating \r\n. */
  6008. ret = mg_write(conn, lenbuf, lenbuf_len);
  6009. if (ret != (int)lenbuf_len) {
  6010. return -1;
  6011. }
  6012. t = ret;
  6013. ret = mg_write(conn, chunk, chunk_len);
  6014. if (ret != (int)chunk_len) {
  6015. return -1;
  6016. }
  6017. t += ret;
  6018. ret = mg_write(conn, "\r\n", 2);
  6019. if (ret != 2) {
  6020. return -1;
  6021. }
  6022. t += ret;
  6023. return t;
  6024. }
  6025. #if defined(GCC_DIAGNOSTIC)
  6026. /* This block forwards format strings to printf implementations,
  6027. * so we need to disable the format-nonliteral warning. */
  6028. #pragma GCC diagnostic push
  6029. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6030. #endif
  6031. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6032. static int
  6033. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6034. {
  6035. va_list ap_copy;
  6036. size_t size = MG_BUF_LEN / 4;
  6037. int len = -1;
  6038. *buf = NULL;
  6039. while (len < 0) {
  6040. if (*buf) {
  6041. mg_free(*buf);
  6042. }
  6043. size *= 4;
  6044. *buf = (char *)mg_malloc(size);
  6045. if (!*buf) {
  6046. break;
  6047. }
  6048. va_copy(ap_copy, ap);
  6049. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6050. va_end(ap_copy);
  6051. (*buf)[size - 1] = 0;
  6052. }
  6053. return len;
  6054. }
  6055. /* Print message to buffer. If buffer is large enough to hold the message,
  6056. * return buffer. If buffer is to small, allocate large enough buffer on
  6057. * heap,
  6058. * and return allocated buffer. */
  6059. static int
  6060. alloc_vprintf(char **out_buf,
  6061. char *prealloc_buf,
  6062. size_t prealloc_size,
  6063. const char *fmt,
  6064. va_list ap)
  6065. {
  6066. va_list ap_copy;
  6067. int len;
  6068. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6069. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6070. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6071. * Therefore, we make two passes: on first pass, get required message
  6072. * length.
  6073. * On second pass, actually print the message. */
  6074. va_copy(ap_copy, ap);
  6075. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6076. va_end(ap_copy);
  6077. if (len < 0) {
  6078. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6079. * Switch to alternative code path that uses incremental
  6080. * allocations.
  6081. */
  6082. va_copy(ap_copy, ap);
  6083. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6084. va_end(ap_copy);
  6085. } else if ((size_t)(len) >= prealloc_size) {
  6086. /* The pre-allocated buffer not large enough. */
  6087. /* Allocate a new buffer. */
  6088. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6089. if (!*out_buf) {
  6090. /* Allocation failed. Return -1 as "out of memory" error. */
  6091. return -1;
  6092. }
  6093. /* Buffer allocation successful. Store the string there. */
  6094. va_copy(ap_copy, ap);
  6095. IGNORE_UNUSED_RESULT(
  6096. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6097. va_end(ap_copy);
  6098. } else {
  6099. /* The pre-allocated buffer is large enough.
  6100. * Use it to store the string and return the address. */
  6101. va_copy(ap_copy, ap);
  6102. IGNORE_UNUSED_RESULT(
  6103. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6104. va_end(ap_copy);
  6105. *out_buf = prealloc_buf;
  6106. }
  6107. return len;
  6108. }
  6109. static int
  6110. alloc_printf(char **out_buf, const char *fmt, ...)
  6111. {
  6112. va_list ap;
  6113. int result;
  6114. va_start(ap, fmt);
  6115. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6116. va_end(ap);
  6117. return result;
  6118. }
  6119. #if defined(GCC_DIAGNOSTIC)
  6120. /* Enable format-nonliteral warning again. */
  6121. #pragma GCC diagnostic pop
  6122. #endif
  6123. static int
  6124. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6125. {
  6126. char mem[MG_BUF_LEN];
  6127. char *buf = NULL;
  6128. int len;
  6129. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6130. len = mg_write(conn, buf, (size_t)len);
  6131. }
  6132. if (buf != mem) {
  6133. mg_free(buf);
  6134. }
  6135. return len;
  6136. }
  6137. CIVETWEB_API int
  6138. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6139. {
  6140. va_list ap;
  6141. int result;
  6142. va_start(ap, fmt);
  6143. result = mg_vprintf(conn, fmt, ap);
  6144. va_end(ap);
  6145. return result;
  6146. }
  6147. CIVETWEB_API int
  6148. mg_url_decode(const char *src,
  6149. int src_len,
  6150. char *dst,
  6151. int dst_len,
  6152. int is_form_url_encoded)
  6153. {
  6154. int i, j, a, b;
  6155. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6156. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6157. if ((i < src_len - 2) && (src[i] == '%')
  6158. && isxdigit((unsigned char)src[i + 1])
  6159. && isxdigit((unsigned char)src[i + 2])) {
  6160. a = tolower((unsigned char)src[i + 1]);
  6161. b = tolower((unsigned char)src[i + 2]);
  6162. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6163. i += 2;
  6164. } else if (is_form_url_encoded && (src[i] == '+')) {
  6165. dst[j] = ' ';
  6166. } else {
  6167. dst[j] = src[i];
  6168. }
  6169. }
  6170. dst[j] = '\0'; /* Null-terminate the destination */
  6171. return (i >= src_len) ? j : -1;
  6172. }
  6173. /* form url decoding of an entire string */
  6174. static void
  6175. url_decode_in_place(char *buf)
  6176. {
  6177. int len = (int)strlen(buf);
  6178. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6179. }
  6180. CIVETWEB_API int
  6181. mg_get_var(const char *data,
  6182. size_t data_len,
  6183. const char *name,
  6184. char *dst,
  6185. size_t dst_len)
  6186. {
  6187. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6188. }
  6189. CIVETWEB_API int
  6190. mg_get_var2(const char *data,
  6191. size_t data_len,
  6192. const char *name,
  6193. char *dst,
  6194. size_t dst_len,
  6195. size_t occurrence)
  6196. {
  6197. const char *p, *e, *s;
  6198. size_t name_len;
  6199. int len;
  6200. if ((dst == NULL) || (dst_len == 0)) {
  6201. len = -2;
  6202. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6203. len = -1;
  6204. dst[0] = '\0';
  6205. } else {
  6206. name_len = strlen(name);
  6207. e = data + data_len;
  6208. len = -1;
  6209. dst[0] = '\0';
  6210. /* data is "var1=val1&var2=val2...". Find variable first */
  6211. for (p = data; p + name_len < e; p++) {
  6212. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6213. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6214. /* Point p to variable value */
  6215. p += name_len + 1;
  6216. /* Point s to the end of the value */
  6217. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6218. if (s == NULL) {
  6219. s = e;
  6220. }
  6221. DEBUG_ASSERT(s >= p);
  6222. if (s < p) {
  6223. return -3;
  6224. }
  6225. /* Decode variable into destination buffer */
  6226. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6227. /* Redirect error code from -1 to -2 (destination buffer too
  6228. * small). */
  6229. if (len == -1) {
  6230. len = -2;
  6231. }
  6232. break;
  6233. }
  6234. }
  6235. }
  6236. return len;
  6237. }
  6238. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6239. CIVETWEB_API int
  6240. mg_split_form_urlencoded(char *data,
  6241. struct mg_header *form_fields,
  6242. unsigned num_form_fields)
  6243. {
  6244. char *b;
  6245. int i;
  6246. int num = 0;
  6247. if (data == NULL) {
  6248. /* parameter error */
  6249. return -1;
  6250. }
  6251. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6252. /* determine the number of expected fields */
  6253. if (data[0] == 0) {
  6254. return 0;
  6255. }
  6256. /* count number of & to return the number of key-value-pairs */
  6257. num = 1;
  6258. while (*data) {
  6259. if (*data == '&') {
  6260. num++;
  6261. }
  6262. data++;
  6263. }
  6264. return num;
  6265. }
  6266. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6267. /* parameter error */
  6268. return -1;
  6269. }
  6270. for (i = 0; i < (int)num_form_fields; i++) {
  6271. /* extract key-value pairs from input data */
  6272. while ((*data == ' ') || (*data == '\t')) {
  6273. /* skip initial spaces */
  6274. data++;
  6275. }
  6276. if (*data == 0) {
  6277. /* end of string reached */
  6278. break;
  6279. }
  6280. form_fields[num].name = data;
  6281. /* find & or = */
  6282. b = data;
  6283. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6284. b++;
  6285. }
  6286. if (*b == 0) {
  6287. /* last key without value */
  6288. form_fields[num].value = NULL;
  6289. } else if (*b == '&') {
  6290. /* mid key without value */
  6291. form_fields[num].value = NULL;
  6292. } else {
  6293. /* terminate string */
  6294. *b = 0;
  6295. /* value starts after '=' */
  6296. data = b + 1;
  6297. form_fields[num].value = data;
  6298. }
  6299. /* new field is stored */
  6300. num++;
  6301. /* find a next key */
  6302. b = strchr(data, '&');
  6303. if (b == 0) {
  6304. /* no more data */
  6305. break;
  6306. } else {
  6307. /* terminate value of last field at '&' */
  6308. *b = 0;
  6309. /* next key-value-pairs starts after '&' */
  6310. data = b + 1;
  6311. }
  6312. }
  6313. /* Decode all values */
  6314. for (i = 0; i < num; i++) {
  6315. if (form_fields[i].name) {
  6316. url_decode_in_place((char *)form_fields[i].name);
  6317. }
  6318. if (form_fields[i].value) {
  6319. url_decode_in_place((char *)form_fields[i].value);
  6320. }
  6321. }
  6322. /* return number of fields found */
  6323. return num;
  6324. }
  6325. /* HCP24: some changes to compare whole var_name */
  6326. CIVETWEB_API int
  6327. mg_get_cookie(const char *cookie_header,
  6328. const char *var_name,
  6329. char *dst,
  6330. size_t dst_size)
  6331. {
  6332. const char *s, *p, *end;
  6333. int name_len, len = -1;
  6334. if ((dst == NULL) || (dst_size == 0)) {
  6335. return -2;
  6336. }
  6337. dst[0] = '\0';
  6338. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6339. return -1;
  6340. }
  6341. name_len = (int)strlen(var_name);
  6342. end = s + strlen(s);
  6343. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6344. if (s[name_len] == '=') {
  6345. /* HCP24: now check is it a substring or a full cookie name */
  6346. if ((s == cookie_header) || (s[-1] == ' ')) {
  6347. s += name_len + 1;
  6348. if ((p = strchr(s, ' ')) == NULL) {
  6349. p = end;
  6350. }
  6351. if (p[-1] == ';') {
  6352. p--;
  6353. }
  6354. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6355. s++;
  6356. p--;
  6357. }
  6358. if ((size_t)(p - s) < dst_size) {
  6359. len = (int)(p - s);
  6360. mg_strlcpy(dst, s, (size_t)len + 1);
  6361. } else {
  6362. len = -3;
  6363. }
  6364. break;
  6365. }
  6366. }
  6367. }
  6368. return len;
  6369. }
  6370. CIVETWEB_API int
  6371. mg_base64_encode(const unsigned char *src,
  6372. size_t src_len,
  6373. char *dst,
  6374. size_t *dst_len)
  6375. {
  6376. static const char *b64 =
  6377. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6378. size_t i, j;
  6379. int a, b, c;
  6380. if (dst_len != NULL) {
  6381. /* Expected length including 0 termination: */
  6382. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6383. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6384. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6385. if (*dst_len < expected_len) {
  6386. if (*dst_len > 0) {
  6387. dst[0] = '\0';
  6388. }
  6389. *dst_len = expected_len;
  6390. return 0;
  6391. }
  6392. }
  6393. for (i = j = 0; i < src_len; i += 3) {
  6394. a = src[i];
  6395. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6396. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6397. dst[j++] = b64[a >> 2];
  6398. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6399. if (i + 1 < src_len) {
  6400. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6401. }
  6402. if (i + 2 < src_len) {
  6403. dst[j++] = b64[c & 63];
  6404. }
  6405. }
  6406. while (j % 4 != 0) {
  6407. dst[j++] = '=';
  6408. }
  6409. dst[j++] = '\0';
  6410. if (dst_len != NULL) {
  6411. *dst_len = (size_t)j;
  6412. }
  6413. /* Return -1 for "OK" */
  6414. return -1;
  6415. }
  6416. static unsigned char
  6417. b64reverse(char letter)
  6418. {
  6419. if ((letter >= 'A') && (letter <= 'Z')) {
  6420. return (unsigned char)(letter - 'A');
  6421. }
  6422. if ((letter >= 'a') && (letter <= 'z')) {
  6423. return (unsigned char)(letter - 'a' + 26);
  6424. }
  6425. if ((letter >= '0') && (letter <= '9')) {
  6426. return (unsigned char)(letter - '0' + 52);
  6427. }
  6428. if (letter == '+') {
  6429. return 62;
  6430. }
  6431. if (letter == '/') {
  6432. return 63;
  6433. }
  6434. if (letter == '=') {
  6435. return 255; /* normal end */
  6436. }
  6437. return 254; /* error */
  6438. }
  6439. CIVETWEB_API int
  6440. mg_base64_decode(const char *src,
  6441. size_t src_len,
  6442. unsigned char *dst,
  6443. size_t *dst_len)
  6444. {
  6445. size_t i;
  6446. unsigned char a, b, c, d;
  6447. size_t dst_len_limit = (size_t)-1;
  6448. size_t dst_len_used = 0;
  6449. if (dst_len != NULL) {
  6450. dst_len_limit = *dst_len;
  6451. *dst_len = 0;
  6452. }
  6453. for (i = 0; i < src_len; i += 4) {
  6454. /* Read 4 characters from BASE64 string */
  6455. a = b64reverse(src[i]);
  6456. if (a >= 254) {
  6457. return (int)i;
  6458. }
  6459. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6460. if (b >= 254) {
  6461. return (int)i + 1;
  6462. }
  6463. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6464. if (c == 254) {
  6465. return (int)i + 2;
  6466. }
  6467. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6468. if (d == 254) {
  6469. return (int)i + 3;
  6470. }
  6471. /* Add first (of 3) decoded character */
  6472. if (dst_len_used < dst_len_limit) {
  6473. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6474. + (unsigned char)(b >> 4));
  6475. }
  6476. dst_len_used++;
  6477. if (c != 255) {
  6478. if (dst_len_used < dst_len_limit) {
  6479. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6480. + (unsigned char)(c >> 2));
  6481. }
  6482. dst_len_used++;
  6483. if (d != 255) {
  6484. if (dst_len_used < dst_len_limit) {
  6485. dst[dst_len_used] =
  6486. (unsigned char)((unsigned char)(c << 6) + d);
  6487. }
  6488. dst_len_used++;
  6489. }
  6490. }
  6491. }
  6492. /* Add terminating zero */
  6493. if (dst_len_used < dst_len_limit) {
  6494. dst[dst_len_used] = '\0';
  6495. }
  6496. dst_len_used++;
  6497. if (dst_len != NULL) {
  6498. *dst_len = dst_len_used;
  6499. }
  6500. if (dst_len_used > dst_len_limit) {
  6501. /* Out of memory */
  6502. return 0;
  6503. }
  6504. /* Return -1 for "OK" */
  6505. return -1;
  6506. }
  6507. static int
  6508. is_put_or_delete_method(const struct mg_connection *conn)
  6509. {
  6510. if (conn) {
  6511. const char *s = conn->request_info.request_method;
  6512. if (s != NULL) {
  6513. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6514. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6515. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6516. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6517. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6518. || !strcmp(s, "COPY"));
  6519. }
  6520. }
  6521. return 0;
  6522. }
  6523. static int
  6524. is_civetweb_webdav_method(const struct mg_connection *conn)
  6525. {
  6526. /* Note: Here we only have to identify the WebDav methods that need special
  6527. * handling in the CivetWeb code - not all methods used in WebDav. In
  6528. * particular, methods used on directories (when using Windows Explorer as
  6529. * WebDav client).
  6530. */
  6531. if (conn) {
  6532. const char *s = conn->request_info.request_method;
  6533. if (s != NULL) {
  6534. /* These are the civetweb builtin DAV methods */
  6535. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6536. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6537. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6538. }
  6539. }
  6540. return 0;
  6541. }
  6542. #if !defined(NO_FILES)
  6543. static int
  6544. extention_matches_script(
  6545. struct mg_connection *conn, /* in: request (must be valid) */
  6546. const char *filename /* in: filename (must be valid) */
  6547. )
  6548. {
  6549. #if !defined(NO_CGI)
  6550. int cgi_config_idx, inc, max;
  6551. #endif
  6552. #if defined(USE_LUA)
  6553. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6554. filename)
  6555. > 0) {
  6556. return 1;
  6557. }
  6558. #endif
  6559. #if defined(USE_DUKTAPE)
  6560. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6561. filename)
  6562. > 0) {
  6563. return 1;
  6564. }
  6565. #endif
  6566. #if !defined(NO_CGI)
  6567. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6568. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6569. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6570. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6571. && (match_prefix_strlen(
  6572. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6573. filename)
  6574. > 0)) {
  6575. return 1;
  6576. }
  6577. }
  6578. #endif
  6579. /* filename and conn could be unused, if all preocessor conditions
  6580. * are false (no script language supported). */
  6581. (void)filename;
  6582. (void)conn;
  6583. return 0;
  6584. }
  6585. static int
  6586. extention_matches_template_text(
  6587. struct mg_connection *conn, /* in: request (must be valid) */
  6588. const char *filename /* in: filename (must be valid) */
  6589. )
  6590. {
  6591. #if defined(USE_LUA)
  6592. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6593. filename)
  6594. > 0) {
  6595. return 1;
  6596. }
  6597. #endif
  6598. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6599. > 0) {
  6600. return 1;
  6601. }
  6602. return 0;
  6603. }
  6604. /* For given directory path, substitute it to valid index file.
  6605. * Return 1 if index file has been found, 0 if not found.
  6606. * If the file is found, it's stats is returned in stp. */
  6607. static int
  6608. substitute_index_file_aux(struct mg_connection *conn,
  6609. char *path,
  6610. size_t path_len,
  6611. struct mg_file_stat *filestat)
  6612. {
  6613. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6614. struct vec filename_vec;
  6615. size_t n = strlen(path);
  6616. int found = 0;
  6617. /* The 'path' given to us points to the directory. Remove all trailing
  6618. * directory separator characters from the end of the path, and
  6619. * then append single directory separator character. */
  6620. while ((n > 0) && (path[n - 1] == '/')) {
  6621. n--;
  6622. }
  6623. path[n] = '/';
  6624. /* Traverse index files list. For each entry, append it to the given
  6625. * path and see if the file exists. If it exists, break the loop */
  6626. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6627. /* Ignore too long entries that may overflow path buffer */
  6628. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6629. continue;
  6630. }
  6631. /* Prepare full path to the index file */
  6632. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6633. /* Does it exist? */
  6634. if (mg_stat(conn, path, filestat)) {
  6635. /* Yes it does, break the loop */
  6636. found = 1;
  6637. break;
  6638. }
  6639. }
  6640. /* If no index file exists, restore directory path */
  6641. if (!found) {
  6642. path[n] = '\0';
  6643. }
  6644. return found;
  6645. }
  6646. /* Same as above, except if the first try fails and a fallback-root is
  6647. * configured, we'll try there also */
  6648. static int
  6649. substitute_index_file(struct mg_connection *conn,
  6650. char *path,
  6651. size_t path_len,
  6652. struct mg_file_stat *filestat)
  6653. {
  6654. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6655. if (ret == 0) {
  6656. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6657. const char *fallback_root_prefix =
  6658. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6659. if ((root_prefix) && (fallback_root_prefix)) {
  6660. const size_t root_prefix_len = strlen(root_prefix);
  6661. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6662. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6663. side effects if we fail */
  6664. size_t sub_path_len;
  6665. const size_t fallback_root_prefix_len =
  6666. strlen(fallback_root_prefix);
  6667. const char *sub_path = path + root_prefix_len;
  6668. while (*sub_path == '/') {
  6669. sub_path++;
  6670. }
  6671. sub_path_len = strlen(sub_path);
  6672. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6673. < sizeof(scratch_path))) {
  6674. /* The concatenations below are all safe because we
  6675. * pre-verified string lengths above */
  6676. char *nul;
  6677. strcpy(scratch_path, fallback_root_prefix);
  6678. nul = strchr(scratch_path, '\0');
  6679. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6680. *nul++ = '/';
  6681. *nul = '\0';
  6682. }
  6683. strcat(scratch_path, sub_path);
  6684. if (substitute_index_file_aux(conn,
  6685. scratch_path,
  6686. sizeof(scratch_path),
  6687. filestat)) {
  6688. mg_strlcpy(path, scratch_path, path_len);
  6689. return 1;
  6690. }
  6691. }
  6692. }
  6693. }
  6694. }
  6695. return ret;
  6696. }
  6697. #endif
  6698. static void
  6699. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6700. char *filename, /* out: filename */
  6701. size_t filename_buf_len, /* in: size of filename buffer */
  6702. struct mg_file_stat *filestat, /* out: file status structure */
  6703. int *is_found, /* out: file found (directly) */
  6704. int *is_script_resource, /* out: handled by a script? */
  6705. int *is_websocket_request, /* out: websocket connection? */
  6706. int *is_put_or_delete_request, /* out: put/delete a file? */
  6707. int *is_webdav_request, /* out: webdav request? */
  6708. int *is_template_text /* out: SSI file or LSP file? */
  6709. )
  6710. {
  6711. char const *accept_encoding;
  6712. #if !defined(NO_FILES)
  6713. const char *uri = conn->request_info.local_uri;
  6714. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6715. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6716. NULL};
  6717. int fileExists = 0;
  6718. const char *rewrite;
  6719. struct vec a, b;
  6720. ptrdiff_t match_len;
  6721. char gz_path[UTF8_PATH_MAX];
  6722. int truncated;
  6723. int i;
  6724. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6725. char *tmp_str;
  6726. size_t tmp_str_len, sep_pos;
  6727. int allow_substitute_script_subresources;
  6728. #endif
  6729. #else
  6730. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6731. #endif
  6732. /* Step 1: Set all initially unknown outputs to zero */
  6733. memset(filestat, 0, sizeof(*filestat));
  6734. *filename = 0;
  6735. *is_found = 0;
  6736. *is_script_resource = 0;
  6737. *is_template_text = 0;
  6738. /* Step 2: Classify the request method */
  6739. /* Step 2a: Check if the request attempts to modify the file system */
  6740. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6741. /* Step 2b: Check if the request uses WebDav method that requires special
  6742. * handling */
  6743. *is_webdav_request = is_civetweb_webdav_method(conn);
  6744. /* Step 3: Check if it is a websocket request, and modify the document
  6745. * root if required */
  6746. #if defined(USE_WEBSOCKET)
  6747. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6748. #if !defined(NO_FILES)
  6749. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6750. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6751. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6752. }
  6753. #endif /* !NO_FILES */
  6754. #else /* USE_WEBSOCKET */
  6755. *is_websocket_request = 0;
  6756. #endif /* USE_WEBSOCKET */
  6757. /* Step 4: Check if gzip encoded response is allowed */
  6758. conn->accept_gzip = 0;
  6759. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6760. if (strstr(accept_encoding, "gzip") != NULL) {
  6761. conn->accept_gzip = 1;
  6762. }
  6763. }
  6764. #if !defined(NO_FILES)
  6765. /* Step 5: If there is no root directory, don't look for files. */
  6766. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6767. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6768. * config is not required. */
  6769. if (roots[0] == NULL) {
  6770. /* all file related outputs have already been set to 0, just return
  6771. */
  6772. return;
  6773. }
  6774. for (i = 0; roots[i] != NULL; i++) {
  6775. /* Step 6: Determine the local file path from the root path and the
  6776. * request uri. */
  6777. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6778. * part of the path one byte on the right. */
  6779. truncated = 0;
  6780. mg_snprintf(conn,
  6781. &truncated,
  6782. filename,
  6783. filename_buf_len - 1,
  6784. "%s%s",
  6785. roots[i],
  6786. uri);
  6787. if (truncated) {
  6788. goto interpret_cleanup;
  6789. }
  6790. /* Step 7: URI rewriting */
  6791. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6792. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6793. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6794. mg_snprintf(conn,
  6795. &truncated,
  6796. filename,
  6797. filename_buf_len - 1,
  6798. "%.*s%s",
  6799. (int)b.len,
  6800. b.ptr,
  6801. uri + match_len);
  6802. break;
  6803. }
  6804. }
  6805. if (truncated) {
  6806. goto interpret_cleanup;
  6807. }
  6808. /* Step 8: Check if the file exists at the server */
  6809. /* Local file path and name, corresponding to requested URI
  6810. * is now stored in "filename" variable. */
  6811. if (mg_stat(conn, filename, filestat)) {
  6812. fileExists = 1;
  6813. break;
  6814. }
  6815. }
  6816. if (fileExists) {
  6817. int uri_len = (int)strlen(uri);
  6818. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6819. /* 8.1: File exists. */
  6820. *is_found = 1;
  6821. /* 8.2: Check if it is a script type. */
  6822. if (extention_matches_script(conn, filename)) {
  6823. /* The request addresses a CGI resource, Lua script or
  6824. * server-side javascript.
  6825. * The URI corresponds to the script itself (like
  6826. * /path/script.cgi), and there is no additional resource
  6827. * path (like /path/script.cgi/something).
  6828. * Requests that modify (replace or delete) a resource, like
  6829. * PUT and DELETE requests, should replace/delete the script
  6830. * file.
  6831. * Requests that read or write from/to a resource, like GET and
  6832. * POST requests, should call the script and return the
  6833. * generated response. */
  6834. *is_script_resource = (!*is_put_or_delete_request);
  6835. }
  6836. /* 8.3: Check for SSI and LSP files */
  6837. if (extention_matches_template_text(conn, filename)) {
  6838. /* Same as above, but for *.lsp and *.shtml files. */
  6839. /* A "template text" is a file delivered directly to the client,
  6840. * but with some text tags replaced by dynamic content.
  6841. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6842. * (LP, LSP) file. */
  6843. *is_template_text = (!*is_put_or_delete_request);
  6844. }
  6845. /* 8.4: If the request target is a directory, there could be
  6846. * a substitute file (index.html, index.cgi, ...). */
  6847. /* But do not substitute a directory for a WebDav request */
  6848. if (filestat->is_directory && is_uri_end_slash
  6849. && (!*is_webdav_request)) {
  6850. /* Use a local copy here, since substitute_index_file will
  6851. * change the content of the file status */
  6852. struct mg_file_stat tmp_filestat;
  6853. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6854. if (substitute_index_file(
  6855. conn, filename, filename_buf_len, &tmp_filestat)) {
  6856. /* Substitute file found. Copy stat to the output, then
  6857. * check if the file is a script file */
  6858. *filestat = tmp_filestat;
  6859. if (extention_matches_script(conn, filename)) {
  6860. /* Substitute file is a script file */
  6861. *is_script_resource = 1;
  6862. } else if (extention_matches_template_text(conn, filename)) {
  6863. /* Substitute file is a LSP or SSI file */
  6864. *is_template_text = 1;
  6865. } else {
  6866. /* Substitute file is a regular file */
  6867. *is_script_resource = 0;
  6868. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6869. }
  6870. }
  6871. /* If there is no substitute file, the server could return
  6872. * a directory listing in a later step */
  6873. }
  6874. return;
  6875. }
  6876. /* Step 9: Check for zipped files: */
  6877. /* If we can't find the actual file, look for the file
  6878. * with the same name but a .gz extension. If we find it,
  6879. * use that and set the gzipped flag in the file struct
  6880. * to indicate that the response need to have the content-
  6881. * encoding: gzip header.
  6882. * We can only do this if the browser declares support. */
  6883. if (conn->accept_gzip) {
  6884. mg_snprintf(
  6885. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6886. if (truncated) {
  6887. goto interpret_cleanup;
  6888. }
  6889. if (mg_stat(conn, gz_path, filestat)) {
  6890. if (filestat) {
  6891. filestat->is_gzipped = 1;
  6892. *is_found = 1;
  6893. }
  6894. /* Currently gz files can not be scripts. */
  6895. return;
  6896. }
  6897. }
  6898. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6899. /* Step 10: Script resources may handle sub-resources */
  6900. /* Support PATH_INFO for CGI scripts. */
  6901. tmp_str_len = strlen(filename);
  6902. tmp_str =
  6903. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6904. if (!tmp_str) {
  6905. /* Out of memory */
  6906. goto interpret_cleanup;
  6907. }
  6908. memcpy(tmp_str, filename, tmp_str_len + 1);
  6909. /* Check config, if index scripts may have sub-resources */
  6910. allow_substitute_script_subresources =
  6911. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6912. "yes");
  6913. if (*is_webdav_request) {
  6914. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6915. * PROPFIND for their subresources? */
  6916. /* allow_substitute_script_subresources = 0; */
  6917. }
  6918. sep_pos = tmp_str_len;
  6919. while (sep_pos > 0) {
  6920. sep_pos--;
  6921. if (tmp_str[sep_pos] == '/') {
  6922. int is_script = 0, does_exist = 0;
  6923. tmp_str[sep_pos] = 0;
  6924. if (tmp_str[0]) {
  6925. is_script = extention_matches_script(conn, tmp_str);
  6926. does_exist = mg_stat(conn, tmp_str, filestat);
  6927. }
  6928. if (does_exist && is_script) {
  6929. filename[sep_pos] = 0;
  6930. memmove(filename + sep_pos + 2,
  6931. filename + sep_pos + 1,
  6932. strlen(filename + sep_pos + 1) + 1);
  6933. conn->path_info = filename + sep_pos + 1;
  6934. filename[sep_pos + 1] = '/';
  6935. *is_script_resource = 1;
  6936. *is_found = 1;
  6937. break;
  6938. }
  6939. if (allow_substitute_script_subresources) {
  6940. if (substitute_index_file(
  6941. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6942. /* some intermediate directory has an index file */
  6943. if (extention_matches_script(conn, tmp_str)) {
  6944. size_t script_name_len = strlen(tmp_str);
  6945. /* subres_name read before this memory locatio will be
  6946. overwritten */
  6947. char *subres_name = filename + sep_pos;
  6948. size_t subres_name_len = strlen(subres_name);
  6949. DEBUG_TRACE("Substitute script %s serving path %s",
  6950. tmp_str,
  6951. filename);
  6952. /* this index file is a script */
  6953. if ((script_name_len + subres_name_len + 2)
  6954. >= filename_buf_len) {
  6955. mg_free(tmp_str);
  6956. goto interpret_cleanup;
  6957. }
  6958. conn->path_info =
  6959. filename + script_name_len + 1; /* new target */
  6960. memmove(conn->path_info, subres_name, subres_name_len);
  6961. conn->path_info[subres_name_len] = 0;
  6962. memcpy(filename, tmp_str, script_name_len + 1);
  6963. *is_script_resource = 1;
  6964. *is_found = 1;
  6965. break;
  6966. } else {
  6967. DEBUG_TRACE("Substitute file %s serving path %s",
  6968. tmp_str,
  6969. filename);
  6970. /* non-script files will not have sub-resources */
  6971. filename[sep_pos] = 0;
  6972. conn->path_info = 0;
  6973. *is_script_resource = 0;
  6974. *is_found = 0;
  6975. break;
  6976. }
  6977. }
  6978. }
  6979. tmp_str[sep_pos] = '/';
  6980. }
  6981. }
  6982. mg_free(tmp_str);
  6983. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6984. #endif /* !defined(NO_FILES) */
  6985. return;
  6986. #if !defined(NO_FILES)
  6987. /* Reset all outputs */
  6988. interpret_cleanup:
  6989. memset(filestat, 0, sizeof(*filestat));
  6990. *filename = 0;
  6991. *is_found = 0;
  6992. *is_script_resource = 0;
  6993. *is_websocket_request = 0;
  6994. *is_put_or_delete_request = 0;
  6995. #endif /* !defined(NO_FILES) */
  6996. }
  6997. /* Check whether full request is buffered. Return:
  6998. * -1 if request or response is malformed
  6999. * 0 if request or response is not yet fully buffered
  7000. * >0 actual request length, including last \r\n\r\n */
  7001. static int
  7002. get_http_header_len(const char *buf, int buflen)
  7003. {
  7004. int i;
  7005. for (i = 0; i < buflen; i++) {
  7006. /* Do an unsigned comparison in some conditions below */
  7007. const unsigned char c = (unsigned char)buf[i];
  7008. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7009. && !isprint(c)) {
  7010. /* abort scan as soon as one malformed character is found */
  7011. return -1;
  7012. }
  7013. if (i < buflen - 1) {
  7014. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7015. /* Two newline, no carriage return - not standard compliant,
  7016. * but it should be accepted */
  7017. return i + 2;
  7018. }
  7019. }
  7020. if (i < buflen - 3) {
  7021. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7022. && (buf[i + 3] == '\n')) {
  7023. /* Two \r\n - standard compliant */
  7024. return i + 4;
  7025. }
  7026. }
  7027. }
  7028. return 0;
  7029. }
  7030. #if !defined(NO_CACHING)
  7031. /* Convert month to the month number. Return -1 on error, or month number */
  7032. static int
  7033. get_month_index(const char *s)
  7034. {
  7035. size_t i;
  7036. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7037. if (!strcmp(s, month_names[i])) {
  7038. return (int)i;
  7039. }
  7040. }
  7041. return -1;
  7042. }
  7043. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7044. static time_t
  7045. parse_date_string(const char *datetime)
  7046. {
  7047. char month_str[32] = {0};
  7048. int second, minute, hour, day, month, year;
  7049. time_t result = (time_t)0;
  7050. struct tm tm;
  7051. if ((sscanf(datetime,
  7052. "%d/%3s/%d %d:%d:%d",
  7053. &day,
  7054. month_str,
  7055. &year,
  7056. &hour,
  7057. &minute,
  7058. &second)
  7059. == 6)
  7060. || (sscanf(datetime,
  7061. "%d %3s %d %d:%d:%d",
  7062. &day,
  7063. month_str,
  7064. &year,
  7065. &hour,
  7066. &minute,
  7067. &second)
  7068. == 6)
  7069. || (sscanf(datetime,
  7070. "%*3s, %d %3s %d %d:%d:%d",
  7071. &day,
  7072. month_str,
  7073. &year,
  7074. &hour,
  7075. &minute,
  7076. &second)
  7077. == 6)
  7078. || (sscanf(datetime,
  7079. "%d-%3s-%d %d:%d:%d",
  7080. &day,
  7081. month_str,
  7082. &year,
  7083. &hour,
  7084. &minute,
  7085. &second)
  7086. == 6)) {
  7087. month = get_month_index(month_str);
  7088. if ((month >= 0) && (year >= 1970)) {
  7089. memset(&tm, 0, sizeof(tm));
  7090. tm.tm_year = year - 1900;
  7091. tm.tm_mon = month;
  7092. tm.tm_mday = day;
  7093. tm.tm_hour = hour;
  7094. tm.tm_min = minute;
  7095. tm.tm_sec = second;
  7096. result = timegm(&tm);
  7097. }
  7098. }
  7099. return result;
  7100. }
  7101. #endif /* !NO_CACHING */
  7102. /* Pre-process URIs according to RFC + protect against directory disclosure
  7103. * attacks by removing '..', excessive '/' and '\' characters */
  7104. static void
  7105. remove_dot_segments(char *inout)
  7106. {
  7107. /* Windows backend protection
  7108. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7109. * in URI by slash */
  7110. char *out_end = inout;
  7111. char *in = inout;
  7112. if (!in) {
  7113. /* Param error. */
  7114. return;
  7115. }
  7116. while (*in) {
  7117. if (*in == '\\') {
  7118. *in = '/';
  7119. }
  7120. in++;
  7121. }
  7122. /* Algorithm "remove_dot_segments" from
  7123. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7124. /* Step 1:
  7125. * The input buffer is initialized.
  7126. * The output buffer is initialized to the empty string.
  7127. */
  7128. in = inout;
  7129. /* Step 2:
  7130. * While the input buffer is not empty, loop as follows:
  7131. */
  7132. /* Less than out_end of the inout buffer is used as output, so keep
  7133. * condition: out_end <= in */
  7134. while (*in) {
  7135. /* Step 2a:
  7136. * If the input buffer begins with a prefix of "../" or "./",
  7137. * then remove that prefix from the input buffer;
  7138. */
  7139. if (!strncmp(in, "../", 3)) {
  7140. in += 3;
  7141. } else if (!strncmp(in, "./", 2)) {
  7142. in += 2;
  7143. }
  7144. /* otherwise */
  7145. /* Step 2b:
  7146. * if the input buffer begins with a prefix of "/./" or "/.",
  7147. * where "." is a complete path segment, then replace that
  7148. * prefix with "/" in the input buffer;
  7149. */
  7150. else if (!strncmp(in, "/./", 3)) {
  7151. in += 2;
  7152. } else if (!strcmp(in, "/.")) {
  7153. in[1] = 0;
  7154. }
  7155. /* otherwise */
  7156. /* Step 2c:
  7157. * if the input buffer begins with a prefix of "/../" or "/..",
  7158. * where ".." is a complete path segment, then replace that
  7159. * prefix with "/" in the input buffer and remove the last
  7160. * segment and its preceding "/" (if any) from the output
  7161. * buffer;
  7162. */
  7163. else if (!strncmp(in, "/../", 4)) {
  7164. in += 3;
  7165. if (inout != out_end) {
  7166. /* remove last segment */
  7167. do {
  7168. out_end--;
  7169. } while ((inout != out_end) && (*out_end != '/'));
  7170. }
  7171. } else if (!strcmp(in, "/..")) {
  7172. in[1] = 0;
  7173. if (inout != out_end) {
  7174. /* remove last segment */
  7175. do {
  7176. out_end--;
  7177. } while ((inout != out_end) && (*out_end != '/'));
  7178. }
  7179. }
  7180. /* otherwise */
  7181. /* Step 2d:
  7182. * if the input buffer consists only of "." or "..", then remove
  7183. * that from the input buffer;
  7184. */
  7185. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7186. *in = 0;
  7187. }
  7188. /* otherwise */
  7189. /* Step 2e:
  7190. * move the first path segment in the input buffer to the end of
  7191. * the output buffer, including the initial "/" character (if
  7192. * any) and any subsequent characters up to, but not including,
  7193. * the next "/" character or the end of the input buffer.
  7194. */
  7195. else {
  7196. do {
  7197. *out_end = *in;
  7198. out_end++;
  7199. in++;
  7200. } while ((*in != 0) && (*in != '/'));
  7201. }
  7202. }
  7203. /* Step 3:
  7204. * Finally, the output buffer is returned as the result of
  7205. * remove_dot_segments.
  7206. */
  7207. /* Terminate output */
  7208. *out_end = 0;
  7209. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7210. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7211. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7212. * or "//" anymore.
  7213. */
  7214. out_end = in = inout;
  7215. while (*in) {
  7216. if (*in == '.') {
  7217. /* remove . at the end or preceding of / */
  7218. char *in_ahead = in;
  7219. do {
  7220. in_ahead++;
  7221. } while (*in_ahead == '.');
  7222. if (*in_ahead == '/') {
  7223. in = in_ahead;
  7224. if ((out_end != inout) && (out_end[-1] == '/')) {
  7225. /* remove generated // */
  7226. out_end--;
  7227. }
  7228. } else if (*in_ahead == 0) {
  7229. in = in_ahead;
  7230. } else {
  7231. do {
  7232. *out_end++ = '.';
  7233. in++;
  7234. } while (in != in_ahead);
  7235. }
  7236. } else if (*in == '/') {
  7237. /* replace // by / */
  7238. *out_end++ = '/';
  7239. do {
  7240. in++;
  7241. } while (*in == '/');
  7242. } else {
  7243. *out_end++ = *in;
  7244. in++;
  7245. }
  7246. }
  7247. *out_end = 0;
  7248. }
  7249. static const struct {
  7250. const char *extension;
  7251. size_t ext_len;
  7252. const char *mime_type;
  7253. } builtin_mime_types[] = {
  7254. /* IANA registered MIME types
  7255. * (http://www.iana.org/assignments/media-types)
  7256. * application types */
  7257. {".bin", 4, "application/octet-stream"},
  7258. {".deb", 4, "application/octet-stream"},
  7259. {".dmg", 4, "application/octet-stream"},
  7260. {".dll", 4, "application/octet-stream"},
  7261. {".doc", 4, "application/msword"},
  7262. {".eps", 4, "application/postscript"},
  7263. {".exe", 4, "application/octet-stream"},
  7264. {".iso", 4, "application/octet-stream"},
  7265. {".js", 3, "application/javascript"},
  7266. {".json", 5, "application/json"},
  7267. {".mjs", 4, "application/javascript"},
  7268. {".msi", 4, "application/octet-stream"},
  7269. {".pdf", 4, "application/pdf"},
  7270. {".ps", 3, "application/postscript"},
  7271. {".rtf", 4, "application/rtf"},
  7272. {".wasm", 5, "application/wasm"},
  7273. {".xhtml", 6, "application/xhtml+xml"},
  7274. {".xsl", 4, "application/xml"},
  7275. {".xslt", 5, "application/xml"},
  7276. /* fonts */
  7277. {".ttf", 4, "application/font-sfnt"},
  7278. {".cff", 4, "application/font-sfnt"},
  7279. {".otf", 4, "application/font-sfnt"},
  7280. {".aat", 4, "application/font-sfnt"},
  7281. {".sil", 4, "application/font-sfnt"},
  7282. {".pfr", 4, "application/font-tdpfr"},
  7283. {".woff", 5, "application/font-woff"},
  7284. {".woff2", 6, "application/font-woff2"},
  7285. /* audio */
  7286. {".mp3", 4, "audio/mpeg"},
  7287. {".oga", 4, "audio/ogg"},
  7288. {".ogg", 4, "audio/ogg"},
  7289. /* image */
  7290. {".gif", 4, "image/gif"},
  7291. {".ief", 4, "image/ief"},
  7292. {".jpeg", 5, "image/jpeg"},
  7293. {".jpg", 4, "image/jpeg"},
  7294. {".jpm", 4, "image/jpm"},
  7295. {".jpx", 4, "image/jpx"},
  7296. {".png", 4, "image/png"},
  7297. {".svg", 4, "image/svg+xml"},
  7298. {".tif", 4, "image/tiff"},
  7299. {".tiff", 5, "image/tiff"},
  7300. /* model */
  7301. {".wrl", 4, "model/vrml"},
  7302. /* text */
  7303. {".css", 4, "text/css"},
  7304. {".csv", 4, "text/csv"},
  7305. {".htm", 4, "text/html"},
  7306. {".html", 5, "text/html"},
  7307. {".sgm", 4, "text/sgml"},
  7308. {".shtm", 5, "text/html"},
  7309. {".shtml", 6, "text/html"},
  7310. {".txt", 4, "text/plain"},
  7311. {".xml", 4, "text/xml"},
  7312. /* video */
  7313. {".mov", 4, "video/quicktime"},
  7314. {".mp4", 4, "video/mp4"},
  7315. {".mpeg", 5, "video/mpeg"},
  7316. {".mpg", 4, "video/mpeg"},
  7317. {".ogv", 4, "video/ogg"},
  7318. {".qt", 3, "video/quicktime"},
  7319. /* not registered types
  7320. * (http://reference.sitepoint.com/html/mime-types-full,
  7321. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7322. {".arj", 4, "application/x-arj-compressed"},
  7323. {".gz", 3, "application/x-gunzip"},
  7324. {".rar", 4, "application/x-arj-compressed"},
  7325. {".swf", 4, "application/x-shockwave-flash"},
  7326. {".tar", 4, "application/x-tar"},
  7327. {".tgz", 4, "application/x-tar-gz"},
  7328. {".torrent", 8, "application/x-bittorrent"},
  7329. {".ppt", 4, "application/x-mspowerpoint"},
  7330. {".xls", 4, "application/x-msexcel"},
  7331. {".zip", 4, "application/x-zip-compressed"},
  7332. {".aac",
  7333. 4,
  7334. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7335. {".flac", 5, "audio/flac"},
  7336. {".aif", 4, "audio/x-aif"},
  7337. {".m3u", 4, "audio/x-mpegurl"},
  7338. {".mid", 4, "audio/x-midi"},
  7339. {".ra", 3, "audio/x-pn-realaudio"},
  7340. {".ram", 4, "audio/x-pn-realaudio"},
  7341. {".wav", 4, "audio/x-wav"},
  7342. {".bmp", 4, "image/bmp"},
  7343. {".ico", 4, "image/x-icon"},
  7344. {".pct", 4, "image/x-pct"},
  7345. {".pict", 5, "image/pict"},
  7346. {".rgb", 4, "image/x-rgb"},
  7347. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7348. {".asf", 4, "video/x-ms-asf"},
  7349. {".avi", 4, "video/x-msvideo"},
  7350. {".m4v", 4, "video/x-m4v"},
  7351. {NULL, 0, NULL}};
  7352. CIVETWEB_API const char *
  7353. mg_get_builtin_mime_type(const char *path)
  7354. {
  7355. const char *ext;
  7356. size_t i, path_len;
  7357. path_len = strlen(path);
  7358. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7359. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7360. if ((path_len > builtin_mime_types[i].ext_len)
  7361. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7362. return builtin_mime_types[i].mime_type;
  7363. }
  7364. }
  7365. return "text/plain";
  7366. }
  7367. /* Look at the "path" extension and figure what mime type it has.
  7368. * Store mime type in the vector. */
  7369. static void
  7370. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7371. {
  7372. struct vec ext_vec, mime_vec;
  7373. const char *list, *ext;
  7374. size_t path_len;
  7375. path_len = strlen(path);
  7376. if ((conn == NULL) || (vec == NULL)) {
  7377. if (vec != NULL) {
  7378. memset(vec, '\0', sizeof(struct vec));
  7379. }
  7380. return;
  7381. }
  7382. /* Scan user-defined mime types first, in case user wants to
  7383. * override default mime types. */
  7384. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7385. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7386. /* ext now points to the path suffix */
  7387. ext = path + path_len - ext_vec.len;
  7388. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7389. *vec = mime_vec;
  7390. return;
  7391. }
  7392. }
  7393. vec->ptr = mg_get_builtin_mime_type(path);
  7394. vec->len = strlen(vec->ptr);
  7395. }
  7396. /* Stringify binary data. Output buffer must be twice as big as input,
  7397. * because each byte takes 2 bytes in string representation */
  7398. static void
  7399. bin2str(char *to, const unsigned char *p, size_t len)
  7400. {
  7401. static const char *hex = "0123456789abcdef";
  7402. for (; len--; p++) {
  7403. *to++ = hex[p[0] >> 4];
  7404. *to++ = hex[p[0] & 0x0f];
  7405. }
  7406. *to = '\0';
  7407. }
  7408. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7409. */
  7410. CIVETWEB_API char *
  7411. mg_md5(char buf[33], ...)
  7412. {
  7413. md5_byte_t hash[16];
  7414. const char *p;
  7415. va_list ap;
  7416. md5_state_t ctx;
  7417. md5_init(&ctx);
  7418. va_start(ap, buf);
  7419. while ((p = va_arg(ap, const char *)) != NULL) {
  7420. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7421. }
  7422. va_end(ap);
  7423. md5_finish(&ctx, hash);
  7424. bin2str(buf, hash, sizeof(hash));
  7425. return buf;
  7426. }
  7427. /* Check the user's password, return 1 if OK */
  7428. static int
  7429. check_password_digest(const char *method,
  7430. const char *ha1,
  7431. const char *uri,
  7432. const char *nonce,
  7433. const char *nc,
  7434. const char *cnonce,
  7435. const char *qop,
  7436. const char *response)
  7437. {
  7438. char ha2[32 + 1], expected_response[32 + 1];
  7439. /* Some of the parameters may be NULL */
  7440. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7441. || (qop == NULL) || (response == NULL)) {
  7442. return 0;
  7443. }
  7444. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7445. if (strlen(response) != 32) {
  7446. return 0;
  7447. }
  7448. mg_md5(ha2, method, ":", uri, NULL);
  7449. mg_md5(expected_response,
  7450. ha1,
  7451. ":",
  7452. nonce,
  7453. ":",
  7454. nc,
  7455. ":",
  7456. cnonce,
  7457. ":",
  7458. qop,
  7459. ":",
  7460. ha2,
  7461. NULL);
  7462. return mg_strcasecmp(response, expected_response) == 0;
  7463. }
  7464. #if !defined(NO_FILESYSTEMS)
  7465. /* Use the global passwords file, if specified by auth_gpass option,
  7466. * or search for .htpasswd in the requested directory. */
  7467. static void
  7468. open_auth_file(struct mg_connection *conn,
  7469. const char *path,
  7470. struct mg_file *filep)
  7471. {
  7472. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7473. char name[UTF8_PATH_MAX];
  7474. const char *p, *e,
  7475. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7476. int truncated;
  7477. if (gpass != NULL) {
  7478. /* Use global passwords file */
  7479. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7480. #if defined(DEBUG)
  7481. /* Use mg_cry_internal here, since gpass has been
  7482. * configured. */
  7483. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7484. #endif
  7485. }
  7486. /* Important: using local struct mg_file to test path for
  7487. * is_directory flag. If filep is used, mg_stat() makes it
  7488. * appear as if auth file was opened.
  7489. * TODO(mid): Check if this is still required after rewriting
  7490. * mg_stat */
  7491. } else if (mg_stat(conn, path, &filep->stat)
  7492. && filep->stat.is_directory) {
  7493. mg_snprintf(conn,
  7494. &truncated,
  7495. name,
  7496. sizeof(name),
  7497. "%s/%s",
  7498. path,
  7499. PASSWORDS_FILE_NAME);
  7500. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7501. #if defined(DEBUG)
  7502. /* Don't use mg_cry_internal here, but only a trace, since
  7503. * this is a typical case. It will occur for every directory
  7504. * without a password file. */
  7505. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7506. #endif
  7507. }
  7508. } else {
  7509. /* Try to find .htpasswd in requested directory. */
  7510. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7511. if (e[0] == '/') {
  7512. break;
  7513. }
  7514. }
  7515. mg_snprintf(conn,
  7516. &truncated,
  7517. name,
  7518. sizeof(name),
  7519. "%.*s/%s",
  7520. (int)(e - p),
  7521. p,
  7522. PASSWORDS_FILE_NAME);
  7523. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7524. #if defined(DEBUG)
  7525. /* Don't use mg_cry_internal here, but only a trace, since
  7526. * this is a typical case. It will occur for every directory
  7527. * without a password file. */
  7528. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7529. #endif
  7530. }
  7531. }
  7532. }
  7533. }
  7534. #endif /* NO_FILESYSTEMS */
  7535. /* Parsed Authorization header */
  7536. struct auth_header {
  7537. char *user;
  7538. int type; /* 1 = basic, 2 = digest */
  7539. char *plain_password; /* Basic only */
  7540. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7541. };
  7542. /* Return 1 on success. Always initializes the auth_header structure. */
  7543. static int
  7544. parse_auth_header(struct mg_connection *conn,
  7545. char *buf,
  7546. size_t buf_size,
  7547. struct auth_header *auth_header)
  7548. {
  7549. char *name, *value, *s;
  7550. const char *ah;
  7551. uint64_t nonce;
  7552. if (!auth_header || !conn) {
  7553. return 0;
  7554. }
  7555. (void)memset(auth_header, 0, sizeof(*auth_header));
  7556. ah = mg_get_header(conn, "Authorization");
  7557. if (ah == NULL) {
  7558. /* No Authorization header at all */
  7559. return 0;
  7560. }
  7561. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7562. /* Basic Auth (we never asked for this, but some client may send it) */
  7563. char *split;
  7564. const char *userpw_b64 = ah + 6;
  7565. size_t userpw_b64_len = strlen(userpw_b64);
  7566. size_t buf_len_r = buf_size;
  7567. if (mg_base64_decode(
  7568. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7569. != -1) {
  7570. return 0; /* decode error */
  7571. }
  7572. split = strchr(buf, ':');
  7573. if (!split) {
  7574. return 0; /* Format error */
  7575. }
  7576. /* Separate string at ':' */
  7577. *split = 0;
  7578. /* User name is before ':', Password is after ':' */
  7579. auth_header->user = buf;
  7580. auth_header->type = 1;
  7581. auth_header->plain_password = split + 1;
  7582. return 1;
  7583. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7584. /* Digest Auth ... implemented below */
  7585. auth_header->type = 2;
  7586. } else {
  7587. /* Unknown or invalid Auth method */
  7588. return 0;
  7589. }
  7590. /* Make modifiable copy of the auth header */
  7591. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7592. s = buf;
  7593. /* Parse authorization header */
  7594. for (;;) {
  7595. /* Gobble initial spaces */
  7596. while (isspace((unsigned char)*s)) {
  7597. s++;
  7598. }
  7599. name = skip_quoted(&s, "=", " ", 0);
  7600. /* Value is either quote-delimited, or ends at first comma or space.
  7601. */
  7602. if (s[0] == '\"') {
  7603. s++;
  7604. value = skip_quoted(&s, "\"", " ", '\\');
  7605. if (s[0] == ',') {
  7606. s++;
  7607. }
  7608. } else {
  7609. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7610. * uses spaces */
  7611. }
  7612. if (*name == '\0') {
  7613. break;
  7614. }
  7615. if (!strcmp(name, "username")) {
  7616. auth_header->user = value;
  7617. } else if (!strcmp(name, "cnonce")) {
  7618. auth_header->cnonce = value;
  7619. } else if (!strcmp(name, "response")) {
  7620. auth_header->response = value;
  7621. } else if (!strcmp(name, "uri")) {
  7622. auth_header->uri = value;
  7623. } else if (!strcmp(name, "qop")) {
  7624. auth_header->qop = value;
  7625. } else if (!strcmp(name, "nc")) {
  7626. auth_header->nc = value;
  7627. } else if (!strcmp(name, "nonce")) {
  7628. auth_header->nonce = value;
  7629. }
  7630. }
  7631. #if !defined(NO_NONCE_CHECK)
  7632. /* Read the nonce from the response. */
  7633. if (auth_header->nonce == NULL) {
  7634. return 0;
  7635. }
  7636. s = NULL;
  7637. nonce = strtoull(auth_header->nonce, &s, 10);
  7638. if ((s == NULL) || (*s != 0)) {
  7639. return 0;
  7640. }
  7641. /* Convert the nonce from the client to a number. */
  7642. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7643. /* The converted number corresponds to the time the nounce has been
  7644. * created. This should not be earlier than the server start. */
  7645. /* Server side nonce check is valuable in all situations but one:
  7646. * if the server restarts frequently, but the client should not see
  7647. * that, so the server should accept nonces from previous starts. */
  7648. /* However, the reasonable default is to not accept a nonce from a
  7649. * previous start, so if anyone changed the access rights between
  7650. * two restarts, a new login is required. */
  7651. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7652. /* nonce is from a previous start of the server and no longer valid
  7653. * (replay attack?) */
  7654. return 0;
  7655. }
  7656. /* Check if the nonce is too high, so it has not (yet) been used by the
  7657. * server. */
  7658. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7659. + conn->dom_ctx->nonce_count)) {
  7660. return 0;
  7661. }
  7662. #else
  7663. (void)nonce;
  7664. #endif
  7665. return (auth_header->user != NULL);
  7666. }
  7667. static const char *
  7668. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7669. {
  7670. if (!filep) {
  7671. return NULL;
  7672. }
  7673. if (filep->access.fp != NULL) {
  7674. return fgets(buf, (int)size, filep->access.fp);
  7675. } else {
  7676. return NULL;
  7677. }
  7678. }
  7679. /* Define the initial recursion depth for procesesing htpasswd files that
  7680. * include other htpasswd
  7681. * (or even the same) files. It is not difficult to provide a file or files
  7682. * s.t. they force civetweb
  7683. * to infinitely recurse and then crash.
  7684. */
  7685. #define INITIAL_DEPTH 9
  7686. #if INITIAL_DEPTH <= 0
  7687. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7688. #endif
  7689. #if !defined(NO_FILESYSTEMS)
  7690. struct read_auth_file_struct {
  7691. struct mg_connection *conn;
  7692. struct auth_header auth_header;
  7693. const char *domain;
  7694. char buf[256 + 256 + 40];
  7695. const char *f_user;
  7696. const char *f_domain;
  7697. const char *f_ha1;
  7698. };
  7699. static int
  7700. read_auth_file(struct mg_file *filep,
  7701. struct read_auth_file_struct *workdata,
  7702. int depth)
  7703. {
  7704. int is_authorized = 0;
  7705. struct mg_file fp;
  7706. size_t l;
  7707. if (!filep || !workdata || (0 == depth)) {
  7708. return 0;
  7709. }
  7710. /* Loop over passwords file */
  7711. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7712. l = strlen(workdata->buf);
  7713. while (l > 0) {
  7714. if (isspace((unsigned char)workdata->buf[l - 1])
  7715. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7716. l--;
  7717. workdata->buf[l] = 0;
  7718. } else
  7719. break;
  7720. }
  7721. if (l < 1) {
  7722. continue;
  7723. }
  7724. workdata->f_user = workdata->buf;
  7725. if (workdata->f_user[0] == ':') {
  7726. /* user names may not contain a ':' and may not be empty,
  7727. * so lines starting with ':' may be used for a special purpose
  7728. */
  7729. if (workdata->f_user[1] == '#') {
  7730. /* :# is a comment */
  7731. continue;
  7732. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7733. if (mg_fopen(workdata->conn,
  7734. workdata->f_user + 9,
  7735. MG_FOPEN_MODE_READ,
  7736. &fp)) {
  7737. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7738. (void)mg_fclose(
  7739. &fp.access); /* ignore error on read only file */
  7740. /* No need to continue processing files once we have a
  7741. * match, since nothing will reset it back
  7742. * to 0.
  7743. */
  7744. if (is_authorized) {
  7745. return is_authorized;
  7746. }
  7747. } else {
  7748. mg_cry_internal(workdata->conn,
  7749. "%s: cannot open authorization file: %s",
  7750. __func__,
  7751. workdata->buf);
  7752. }
  7753. continue;
  7754. }
  7755. /* everything is invalid for the moment (might change in the
  7756. * future) */
  7757. mg_cry_internal(workdata->conn,
  7758. "%s: syntax error in authorization file: %s",
  7759. __func__,
  7760. workdata->buf);
  7761. continue;
  7762. }
  7763. workdata->f_domain = strchr(workdata->f_user, ':');
  7764. if (workdata->f_domain == NULL) {
  7765. mg_cry_internal(workdata->conn,
  7766. "%s: syntax error in authorization file: %s",
  7767. __func__,
  7768. workdata->buf);
  7769. continue;
  7770. }
  7771. *(char *)(workdata->f_domain) = 0;
  7772. (workdata->f_domain)++;
  7773. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7774. if (workdata->f_ha1 == NULL) {
  7775. mg_cry_internal(workdata->conn,
  7776. "%s: syntax error in authorization file: %s",
  7777. __func__,
  7778. workdata->buf);
  7779. continue;
  7780. }
  7781. *(char *)(workdata->f_ha1) = 0;
  7782. (workdata->f_ha1)++;
  7783. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7784. && !strcmp(workdata->domain, workdata->f_domain)) {
  7785. switch (workdata->auth_header.type) {
  7786. case 1: /* Basic */
  7787. {
  7788. char md5[33];
  7789. mg_md5(md5,
  7790. workdata->f_user,
  7791. ":",
  7792. workdata->domain,
  7793. ":",
  7794. workdata->auth_header.plain_password,
  7795. NULL);
  7796. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7797. }
  7798. case 2: /* Digest */
  7799. return check_password_digest(
  7800. workdata->conn->request_info.request_method,
  7801. workdata->f_ha1,
  7802. workdata->auth_header.uri,
  7803. workdata->auth_header.nonce,
  7804. workdata->auth_header.nc,
  7805. workdata->auth_header.cnonce,
  7806. workdata->auth_header.qop,
  7807. workdata->auth_header.response);
  7808. default: /* None/Other/Unknown */
  7809. return 0;
  7810. }
  7811. }
  7812. }
  7813. return is_authorized;
  7814. }
  7815. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7816. static int
  7817. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7818. {
  7819. struct read_auth_file_struct workdata;
  7820. char buf[MG_BUF_LEN];
  7821. if (!conn || !conn->dom_ctx) {
  7822. return 0;
  7823. }
  7824. memset(&workdata, 0, sizeof(workdata));
  7825. workdata.conn = conn;
  7826. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7827. return 0;
  7828. }
  7829. /* CGI needs it as REMOTE_USER */
  7830. conn->request_info.remote_user =
  7831. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7832. if (realm) {
  7833. workdata.domain = realm;
  7834. } else {
  7835. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7836. }
  7837. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7838. }
  7839. /* Public function to check http digest authentication header */
  7840. CIVETWEB_API int
  7841. mg_check_digest_access_authentication(struct mg_connection *conn,
  7842. const char *realm,
  7843. const char *filename)
  7844. {
  7845. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7846. int auth;
  7847. if (!conn || !filename) {
  7848. return -1;
  7849. }
  7850. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7851. return -2;
  7852. }
  7853. auth = authorize(conn, &file, realm);
  7854. mg_fclose(&file.access);
  7855. return auth;
  7856. }
  7857. #endif /* NO_FILESYSTEMS */
  7858. /* Return 1 if request is authorised, 0 otherwise. */
  7859. static int
  7860. check_authorization(struct mg_connection *conn, const char *path)
  7861. {
  7862. #if !defined(NO_FILESYSTEMS)
  7863. char fname[UTF8_PATH_MAX];
  7864. struct vec uri_vec, filename_vec;
  7865. const char *list;
  7866. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7867. int authorized = 1, truncated;
  7868. if (!conn || !conn->dom_ctx) {
  7869. return 0;
  7870. }
  7871. list = conn->dom_ctx->config[PROTECT_URI];
  7872. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7873. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7874. mg_snprintf(conn,
  7875. &truncated,
  7876. fname,
  7877. sizeof(fname),
  7878. "%.*s",
  7879. (int)filename_vec.len,
  7880. filename_vec.ptr);
  7881. if (truncated
  7882. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7883. mg_cry_internal(conn,
  7884. "%s: cannot open %s: %s",
  7885. __func__,
  7886. fname,
  7887. strerror(errno));
  7888. }
  7889. break;
  7890. }
  7891. }
  7892. if (!is_file_opened(&file.access)) {
  7893. open_auth_file(conn, path, &file);
  7894. }
  7895. if (is_file_opened(&file.access)) {
  7896. authorized = authorize(conn, &file, NULL);
  7897. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7898. }
  7899. return authorized;
  7900. #else
  7901. (void)conn;
  7902. (void)path;
  7903. return 1;
  7904. #endif /* NO_FILESYSTEMS */
  7905. }
  7906. /* Internal function. Assumes conn is valid */
  7907. static void
  7908. send_authorization_request(struct mg_connection *conn, const char *realm)
  7909. {
  7910. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7911. int trunc = 0;
  7912. char buf[128];
  7913. if (!realm) {
  7914. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7915. }
  7916. mg_lock_context(conn->phys_ctx);
  7917. nonce += conn->dom_ctx->nonce_count;
  7918. ++conn->dom_ctx->nonce_count;
  7919. mg_unlock_context(conn->phys_ctx);
  7920. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7921. conn->must_close = 1;
  7922. /* Create 401 response */
  7923. mg_response_header_start(conn, 401);
  7924. send_no_cache_header(conn);
  7925. send_additional_header(conn);
  7926. mg_response_header_add(conn, "Content-Length", "0", -1);
  7927. /* Content for "WWW-Authenticate" header */
  7928. mg_snprintf(conn,
  7929. &trunc,
  7930. buf,
  7931. sizeof(buf),
  7932. "Digest qop=\"auth\", realm=\"%s\", "
  7933. "nonce=\"%" UINT64_FMT "\"",
  7934. realm,
  7935. nonce);
  7936. if (!trunc) {
  7937. /* !trunc should always be true */
  7938. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7939. }
  7940. /* Send all headers */
  7941. mg_response_header_send(conn);
  7942. }
  7943. /* Interface function. Parameters are provided by the user, so do
  7944. * at least some basic checks.
  7945. */
  7946. CIVETWEB_API int
  7947. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7948. const char *realm)
  7949. {
  7950. if (conn && conn->dom_ctx) {
  7951. send_authorization_request(conn, realm);
  7952. return 0;
  7953. }
  7954. return -1;
  7955. }
  7956. #if !defined(NO_FILES)
  7957. static int
  7958. is_authorized_for_put(struct mg_connection *conn)
  7959. {
  7960. int ret = 0;
  7961. if (conn) {
  7962. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7963. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7964. if (passfile != NULL
  7965. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7966. ret = authorize(conn, &file, NULL);
  7967. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7968. }
  7969. }
  7970. DEBUG_TRACE("file write authorization: %i", ret);
  7971. return ret;
  7972. }
  7973. #endif
  7974. CIVETWEB_API int
  7975. mg_modify_passwords_file_ha1(const char *fname,
  7976. const char *domain,
  7977. const char *user,
  7978. const char *ha1)
  7979. {
  7980. int found = 0, i, result = 1;
  7981. char line[512], u[256], d[256], h[256];
  7982. struct stat st = {0};
  7983. FILE *fp = NULL;
  7984. char *temp_file = NULL;
  7985. int temp_file_offs = 0;
  7986. /* Regard empty password as no password - remove user record. */
  7987. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7988. ha1 = NULL;
  7989. }
  7990. /* Other arguments must not be empty */
  7991. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7992. return 0;
  7993. }
  7994. /* Using the given file format, user name and domain must not contain
  7995. * the ':' character */
  7996. if (strchr(user, ':') != NULL) {
  7997. return 0;
  7998. }
  7999. if (strchr(domain, ':') != NULL) {
  8000. return 0;
  8001. }
  8002. /* Do not allow control characters like newline in user name and domain.
  8003. * Do not allow excessively long names either. */
  8004. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  8005. if (iscntrl((unsigned char)user[i])) {
  8006. return 0;
  8007. }
  8008. }
  8009. if (user[i]) {
  8010. return 0; /* user name too long */
  8011. }
  8012. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8013. if (iscntrl((unsigned char)domain[i])) {
  8014. return 0;
  8015. }
  8016. }
  8017. if (domain[i]) {
  8018. return 0; /* domain name too long */
  8019. }
  8020. /* The maximum length of the path to the password file is limited */
  8021. if (strlen(fname) >= UTF8_PATH_MAX) {
  8022. return 0;
  8023. }
  8024. /* Check if the file exists, and get file size */
  8025. if (0 == stat(fname, &st)) {
  8026. int temp_buf_len;
  8027. if (st.st_size > 10485760) {
  8028. /* Some funster provided a >10 MB text file */
  8029. return 0;
  8030. }
  8031. /* Add enough space for one more line */
  8032. temp_buf_len = (int)st.st_size + 1024;
  8033. /* Allocate memory (instead of using a temporary file) */
  8034. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8035. if (!temp_file) {
  8036. /* Out of memory */
  8037. return 0;
  8038. }
  8039. /* File exists. Read it into a memory buffer. */
  8040. fp = fopen(fname, "r");
  8041. if (fp == NULL) {
  8042. /* Cannot read file. No permission? */
  8043. mg_free(temp_file);
  8044. return 0;
  8045. }
  8046. /* Read content and store in memory */
  8047. while ((fgets(line, sizeof(line), fp) != NULL)
  8048. && ((temp_file_offs + 600) < temp_buf_len)) {
  8049. /* file format is "user:domain:hash\n" */
  8050. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8051. continue;
  8052. }
  8053. u[255] = 0;
  8054. d[255] = 0;
  8055. h[255] = 0;
  8056. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8057. /* Found the user: change the password hash or drop the user
  8058. */
  8059. if ((ha1 != NULL) && (!found)) {
  8060. i = sprintf(temp_file + temp_file_offs,
  8061. "%s:%s:%s\n",
  8062. user,
  8063. domain,
  8064. ha1);
  8065. if (i < 1) {
  8066. fclose(fp);
  8067. mg_free(temp_file);
  8068. return 0;
  8069. }
  8070. temp_file_offs += i;
  8071. }
  8072. found = 1;
  8073. } else {
  8074. /* Copy existing user, including password hash */
  8075. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8076. if (i < 1) {
  8077. fclose(fp);
  8078. mg_free(temp_file);
  8079. return 0;
  8080. }
  8081. temp_file_offs += i;
  8082. }
  8083. }
  8084. fclose(fp);
  8085. }
  8086. /* Create new file */
  8087. fp = fopen(fname, "w");
  8088. if (!fp) {
  8089. mg_free(temp_file);
  8090. return 0;
  8091. }
  8092. #if !defined(_WIN32)
  8093. /* On Linux & co., restrict file read/write permissions to the owner */
  8094. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8095. result = 0;
  8096. }
  8097. #endif
  8098. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8099. /* Store buffered content of old file */
  8100. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8101. != (size_t)temp_file_offs) {
  8102. result = 0;
  8103. }
  8104. }
  8105. /* If new user, just add it */
  8106. if ((ha1 != NULL) && (!found)) {
  8107. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8108. result = 0;
  8109. }
  8110. }
  8111. /* All data written */
  8112. if (fclose(fp) != 0) {
  8113. result = 0;
  8114. }
  8115. mg_free(temp_file);
  8116. return result;
  8117. }
  8118. CIVETWEB_API int
  8119. mg_modify_passwords_file(const char *fname,
  8120. const char *domain,
  8121. const char *user,
  8122. const char *pass)
  8123. {
  8124. char ha1buf[33];
  8125. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8126. return 0;
  8127. }
  8128. if ((pass == NULL) || (pass[0] == 0)) {
  8129. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8130. }
  8131. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8132. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8133. }
  8134. static int
  8135. is_valid_port(unsigned long port)
  8136. {
  8137. return (port <= 0xffff);
  8138. }
  8139. static int
  8140. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8141. {
  8142. struct addrinfo hints, *res, *ressave;
  8143. int func_ret = 0;
  8144. int gai_ret;
  8145. memset(&hints, 0, sizeof(struct addrinfo));
  8146. hints.ai_family = af;
  8147. if (!resolve_src) {
  8148. hints.ai_flags = AI_NUMERICHOST;
  8149. }
  8150. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8151. if (gai_ret != 0) {
  8152. /* gai_strerror could be used to convert gai_ret to a string */
  8153. /* POSIX return values: see
  8154. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8155. */
  8156. /* Windows return values: see
  8157. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8158. */
  8159. return 0;
  8160. }
  8161. ressave = res;
  8162. while (res) {
  8163. if ((dstlen >= (size_t)res->ai_addrlen)
  8164. && (res->ai_addr->sa_family == af)) {
  8165. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8166. func_ret = 1;
  8167. }
  8168. res = res->ai_next;
  8169. }
  8170. freeaddrinfo(ressave);
  8171. return func_ret;
  8172. }
  8173. static int
  8174. connect_socket(
  8175. struct mg_context *ctx /* may be NULL */,
  8176. const char *host,
  8177. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8178. int use_ssl, /* 0 or 1 */
  8179. struct mg_error_data *error,
  8180. SOCKET *sock /* output: socket, must not be NULL */,
  8181. union usa *sa /* output: socket address, must not be NULL */
  8182. )
  8183. {
  8184. int ip_ver = 0;
  8185. int conn_ret = -1;
  8186. int sockerr = 0;
  8187. *sock = INVALID_SOCKET;
  8188. memset(sa, 0, sizeof(*sa));
  8189. if (host == NULL) {
  8190. if (error != NULL) {
  8191. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8192. mg_snprintf(NULL,
  8193. NULL, /* No truncation check for ebuf */
  8194. error->text,
  8195. error->text_buffer_size,
  8196. "%s",
  8197. "NULL host");
  8198. }
  8199. return 0;
  8200. }
  8201. #if defined(USE_X_DOM_SOCKET)
  8202. if (port == -99) {
  8203. /* Unix domain socket */
  8204. size_t hostlen = strlen(host);
  8205. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8206. if (error != NULL) {
  8207. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8208. mg_snprintf(NULL,
  8209. NULL, /* No truncation check for ebuf */
  8210. error->text,
  8211. error->text_buffer_size,
  8212. "%s",
  8213. "host length exceeds limit");
  8214. }
  8215. return 0;
  8216. }
  8217. } else
  8218. #endif
  8219. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8220. if (error != NULL) {
  8221. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8222. mg_snprintf(NULL,
  8223. NULL, /* No truncation check for ebuf */
  8224. error->text,
  8225. error->text_buffer_size,
  8226. "%s",
  8227. "invalid port");
  8228. }
  8229. return 0;
  8230. }
  8231. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) \
  8232. && !defined(NO_SSL_DL)
  8233. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8234. if (use_ssl && (TLS_client_method == NULL)) {
  8235. if (error != NULL) {
  8236. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8237. mg_snprintf(NULL,
  8238. NULL, /* No truncation check for ebuf */
  8239. error->text,
  8240. error->text_buffer_size,
  8241. "%s",
  8242. "SSL is not initialized");
  8243. }
  8244. return 0;
  8245. }
  8246. #else
  8247. if (use_ssl && (SSLv23_client_method == NULL)) {
  8248. if (error != 0) {
  8249. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8250. mg_snprintf(NULL,
  8251. NULL, /* No truncation check for ebuf */
  8252. error->text,
  8253. error->text_buffer_size,
  8254. "%s",
  8255. "SSL is not initialized");
  8256. }
  8257. return 0;
  8258. }
  8259. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8260. #else
  8261. (void)use_ssl;
  8262. #endif /* NO SSL */
  8263. #if defined(USE_X_DOM_SOCKET)
  8264. if (port == -99) {
  8265. size_t hostlen = strlen(host);
  8266. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8267. ip_ver = -99;
  8268. sa->sun.sun_family = AF_UNIX;
  8269. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8270. memcpy(sa->sun.sun_path, host, hostlen);
  8271. } else
  8272. #endif
  8273. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8274. sa->sin.sin_port = htons((uint16_t)port);
  8275. ip_ver = 4;
  8276. #if defined(USE_IPV6)
  8277. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8278. sa->sin6.sin6_port = htons((uint16_t)port);
  8279. ip_ver = 6;
  8280. } else if (host[0] == '[') {
  8281. /* While getaddrinfo on Windows will work with [::1],
  8282. * getaddrinfo on Linux only works with ::1 (without []). */
  8283. size_t l = strlen(host + 1);
  8284. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8285. if (h) {
  8286. h[l - 1] = 0;
  8287. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8288. sa->sin6.sin6_port = htons((uint16_t)port);
  8289. ip_ver = 6;
  8290. }
  8291. mg_free(h);
  8292. }
  8293. #endif
  8294. }
  8295. if (ip_ver == 0) {
  8296. if (error != NULL) {
  8297. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8298. mg_snprintf(NULL,
  8299. NULL, /* No truncation check for ebuf */
  8300. error->text,
  8301. error->text_buffer_size,
  8302. "%s",
  8303. "host not found");
  8304. }
  8305. return 0;
  8306. }
  8307. if (ip_ver == 4) {
  8308. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8309. }
  8310. #if defined(USE_IPV6)
  8311. else if (ip_ver == 6) {
  8312. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8313. }
  8314. #endif
  8315. #if defined(USE_X_DOM_SOCKET)
  8316. else if (ip_ver == -99) {
  8317. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8318. }
  8319. #endif
  8320. if (*sock == INVALID_SOCKET) {
  8321. if (error != NULL) {
  8322. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8323. error->code_sub = (unsigned)ERRNO;
  8324. mg_snprintf(NULL,
  8325. NULL, /* No truncation check for ebuf */
  8326. error->text,
  8327. error->text_buffer_size,
  8328. "socket(): %s",
  8329. strerror(ERRNO));
  8330. }
  8331. return 0;
  8332. }
  8333. if (0 != set_non_blocking_mode(*sock)) {
  8334. if (error != NULL) {
  8335. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8336. error->code_sub = (unsigned)ERRNO;
  8337. mg_snprintf(NULL,
  8338. NULL, /* No truncation check for ebuf */
  8339. error->text,
  8340. error->text_buffer_size,
  8341. "Cannot set socket to non-blocking: %s",
  8342. strerror(ERRNO));
  8343. }
  8344. closesocket(*sock);
  8345. *sock = INVALID_SOCKET;
  8346. return 0;
  8347. }
  8348. set_close_on_exec(*sock, NULL, ctx);
  8349. if (ip_ver == 4) {
  8350. /* connected with IPv4 */
  8351. conn_ret = connect(*sock,
  8352. (struct sockaddr *)((void *)&sa->sin),
  8353. sizeof(sa->sin));
  8354. }
  8355. #if defined(USE_IPV6)
  8356. else if (ip_ver == 6) {
  8357. /* connected with IPv6 */
  8358. conn_ret = connect(*sock,
  8359. (struct sockaddr *)((void *)&sa->sin6),
  8360. sizeof(sa->sin6));
  8361. }
  8362. #endif
  8363. #if defined(USE_X_DOM_SOCKET)
  8364. else if (ip_ver == -99) {
  8365. /* connected to domain socket */
  8366. conn_ret = connect(*sock,
  8367. (struct sockaddr *)((void *)&sa->sun),
  8368. sizeof(sa->sun));
  8369. }
  8370. #endif
  8371. if (conn_ret != 0) {
  8372. sockerr = ERRNO;
  8373. }
  8374. #if defined(_WIN32)
  8375. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8376. #else
  8377. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8378. #endif
  8379. /* Data for getsockopt */
  8380. void *psockerr = &sockerr;
  8381. int ret;
  8382. #if defined(_WIN32)
  8383. int len = (int)sizeof(sockerr);
  8384. #else
  8385. socklen_t len = (socklen_t)sizeof(sockerr);
  8386. #endif
  8387. /* Data for poll */
  8388. struct mg_pollfd pfd[2];
  8389. int pollres;
  8390. int ms_wait = 10000; /* 10 second timeout */
  8391. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8392. unsigned int num_sock = 1; /* use one or two sockets */
  8393. /* For a non-blocking socket, the connect sequence is:
  8394. * 1) call connect (will not block)
  8395. * 2) wait until the socket is ready for writing (select or poll)
  8396. * 3) check connection state with getsockopt
  8397. */
  8398. pfd[0].fd = *sock;
  8399. pfd[0].events = POLLOUT;
  8400. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8401. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8402. pfd[num_sock].events = POLLIN;
  8403. num_sock++;
  8404. }
  8405. pollres =
  8406. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8407. if (pollres != 1) {
  8408. /* Not connected */
  8409. if (error != NULL) {
  8410. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8411. mg_snprintf(NULL,
  8412. NULL, /* No truncation check for ebuf */
  8413. error->text,
  8414. error->text_buffer_size,
  8415. "connect(%s:%d): timeout",
  8416. host,
  8417. port);
  8418. }
  8419. closesocket(*sock);
  8420. *sock = INVALID_SOCKET;
  8421. return 0;
  8422. }
  8423. #if defined(_WIN32)
  8424. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8425. #else
  8426. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8427. #endif
  8428. if ((ret == 0) && (sockerr == 0)) {
  8429. conn_ret = 0;
  8430. }
  8431. }
  8432. if (conn_ret != 0) {
  8433. /* Not connected */
  8434. if (error != NULL) {
  8435. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8436. error->code_sub = (unsigned)ERRNO;
  8437. mg_snprintf(NULL,
  8438. NULL, /* No truncation check for ebuf */
  8439. error->text,
  8440. error->text_buffer_size,
  8441. "connect(%s:%d): error %s",
  8442. host,
  8443. port,
  8444. strerror(sockerr));
  8445. }
  8446. closesocket(*sock);
  8447. *sock = INVALID_SOCKET;
  8448. return 0;
  8449. }
  8450. return 1;
  8451. }
  8452. CIVETWEB_API int
  8453. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8454. {
  8455. static const char *dont_escape = "._-$,;~()";
  8456. static const char *hex = "0123456789abcdef";
  8457. char *pos = dst;
  8458. const char *end = dst + dst_len - 1;
  8459. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8460. if (isalnum((unsigned char)*src)
  8461. || (strchr(dont_escape, *src) != NULL)) {
  8462. *pos = *src;
  8463. } else if (pos + 2 < end) {
  8464. pos[0] = '%';
  8465. pos[1] = hex[(unsigned char)*src >> 4];
  8466. pos[2] = hex[(unsigned char)*src & 0xf];
  8467. pos += 2;
  8468. } else {
  8469. break;
  8470. }
  8471. }
  8472. *pos = '\0';
  8473. return (*src == '\0') ? (int)(pos - dst) : -1;
  8474. }
  8475. /* Return 0 on success, non-zero if an error occurs. */
  8476. static int
  8477. print_dir_entry(struct mg_connection *conn, struct de *de)
  8478. {
  8479. size_t namesize, escsize, i;
  8480. char *href, *esc, *p;
  8481. char size[64], mod[64];
  8482. #if defined(REENTRANT_TIME)
  8483. struct tm _tm;
  8484. struct tm *tm = &_tm;
  8485. #else
  8486. struct tm *tm;
  8487. #endif
  8488. /* Estimate worst case size for encoding and escaping */
  8489. namesize = strlen(de->file_name) + 1;
  8490. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8491. href = (char *)mg_malloc(namesize * 3 + escsize);
  8492. if (href == NULL) {
  8493. return -1;
  8494. }
  8495. mg_url_encode(de->file_name, href, namesize * 3);
  8496. esc = NULL;
  8497. if (escsize > 0) {
  8498. /* HTML escaping needed */
  8499. esc = href + namesize * 3;
  8500. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8501. mg_strlcpy(p, de->file_name + i, 2);
  8502. if (*p == '&') {
  8503. strcpy(p, "&amp;");
  8504. } else if (*p == '<') {
  8505. strcpy(p, "&lt;");
  8506. } else if (*p == '>') {
  8507. strcpy(p, "&gt;");
  8508. }
  8509. }
  8510. }
  8511. if (de->file.is_directory) {
  8512. mg_snprintf(conn,
  8513. NULL, /* Buffer is big enough */
  8514. size,
  8515. sizeof(size),
  8516. "%s",
  8517. "[DIRECTORY]");
  8518. } else {
  8519. /* We use (signed) cast below because MSVC 6 compiler cannot
  8520. * convert unsigned __int64 to double. Sigh. */
  8521. if (de->file.size < 1024) {
  8522. mg_snprintf(conn,
  8523. NULL, /* Buffer is big enough */
  8524. size,
  8525. sizeof(size),
  8526. "%d",
  8527. (int)de->file.size);
  8528. } else if (de->file.size < 0x100000) {
  8529. mg_snprintf(conn,
  8530. NULL, /* Buffer is big enough */
  8531. size,
  8532. sizeof(size),
  8533. "%.1fk",
  8534. (double)de->file.size / 1024.0);
  8535. } else if (de->file.size < 0x40000000) {
  8536. mg_snprintf(conn,
  8537. NULL, /* Buffer is big enough */
  8538. size,
  8539. sizeof(size),
  8540. "%.1fM",
  8541. (double)de->file.size / 1048576);
  8542. } else {
  8543. mg_snprintf(conn,
  8544. NULL, /* Buffer is big enough */
  8545. size,
  8546. sizeof(size),
  8547. "%.1fG",
  8548. (double)de->file.size / 1073741824);
  8549. }
  8550. }
  8551. /* Note: mg_snprintf will not cause a buffer overflow above.
  8552. * So, string truncation checks are not required here. */
  8553. #if defined(REENTRANT_TIME)
  8554. localtime_r(&de->file.last_modified, tm);
  8555. #else
  8556. tm = localtime(&de->file.last_modified);
  8557. #endif
  8558. if (tm != NULL) {
  8559. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8560. } else {
  8561. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8562. }
  8563. mg_printf(conn,
  8564. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8565. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8566. href,
  8567. de->file.is_directory ? "/" : "",
  8568. esc ? esc : de->file_name,
  8569. de->file.is_directory ? "/" : "",
  8570. mod,
  8571. size);
  8572. mg_free(href);
  8573. return 0;
  8574. }
  8575. /* This function is called from send_directory() and used for
  8576. * sorting directory entries by size, name, or modification time. */
  8577. static int
  8578. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8579. {
  8580. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8581. if (p1 && p2) {
  8582. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8583. int cmp_result = 0;
  8584. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8585. query_string = "n";
  8586. }
  8587. /* Sort Directories vs Files */
  8588. if (a->file.is_directory && !b->file.is_directory) {
  8589. return -1; /* Always put directories on top */
  8590. } else if (!a->file.is_directory && b->file.is_directory) {
  8591. return 1; /* Always put directories on top */
  8592. }
  8593. /* Sort by size or date */
  8594. if (*query_string == 's') {
  8595. cmp_result = (a->file.size == b->file.size)
  8596. ? 0
  8597. : ((a->file.size > b->file.size) ? 1 : -1);
  8598. } else if (*query_string == 'd') {
  8599. cmp_result =
  8600. (a->file.last_modified == b->file.last_modified)
  8601. ? 0
  8602. : ((a->file.last_modified > b->file.last_modified) ? 1
  8603. : -1);
  8604. }
  8605. /* Sort by name:
  8606. * if (*query_string == 'n') ...
  8607. * but also sort files of same size/date by name as secondary criterion.
  8608. */
  8609. if (cmp_result == 0) {
  8610. cmp_result = strcmp(a->file_name, b->file_name);
  8611. }
  8612. /* For descending order, invert result */
  8613. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8614. }
  8615. return 0;
  8616. }
  8617. static int
  8618. must_hide_file(struct mg_connection *conn, const char *path)
  8619. {
  8620. if (conn && conn->dom_ctx) {
  8621. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8622. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8623. return (match_prefix_strlen(pw_pattern, path) > 0)
  8624. || (match_prefix_strlen(pattern, path) > 0);
  8625. }
  8626. return 0;
  8627. }
  8628. #if !defined(NO_FILESYSTEMS)
  8629. static int
  8630. scan_directory(struct mg_connection *conn,
  8631. const char *dir,
  8632. void *data,
  8633. int (*cb)(struct de *, void *))
  8634. {
  8635. char path[UTF8_PATH_MAX];
  8636. struct dirent *dp;
  8637. DIR *dirp;
  8638. struct de de;
  8639. int truncated;
  8640. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8641. return 0;
  8642. } else {
  8643. while ((dp = mg_readdir(dirp)) != NULL) {
  8644. /* Do not show current dir and hidden files */
  8645. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8646. || must_hide_file(conn, dp->d_name)) {
  8647. continue;
  8648. }
  8649. mg_snprintf(
  8650. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8651. /* If we don't memset stat structure to zero, mtime will have
  8652. * garbage and strftime() will segfault later on in
  8653. * print_dir_entry(). memset is required only if mg_stat()
  8654. * fails. For more details, see
  8655. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8656. memset(&de.file, 0, sizeof(de.file));
  8657. if (truncated) {
  8658. /* If the path is not complete, skip processing. */
  8659. continue;
  8660. }
  8661. if (!mg_stat(conn, path, &de.file)) {
  8662. mg_cry_internal(conn,
  8663. "%s: mg_stat(%s) failed: %s",
  8664. __func__,
  8665. path,
  8666. strerror(ERRNO));
  8667. }
  8668. de.file_name = dp->d_name;
  8669. if (cb(&de, data)) {
  8670. /* stopped */
  8671. break;
  8672. }
  8673. }
  8674. (void)mg_closedir(dirp);
  8675. }
  8676. return 1;
  8677. }
  8678. #endif /* NO_FILESYSTEMS */
  8679. #if !defined(NO_FILES)
  8680. static int
  8681. remove_directory(struct mg_connection *conn, const char *dir)
  8682. {
  8683. char path[UTF8_PATH_MAX];
  8684. struct dirent *dp;
  8685. DIR *dirp;
  8686. struct de de;
  8687. int truncated;
  8688. int ok = 1;
  8689. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8690. return 0;
  8691. } else {
  8692. while ((dp = mg_readdir(dirp)) != NULL) {
  8693. /* Do not show current dir (but show hidden files as they will
  8694. * also be removed) */
  8695. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8696. continue;
  8697. }
  8698. mg_snprintf(
  8699. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8700. /* If we don't memset stat structure to zero, mtime will have
  8701. * garbage and strftime() will segfault later on in
  8702. * print_dir_entry(). memset is required only if mg_stat()
  8703. * fails. For more details, see
  8704. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8705. memset(&de.file, 0, sizeof(de.file));
  8706. if (truncated) {
  8707. /* Do not delete anything shorter */
  8708. ok = 0;
  8709. continue;
  8710. }
  8711. if (!mg_stat(conn, path, &de.file)) {
  8712. mg_cry_internal(conn,
  8713. "%s: mg_stat(%s) failed: %s",
  8714. __func__,
  8715. path,
  8716. strerror(ERRNO));
  8717. ok = 0;
  8718. }
  8719. if (de.file.is_directory) {
  8720. if (remove_directory(conn, path) == 0) {
  8721. ok = 0;
  8722. }
  8723. } else {
  8724. /* This will fail file is the file is in memory */
  8725. if (mg_remove(conn, path) == 0) {
  8726. ok = 0;
  8727. }
  8728. }
  8729. }
  8730. (void)mg_closedir(dirp);
  8731. IGNORE_UNUSED_RESULT(rmdir(dir));
  8732. }
  8733. return ok;
  8734. }
  8735. #endif
  8736. struct dir_scan_data {
  8737. struct de *entries;
  8738. size_t num_entries;
  8739. size_t arr_size;
  8740. };
  8741. #if !defined(NO_FILESYSTEMS)
  8742. static int
  8743. dir_scan_callback(struct de *de, void *data)
  8744. {
  8745. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8746. struct de *entries = dsd->entries;
  8747. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8748. /* Here "entries" is a temporary pointer and can be replaced,
  8749. * "dsd->entries" is the original pointer */
  8750. entries =
  8751. (struct de *)mg_realloc(entries,
  8752. dsd->arr_size * 2 * sizeof(entries[0]));
  8753. if (entries == NULL) {
  8754. /* stop scan */
  8755. return 1;
  8756. }
  8757. dsd->entries = entries;
  8758. dsd->arr_size *= 2;
  8759. }
  8760. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8761. if (entries[dsd->num_entries].file_name == NULL) {
  8762. /* stop scan */
  8763. return 1;
  8764. }
  8765. entries[dsd->num_entries].file = de->file;
  8766. dsd->num_entries++;
  8767. return 0;
  8768. }
  8769. static void
  8770. handle_directory_request(struct mg_connection *conn, const char *dir)
  8771. {
  8772. size_t i;
  8773. int sort_direction;
  8774. struct dir_scan_data data = {NULL, 0, 128};
  8775. char date[64], *esc, *p;
  8776. const char *title;
  8777. time_t curtime = time(NULL);
  8778. if (!conn) {
  8779. return;
  8780. }
  8781. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8782. mg_send_http_error(conn,
  8783. 500,
  8784. "Error: Cannot open directory\nopendir(%s): %s",
  8785. dir,
  8786. strerror(ERRNO));
  8787. return;
  8788. }
  8789. gmt_time_string(date, sizeof(date), &curtime);
  8790. esc = NULL;
  8791. title = conn->request_info.local_uri;
  8792. if (title[strcspn(title, "&<>")]) {
  8793. /* HTML escaping needed */
  8794. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8795. if (esc) {
  8796. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8797. mg_strlcpy(p, title + i, 2);
  8798. if (*p == '&') {
  8799. strcpy(p, "&amp;");
  8800. } else if (*p == '<') {
  8801. strcpy(p, "&lt;");
  8802. } else if (*p == '>') {
  8803. strcpy(p, "&gt;");
  8804. }
  8805. }
  8806. } else {
  8807. title = "";
  8808. }
  8809. }
  8810. sort_direction = ((conn->request_info.query_string != NULL)
  8811. && (conn->request_info.query_string[0] != '\0')
  8812. && (conn->request_info.query_string[1] == 'd'))
  8813. ? 'a'
  8814. : 'd';
  8815. conn->must_close = 1;
  8816. /* Create 200 OK response */
  8817. mg_response_header_start(conn, 200);
  8818. send_static_cache_header(conn);
  8819. send_additional_header(conn);
  8820. mg_response_header_add(conn,
  8821. "Content-Type",
  8822. "text/html; charset=utf-8",
  8823. -1);
  8824. /* Send all headers */
  8825. mg_response_header_send(conn);
  8826. /* Body */
  8827. mg_printf(conn,
  8828. "<!DOCTYPE html>"
  8829. "<html><head><title>Index of %s</title>"
  8830. "<style>th {text-align: left;}</style></head>"
  8831. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8832. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8833. "<th><a href=\"?d%c\">Modified</a></th>"
  8834. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8835. "<tr><td colspan=\"3\"><hr></td></tr>",
  8836. esc ? esc : title,
  8837. esc ? esc : title,
  8838. sort_direction,
  8839. sort_direction,
  8840. sort_direction);
  8841. mg_free(esc);
  8842. /* Print first entry - link to a parent directory */
  8843. mg_printf(conn,
  8844. "<tr><td><a href=\"%s\">%s</a></td>"
  8845. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8846. "..",
  8847. "Parent directory",
  8848. "-",
  8849. "-");
  8850. /* Sort and print directory entries */
  8851. if (data.entries != NULL) {
  8852. mg_sort(data.entries,
  8853. data.num_entries,
  8854. sizeof(data.entries[0]),
  8855. compare_dir_entries,
  8856. (void *)conn->request_info.query_string);
  8857. for (i = 0; i < data.num_entries; i++) {
  8858. print_dir_entry(conn, &data.entries[i]);
  8859. mg_free(data.entries[i].file_name);
  8860. }
  8861. mg_free(data.entries);
  8862. }
  8863. mg_printf(conn, "%s", "</table></pre></body></html>");
  8864. conn->status_code = 200;
  8865. }
  8866. #endif /* NO_FILESYSTEMS */
  8867. /* Send len bytes from the opened file to the client. */
  8868. static void
  8869. send_file_data(struct mg_connection *conn,
  8870. struct mg_file *filep,
  8871. int64_t offset,
  8872. int64_t len,
  8873. int no_buffering)
  8874. {
  8875. char buf[MG_BUF_LEN];
  8876. int to_read, num_read, num_written;
  8877. int64_t size;
  8878. if (!filep || !conn) {
  8879. return;
  8880. }
  8881. /* Sanity check the offset */
  8882. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8883. : (int64_t)(filep->stat.size);
  8884. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8885. if (len > 0 && filep->access.fp != NULL) {
  8886. /* file stored on disk */
  8887. #if defined(__linux__)
  8888. /* sendfile is only available for Linux */
  8889. if ((conn->ssl == 0) && (conn->throttle == 0)
  8890. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8891. "yes"))) {
  8892. off_t sf_offs = (off_t)offset;
  8893. ssize_t sf_sent;
  8894. int sf_file = fileno(filep->access.fp);
  8895. int loop_cnt = 0;
  8896. do {
  8897. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8898. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8899. size_t sf_tosend =
  8900. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8901. sf_sent =
  8902. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8903. if (sf_sent > 0) {
  8904. len -= sf_sent;
  8905. offset += sf_sent;
  8906. } else if (loop_cnt == 0) {
  8907. /* This file can not be sent using sendfile.
  8908. * This might be the case for pseudo-files in the
  8909. * /sys/ and /proc/ file system.
  8910. * Use the regular user mode copy code instead. */
  8911. break;
  8912. } else if (sf_sent == 0) {
  8913. /* No error, but 0 bytes sent. May be EOF? */
  8914. return;
  8915. }
  8916. loop_cnt++;
  8917. } while ((len > 0) && (sf_sent >= 0));
  8918. if (sf_sent > 0) {
  8919. return; /* OK */
  8920. }
  8921. /* sf_sent<0 means error, thus fall back to the classic way */
  8922. /* This is always the case, if sf_file is not a "normal" file,
  8923. * e.g., for sending data from the output of a CGI process. */
  8924. offset = (int64_t)sf_offs;
  8925. }
  8926. #endif
  8927. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8928. mg_cry_internal(conn,
  8929. "%s: fseeko() failed: %s",
  8930. __func__,
  8931. strerror(ERRNO));
  8932. mg_send_http_error(
  8933. conn,
  8934. 500,
  8935. "%s",
  8936. "Error: Unable to access file at requested position.");
  8937. } else {
  8938. while (len > 0) {
  8939. /* Calculate how much to read from the file into the buffer. */
  8940. /* If no_buffering is set, we should not wait until the
  8941. * CGI->Server buffer is filled, but send everything
  8942. * immediately. In theory buffering could be turned off using
  8943. * setbuf(filep->access.fp, NULL);
  8944. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8945. * but in practice this does not work. A "Linux only" solution
  8946. * may be to use select(). The only portable way is to read byte
  8947. * by byte, but this is quite inefficient from a performance
  8948. * point of view. */
  8949. to_read = no_buffering ? 1 : sizeof(buf);
  8950. if ((int64_t)to_read > len) {
  8951. to_read = (int)len;
  8952. }
  8953. /* Read from file, exit the loop on error */
  8954. if ((num_read = pull_inner(filep->access.fp,
  8955. NULL,
  8956. buf,
  8957. to_read,
  8958. /* unused */ 0.0))
  8959. <= 0) {
  8960. break;
  8961. }
  8962. /* Send read bytes to the client, exit the loop on error */
  8963. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8964. != num_read) {
  8965. break;
  8966. }
  8967. /* Both read and were successful, adjust counters */
  8968. len -= num_written;
  8969. }
  8970. }
  8971. }
  8972. }
  8973. static int
  8974. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8975. {
  8976. return sscanf(header,
  8977. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8978. a,
  8979. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8980. // to an integer value, but function will not report
  8981. // conversion errors; consider using 'strtol' instead
  8982. }
  8983. static void
  8984. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8985. {
  8986. if ((filestat != NULL) && (buf != NULL)) {
  8987. mg_snprintf(NULL,
  8988. NULL, /* All calls to construct_etag use 64 byte buffer */
  8989. buf,
  8990. buf_len,
  8991. "\"%lx.%" INT64_FMT "\"",
  8992. (unsigned long)filestat->last_modified,
  8993. filestat->size);
  8994. }
  8995. }
  8996. static void
  8997. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8998. {
  8999. if (filep != NULL && filep->fp != NULL) {
  9000. #if defined(_WIN32)
  9001. (void)conn; /* Unused. */
  9002. #else
  9003. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  9004. mg_cry_internal(conn,
  9005. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  9006. __func__,
  9007. strerror(ERRNO));
  9008. }
  9009. #endif
  9010. }
  9011. }
  9012. #if defined(USE_ZLIB)
  9013. #include "mod_zlib.inl"
  9014. #endif
  9015. #if !defined(NO_FILESYSTEMS)
  9016. static void
  9017. handle_static_file_request(struct mg_connection *conn,
  9018. const char *path,
  9019. struct mg_file *filep,
  9020. const char *mime_type,
  9021. const char *additional_headers)
  9022. {
  9023. char lm[64], etag[64];
  9024. char range[128]; /* large enough, so there will be no overflow */
  9025. const char *range_hdr;
  9026. int64_t cl, r1, r2;
  9027. struct vec mime_vec;
  9028. int n, truncated;
  9029. char gz_path[UTF8_PATH_MAX];
  9030. const char *encoding = 0;
  9031. int is_head_request;
  9032. #if defined(USE_ZLIB)
  9033. /* Compression is allowed, unless there is a reason not to use
  9034. * compression. If the file is already compressed, too small or a
  9035. * "range" request was made, on the fly compression is not possible. */
  9036. int allow_on_the_fly_compression = 1;
  9037. #endif
  9038. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9039. return;
  9040. }
  9041. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9042. if (mime_type == NULL) {
  9043. get_mime_type(conn, path, &mime_vec);
  9044. } else {
  9045. mime_vec.ptr = mime_type;
  9046. mime_vec.len = strlen(mime_type);
  9047. }
  9048. if (filep->stat.size > INT64_MAX) {
  9049. mg_send_http_error(conn,
  9050. 500,
  9051. "Error: File size is too large to send\n%" INT64_FMT,
  9052. filep->stat.size);
  9053. return;
  9054. }
  9055. cl = (int64_t)filep->stat.size;
  9056. conn->status_code = 200;
  9057. range[0] = '\0';
  9058. #if defined(USE_ZLIB)
  9059. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9060. * it's important to rewrite the filename after resolving
  9061. * the mime type from it, to preserve the actual file's type */
  9062. if (!conn->accept_gzip) {
  9063. allow_on_the_fly_compression = 0;
  9064. }
  9065. #endif
  9066. /* Check if there is a range header */
  9067. range_hdr = mg_get_header(conn, "Range");
  9068. /* For gzipped files, add *.gz */
  9069. if (filep->stat.is_gzipped) {
  9070. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9071. if (truncated) {
  9072. mg_send_http_error(conn,
  9073. 500,
  9074. "Error: Path of zipped file too long (%s)",
  9075. path);
  9076. return;
  9077. }
  9078. path = gz_path;
  9079. encoding = "gzip";
  9080. #if defined(USE_ZLIB)
  9081. /* File is already compressed. No "on the fly" compression. */
  9082. allow_on_the_fly_compression = 0;
  9083. #endif
  9084. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9085. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9086. struct mg_file_stat file_stat;
  9087. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9088. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9089. && !file_stat.is_directory) {
  9090. file_stat.is_gzipped = 1;
  9091. filep->stat = file_stat;
  9092. cl = (int64_t)filep->stat.size;
  9093. path = gz_path;
  9094. encoding = "gzip";
  9095. #if defined(USE_ZLIB)
  9096. /* File is already compressed. No "on the fly" compression. */
  9097. allow_on_the_fly_compression = 0;
  9098. #endif
  9099. }
  9100. }
  9101. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9102. mg_send_http_error(conn,
  9103. 500,
  9104. "Error: Cannot open file\nfopen(%s): %s",
  9105. path,
  9106. strerror(ERRNO));
  9107. return;
  9108. }
  9109. fclose_on_exec(&filep->access, conn);
  9110. /* If "Range" request was made: parse header, send only selected part
  9111. * of the file. */
  9112. r1 = r2 = 0;
  9113. if ((range_hdr != NULL)
  9114. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9115. && (r2 >= 0)) {
  9116. /* actually, range requests don't play well with a pre-gzipped
  9117. * file (since the range is specified in the uncompressed space) */
  9118. if (filep->stat.is_gzipped) {
  9119. mg_send_http_error(
  9120. conn,
  9121. 416, /* 416 = Range Not Satisfiable */
  9122. "%s",
  9123. "Error: Range requests in gzipped files are not supported");
  9124. (void)mg_fclose(
  9125. &filep->access); /* ignore error on read only file */
  9126. return;
  9127. }
  9128. conn->status_code = 206;
  9129. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9130. mg_snprintf(conn,
  9131. NULL, /* range buffer is big enough */
  9132. range,
  9133. sizeof(range),
  9134. "bytes "
  9135. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9136. r1,
  9137. r1 + cl - 1,
  9138. filep->stat.size);
  9139. #if defined(USE_ZLIB)
  9140. /* Do not compress ranges. */
  9141. allow_on_the_fly_compression = 0;
  9142. #endif
  9143. }
  9144. /* Do not compress small files. Small files do not benefit from file
  9145. * compression, but there is still some overhead. */
  9146. #if defined(USE_ZLIB)
  9147. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9148. /* File is below the size limit. */
  9149. allow_on_the_fly_compression = 0;
  9150. }
  9151. #endif
  9152. /* Prepare Etag, and Last-Modified headers. */
  9153. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9154. construct_etag(etag, sizeof(etag), &filep->stat);
  9155. /* Create 2xx (200, 206) response */
  9156. mg_response_header_start(conn, conn->status_code);
  9157. send_static_cache_header(conn);
  9158. send_additional_header(conn);
  9159. send_cors_header(conn);
  9160. mg_response_header_add(conn,
  9161. "Content-Type",
  9162. mime_vec.ptr,
  9163. (int)mime_vec.len);
  9164. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9165. mg_response_header_add(conn, "Etag", etag, -1);
  9166. #if defined(USE_ZLIB)
  9167. /* On the fly compression allowed */
  9168. if (allow_on_the_fly_compression) {
  9169. /* For on the fly compression, we don't know the content size in
  9170. * advance, so we have to use chunked encoding */
  9171. encoding = "gzip";
  9172. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9173. /* HTTP/2 is always using "chunks" (frames) */
  9174. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9175. }
  9176. } else
  9177. #endif
  9178. {
  9179. /* Without on-the-fly compression, we know the content-length
  9180. * and we can use ranges (with on-the-fly compression we cannot).
  9181. * So we send these response headers only in this case. */
  9182. char len[32];
  9183. int trunc = 0;
  9184. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9185. if (!trunc) {
  9186. mg_response_header_add(conn, "Content-Length", len, -1);
  9187. }
  9188. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9189. }
  9190. if (encoding) {
  9191. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9192. }
  9193. if (range[0] != 0) {
  9194. mg_response_header_add(conn, "Content-Range", range, -1);
  9195. }
  9196. /* The code above does not add any header starting with X- to make
  9197. * sure no one of the additional_headers is included twice */
  9198. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9199. mg_response_header_add_lines(conn, additional_headers);
  9200. }
  9201. /* Send all headers */
  9202. mg_response_header_send(conn);
  9203. if (!is_head_request) {
  9204. #if defined(USE_ZLIB)
  9205. if (allow_on_the_fly_compression) {
  9206. /* Compress and send */
  9207. send_compressed_data(conn, filep);
  9208. } else
  9209. #endif
  9210. {
  9211. /* Send file directly */
  9212. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9213. }
  9214. }
  9215. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9216. }
  9217. CIVETWEB_API int
  9218. mg_send_file_body(struct mg_connection *conn, const char *path)
  9219. {
  9220. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9221. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9222. return -1;
  9223. }
  9224. fclose_on_exec(&file.access, conn);
  9225. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9226. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9227. return 0; /* >= 0 for OK */
  9228. }
  9229. #endif /* NO_FILESYSTEMS */
  9230. #if !defined(NO_CACHING)
  9231. /* Return True if we should reply 304 Not Modified. */
  9232. static int
  9233. is_not_modified(const struct mg_connection *conn,
  9234. const struct mg_file_stat *filestat)
  9235. {
  9236. char etag[64];
  9237. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9238. const char *inm = mg_get_header(conn, "If-None-Match");
  9239. construct_etag(etag, sizeof(etag), filestat);
  9240. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9241. || ((ims != NULL)
  9242. && (filestat->last_modified <= parse_date_string(ims)));
  9243. }
  9244. static void
  9245. handle_not_modified_static_file_request(struct mg_connection *conn,
  9246. struct mg_file *filep)
  9247. {
  9248. char lm[64], etag[64];
  9249. if ((conn == NULL) || (filep == NULL)) {
  9250. return;
  9251. }
  9252. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9253. construct_etag(etag, sizeof(etag), &filep->stat);
  9254. /* Create 304 "not modified" response */
  9255. mg_response_header_start(conn, 304);
  9256. send_static_cache_header(conn);
  9257. send_additional_header(conn);
  9258. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9259. mg_response_header_add(conn, "Etag", etag, -1);
  9260. /* Send all headers */
  9261. mg_response_header_send(conn);
  9262. }
  9263. #endif
  9264. #if !defined(NO_FILESYSTEMS)
  9265. CIVETWEB_API void
  9266. mg_send_file(struct mg_connection *conn, const char *path)
  9267. {
  9268. mg_send_mime_file2(conn, path, NULL, NULL);
  9269. }
  9270. CIVETWEB_API void
  9271. mg_send_mime_file(struct mg_connection *conn,
  9272. const char *path,
  9273. const char *mime_type)
  9274. {
  9275. mg_send_mime_file2(conn, path, mime_type, NULL);
  9276. }
  9277. CIVETWEB_API void
  9278. mg_send_mime_file2(struct mg_connection *conn,
  9279. const char *path,
  9280. const char *mime_type,
  9281. const char *additional_headers)
  9282. {
  9283. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9284. if (!conn) {
  9285. /* No conn */
  9286. return;
  9287. }
  9288. if (mg_stat(conn, path, &file.stat)) {
  9289. #if !defined(NO_CACHING)
  9290. if (is_not_modified(conn, &file.stat)) {
  9291. /* Send 304 "Not Modified" - this must not send any body data */
  9292. handle_not_modified_static_file_request(conn, &file);
  9293. } else
  9294. #endif /* NO_CACHING */
  9295. if (file.stat.is_directory) {
  9296. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9297. "yes")) {
  9298. handle_directory_request(conn, path);
  9299. } else {
  9300. mg_send_http_error(conn,
  9301. 403,
  9302. "%s",
  9303. "Error: Directory listing denied");
  9304. }
  9305. } else {
  9306. handle_static_file_request(
  9307. conn, path, &file, mime_type, additional_headers);
  9308. }
  9309. } else {
  9310. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9311. }
  9312. }
  9313. /* For a given PUT path, create all intermediate subdirectories.
  9314. * Return 0 if the path itself is a directory.
  9315. * Return 1 if the path leads to a file.
  9316. * Return -1 for if the path is too long.
  9317. * Return -2 if path can not be created.
  9318. */
  9319. static int
  9320. put_dir(struct mg_connection *conn, const char *path)
  9321. {
  9322. char buf[UTF8_PATH_MAX];
  9323. const char *s, *p;
  9324. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9325. size_t len;
  9326. int res = 1;
  9327. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9328. len = (size_t)(p - path);
  9329. if (len >= sizeof(buf)) {
  9330. /* path too long */
  9331. res = -1;
  9332. break;
  9333. }
  9334. memcpy(buf, path, len);
  9335. buf[len] = '\0';
  9336. /* Try to create intermediate directory */
  9337. DEBUG_TRACE("mkdir(%s)", buf);
  9338. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9339. /* path does not exist and can not be created */
  9340. res = -2;
  9341. break;
  9342. }
  9343. /* Is path itself a directory? */
  9344. if (p[1] == '\0') {
  9345. res = 0;
  9346. }
  9347. }
  9348. return res;
  9349. }
  9350. static void
  9351. remove_bad_file(const struct mg_connection *conn, const char *path)
  9352. {
  9353. int r = mg_remove(conn, path);
  9354. if (r != 0) {
  9355. mg_cry_internal(conn,
  9356. "%s: Cannot remove invalid file %s",
  9357. __func__,
  9358. path);
  9359. }
  9360. }
  9361. CIVETWEB_API long long
  9362. mg_store_body(struct mg_connection *conn, const char *path)
  9363. {
  9364. char buf[MG_BUF_LEN];
  9365. long long len = 0;
  9366. int ret, n;
  9367. struct mg_file fi;
  9368. if (conn->consumed_content != 0) {
  9369. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9370. return -11;
  9371. }
  9372. ret = put_dir(conn, path);
  9373. if (ret < 0) {
  9374. /* -1 for path too long,
  9375. * -2 for path can not be created. */
  9376. return ret;
  9377. }
  9378. if (ret != 1) {
  9379. /* Return 0 means, path itself is a directory. */
  9380. return 0;
  9381. }
  9382. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9383. return -12;
  9384. }
  9385. ret = mg_read(conn, buf, sizeof(buf));
  9386. while (ret > 0) {
  9387. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9388. if (n != ret) {
  9389. (void)mg_fclose(
  9390. &fi.access); /* File is bad and will be removed anyway. */
  9391. remove_bad_file(conn, path);
  9392. return -13;
  9393. }
  9394. len += ret;
  9395. ret = mg_read(conn, buf, sizeof(buf));
  9396. }
  9397. /* File is open for writing. If fclose fails, there was probably an
  9398. * error flushing the buffer to disk, so the file on disk might be
  9399. * broken. Delete it and return an error to the caller. */
  9400. if (mg_fclose(&fi.access) != 0) {
  9401. remove_bad_file(conn, path);
  9402. return -14;
  9403. }
  9404. return len;
  9405. }
  9406. #endif /* NO_FILESYSTEMS */
  9407. /* Parse a buffer:
  9408. * Forward the string pointer till the end of a word, then
  9409. * terminate it and forward till the begin of the next word.
  9410. */
  9411. static int
  9412. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9413. {
  9414. /* Forward until a space is found - use isgraph here */
  9415. /* Extended ASCII characters are also treated as word characters. */
  9416. /* See http://www.cplusplus.com/reference/cctype/ */
  9417. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9418. (*ppw)++;
  9419. }
  9420. /* Check end of word */
  9421. if (eol) {
  9422. /* must be a end of line */
  9423. if ((**ppw != '\r') && (**ppw != '\n')) {
  9424. return -1;
  9425. }
  9426. } else {
  9427. /* must be a end of a word, but not a line */
  9428. if (**ppw != ' ') {
  9429. return -1;
  9430. }
  9431. }
  9432. /* Terminate and forward to the next word */
  9433. do {
  9434. **ppw = 0;
  9435. (*ppw)++;
  9436. } while (isspace((unsigned char)**ppw));
  9437. /* Check after term */
  9438. if (!eol) {
  9439. /* if it's not the end of line, there must be a next word */
  9440. if (!isgraph((unsigned char)**ppw)) {
  9441. return -1;
  9442. }
  9443. }
  9444. /* ok */
  9445. return 1;
  9446. }
  9447. /* Parse HTTP headers from the given buffer, advance buf pointer
  9448. * to the point where parsing stopped.
  9449. * All parameters must be valid pointers (not NULL).
  9450. * Return <0 on error. */
  9451. static int
  9452. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9453. {
  9454. int i;
  9455. int num_headers = 0;
  9456. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9457. char *dp = *buf;
  9458. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9459. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9460. dp++;
  9461. }
  9462. if (dp == *buf) {
  9463. /* End of headers reached. */
  9464. break;
  9465. }
  9466. /* Drop all spaces after header name before : */
  9467. while (*dp == ' ') {
  9468. *dp = 0;
  9469. dp++;
  9470. }
  9471. if (*dp != ':') {
  9472. /* This is not a valid field. */
  9473. return -1;
  9474. }
  9475. /* End of header key (*dp == ':') */
  9476. /* Truncate here and set the key name */
  9477. *dp = 0;
  9478. hdr[i].name = *buf;
  9479. /* Skip all spaces */
  9480. do {
  9481. dp++;
  9482. } while ((*dp == ' ') || (*dp == '\t'));
  9483. /* The rest of the line is the value */
  9484. hdr[i].value = dp;
  9485. /* Find end of line */
  9486. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9487. dp++;
  9488. };
  9489. /* eliminate \r */
  9490. if (*dp == '\r') {
  9491. *dp = 0;
  9492. dp++;
  9493. if (*dp != '\n') {
  9494. /* This is not a valid line. */
  9495. return -1;
  9496. }
  9497. }
  9498. /* here *dp is either 0 or '\n' */
  9499. /* in any case, we have found a complete header */
  9500. num_headers = i + 1;
  9501. if (*dp) {
  9502. *dp = 0;
  9503. dp++;
  9504. *buf = dp;
  9505. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9506. /* We've had CRLF twice in a row
  9507. * This is the end of the headers */
  9508. break;
  9509. }
  9510. /* continue within the loop, find the next header */
  9511. } else {
  9512. *buf = dp;
  9513. break;
  9514. }
  9515. }
  9516. return num_headers;
  9517. }
  9518. struct mg_http_method_info {
  9519. const char *name;
  9520. int request_has_body;
  9521. int response_has_body;
  9522. int is_safe;
  9523. int is_idempotent;
  9524. int is_cacheable;
  9525. };
  9526. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9527. static const struct mg_http_method_info http_methods[] = {
  9528. /* HTTP (RFC 2616) */
  9529. {"GET", 0, 1, 1, 1, 1},
  9530. {"POST", 1, 1, 0, 0, 0},
  9531. {"PUT", 1, 0, 0, 1, 0},
  9532. {"DELETE", 0, 0, 0, 1, 0},
  9533. {"HEAD", 0, 0, 1, 1, 1},
  9534. {"OPTIONS", 0, 0, 1, 1, 0},
  9535. {"CONNECT", 1, 1, 0, 0, 0},
  9536. /* TRACE method (RFC 2616) is not supported for security reasons */
  9537. /* PATCH method (RFC 5789) */
  9538. {"PATCH", 1, 0, 0, 0, 0},
  9539. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9540. /* WEBDAV (RFC 2518) */
  9541. {"PROPFIND", 0, 1, 1, 1, 0},
  9542. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9543. * Some PROPFIND results MAY be cached, with care,
  9544. * as there is no cache validation mechanism for
  9545. * most properties. This method is both safe and
  9546. * idempotent (see Section 9.1 of [RFC2616]). */
  9547. {"MKCOL", 0, 0, 0, 1, 0},
  9548. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9549. * When MKCOL is invoked without a request body,
  9550. * the newly created collection SHOULD have no
  9551. * members. A MKCOL request message may contain
  9552. * a message body. The precise behavior of a MKCOL
  9553. * request when the body is present is undefined,
  9554. * ... ==> We do not support MKCOL with body data.
  9555. * This method is idempotent, but not safe (see
  9556. * Section 9.1 of [RFC2616]). Responses to this
  9557. * method MUST NOT be cached. */
  9558. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9559. {"LOCK", 1, 1, 0, 0, 0},
  9560. {"UNLOCK", 1, 0, 0, 0, 0},
  9561. {"PROPPATCH", 1, 1, 0, 0, 0},
  9562. {"COPY", 1, 0, 0, 0, 0},
  9563. {"MOVE", 1, 1, 0, 0, 0},
  9564. /* Unsupported WEBDAV Methods: */
  9565. /* + 11 methods from RFC 3253 */
  9566. /* ORDERPATCH (RFC 3648) */
  9567. /* ACL (RFC 3744) */
  9568. /* SEARCH (RFC 5323) */
  9569. /* + MicroSoft extensions
  9570. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9571. /* REPORT method (RFC 3253) */
  9572. {"REPORT", 1, 1, 1, 1, 1},
  9573. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9574. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9575. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9576. * to be useful for REST in case a "GET request with body" is
  9577. * required. */
  9578. {NULL, 0, 0, 0, 0, 0}
  9579. /* end of list */
  9580. };
  9581. /* All method names */
  9582. static char *all_methods = NULL; /* Built by mg_init_library */
  9583. static const struct mg_http_method_info *
  9584. get_http_method_info(const char *method)
  9585. {
  9586. /* Check if the method is known to the server. The list of all known
  9587. * HTTP methods can be found here at
  9588. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9589. */
  9590. const struct mg_http_method_info *m = http_methods;
  9591. while (m->name) {
  9592. if (!strcmp(m->name, method)) {
  9593. return m;
  9594. }
  9595. m++;
  9596. }
  9597. return NULL;
  9598. }
  9599. static int
  9600. is_valid_http_method(const char *method)
  9601. {
  9602. return (get_http_method_info(method) != NULL);
  9603. }
  9604. /* Parse HTTP request, fill in mg_request_info structure.
  9605. * This function modifies the buffer by NUL-terminating
  9606. * HTTP request components, header names and header values.
  9607. * Parameters:
  9608. * buf (in/out): pointer to the HTTP header to parse and split
  9609. * len (in): length of HTTP header buffer
  9610. * re (out): parsed header as mg_request_info
  9611. * buf and ri must be valid pointers (not NULL), len>0.
  9612. * Returns <0 on error. */
  9613. static int
  9614. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9615. {
  9616. int request_length;
  9617. int init_skip = 0;
  9618. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9619. * remote_port */
  9620. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9621. NULL;
  9622. ri->num_headers = 0;
  9623. /* RFC says that all initial whitespaces should be ignored */
  9624. /* This included all leading \r and \n (isspace) */
  9625. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9626. while ((len > 0) && isspace((unsigned char)*buf)) {
  9627. buf++;
  9628. len--;
  9629. init_skip++;
  9630. }
  9631. if (len == 0) {
  9632. /* Incomplete request */
  9633. return 0;
  9634. }
  9635. /* Control characters are not allowed, including zero */
  9636. if (iscntrl((unsigned char)*buf)) {
  9637. return -1;
  9638. }
  9639. /* Find end of HTTP header */
  9640. request_length = get_http_header_len(buf, len);
  9641. if (request_length <= 0) {
  9642. return request_length;
  9643. }
  9644. buf[request_length - 1] = '\0';
  9645. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9646. return -1;
  9647. }
  9648. /* The first word has to be the HTTP method */
  9649. ri->request_method = buf;
  9650. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9651. return -1;
  9652. }
  9653. /* The second word is the URI */
  9654. ri->request_uri = buf;
  9655. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9656. return -1;
  9657. }
  9658. /* Next would be the HTTP version */
  9659. ri->http_version = buf;
  9660. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9661. return -1;
  9662. }
  9663. /* Check for a valid HTTP version key */
  9664. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9665. /* Invalid request */
  9666. return -1;
  9667. }
  9668. ri->http_version += 5;
  9669. /* Check for a valid http method */
  9670. if (!is_valid_http_method(ri->request_method)) {
  9671. return -1;
  9672. }
  9673. /* Parse all HTTP headers */
  9674. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9675. if (ri->num_headers < 0) {
  9676. /* Error while parsing headers */
  9677. return -1;
  9678. }
  9679. return request_length + init_skip;
  9680. }
  9681. static int
  9682. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9683. {
  9684. int response_length;
  9685. int init_skip = 0;
  9686. char *tmp, *tmp2;
  9687. long l;
  9688. /* Initialize elements. */
  9689. ri->http_version = ri->status_text = NULL;
  9690. ri->num_headers = ri->status_code = 0;
  9691. /* RFC says that all initial whitespaces should be ignored */
  9692. /* This included all leading \r and \n (isspace) */
  9693. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9694. while ((len > 0) && isspace((unsigned char)*buf)) {
  9695. buf++;
  9696. len--;
  9697. init_skip++;
  9698. }
  9699. if (len == 0) {
  9700. /* Incomplete request */
  9701. return 0;
  9702. }
  9703. /* Control characters are not allowed, including zero */
  9704. if (iscntrl((unsigned char)*buf)) {
  9705. return -1;
  9706. }
  9707. /* Find end of HTTP header */
  9708. response_length = get_http_header_len(buf, len);
  9709. if (response_length <= 0) {
  9710. return response_length;
  9711. }
  9712. buf[response_length - 1] = '\0';
  9713. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9714. return -1;
  9715. }
  9716. /* The first word is the HTTP version */
  9717. /* Check for a valid HTTP version key */
  9718. if (strncmp(buf, "HTTP/", 5) != 0) {
  9719. /* Invalid request */
  9720. return -1;
  9721. }
  9722. buf += 5;
  9723. if (!isgraph((unsigned char)buf[0])) {
  9724. /* Invalid request */
  9725. return -1;
  9726. }
  9727. ri->http_version = buf;
  9728. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9729. return -1;
  9730. }
  9731. /* The second word is the status as a number */
  9732. tmp = buf;
  9733. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9734. return -1;
  9735. }
  9736. l = strtol(tmp, &tmp2, 10);
  9737. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9738. /* Everything else but a 3 digit code is invalid */
  9739. return -1;
  9740. }
  9741. ri->status_code = (int)l;
  9742. /* The rest of the line is the status text */
  9743. ri->status_text = buf;
  9744. /* Find end of status text */
  9745. /* isgraph or isspace = isprint */
  9746. while (isprint((unsigned char)*buf)) {
  9747. buf++;
  9748. }
  9749. if ((*buf != '\r') && (*buf != '\n')) {
  9750. return -1;
  9751. }
  9752. /* Terminate string and forward buf to next line */
  9753. do {
  9754. *buf = 0;
  9755. buf++;
  9756. } while (isspace((unsigned char)*buf));
  9757. /* Parse all HTTP headers */
  9758. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9759. if (ri->num_headers < 0) {
  9760. /* Error while parsing headers */
  9761. return -1;
  9762. }
  9763. return response_length + init_skip;
  9764. }
  9765. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9766. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9767. * buffer (which marks the end of HTTP request). Buffer buf may already
  9768. * have some data. The length of the data is stored in nread.
  9769. * Upon every read operation, increase nread by the number of bytes read. */
  9770. static int
  9771. read_message(FILE *fp,
  9772. struct mg_connection *conn,
  9773. char *buf,
  9774. int bufsiz,
  9775. int *nread)
  9776. {
  9777. int request_len, n = 0;
  9778. struct timespec last_action_time;
  9779. double request_timeout;
  9780. if (!conn) {
  9781. return 0;
  9782. }
  9783. memset(&last_action_time, 0, sizeof(last_action_time));
  9784. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9785. /* value of request_timeout is in seconds, config in milliseconds */
  9786. request_timeout =
  9787. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9788. } else {
  9789. request_timeout =
  9790. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9791. / 1000.0;
  9792. }
  9793. if (conn->handled_requests > 0) {
  9794. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9795. request_timeout =
  9796. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9797. / 1000.0;
  9798. }
  9799. }
  9800. request_len = get_http_header_len(buf, *nread);
  9801. while (request_len == 0) {
  9802. /* Full request not yet received */
  9803. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9804. /* Server is to be stopped. */
  9805. return -1;
  9806. }
  9807. if (*nread >= bufsiz) {
  9808. /* Request too long */
  9809. return -2;
  9810. }
  9811. n = pull_inner(
  9812. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9813. if (n == -2) {
  9814. /* Receive error */
  9815. return -1;
  9816. }
  9817. /* update clock after every read request */
  9818. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9819. if (n > 0) {
  9820. *nread += n;
  9821. request_len = get_http_header_len(buf, *nread);
  9822. }
  9823. if ((n <= 0) && (request_timeout >= 0)) {
  9824. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9825. > request_timeout) {
  9826. /* Timeout */
  9827. return -3;
  9828. }
  9829. }
  9830. }
  9831. return request_len;
  9832. }
  9833. #if !defined(NO_CGI) || !defined(NO_FILES)
  9834. static int
  9835. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9836. {
  9837. const char *expect;
  9838. char buf[MG_BUF_LEN];
  9839. int success = 0;
  9840. if (!conn) {
  9841. return 0;
  9842. }
  9843. expect = mg_get_header(conn, "Expect");
  9844. DEBUG_ASSERT(fp != NULL);
  9845. if (!fp) {
  9846. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9847. return 0;
  9848. }
  9849. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9850. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9851. */
  9852. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9853. } else {
  9854. if (expect != NULL) {
  9855. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9856. conn->status_code = 100;
  9857. } else {
  9858. conn->status_code = 200;
  9859. }
  9860. DEBUG_ASSERT(conn->consumed_content == 0);
  9861. if (conn->consumed_content != 0) {
  9862. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9863. return 0;
  9864. }
  9865. for (;;) {
  9866. int nread = mg_read(conn, buf, sizeof(buf));
  9867. if (nread <= 0) {
  9868. success = (nread == 0);
  9869. break;
  9870. }
  9871. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9872. break;
  9873. }
  9874. }
  9875. /* Each error code path in this function must send an error */
  9876. if (!success) {
  9877. /* NOTE: Maybe some data has already been sent. */
  9878. /* TODO (low): If some data has been sent, a correct error
  9879. * reply can no longer be sent, so just close the connection */
  9880. mg_send_http_error(conn, 500, "%s", "");
  9881. }
  9882. }
  9883. return success;
  9884. }
  9885. #endif
  9886. #if defined(USE_TIMERS)
  9887. #define TIMER_API static
  9888. #include "timer.inl"
  9889. #endif /* USE_TIMERS */
  9890. #if !defined(NO_CGI)
  9891. /* This structure helps to create an environment for the spawned CGI
  9892. * program.
  9893. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9894. * last element must be NULL.
  9895. * However, on Windows there is a requirement that all these
  9896. * VARIABLE=VALUE\0
  9897. * strings must reside in a contiguous buffer. The end of the buffer is
  9898. * marked by two '\0' characters.
  9899. * We satisfy both worlds: we create an envp array (which is vars), all
  9900. * entries are actually pointers inside buf. */
  9901. struct cgi_environment {
  9902. struct mg_connection *conn;
  9903. /* Data block */
  9904. char *buf; /* Environment buffer */
  9905. size_t buflen; /* Space available in buf */
  9906. size_t bufused; /* Space taken in buf */
  9907. /* Index block */
  9908. char **var; /* char **envp */
  9909. size_t varlen; /* Number of variables available in var */
  9910. size_t varused; /* Number of variables stored in var */
  9911. };
  9912. static void addenv(struct cgi_environment *env,
  9913. PRINTF_FORMAT_STRING(const char *fmt),
  9914. ...) PRINTF_ARGS(2, 3);
  9915. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9916. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9917. static void
  9918. addenv(struct cgi_environment *env, const char *fmt, ...)
  9919. {
  9920. size_t i, n, space;
  9921. int truncated = 0;
  9922. char *added;
  9923. va_list ap;
  9924. if ((env->varlen - env->varused) < 2) {
  9925. mg_cry_internal(env->conn,
  9926. "%s: Cannot register CGI variable [%s]",
  9927. __func__,
  9928. fmt);
  9929. return;
  9930. }
  9931. /* Calculate how much space is left in the buffer */
  9932. space = (env->buflen - env->bufused);
  9933. do {
  9934. /* Space for "\0\0" is always needed. */
  9935. if (space <= 2) {
  9936. /* Allocate new buffer */
  9937. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9938. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9939. if (!added) {
  9940. /* Out of memory */
  9941. mg_cry_internal(
  9942. env->conn,
  9943. "%s: Cannot allocate memory for CGI variable [%s]",
  9944. __func__,
  9945. fmt);
  9946. return;
  9947. }
  9948. /* Retarget pointers */
  9949. env->buf = added;
  9950. env->buflen = n;
  9951. for (i = 0, n = 0; i < env->varused; i++) {
  9952. env->var[i] = added + n;
  9953. n += strlen(added + n) + 1;
  9954. }
  9955. space = (env->buflen - env->bufused);
  9956. }
  9957. /* Make a pointer to the free space int the buffer */
  9958. added = env->buf + env->bufused;
  9959. /* Copy VARIABLE=VALUE\0 string into the free space */
  9960. va_start(ap, fmt);
  9961. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9962. va_end(ap);
  9963. /* Do not add truncated strings to the environment */
  9964. if (truncated) {
  9965. /* Reallocate the buffer */
  9966. space = 0;
  9967. }
  9968. } while (truncated);
  9969. /* Calculate number of bytes added to the environment */
  9970. n = strlen(added) + 1;
  9971. env->bufused += n;
  9972. /* Append a pointer to the added string into the envp array */
  9973. env->var[env->varused] = added;
  9974. env->varused++;
  9975. }
  9976. /* Return 0 on success, non-zero if an error occurs. */
  9977. static int
  9978. prepare_cgi_environment(struct mg_connection *conn,
  9979. const char *prog,
  9980. struct cgi_environment *env,
  9981. int cgi_config_idx)
  9982. {
  9983. const char *s;
  9984. struct vec var_vec;
  9985. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9986. int i, truncated, uri_len;
  9987. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9988. return -1;
  9989. }
  9990. env->conn = conn;
  9991. env->buflen = CGI_ENVIRONMENT_SIZE;
  9992. env->bufused = 0;
  9993. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9994. if (env->buf == NULL) {
  9995. mg_cry_internal(conn,
  9996. "%s: Not enough memory for environmental buffer",
  9997. __func__);
  9998. return -1;
  9999. }
  10000. env->varlen = MAX_CGI_ENVIR_VARS;
  10001. env->varused = 0;
  10002. env->var =
  10003. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  10004. if (env->var == NULL) {
  10005. mg_cry_internal(conn,
  10006. "%s: Not enough memory for environmental variables",
  10007. __func__);
  10008. mg_free(env->buf);
  10009. return -1;
  10010. }
  10011. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10012. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10013. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10014. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10015. addenv(env,
  10016. "FALLBACK_DOCUMENT_ROOT=%s",
  10017. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10018. }
  10019. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10020. /* Prepare the environment block */
  10021. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10022. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10023. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10024. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10025. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10026. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10027. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10028. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10029. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10030. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10031. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10032. /* SCRIPT_NAME */
  10033. uri_len = (int)strlen(conn->request_info.local_uri);
  10034. if (conn->path_info == NULL) {
  10035. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10036. /* URI: /path_to_script/script.cgi */
  10037. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10038. } else {
  10039. /* URI: /path_to_script/ ... using index.cgi */
  10040. const char *index_file = strrchr(prog, '/');
  10041. if (index_file) {
  10042. addenv(env,
  10043. "SCRIPT_NAME=%s%s",
  10044. conn->request_info.local_uri,
  10045. index_file + 1);
  10046. }
  10047. }
  10048. } else {
  10049. /* URI: /path_to_script/script.cgi/path_info */
  10050. addenv(env,
  10051. "SCRIPT_NAME=%.*s",
  10052. uri_len - (int)strlen(conn->path_info),
  10053. conn->request_info.local_uri);
  10054. }
  10055. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10056. if (conn->path_info == NULL) {
  10057. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10058. } else {
  10059. addenv(env,
  10060. "PATH_TRANSLATED=%s%s",
  10061. conn->dom_ctx->config[DOCUMENT_ROOT],
  10062. conn->path_info);
  10063. }
  10064. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10065. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10066. addenv(env, "CONTENT_TYPE=%s", s);
  10067. }
  10068. if (conn->request_info.query_string != NULL) {
  10069. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10070. }
  10071. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10072. addenv(env, "CONTENT_LENGTH=%s", s);
  10073. }
  10074. if ((s = getenv("PATH")) != NULL) {
  10075. addenv(env, "PATH=%s", s);
  10076. }
  10077. if (conn->path_info != NULL) {
  10078. addenv(env, "PATH_INFO=%s", conn->path_info);
  10079. }
  10080. if (conn->status_code > 0) {
  10081. /* CGI error handler should show the status code */
  10082. addenv(env, "STATUS=%d", conn->status_code);
  10083. }
  10084. #if defined(_WIN32)
  10085. if ((s = getenv("COMSPEC")) != NULL) {
  10086. addenv(env, "COMSPEC=%s", s);
  10087. }
  10088. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10089. addenv(env, "SYSTEMROOT=%s", s);
  10090. }
  10091. if ((s = getenv("SystemDrive")) != NULL) {
  10092. addenv(env, "SystemDrive=%s", s);
  10093. }
  10094. if ((s = getenv("ProgramFiles")) != NULL) {
  10095. addenv(env, "ProgramFiles=%s", s);
  10096. }
  10097. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10098. addenv(env, "ProgramFiles(x86)=%s", s);
  10099. }
  10100. #else
  10101. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10102. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10103. }
  10104. #endif /* _WIN32 */
  10105. if ((s = getenv("PERLLIB")) != NULL) {
  10106. addenv(env, "PERLLIB=%s", s);
  10107. }
  10108. if (conn->request_info.remote_user != NULL) {
  10109. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10110. addenv(env, "%s", "AUTH_TYPE=Digest");
  10111. }
  10112. /* Add all headers as HTTP_* variables */
  10113. for (i = 0; i < conn->request_info.num_headers; i++) {
  10114. (void)mg_snprintf(conn,
  10115. &truncated,
  10116. http_var_name,
  10117. sizeof(http_var_name),
  10118. "HTTP_%s",
  10119. conn->request_info.http_headers[i].name);
  10120. if (truncated) {
  10121. mg_cry_internal(conn,
  10122. "%s: HTTP header variable too long [%s]",
  10123. __func__,
  10124. conn->request_info.http_headers[i].name);
  10125. continue;
  10126. }
  10127. /* Convert variable name into uppercase, and change - to _ */
  10128. for (p = http_var_name; *p != '\0'; p++) {
  10129. if (*p == '-') {
  10130. *p = '_';
  10131. }
  10132. *p = (char)toupper((unsigned char)*p);
  10133. }
  10134. addenv(env,
  10135. "%s=%s",
  10136. http_var_name,
  10137. conn->request_info.http_headers[i].value);
  10138. }
  10139. /* Add user-specified variables */
  10140. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10141. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10142. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10143. }
  10144. env->var[env->varused] = NULL;
  10145. env->buf[env->bufused] = '\0';
  10146. return 0;
  10147. }
  10148. /* Data for CGI process control: PID and number of references */
  10149. struct process_control_data {
  10150. pid_t pid;
  10151. ptrdiff_t references;
  10152. };
  10153. static int
  10154. abort_cgi_process(void *data)
  10155. {
  10156. /* Waitpid checks for child status and won't work for a pid that does
  10157. * not identify a child of the current process. Thus, if the pid is
  10158. * reused, we will not affect a different process. */
  10159. struct process_control_data *proc = (struct process_control_data *)data;
  10160. int status = 0;
  10161. ptrdiff_t refs;
  10162. pid_t ret_pid;
  10163. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10164. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10165. /* Stop child process */
  10166. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10167. kill(proc->pid, SIGABRT);
  10168. /* Wait until process is terminated (don't leave zombies) */
  10169. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10170. ;
  10171. } else {
  10172. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10173. }
  10174. /* Dec reference counter */
  10175. refs = mg_atomic_dec(&proc->references);
  10176. if (refs == 0) {
  10177. /* no more references - free data */
  10178. mg_free(data);
  10179. }
  10180. return 0;
  10181. }
  10182. /* Local (static) function assumes all arguments are valid. */
  10183. static void
  10184. handle_cgi_request(struct mg_connection *conn,
  10185. const char *prog,
  10186. int cgi_config_idx)
  10187. {
  10188. char *buf;
  10189. size_t buflen;
  10190. int headers_len, data_len, i, truncated;
  10191. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10192. const char *status, *status_text;
  10193. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10194. struct mg_request_info ri;
  10195. struct cgi_environment blk;
  10196. FILE *in = NULL, *out = NULL, *err = NULL;
  10197. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10198. pid_t pid = (pid_t)-1;
  10199. struct process_control_data *proc = NULL;
  10200. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10201. int no_buffering = 0;
  10202. #if defined(USE_TIMERS)
  10203. double cgi_timeout;
  10204. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10205. /* Get timeout in seconds */
  10206. cgi_timeout =
  10207. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10208. } else {
  10209. cgi_timeout =
  10210. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10211. }
  10212. #endif
  10213. if (cfg_buffering != NULL) {
  10214. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10215. no_buffering = 1;
  10216. }
  10217. }
  10218. buf = NULL;
  10219. buflen = conn->phys_ctx->max_request_size;
  10220. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10221. if (i != 0) {
  10222. blk.buf = NULL;
  10223. blk.var = NULL;
  10224. goto done;
  10225. }
  10226. /* CGI must be executed in its own directory. 'dir' must point to the
  10227. * directory containing executable program, 'p' must point to the
  10228. * executable program name relative to 'dir'. */
  10229. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10230. if (truncated) {
  10231. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10232. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10233. goto done;
  10234. }
  10235. if ((p = strrchr(dir, '/')) != NULL) {
  10236. *p++ = '\0';
  10237. } else {
  10238. dir[0] = '.';
  10239. dir[1] = '\0';
  10240. p = (char *)prog;
  10241. }
  10242. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10243. status = strerror(ERRNO);
  10244. mg_cry_internal(
  10245. conn,
  10246. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10247. prog,
  10248. status);
  10249. mg_send_http_error(conn,
  10250. 500,
  10251. "Error: Cannot create CGI pipe: %s",
  10252. status);
  10253. goto done;
  10254. }
  10255. proc = (struct process_control_data *)
  10256. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10257. if (proc == NULL) {
  10258. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10259. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10260. goto done;
  10261. }
  10262. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10263. pid = spawn_process(
  10264. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10265. if (pid == (pid_t)-1) {
  10266. status = strerror(ERRNO);
  10267. mg_cry_internal(
  10268. conn,
  10269. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10270. prog,
  10271. status);
  10272. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10273. mg_free(proc);
  10274. proc = NULL;
  10275. goto done;
  10276. }
  10277. /* Store data in shared process_control_data */
  10278. proc->pid = pid;
  10279. proc->references = 1;
  10280. #if defined(USE_TIMERS)
  10281. if (cgi_timeout > 0.0) {
  10282. proc->references = 2;
  10283. // Start a timer for CGI
  10284. timer_add(conn->phys_ctx,
  10285. cgi_timeout /* in seconds */,
  10286. 0.0,
  10287. 1,
  10288. abort_cgi_process,
  10289. (void *)proc,
  10290. NULL);
  10291. }
  10292. #endif
  10293. /* Parent closes only one side of the pipes.
  10294. * If we don't mark them as closed, close() attempt before
  10295. * return from this function throws an exception on Windows.
  10296. * Windows does not like when closed descriptor is closed again. */
  10297. (void)close(fdin[0]);
  10298. (void)close(fdout[1]);
  10299. (void)close(fderr[1]);
  10300. fdin[0] = fdout[1] = fderr[1] = -1;
  10301. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10302. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10303. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10304. status = strerror(ERRNO);
  10305. mg_cry_internal(conn,
  10306. "Error: CGI program \"%s\": Can not open fd: %s",
  10307. prog,
  10308. status);
  10309. mg_send_http_error(conn,
  10310. 500,
  10311. "Error: CGI can not open fd\nfdopen: %s",
  10312. status);
  10313. goto done;
  10314. }
  10315. setbuf(in, NULL);
  10316. setbuf(out, NULL);
  10317. setbuf(err, NULL);
  10318. fout.access.fp = out;
  10319. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10320. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10321. conn->content_len);
  10322. /* This is a POST/PUT request, or another request with body data. */
  10323. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10324. /* Error sending the body data */
  10325. mg_cry_internal(
  10326. conn,
  10327. "Error: CGI program \"%s\": Forward body data failed",
  10328. prog);
  10329. goto done;
  10330. }
  10331. }
  10332. /* Close so child gets an EOF. */
  10333. fclose(in);
  10334. in = NULL;
  10335. fdin[1] = -1;
  10336. /* Now read CGI reply into a buffer. We need to set correct
  10337. * status code, thus we need to see all HTTP headers first.
  10338. * Do not send anything back to client, until we buffer in all
  10339. * HTTP headers. */
  10340. data_len = 0;
  10341. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10342. if (buf == NULL) {
  10343. mg_send_http_error(conn,
  10344. 500,
  10345. "Error: Not enough memory for CGI buffer (%u bytes)",
  10346. (unsigned int)buflen);
  10347. mg_cry_internal(
  10348. conn,
  10349. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10350. "bytes)",
  10351. prog,
  10352. (unsigned int)buflen);
  10353. goto done;
  10354. }
  10355. DEBUG_TRACE("CGI: %s", "wait for response");
  10356. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10357. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10358. if (headers_len <= 0) {
  10359. /* Could not parse the CGI response. Check if some error message on
  10360. * stderr. */
  10361. i = pull_all(err, conn, buf, (int)buflen);
  10362. if (i > 0) {
  10363. /* CGI program explicitly sent an error */
  10364. /* Write the error message to the internal log */
  10365. mg_cry_internal(conn,
  10366. "Error: CGI program \"%s\" sent error "
  10367. "message: [%.*s]",
  10368. prog,
  10369. i,
  10370. buf);
  10371. /* Don't send the error message back to the client */
  10372. mg_send_http_error(conn,
  10373. 500,
  10374. "Error: CGI program \"%s\" failed.",
  10375. prog);
  10376. } else {
  10377. /* CGI program did not explicitly send an error, but a broken
  10378. * respon header */
  10379. mg_cry_internal(conn,
  10380. "Error: CGI program sent malformed or too big "
  10381. "(>%u bytes) HTTP headers: [%.*s]",
  10382. (unsigned)buflen,
  10383. data_len,
  10384. buf);
  10385. mg_send_http_error(conn,
  10386. 500,
  10387. "Error: CGI program sent malformed or too big "
  10388. "(>%u bytes) HTTP headers: [%.*s]",
  10389. (unsigned)buflen,
  10390. data_len,
  10391. buf);
  10392. }
  10393. /* in both cases, abort processing CGI */
  10394. goto done;
  10395. }
  10396. pbuf = buf;
  10397. buf[headers_len - 1] = '\0';
  10398. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10399. /* Make up and send the status line */
  10400. status_text = "OK";
  10401. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10402. != NULL) {
  10403. conn->status_code = atoi(status);
  10404. status_text = status;
  10405. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10406. status_text++;
  10407. }
  10408. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10409. != NULL) {
  10410. conn->status_code = 307;
  10411. } else {
  10412. conn->status_code = 200;
  10413. }
  10414. if (!should_keep_alive(conn)) {
  10415. conn->must_close = 1;
  10416. }
  10417. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10418. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10419. /* Send headers */
  10420. for (i = 0; i < ri.num_headers; i++) {
  10421. DEBUG_TRACE("CGI header: %s: %s",
  10422. ri.http_headers[i].name,
  10423. ri.http_headers[i].value);
  10424. mg_printf(conn,
  10425. "%s: %s\r\n",
  10426. ri.http_headers[i].name,
  10427. ri.http_headers[i].value);
  10428. }
  10429. mg_write(conn, "\r\n", 2);
  10430. /* Send chunk of data that may have been read after the headers */
  10431. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10432. /* Read the rest of CGI output and send to the client */
  10433. DEBUG_TRACE("CGI: %s", "forward all data");
  10434. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10435. DEBUG_TRACE("CGI: %s", "all data sent");
  10436. done:
  10437. mg_free(blk.var);
  10438. mg_free(blk.buf);
  10439. if (pid != (pid_t)-1) {
  10440. abort_cgi_process((void *)proc);
  10441. }
  10442. if (fdin[0] != -1) {
  10443. close(fdin[0]);
  10444. }
  10445. if (fdout[1] != -1) {
  10446. close(fdout[1]);
  10447. }
  10448. if (fderr[1] != -1) {
  10449. close(fderr[1]);
  10450. }
  10451. if (in != NULL) {
  10452. fclose(in);
  10453. } else if (fdin[1] != -1) {
  10454. close(fdin[1]);
  10455. }
  10456. if (out != NULL) {
  10457. fclose(out);
  10458. } else if (fdout[0] != -1) {
  10459. close(fdout[0]);
  10460. }
  10461. if (err != NULL) {
  10462. fclose(err);
  10463. } else if (fderr[0] != -1) {
  10464. close(fderr[0]);
  10465. }
  10466. mg_free(buf);
  10467. }
  10468. #endif /* !NO_CGI */
  10469. #if !defined(NO_FILES)
  10470. static void
  10471. dav_mkcol(struct mg_connection *conn, const char *path)
  10472. {
  10473. int rc, body_len;
  10474. struct de de;
  10475. if (conn == NULL) {
  10476. return;
  10477. }
  10478. /* TODO (mid): Check the mg_send_http_error situations in this function
  10479. */
  10480. memset(&de.file, 0, sizeof(de.file));
  10481. if (!mg_stat(conn, path, &de.file)) {
  10482. mg_cry_internal(conn,
  10483. "%s: mg_stat(%s) failed: %s",
  10484. __func__,
  10485. path,
  10486. strerror(ERRNO));
  10487. }
  10488. if (de.file.last_modified) {
  10489. /* TODO (mid): This check does not seem to make any sense ! */
  10490. /* TODO (mid): Add a webdav unit test first, before changing
  10491. * anything here. */
  10492. mg_send_http_error(
  10493. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10494. return;
  10495. }
  10496. body_len = conn->data_len - conn->request_len;
  10497. if (body_len > 0) {
  10498. mg_send_http_error(
  10499. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10500. return;
  10501. }
  10502. rc = mg_mkdir(conn, path, 0755);
  10503. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10504. if (rc == 0) {
  10505. /* Create 201 "Created" response */
  10506. mg_response_header_start(conn, 201);
  10507. send_static_cache_header(conn);
  10508. send_additional_header(conn);
  10509. mg_response_header_add(conn, "Content-Length", "0", -1);
  10510. /* Send all headers - there is no body */
  10511. mg_response_header_send(conn);
  10512. } else {
  10513. int http_status = 500;
  10514. switch (errno) {
  10515. case EEXIST:
  10516. http_status = 405;
  10517. break;
  10518. case EACCES:
  10519. http_status = 403;
  10520. break;
  10521. case ENOENT:
  10522. http_status = 409;
  10523. break;
  10524. }
  10525. mg_send_http_error(conn,
  10526. http_status,
  10527. "Error processing %s: %s",
  10528. path,
  10529. strerror(ERRNO));
  10530. }
  10531. }
  10532. /* Forward decrlaration */
  10533. static int get_uri_type(const char *uri);
  10534. static const char *
  10535. get_rel_url_at_current_server(const char *uri,
  10536. const struct mg_connection *conn);
  10537. static void
  10538. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10539. {
  10540. const char *overwrite_hdr;
  10541. const char *destination_hdr;
  10542. const char *root;
  10543. int rc, dest_uri_type;
  10544. int http_status = 400;
  10545. int do_overwrite = 0;
  10546. int destination_ok = 0;
  10547. char dest_path[UTF8_PATH_MAX];
  10548. struct mg_file_stat ignored;
  10549. if (conn == NULL) {
  10550. return;
  10551. }
  10552. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10553. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10554. destination_hdr = mg_get_header(conn, "Destination");
  10555. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10556. do_overwrite = 1;
  10557. }
  10558. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10559. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10560. return;
  10561. }
  10562. if (root != NULL) {
  10563. char *local_dest = NULL;
  10564. dest_uri_type = get_uri_type(destination_hdr);
  10565. if (dest_uri_type == 2) {
  10566. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10567. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10568. const char *h =
  10569. get_rel_url_at_current_server(destination_hdr, conn);
  10570. if (h) {
  10571. size_t len = strlen(h);
  10572. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10573. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10574. }
  10575. }
  10576. if (local_dest != NULL) {
  10577. remove_dot_segments(local_dest);
  10578. if (local_dest[0] == '/') {
  10579. int trunc_check = 0;
  10580. mg_snprintf(conn,
  10581. &trunc_check,
  10582. dest_path,
  10583. sizeof(dest_path),
  10584. "%s/%s",
  10585. root,
  10586. local_dest);
  10587. if (trunc_check == 0) {
  10588. destination_ok = 1;
  10589. }
  10590. }
  10591. mg_free(local_dest);
  10592. }
  10593. }
  10594. if (!destination_ok) {
  10595. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10596. return;
  10597. }
  10598. /* Check now if this file exists */
  10599. if (mg_stat(conn, dest_path, &ignored)) {
  10600. /* File exists */
  10601. if (do_overwrite) {
  10602. /* Overwrite allowed: delete the file first */
  10603. if (0 != remove(dest_path)) {
  10604. /* No overwrite: return error */
  10605. mg_send_http_error(conn,
  10606. 403,
  10607. "Cannot overwrite file: %s",
  10608. dest_path);
  10609. return;
  10610. }
  10611. } else {
  10612. /* No overwrite: return error */
  10613. mg_send_http_error(conn,
  10614. 412,
  10615. "Destination already exists: %s",
  10616. dest_path);
  10617. return;
  10618. }
  10619. }
  10620. /* Copy / Move / Rename operation. */
  10621. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10622. #if defined(_WIN32)
  10623. {
  10624. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10625. wchar_t wSource[UTF16_PATH_MAX];
  10626. wchar_t wDest[UTF16_PATH_MAX];
  10627. BOOL ok;
  10628. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10629. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10630. if (do_copy) {
  10631. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10632. } else {
  10633. ok = MoveFileExW(wSource,
  10634. wDest,
  10635. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10636. }
  10637. if (ok) {
  10638. rc = 0;
  10639. } else {
  10640. DWORD lastErr = GetLastError();
  10641. if (lastErr == ERROR_ALREADY_EXISTS) {
  10642. mg_send_http_error(conn,
  10643. 412,
  10644. "Destination already exists: %s",
  10645. dest_path);
  10646. return;
  10647. }
  10648. rc = -1;
  10649. http_status = 400;
  10650. }
  10651. }
  10652. #else
  10653. {
  10654. /* Linux uses already UTF-8, we don't need to convert file names. */
  10655. if (do_copy) {
  10656. /* TODO: COPY for Linux. */
  10657. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10658. return;
  10659. }
  10660. rc = rename(path, dest_path);
  10661. if (rc) {
  10662. switch (errno) {
  10663. case EEXIST:
  10664. http_status = 412;
  10665. break;
  10666. case EACCES:
  10667. http_status = 403;
  10668. break;
  10669. case ENOENT:
  10670. http_status = 409;
  10671. break;
  10672. }
  10673. }
  10674. }
  10675. #endif
  10676. if (rc == 0) {
  10677. /* Create 204 "No Content" response */
  10678. mg_response_header_start(conn, 204);
  10679. mg_response_header_add(conn, "Content-Length", "0", -1);
  10680. /* Send all headers - there is no body */
  10681. mg_response_header_send(conn);
  10682. } else {
  10683. mg_send_http_error(conn, http_status, "Operation failed");
  10684. }
  10685. }
  10686. static void
  10687. put_file(struct mg_connection *conn, const char *path)
  10688. {
  10689. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10690. const char *range;
  10691. int64_t r1, r2;
  10692. int rc;
  10693. if (conn == NULL) {
  10694. return;
  10695. }
  10696. DEBUG_TRACE("store %s", path);
  10697. if (mg_stat(conn, path, &file.stat)) {
  10698. /* File already exists */
  10699. conn->status_code = 200;
  10700. if (file.stat.is_directory) {
  10701. /* This is an already existing directory,
  10702. * so there is nothing to do for the server. */
  10703. rc = 0;
  10704. } else {
  10705. /* File exists and is not a directory. */
  10706. /* Can it be replaced? */
  10707. /* Check if the server may write this file */
  10708. if (access(path, W_OK) == 0) {
  10709. /* Access granted */
  10710. rc = 1;
  10711. } else {
  10712. mg_send_http_error(
  10713. conn,
  10714. 403,
  10715. "Error: Put not possible\nReplacing %s is not allowed",
  10716. path);
  10717. return;
  10718. }
  10719. }
  10720. } else {
  10721. /* File should be created */
  10722. conn->status_code = 201;
  10723. rc = put_dir(conn, path);
  10724. }
  10725. if (rc == 0) {
  10726. /* put_dir returns 0 if path is a directory */
  10727. /* Create response */
  10728. mg_response_header_start(conn, conn->status_code);
  10729. send_no_cache_header(conn);
  10730. send_additional_header(conn);
  10731. mg_response_header_add(conn, "Content-Length", "0", -1);
  10732. /* Send all headers - there is no body */
  10733. mg_response_header_send(conn);
  10734. /* Request to create a directory has been fulfilled successfully.
  10735. * No need to put a file. */
  10736. return;
  10737. }
  10738. if (rc == -1) {
  10739. /* put_dir returns -1 if the path is too long */
  10740. mg_send_http_error(conn,
  10741. 414,
  10742. "Error: Path too long\nput_dir(%s): %s",
  10743. path,
  10744. strerror(ERRNO));
  10745. return;
  10746. }
  10747. if (rc == -2) {
  10748. /* put_dir returns -2 if the directory can not be created */
  10749. mg_send_http_error(conn,
  10750. 500,
  10751. "Error: Can not create directory\nput_dir(%s): %s",
  10752. path,
  10753. strerror(ERRNO));
  10754. return;
  10755. }
  10756. /* A file should be created or overwritten. */
  10757. /* Currently CivetWeb does not need read+write access. */
  10758. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10759. || file.access.fp == NULL) {
  10760. (void)mg_fclose(&file.access);
  10761. mg_send_http_error(conn,
  10762. 500,
  10763. "Error: Can not create file\nfopen(%s): %s",
  10764. path,
  10765. strerror(ERRNO));
  10766. return;
  10767. }
  10768. fclose_on_exec(&file.access, conn);
  10769. range = mg_get_header(conn, "Content-Range");
  10770. r1 = r2 = 0;
  10771. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10772. conn->status_code = 206; /* Partial content */
  10773. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10774. mg_send_http_error(conn,
  10775. 500,
  10776. "Error: Internal error processing file %s",
  10777. path);
  10778. return;
  10779. }
  10780. }
  10781. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10782. /* forward_body_data failed.
  10783. * The error code has already been sent to the client,
  10784. * and conn->status_code is already set. */
  10785. (void)mg_fclose(&file.access);
  10786. return;
  10787. }
  10788. if (mg_fclose(&file.access) != 0) {
  10789. /* fclose failed. This might have different reasons, but a likely
  10790. * one is "no space on disk", http 507. */
  10791. conn->status_code = 507;
  10792. }
  10793. /* Create response (status_code has been set before) */
  10794. mg_response_header_start(conn, conn->status_code);
  10795. send_no_cache_header(conn);
  10796. send_additional_header(conn);
  10797. mg_response_header_add(conn, "Content-Length", "0", -1);
  10798. /* Send all headers - there is no body */
  10799. mg_response_header_send(conn);
  10800. }
  10801. static void
  10802. delete_file(struct mg_connection *conn, const char *path)
  10803. {
  10804. struct de de;
  10805. memset(&de.file, 0, sizeof(de.file));
  10806. if (!mg_stat(conn, path, &de.file)) {
  10807. /* mg_stat returns 0 if the file does not exist */
  10808. mg_send_http_error(conn,
  10809. 404,
  10810. "Error: Cannot delete file\nFile %s not found",
  10811. path);
  10812. return;
  10813. }
  10814. DEBUG_TRACE("delete %s", path);
  10815. if (de.file.is_directory) {
  10816. if (remove_directory(conn, path)) {
  10817. /* Delete is successful: Return 204 without content. */
  10818. mg_send_http_error(conn, 204, "%s", "");
  10819. } else {
  10820. /* Delete is not successful: Return 500 (Server error). */
  10821. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10822. }
  10823. return;
  10824. }
  10825. /* This is an existing file (not a directory).
  10826. * Check if write permission is granted. */
  10827. if (access(path, W_OK) != 0) {
  10828. /* File is read only */
  10829. mg_send_http_error(
  10830. conn,
  10831. 403,
  10832. "Error: Delete not possible\nDeleting %s is not allowed",
  10833. path);
  10834. return;
  10835. }
  10836. /* Try to delete it. */
  10837. if (mg_remove(conn, path) == 0) {
  10838. /* Delete was successful: Return 204 without content. */
  10839. mg_response_header_start(conn, 204);
  10840. send_no_cache_header(conn);
  10841. send_additional_header(conn);
  10842. mg_response_header_add(conn, "Content-Length", "0", -1);
  10843. mg_response_header_send(conn);
  10844. } else {
  10845. /* Delete not successful (file locked). */
  10846. mg_send_http_error(conn,
  10847. 423,
  10848. "Error: Cannot delete file\nremove(%s): %s",
  10849. path,
  10850. strerror(ERRNO));
  10851. }
  10852. }
  10853. #endif /* !NO_FILES */
  10854. #if !defined(NO_FILESYSTEMS)
  10855. static void
  10856. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10857. static void
  10858. do_ssi_include(struct mg_connection *conn,
  10859. const char *ssi,
  10860. char *tag,
  10861. int include_level)
  10862. {
  10863. char file_name[MG_BUF_LEN], path[512], *p;
  10864. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10865. size_t len;
  10866. int truncated = 0;
  10867. if (conn == NULL) {
  10868. return;
  10869. }
  10870. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10871. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10872. * always < MG_BUF_LEN. */
  10873. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10874. /* File name is relative to the webserver root */
  10875. file_name[511] = 0;
  10876. (void)mg_snprintf(conn,
  10877. &truncated,
  10878. path,
  10879. sizeof(path),
  10880. "%s/%s",
  10881. conn->dom_ctx->config[DOCUMENT_ROOT],
  10882. file_name);
  10883. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10884. /* File name is relative to the webserver working directory
  10885. * or it is absolute system path */
  10886. file_name[511] = 0;
  10887. (void)
  10888. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10889. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10890. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10891. /* File name is relative to the current document */
  10892. file_name[511] = 0;
  10893. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10894. if (!truncated) {
  10895. if ((p = strrchr(path, '/')) != NULL) {
  10896. p[1] = '\0';
  10897. }
  10898. len = strlen(path);
  10899. (void)mg_snprintf(conn,
  10900. &truncated,
  10901. path + len,
  10902. sizeof(path) - len,
  10903. "%s",
  10904. file_name);
  10905. }
  10906. } else {
  10907. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10908. return;
  10909. }
  10910. if (truncated) {
  10911. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10912. return;
  10913. }
  10914. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10915. mg_cry_internal(conn,
  10916. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10917. tag,
  10918. path,
  10919. strerror(ERRNO));
  10920. } else {
  10921. fclose_on_exec(&file.access, conn);
  10922. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10923. > 0) {
  10924. send_ssi_file(conn, path, &file, include_level + 1);
  10925. } else {
  10926. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10927. }
  10928. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10929. }
  10930. }
  10931. #if !defined(NO_POPEN)
  10932. static void
  10933. do_ssi_exec(struct mg_connection *conn, char *tag)
  10934. {
  10935. char cmd[1024] = "";
  10936. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10937. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10938. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10939. } else {
  10940. cmd[1023] = 0;
  10941. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10942. mg_cry_internal(conn,
  10943. "Cannot SSI #exec: [%s]: %s",
  10944. cmd,
  10945. strerror(ERRNO));
  10946. } else {
  10947. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10948. pclose(file.access.fp);
  10949. }
  10950. }
  10951. }
  10952. #endif /* !NO_POPEN */
  10953. static int
  10954. mg_fgetc(struct mg_file *filep)
  10955. {
  10956. if (filep == NULL) {
  10957. return EOF;
  10958. }
  10959. if (filep->access.fp != NULL) {
  10960. return fgetc(filep->access.fp);
  10961. } else {
  10962. return EOF;
  10963. }
  10964. }
  10965. static void
  10966. send_ssi_file(struct mg_connection *conn,
  10967. const char *path,
  10968. struct mg_file *filep,
  10969. int include_level)
  10970. {
  10971. char buf[MG_BUF_LEN];
  10972. int ch, len, in_tag, in_ssi_tag;
  10973. if (include_level > 10) {
  10974. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10975. return;
  10976. }
  10977. in_tag = in_ssi_tag = len = 0;
  10978. /* Read file, byte by byte, and look for SSI include tags */
  10979. while ((ch = mg_fgetc(filep)) != EOF) {
  10980. if (in_tag) {
  10981. /* We are in a tag, either SSI tag or html tag */
  10982. if (ch == '>') {
  10983. /* Tag is closing */
  10984. buf[len++] = '>';
  10985. if (in_ssi_tag) {
  10986. /* Handle SSI tag */
  10987. buf[len] = 0;
  10988. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10989. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10990. #if !defined(NO_POPEN)
  10991. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10992. do_ssi_exec(conn, buf + 9);
  10993. #endif /* !NO_POPEN */
  10994. } else {
  10995. mg_cry_internal(conn,
  10996. "%s: unknown SSI "
  10997. "command: \"%s\"",
  10998. path,
  10999. buf);
  11000. }
  11001. len = 0;
  11002. in_ssi_tag = in_tag = 0;
  11003. } else {
  11004. /* Not an SSI tag */
  11005. /* Flush buffer */
  11006. (void)mg_write(conn, buf, (size_t)len);
  11007. len = 0;
  11008. in_tag = 0;
  11009. }
  11010. } else {
  11011. /* Tag is still open */
  11012. buf[len++] = (char)(ch & 0xff);
  11013. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11014. /* All SSI tags start with <!--# */
  11015. in_ssi_tag = 1;
  11016. }
  11017. if ((len + 2) > (int)sizeof(buf)) {
  11018. /* Tag to long for buffer */
  11019. mg_cry_internal(conn, "%s: tag is too large", path);
  11020. return;
  11021. }
  11022. }
  11023. } else {
  11024. /* We are not in a tag yet. */
  11025. if (ch == '<') {
  11026. /* Tag is opening */
  11027. in_tag = 1;
  11028. if (len > 0) {
  11029. /* Flush current buffer.
  11030. * Buffer is filled with "len" bytes. */
  11031. (void)mg_write(conn, buf, (size_t)len);
  11032. }
  11033. /* Store the < */
  11034. len = 1;
  11035. buf[0] = '<';
  11036. } else {
  11037. /* No Tag */
  11038. /* Add data to buffer */
  11039. buf[len++] = (char)(ch & 0xff);
  11040. /* Flush if buffer is full */
  11041. if (len == (int)sizeof(buf)) {
  11042. mg_write(conn, buf, (size_t)len);
  11043. len = 0;
  11044. }
  11045. }
  11046. }
  11047. }
  11048. /* Send the rest of buffered data */
  11049. if (len > 0) {
  11050. mg_write(conn, buf, (size_t)len);
  11051. }
  11052. }
  11053. static void
  11054. handle_ssi_file_request(struct mg_connection *conn,
  11055. const char *path,
  11056. struct mg_file *filep)
  11057. {
  11058. char date[64];
  11059. time_t curtime = time(NULL);
  11060. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11061. return;
  11062. }
  11063. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11064. /* File exists (precondition for calling this function),
  11065. * but can not be opened by the server. */
  11066. mg_send_http_error(conn,
  11067. 500,
  11068. "Error: Cannot read file\nfopen(%s): %s",
  11069. path,
  11070. strerror(ERRNO));
  11071. } else {
  11072. /* Set "must_close" for HTTP/1.x, since we do not know the
  11073. * content length */
  11074. conn->must_close = 1;
  11075. gmt_time_string(date, sizeof(date), &curtime);
  11076. fclose_on_exec(&filep->access, conn);
  11077. /* 200 OK response */
  11078. mg_response_header_start(conn, 200);
  11079. send_no_cache_header(conn);
  11080. send_additional_header(conn);
  11081. send_cors_header(conn);
  11082. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11083. mg_response_header_send(conn);
  11084. /* Header sent, now send body */
  11085. send_ssi_file(conn, path, filep, 0);
  11086. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11087. }
  11088. }
  11089. #endif /* NO_FILESYSTEMS */
  11090. #if !defined(NO_FILES)
  11091. static void
  11092. send_options(struct mg_connection *conn)
  11093. {
  11094. if (!conn || !all_methods) {
  11095. return;
  11096. }
  11097. /* We do not set a "Cache-Control" header here, but leave the default.
  11098. * Since browsers do not send an OPTIONS request, we can not test the
  11099. * effect anyway. */
  11100. mg_response_header_start(conn, 200);
  11101. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11102. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11103. /* Use the same as before */
  11104. mg_response_header_add(conn, "Allow", all_methods, -1);
  11105. mg_response_header_add(conn, "DAV", "1", -1);
  11106. } else {
  11107. /* TODO: Check this later for HTTP/2 */
  11108. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11109. }
  11110. send_additional_header(conn);
  11111. mg_response_header_send(conn);
  11112. }
  11113. /* Writes PROPFIND properties for a collection element */
  11114. static int
  11115. print_props(struct mg_connection *conn,
  11116. const char *uri,
  11117. const char *name,
  11118. struct mg_file_stat *filep)
  11119. {
  11120. size_t i;
  11121. char mtime[64];
  11122. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11123. char *link_concat;
  11124. size_t link_concat_len;
  11125. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11126. return 0;
  11127. }
  11128. link_concat_len = strlen(uri) + strlen(name) + 1;
  11129. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11130. if (!link_concat) {
  11131. return 0;
  11132. }
  11133. strcpy(link_concat, uri);
  11134. strcat(link_concat, name);
  11135. /* Get full link used in request */
  11136. mg_construct_local_link(
  11137. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11138. /*
  11139. OutputDebugStringA("print_props:\n uri: ");
  11140. OutputDebugStringA(uri);
  11141. OutputDebugStringA("\n name: ");
  11142. OutputDebugStringA(name);
  11143. OutputDebugStringA("\n link: ");
  11144. OutputDebugStringA(link_buf);
  11145. OutputDebugStringA("\n");
  11146. */
  11147. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11148. mg_printf(conn,
  11149. "<d:response>"
  11150. "<d:href>%s</d:href>"
  11151. "<d:propstat>"
  11152. "<d:prop>"
  11153. "<d:resourcetype>%s</d:resourcetype>"
  11154. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11155. "<d:getlastmodified>%s</d:getlastmodified>"
  11156. "<d:lockdiscovery>",
  11157. link_buf,
  11158. filep->is_directory ? "<d:collection/>" : "",
  11159. filep->size,
  11160. mtime);
  11161. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11162. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11163. if (!strcmp(dav_lock[i].path, link_buf)) {
  11164. mg_printf(conn,
  11165. "<d:activelock>"
  11166. "<d:locktype><d:write/></d:locktype>"
  11167. "<d:lockscope><d:exclusive/></d:lockscope>"
  11168. "<d:depth>0</d:depth>"
  11169. "<d:owner>%s</d:owner>"
  11170. "<d:timeout>Second-%u</d:timeout>"
  11171. "<d:locktoken>"
  11172. "<d:href>%s</d:href>"
  11173. "</d:locktoken>"
  11174. "</d:activelock>\n",
  11175. dav_lock[i].user,
  11176. (unsigned)LOCK_DURATION_S,
  11177. dav_lock[i].token);
  11178. }
  11179. }
  11180. mg_printf(conn,
  11181. "</d:lockdiscovery>"
  11182. "</d:prop>"
  11183. "<d:status>HTTP/1.1 200 OK</d:status>"
  11184. "</d:propstat>"
  11185. "</d:response>\n");
  11186. mg_free(link_concat);
  11187. return 1;
  11188. }
  11189. static int
  11190. print_dav_dir_entry(struct de *de, void *data)
  11191. {
  11192. struct mg_connection *conn = (struct mg_connection *)data;
  11193. if (!de || !conn
  11194. || !print_props(
  11195. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11196. /* stop scan */
  11197. return 1;
  11198. }
  11199. return 0;
  11200. }
  11201. static void
  11202. handle_propfind(struct mg_connection *conn,
  11203. const char *path,
  11204. struct mg_file_stat *filep)
  11205. {
  11206. const char *depth = mg_get_header(conn, "Depth");
  11207. if (!conn || !path || !filep || !conn->dom_ctx) {
  11208. return;
  11209. }
  11210. /* return 207 "Multi-Status" */
  11211. conn->must_close = 1;
  11212. mg_response_header_start(conn, 207);
  11213. send_static_cache_header(conn);
  11214. send_additional_header(conn);
  11215. mg_response_header_add(conn,
  11216. "Content-Type",
  11217. "application/xml; charset=utf-8",
  11218. -1);
  11219. mg_response_header_send(conn);
  11220. /* Content */
  11221. mg_printf(conn,
  11222. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11223. "<d:multistatus xmlns:d='DAV:'>\n");
  11224. /* Print properties for the requested resource itself */
  11225. print_props(conn, conn->request_info.local_uri, "", filep);
  11226. /* If it is a directory, print directory entries too if Depth is not 0
  11227. */
  11228. if (filep->is_directory
  11229. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11230. "yes")
  11231. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11232. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11233. }
  11234. mg_printf(conn, "%s\n", "</d:multistatus>");
  11235. }
  11236. static void
  11237. dav_lock_file(struct mg_connection *conn, const char *path)
  11238. {
  11239. /* internal function - therefore conn is assumed to be valid */
  11240. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11241. uint64_t new_locktime;
  11242. int lock_index = -1;
  11243. int i;
  11244. uint64_t LOCK_DURATION_NS =
  11245. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11246. struct twebdav_lock *dav_lock = NULL;
  11247. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11248. || !conn->phys_ctx) {
  11249. return;
  11250. }
  11251. dav_lock = conn->phys_ctx->webdav_lock;
  11252. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11253. /* const char *refresh = mg_get_header(conn, "If"); */
  11254. /* Link refresh should have an "If" header:
  11255. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11256. * But it seems Windows Explorer does not send them.
  11257. */
  11258. mg_lock_context(conn->phys_ctx);
  11259. new_locktime = mg_get_current_time_ns();
  11260. /* Find a slot for a lock */
  11261. while (lock_index < 0) {
  11262. /* find existing lock */
  11263. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11264. if (!strcmp(dav_lock[i].path, link_buf)) {
  11265. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11266. /* locked by the same user */
  11267. dav_lock[i].locktime = new_locktime;
  11268. lock_index = i;
  11269. break;
  11270. } else {
  11271. /* already locked by someone else */
  11272. if (new_locktime
  11273. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11274. /* Lock expired */
  11275. dav_lock[i].path[0] = 0;
  11276. } else {
  11277. /* Lock still valid */
  11278. mg_unlock_context(conn->phys_ctx);
  11279. mg_send_http_error(conn, 423, "%s", "Already locked");
  11280. return;
  11281. }
  11282. }
  11283. }
  11284. }
  11285. /* create new lock token */
  11286. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11287. if (dav_lock[i].path[0] == 0) {
  11288. char s[32];
  11289. dav_lock[i].locktime = mg_get_current_time_ns();
  11290. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11291. mg_md5(dav_lock[i].token,
  11292. link_buf,
  11293. "\x01",
  11294. s,
  11295. "\x01",
  11296. conn->request_info.remote_user,
  11297. NULL);
  11298. mg_strlcpy(dav_lock[i].path,
  11299. link_buf,
  11300. sizeof(dav_lock[i].path));
  11301. mg_strlcpy(dav_lock[i].user,
  11302. conn->request_info.remote_user,
  11303. sizeof(dav_lock[i].user));
  11304. lock_index = i;
  11305. break;
  11306. }
  11307. }
  11308. if (lock_index < 0) {
  11309. /* too many locks. Find oldest lock */
  11310. uint64_t oldest_locktime = dav_lock[0].locktime;
  11311. lock_index = 0;
  11312. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11313. if (dav_lock[i].locktime < oldest_locktime) {
  11314. oldest_locktime = dav_lock[i].locktime;
  11315. lock_index = i;
  11316. }
  11317. }
  11318. /* invalidate oldest lock */
  11319. dav_lock[lock_index].path[0] = 0;
  11320. }
  11321. }
  11322. mg_unlock_context(conn->phys_ctx);
  11323. /* return 200 "OK" */
  11324. conn->must_close = 1;
  11325. mg_response_header_start(conn, 200);
  11326. send_static_cache_header(conn);
  11327. send_additional_header(conn);
  11328. mg_response_header_add(conn,
  11329. "Content-Type",
  11330. "application/xml; charset=utf-8",
  11331. -1);
  11332. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11333. mg_response_header_send(conn);
  11334. /* Content */
  11335. mg_printf(conn,
  11336. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11337. "<d:prop xmlns:d=\"DAV:\">\n"
  11338. " <d:lockdiscovery>\n"
  11339. " <d:activelock>\n"
  11340. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11341. " <d:locktype><d:write/></d:locktype>\n"
  11342. " <d:owner>\n"
  11343. " <d:href>%s</d:href>\n"
  11344. " </d:owner>\n"
  11345. " <d:timeout>Second-%u</d:timeout>\n"
  11346. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11347. " <d:lockroot>\n"
  11348. " <d:href>%s</d:href>\n"
  11349. " </d:lockroot>\n"
  11350. " </d:activelock>\n"
  11351. " </d:lockdiscovery>\n"
  11352. " </d:prop>\n",
  11353. dav_lock[lock_index].user,
  11354. (LOCK_DURATION_S),
  11355. dav_lock[lock_index].token,
  11356. dav_lock[lock_index].path);
  11357. }
  11358. static void
  11359. dav_unlock_file(struct mg_connection *conn, const char *path)
  11360. {
  11361. /* internal function - therefore conn is assumed to be valid */
  11362. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11363. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11364. int lock_index;
  11365. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11366. return;
  11367. }
  11368. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11369. mg_lock_context(conn->phys_ctx);
  11370. /* find existing lock */
  11371. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11372. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11373. /* Success: return 204 "No Content" */
  11374. mg_unlock_context(conn->phys_ctx);
  11375. conn->must_close = 1;
  11376. mg_response_header_start(conn, 204);
  11377. mg_response_header_send(conn);
  11378. return;
  11379. }
  11380. }
  11381. mg_unlock_context(conn->phys_ctx);
  11382. /* Error: Cannot unlock a resource that is not locked */
  11383. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11384. }
  11385. static void
  11386. dav_proppatch(struct mg_connection *conn, const char *path)
  11387. {
  11388. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11389. if (!conn || !path || !conn->dom_ctx) {
  11390. return;
  11391. }
  11392. /* return 207 "Multi-Status" */
  11393. conn->must_close = 1;
  11394. mg_response_header_start(conn, 207);
  11395. send_static_cache_header(conn);
  11396. send_additional_header(conn);
  11397. mg_response_header_add(conn,
  11398. "Content-Type",
  11399. "application/xml; charset=utf-8",
  11400. -1);
  11401. mg_response_header_send(conn);
  11402. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11403. /* Content */
  11404. mg_printf(conn,
  11405. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11406. "<d:multistatus xmlns:d='DAV:'>\n"
  11407. "<d:response>\n<d:href>%s</d:href>\n",
  11408. link_buf);
  11409. mg_printf(conn,
  11410. "<d:propstat><d:status>HTTP/1.1 403 "
  11411. "Forbidden</d:status></d:propstat>\n");
  11412. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11413. }
  11414. #endif
  11415. CIVETWEB_API void
  11416. mg_lock_connection(struct mg_connection *conn)
  11417. {
  11418. if (conn) {
  11419. (void)pthread_mutex_lock(&conn->mutex);
  11420. }
  11421. }
  11422. CIVETWEB_API void
  11423. mg_unlock_connection(struct mg_connection *conn)
  11424. {
  11425. if (conn) {
  11426. (void)pthread_mutex_unlock(&conn->mutex);
  11427. }
  11428. }
  11429. CIVETWEB_API void
  11430. mg_lock_context(struct mg_context *ctx)
  11431. {
  11432. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11433. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11434. }
  11435. }
  11436. CIVETWEB_API void
  11437. mg_unlock_context(struct mg_context *ctx)
  11438. {
  11439. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11440. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11441. }
  11442. }
  11443. #if defined(USE_LUA)
  11444. #include "mod_lua.inl"
  11445. #endif /* USE_LUA */
  11446. #if defined(USE_DUKTAPE)
  11447. #include "mod_duktape.inl"
  11448. #endif /* USE_DUKTAPE */
  11449. #if defined(USE_WEBSOCKET)
  11450. #if !defined(NO_SSL_DL)
  11451. #if !defined(OPENSSL_API_3_0)
  11452. #define SHA_API static
  11453. #include "sha1.inl"
  11454. #endif
  11455. #endif
  11456. static int
  11457. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11458. {
  11459. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11460. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11461. size_t dst_len = sizeof(b64_sha);
  11462. #if !defined(OPENSSL_API_3_0)
  11463. SHA_CTX sha_ctx;
  11464. #endif
  11465. int truncated;
  11466. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11467. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11468. if (truncated) {
  11469. conn->must_close = 1;
  11470. return 0;
  11471. }
  11472. DEBUG_TRACE("%s", "Send websocket handshake");
  11473. #if defined(OPENSSL_API_3_0)
  11474. EVP_Digest((unsigned char *)buf,
  11475. (uint32_t)strlen(buf),
  11476. (unsigned char *)sha,
  11477. NULL,
  11478. EVP_get_digestbyname("sha1"),
  11479. NULL);
  11480. #else
  11481. SHA1_Init(&sha_ctx);
  11482. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11483. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11484. #endif
  11485. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11486. mg_printf(conn,
  11487. "HTTP/1.1 101 Switching Protocols\r\n"
  11488. "Upgrade: websocket\r\n"
  11489. "Connection: Upgrade\r\n"
  11490. "Sec-WebSocket-Accept: %s\r\n",
  11491. b64_sha);
  11492. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11493. // Send negotiated compression extension parameters
  11494. websocket_deflate_response(conn);
  11495. #endif
  11496. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11497. mg_printf(conn,
  11498. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11499. conn->request_info.acceptedWebSocketSubprotocol);
  11500. } else {
  11501. mg_printf(conn, "%s", "\r\n");
  11502. }
  11503. return 1;
  11504. }
  11505. #if !defined(MG_MAX_UNANSWERED_PING)
  11506. /* Configuration of the maximum number of websocket PINGs that might
  11507. * stay unanswered before the connection is considered broken.
  11508. * Note: The name of this define may still change (until it is
  11509. * defined as a compile parameter in a documentation).
  11510. */
  11511. #define MG_MAX_UNANSWERED_PING (5)
  11512. #endif
  11513. static void
  11514. read_websocket(struct mg_connection *conn,
  11515. mg_websocket_data_handler ws_data_handler,
  11516. void *callback_data)
  11517. {
  11518. /* Pointer to the beginning of the portion of the incoming websocket
  11519. * message queue.
  11520. * The original websocket upgrade request is never removed, so the queue
  11521. * begins after it. */
  11522. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11523. int n, error, exit_by_callback;
  11524. int ret;
  11525. /* body_len is the length of the entire queue in bytes
  11526. * len is the length of the current message
  11527. * data_len is the length of the current message's data payload
  11528. * header_len is the length of the current message's header */
  11529. size_t i, len, mask_len = 0, header_len, body_len;
  11530. uint64_t data_len = 0;
  11531. /* "The masking key is a 32-bit value chosen at random by the client."
  11532. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11533. */
  11534. unsigned char mask[4];
  11535. /* data points to the place where the message is stored when passed to
  11536. * the websocket_data callback. This is either mem on the stack, or a
  11537. * dynamically allocated buffer if it is too large. */
  11538. unsigned char mem[4096];
  11539. unsigned char mop; /* mask flag and opcode */
  11540. /* Variables used for connection monitoring */
  11541. double timeout = -1.0;
  11542. int enable_ping_pong = 0;
  11543. int ping_count = 0;
  11544. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11545. enable_ping_pong =
  11546. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11547. "yes");
  11548. }
  11549. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11550. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11551. }
  11552. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11553. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11554. }
  11555. if (timeout <= 0.0) {
  11556. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11557. }
  11558. /* Enter data processing loop */
  11559. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11560. conn->request_info.remote_addr,
  11561. conn->request_info.remote_port);
  11562. conn->in_websocket_handling = 1;
  11563. mg_set_thread_name("wsock");
  11564. /* Loop continuously, reading messages from the socket, invoking the
  11565. * callback, and waiting repeatedly until an error occurs. */
  11566. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11567. && (!conn->must_close)) {
  11568. header_len = 0;
  11569. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11570. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11571. len = buf[1] & 127;
  11572. mask_len = (buf[1] & 128) ? 4 : 0;
  11573. if ((len < 126) && (body_len >= mask_len)) {
  11574. /* inline 7-bit length field */
  11575. data_len = len;
  11576. header_len = 2 + mask_len;
  11577. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11578. /* 16-bit length field */
  11579. header_len = 4 + mask_len;
  11580. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11581. } else if (body_len >= (10 + mask_len)) {
  11582. /* 64-bit length field */
  11583. uint32_t l1, l2;
  11584. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11585. memcpy(&l2, &buf[6], 4);
  11586. header_len = 10 + mask_len;
  11587. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11588. if (data_len > (uint64_t)0x7FFF0000ul) {
  11589. /* no can do */
  11590. mg_cry_internal(
  11591. conn,
  11592. "%s",
  11593. "websocket out of memory; closing connection");
  11594. break;
  11595. }
  11596. }
  11597. }
  11598. if ((header_len > 0) && (body_len >= header_len)) {
  11599. /* Allocate space to hold websocket payload */
  11600. unsigned char *data = mem;
  11601. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11602. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11603. conn->phys_ctx);
  11604. if (data == NULL) {
  11605. /* Allocation failed, exit the loop and then close the
  11606. * connection */
  11607. mg_cry_internal(
  11608. conn,
  11609. "%s",
  11610. "websocket out of memory; closing connection");
  11611. break;
  11612. }
  11613. }
  11614. /* Copy the mask before we shift the queue and destroy it */
  11615. if (mask_len > 0) {
  11616. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11617. } else {
  11618. memset(mask, 0, sizeof(mask));
  11619. }
  11620. /* Read frame payload from the first message in the queue into
  11621. * data and advance the queue by moving the memory in place. */
  11622. DEBUG_ASSERT(body_len >= header_len);
  11623. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11624. mop = buf[0]; /* current mask and opcode */
  11625. /* Overflow case */
  11626. len = body_len - header_len;
  11627. memcpy(data, buf + header_len, len);
  11628. error = 0;
  11629. while ((uint64_t)len < data_len) {
  11630. n = pull_inner(NULL,
  11631. conn,
  11632. (char *)(data + len),
  11633. (int)(data_len - len),
  11634. timeout);
  11635. if (n <= -2) {
  11636. error = 1;
  11637. break;
  11638. } else if (n > 0) {
  11639. len += (size_t)n;
  11640. } else {
  11641. /* Timeout: should retry */
  11642. /* TODO: retry condition */
  11643. }
  11644. }
  11645. if (error) {
  11646. mg_cry_internal(
  11647. conn,
  11648. "%s",
  11649. "Websocket pull failed; closing connection");
  11650. if (data != mem) {
  11651. mg_free(data);
  11652. }
  11653. break;
  11654. }
  11655. conn->data_len = conn->request_len;
  11656. } else {
  11657. mop = buf[0]; /* current mask and opcode, overwritten by
  11658. * memmove() */
  11659. /* Length of the message being read at the front of the
  11660. * queue. Cast to 31 bit is OK, since we limited
  11661. * data_len before. */
  11662. len = (size_t)data_len + header_len;
  11663. /* Copy the data payload into the data pointer for the
  11664. * callback. Cast to 31 bit is OK, since we
  11665. * limited data_len */
  11666. memcpy(data, buf + header_len, (size_t)data_len);
  11667. /* Move the queue forward len bytes */
  11668. memmove(buf, buf + len, body_len - len);
  11669. /* Mark the queue as advanced */
  11670. conn->data_len -= (int)len;
  11671. }
  11672. /* Apply mask if necessary */
  11673. if (mask_len > 0) {
  11674. for (i = 0; i < (size_t)data_len; i++) {
  11675. data[i] ^= mask[i & 3];
  11676. }
  11677. }
  11678. exit_by_callback = 0;
  11679. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11680. /* filter PONG messages */
  11681. DEBUG_TRACE("PONG from %s:%u",
  11682. conn->request_info.remote_addr,
  11683. conn->request_info.remote_port);
  11684. /* No unanwered PINGs left */
  11685. ping_count = 0;
  11686. } else if (enable_ping_pong
  11687. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11688. /* reply PING messages */
  11689. DEBUG_TRACE("Reply PING from %s:%u",
  11690. conn->request_info.remote_addr,
  11691. conn->request_info.remote_port);
  11692. ret = mg_websocket_write(conn,
  11693. MG_WEBSOCKET_OPCODE_PONG,
  11694. (char *)data,
  11695. (size_t)data_len);
  11696. if (ret <= 0) {
  11697. /* Error: send failed */
  11698. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11699. break;
  11700. }
  11701. } else {
  11702. /* Exit the loop if callback signals to exit (server side),
  11703. * or "connection close" opcode received (client side). */
  11704. if (ws_data_handler != NULL) {
  11705. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11706. if (mop & 0x40) {
  11707. /* Inflate the data received if bit RSV1 is set. */
  11708. if (!conn->websocket_deflate_initialized) {
  11709. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11710. exit_by_callback = 1;
  11711. }
  11712. if (!exit_by_callback) {
  11713. size_t inflate_buf_size_old = 0;
  11714. size_t inflate_buf_size =
  11715. data_len
  11716. * 4; // Initial guess of the inflated message
  11717. // size. We double the memory when needed.
  11718. Bytef *inflated = NULL;
  11719. Bytef *new_mem = NULL;
  11720. conn->websocket_inflate_state.avail_in =
  11721. (uInt)(data_len + 4);
  11722. conn->websocket_inflate_state.next_in = data;
  11723. // Add trailing 0x00 0x00 0xff 0xff bytes
  11724. data[data_len] = '\x00';
  11725. data[data_len + 1] = '\x00';
  11726. data[data_len + 2] = '\xff';
  11727. data[data_len + 3] = '\xff';
  11728. do {
  11729. if (inflate_buf_size_old == 0) {
  11730. new_mem =
  11731. (Bytef *)mg_calloc(inflate_buf_size,
  11732. sizeof(Bytef));
  11733. } else {
  11734. inflate_buf_size *= 2;
  11735. new_mem =
  11736. (Bytef *)mg_realloc(inflated,
  11737. inflate_buf_size);
  11738. }
  11739. if (new_mem == NULL) {
  11740. mg_cry_internal(
  11741. conn,
  11742. "Out of memory: Cannot allocate "
  11743. "inflate buffer of %lu bytes",
  11744. (unsigned long)inflate_buf_size);
  11745. exit_by_callback = 1;
  11746. break;
  11747. }
  11748. inflated = new_mem;
  11749. conn->websocket_inflate_state.avail_out =
  11750. (uInt)(inflate_buf_size
  11751. - inflate_buf_size_old);
  11752. conn->websocket_inflate_state.next_out =
  11753. inflated + inflate_buf_size_old;
  11754. ret = inflate(&conn->websocket_inflate_state,
  11755. Z_SYNC_FLUSH);
  11756. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11757. || ret == Z_MEM_ERROR) {
  11758. mg_cry_internal(
  11759. conn,
  11760. "ZLIB inflate error: %i %s",
  11761. ret,
  11762. (conn->websocket_inflate_state.msg
  11763. ? conn->websocket_inflate_state.msg
  11764. : "<no error message>"));
  11765. exit_by_callback = 1;
  11766. break;
  11767. }
  11768. inflate_buf_size_old = inflate_buf_size;
  11769. } while (conn->websocket_inflate_state.avail_out
  11770. == 0);
  11771. inflate_buf_size -=
  11772. conn->websocket_inflate_state.avail_out;
  11773. if (!ws_data_handler(conn,
  11774. mop,
  11775. (char *)inflated,
  11776. inflate_buf_size,
  11777. callback_data)) {
  11778. exit_by_callback = 1;
  11779. }
  11780. mg_free(inflated);
  11781. }
  11782. } else
  11783. #endif
  11784. if (!ws_data_handler(conn,
  11785. mop,
  11786. (char *)data,
  11787. (size_t)data_len,
  11788. callback_data)) {
  11789. exit_by_callback = 1;
  11790. }
  11791. }
  11792. }
  11793. /* It a buffer has been allocated, free it again */
  11794. if (data != mem) {
  11795. mg_free(data);
  11796. }
  11797. if (exit_by_callback) {
  11798. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11799. conn->request_info.remote_addr,
  11800. conn->request_info.remote_port);
  11801. break;
  11802. }
  11803. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11804. /* Opcode == 8, connection close */
  11805. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11806. conn->request_info.remote_addr,
  11807. conn->request_info.remote_port);
  11808. break;
  11809. }
  11810. /* Not breaking the loop, process next websocket frame. */
  11811. } else {
  11812. /* Read from the socket into the next available location in the
  11813. * message queue. */
  11814. n = pull_inner(NULL,
  11815. conn,
  11816. conn->buf + conn->data_len,
  11817. conn->buf_size - conn->data_len,
  11818. timeout);
  11819. if (n <= -2) {
  11820. /* Error, no bytes read */
  11821. DEBUG_TRACE("PULL from %s:%u failed",
  11822. conn->request_info.remote_addr,
  11823. conn->request_info.remote_port);
  11824. break;
  11825. }
  11826. if (n > 0) {
  11827. conn->data_len += n;
  11828. /* Reset open PING count */
  11829. ping_count = 0;
  11830. } else {
  11831. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11832. && (!conn->must_close)) {
  11833. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11834. /* Stop sending PING */
  11835. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11836. "- closing connection",
  11837. ping_count,
  11838. conn->request_info.remote_addr,
  11839. conn->request_info.remote_port);
  11840. break;
  11841. }
  11842. if (enable_ping_pong) {
  11843. /* Send Websocket PING message */
  11844. DEBUG_TRACE("PING to %s:%u",
  11845. conn->request_info.remote_addr,
  11846. conn->request_info.remote_port);
  11847. ret = mg_websocket_write(conn,
  11848. MG_WEBSOCKET_OPCODE_PING,
  11849. NULL,
  11850. 0);
  11851. if (ret <= 0) {
  11852. /* Error: send failed */
  11853. DEBUG_TRACE("Send PING failed (%i)", ret);
  11854. break;
  11855. }
  11856. ping_count++;
  11857. }
  11858. }
  11859. /* Timeout: should retry */
  11860. /* TODO: get timeout def */
  11861. }
  11862. }
  11863. }
  11864. /* Leave data processing loop */
  11865. mg_set_thread_name("worker");
  11866. conn->in_websocket_handling = 0;
  11867. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11868. conn->request_info.remote_addr,
  11869. conn->request_info.remote_port);
  11870. }
  11871. static int
  11872. mg_websocket_write_exec(struct mg_connection *conn,
  11873. int opcode,
  11874. const char *data,
  11875. size_t dataLen,
  11876. uint32_t masking_key)
  11877. {
  11878. unsigned char header[14];
  11879. size_t headerLen;
  11880. int retval;
  11881. #if defined(GCC_DIAGNOSTIC)
  11882. /* Disable spurious conversion warning for GCC */
  11883. #pragma GCC diagnostic push
  11884. #pragma GCC diagnostic ignored "-Wconversion"
  11885. #endif
  11886. /* Note that POSIX/Winsock's send() is threadsafe
  11887. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11888. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11889. * push(), although that is only a problem if the packet is large or
  11890. * outgoing buffer is full). */
  11891. /* TODO: Check if this lock should be moved to user land.
  11892. * Currently the server sets this lock for websockets, but
  11893. * not for any other connection. It must be set for every
  11894. * conn read/written by more than one thread, no matter if
  11895. * it is a websocket or regular connection. */
  11896. (void)mg_lock_connection(conn);
  11897. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11898. size_t deflated_size = 0;
  11899. Bytef *deflated = 0;
  11900. // Deflate websocket messages over 100kb
  11901. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11902. if (use_deflate) {
  11903. if (!conn->websocket_deflate_initialized) {
  11904. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11905. return 0;
  11906. }
  11907. // Deflating the message
  11908. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11909. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11910. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11911. deflated_size = (size_t)compressBound((uLong)dataLen);
  11912. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11913. if (deflated == NULL) {
  11914. mg_cry_internal(
  11915. conn,
  11916. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11917. (unsigned long)deflated_size);
  11918. mg_unlock_connection(conn);
  11919. return -1;
  11920. }
  11921. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11922. conn->websocket_deflate_state.next_out = deflated;
  11923. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11924. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11925. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11926. } else
  11927. #endif
  11928. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11929. #if defined(GCC_DIAGNOSTIC)
  11930. #pragma GCC diagnostic pop
  11931. #endif
  11932. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11933. if (dataLen < 126) {
  11934. /* inline 7-bit length field */
  11935. header[1] = (unsigned char)dataLen;
  11936. headerLen = 2;
  11937. } else if (dataLen <= 0xFFFF) {
  11938. /* 16-bit length field */
  11939. uint16_t len = htons((uint16_t)dataLen);
  11940. header[1] = 126;
  11941. memcpy(header + 2, &len, 2);
  11942. headerLen = 4;
  11943. } else {
  11944. /* 64-bit length field */
  11945. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11946. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11947. header[1] = 127;
  11948. memcpy(header + 2, &len1, 4);
  11949. memcpy(header + 6, &len2, 4);
  11950. headerLen = 10;
  11951. }
  11952. if (masking_key) {
  11953. /* add mask */
  11954. header[1] |= 0x80;
  11955. memcpy(header + headerLen, &masking_key, 4);
  11956. headerLen += 4;
  11957. }
  11958. retval = mg_write(conn, header, headerLen);
  11959. if (retval != (int)headerLen) {
  11960. /* Did not send complete header */
  11961. retval = -1;
  11962. } else {
  11963. if (dataLen > 0) {
  11964. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11965. if (use_deflate) {
  11966. retval = mg_write(conn, deflated, dataLen);
  11967. mg_free(deflated);
  11968. } else
  11969. #endif
  11970. retval = mg_write(conn, data, dataLen);
  11971. }
  11972. /* if dataLen == 0, the header length (2) is returned */
  11973. }
  11974. /* TODO: Remove this unlock as well, when lock is removed. */
  11975. mg_unlock_connection(conn);
  11976. return retval;
  11977. }
  11978. CIVETWEB_API int
  11979. mg_websocket_write(struct mg_connection *conn,
  11980. int opcode,
  11981. const char *data,
  11982. size_t dataLen)
  11983. {
  11984. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11985. }
  11986. static void
  11987. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11988. {
  11989. size_t i = 0;
  11990. i = 0;
  11991. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11992. /* Convert in 32 bit words, if data is 4 byte aligned */
  11993. while (i < (in_len - 3)) {
  11994. *(uint32_t *)(void *)(out + i) =
  11995. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11996. i += 4;
  11997. }
  11998. }
  11999. if (i != in_len) {
  12000. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  12001. while (i < in_len) {
  12002. *(uint8_t *)(void *)(out + i) =
  12003. *(uint8_t *)(void *)(in + i)
  12004. ^ *(((uint8_t *)&masking_key) + (i % 4));
  12005. i++;
  12006. }
  12007. }
  12008. }
  12009. CIVETWEB_API int
  12010. mg_websocket_client_write(struct mg_connection *conn,
  12011. int opcode,
  12012. const char *data,
  12013. size_t dataLen)
  12014. {
  12015. int retval = -1;
  12016. char *masked_data =
  12017. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12018. uint32_t masking_key = 0;
  12019. if (masked_data == NULL) {
  12020. /* Return -1 in an error case */
  12021. mg_cry_internal(conn,
  12022. "%s",
  12023. "Cannot allocate buffer for masked websocket response: "
  12024. "Out of memory");
  12025. return -1;
  12026. }
  12027. do {
  12028. /* Get a masking key - but not 0 */
  12029. masking_key = (uint32_t)get_random();
  12030. } while (masking_key == 0);
  12031. mask_data(data, dataLen, masking_key, masked_data);
  12032. retval = mg_websocket_write_exec(
  12033. conn, opcode, masked_data, dataLen, masking_key);
  12034. mg_free(masked_data);
  12035. return retval;
  12036. }
  12037. static void
  12038. handle_websocket_request(struct mg_connection *conn,
  12039. const char *path,
  12040. int is_callback_resource,
  12041. struct mg_websocket_subprotocols *subprotocols,
  12042. mg_websocket_connect_handler ws_connect_handler,
  12043. mg_websocket_ready_handler ws_ready_handler,
  12044. mg_websocket_data_handler ws_data_handler,
  12045. mg_websocket_close_handler ws_close_handler,
  12046. void *cbData)
  12047. {
  12048. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12049. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12050. ptrdiff_t lua_websock = 0;
  12051. #if !defined(USE_LUA)
  12052. (void)path;
  12053. #endif
  12054. /* Step 1: Check websocket protocol version. */
  12055. /* Step 1.1: Check Sec-WebSocket-Key. */
  12056. if (!websock_key) {
  12057. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12058. * requires a Sec-WebSocket-Key header.
  12059. */
  12060. /* It could be the hixie draft version
  12061. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12062. */
  12063. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12064. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12065. char key3[8];
  12066. if ((key1 != NULL) && (key2 != NULL)) {
  12067. /* This version uses 8 byte body data in a GET request */
  12068. conn->content_len = 8;
  12069. if (8 == mg_read(conn, key3, 8)) {
  12070. /* This is the hixie version */
  12071. mg_send_http_error(conn,
  12072. 426,
  12073. "%s",
  12074. "Protocol upgrade to RFC 6455 required");
  12075. return;
  12076. }
  12077. }
  12078. /* This is an unknown version */
  12079. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12080. return;
  12081. }
  12082. /* Step 1.2: Check websocket protocol version. */
  12083. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12084. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12085. /* Reject wrong versions */
  12086. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12087. return;
  12088. }
  12089. /* Step 1.3: Could check for "Host", but we do not really need this
  12090. * value for anything, so just ignore it. */
  12091. /* Step 2: If a callback is responsible, call it. */
  12092. if (is_callback_resource) {
  12093. /* Step 2.1 check and select subprotocol */
  12094. const char *protocols[64]; // max 64 headers
  12095. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12096. "Sec-WebSocket-Protocol",
  12097. protocols,
  12098. 64);
  12099. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12100. int headerNo, idx;
  12101. size_t len;
  12102. const char *sep, *curSubProtocol,
  12103. *acceptedWebSocketSubprotocol = NULL;
  12104. /* look for matching subprotocol */
  12105. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12106. /* There might be multiple headers ... */
  12107. const char *protocol = protocols[headerNo];
  12108. curSubProtocol = protocol;
  12109. /* ... and in every header there might be a , separated list */
  12110. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12111. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12112. curSubProtocol++;
  12113. sep = strchr(curSubProtocol, ',');
  12114. if (sep) {
  12115. len = (size_t)(sep - curSubProtocol);
  12116. } else {
  12117. len = strlen(curSubProtocol);
  12118. }
  12119. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12120. // COMPARE: curSubProtocol ==
  12121. // subprotocols->subprotocols[idx]
  12122. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12123. && (strncmp(curSubProtocol,
  12124. subprotocols->subprotocols[idx],
  12125. len)
  12126. == 0)) {
  12127. acceptedWebSocketSubprotocol =
  12128. subprotocols->subprotocols[idx];
  12129. break;
  12130. }
  12131. }
  12132. curSubProtocol += len;
  12133. }
  12134. }
  12135. conn->request_info.acceptedWebSocketSubprotocol =
  12136. acceptedWebSocketSubprotocol;
  12137. }
  12138. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12139. websocket_deflate_negotiate(conn);
  12140. #endif
  12141. if ((ws_connect_handler != NULL)
  12142. && (ws_connect_handler(conn, cbData) != 0)) {
  12143. /* C callback has returned non-zero, do not proceed with
  12144. * handshake.
  12145. */
  12146. /* Note that C callbacks are no longer called when Lua is
  12147. * responsible, so C can no longer filter callbacks for Lua. */
  12148. return;
  12149. }
  12150. }
  12151. #if defined(USE_LUA)
  12152. /* Step 3: No callback. Check if Lua is responsible. */
  12153. else {
  12154. /* Step 3.1: Check if Lua is responsible. */
  12155. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12156. lua_websock = match_prefix_strlen(
  12157. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12158. }
  12159. if (lua_websock > 0) {
  12160. /* Step 3.2: Lua is responsible: call it. */
  12161. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12162. if (!conn->lua_websocket_state) {
  12163. /* Lua rejected the new client */
  12164. return;
  12165. }
  12166. }
  12167. }
  12168. #endif
  12169. /* Step 4: Check if there is a responsible websocket handler. */
  12170. if (!is_callback_resource && !lua_websock) {
  12171. /* There is no callback, and Lua is not responsible either. */
  12172. /* Reply with a 404 Not Found. We are still at a standard
  12173. * HTTP request here, before the websocket handshake, so
  12174. * we can still send standard HTTP error replies. */
  12175. mg_send_http_error(conn, 404, "%s", "Not found");
  12176. return;
  12177. }
  12178. /* Step 5: The websocket connection has been accepted */
  12179. if (!send_websocket_handshake(conn, websock_key)) {
  12180. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12181. return;
  12182. }
  12183. /* Step 6: Call the ready handler */
  12184. if (is_callback_resource) {
  12185. if (ws_ready_handler != NULL) {
  12186. ws_ready_handler(conn, cbData);
  12187. }
  12188. #if defined(USE_LUA)
  12189. } else if (lua_websock) {
  12190. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12191. /* the ready handler returned false */
  12192. return;
  12193. }
  12194. #endif
  12195. }
  12196. /* Step 7: Enter the read loop */
  12197. if (is_callback_resource) {
  12198. read_websocket(conn, ws_data_handler, cbData);
  12199. #if defined(USE_LUA)
  12200. } else if (lua_websock) {
  12201. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12202. #endif
  12203. }
  12204. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12205. /* Step 8: Close the deflate & inflate buffers */
  12206. if (conn->websocket_deflate_initialized) {
  12207. deflateEnd(&conn->websocket_deflate_state);
  12208. inflateEnd(&conn->websocket_inflate_state);
  12209. }
  12210. #endif
  12211. /* Step 9: Call the close handler */
  12212. if (ws_close_handler) {
  12213. ws_close_handler(conn, cbData);
  12214. }
  12215. }
  12216. #endif /* !USE_WEBSOCKET */
  12217. /* Is upgrade request:
  12218. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12219. * 1 = upgrade to websocket
  12220. * 2 = upgrade to HTTP/2
  12221. * -1 = upgrade to unknown protocol
  12222. */
  12223. static int
  12224. should_switch_to_protocol(const struct mg_connection *conn)
  12225. {
  12226. const char *connection_headers[8];
  12227. const char *upgrade_to;
  12228. int connection_header_count, i, should_upgrade;
  12229. /* A websocket protocol has the following HTTP headers:
  12230. *
  12231. * Connection: Upgrade
  12232. * Upgrade: Websocket
  12233. *
  12234. * It seems some clients use multiple headers:
  12235. * see https://github.com/civetweb/civetweb/issues/1083
  12236. */
  12237. connection_header_count = get_req_headers(&conn->request_info,
  12238. "Connection",
  12239. connection_headers,
  12240. 8);
  12241. should_upgrade = 0;
  12242. for (i = 0; i < connection_header_count; i++) {
  12243. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12244. should_upgrade = 1;
  12245. }
  12246. }
  12247. if (!should_upgrade) {
  12248. return PROTOCOL_TYPE_HTTP1;
  12249. }
  12250. upgrade_to = mg_get_header(conn, "Upgrade");
  12251. if (upgrade_to == NULL) {
  12252. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12253. return -1;
  12254. }
  12255. /* Upgrade to ... */
  12256. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12257. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12258. * "Sec-WebSocket-Version" are also required.
  12259. * Don't check them here, since even an unsupported websocket protocol
  12260. * request still IS a websocket request (in contrast to a standard HTTP
  12261. * request). It will fail later in handle_websocket_request.
  12262. */
  12263. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12264. }
  12265. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12266. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12267. }
  12268. /* Upgrade to another protocol */
  12269. return -1;
  12270. }
  12271. static int
  12272. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12273. {
  12274. int n;
  12275. unsigned int a, b, c, d, slash;
  12276. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12277. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12278. // integer value, but function will not report conversion
  12279. // errors; consider using 'strtol' instead
  12280. slash = 32;
  12281. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12282. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12283. // an integer value, but function will not report conversion
  12284. // errors; consider using 'strtol' instead
  12285. n = 0;
  12286. }
  12287. }
  12288. if ((n > 0) && ((size_t)n == vec->len)) {
  12289. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12290. /* IPv4 format */
  12291. if (sa->sa.sa_family == AF_INET) {
  12292. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12293. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12294. | ((uint32_t)c << 8) | (uint32_t)d;
  12295. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12296. return (ip & mask) == net;
  12297. }
  12298. return 0;
  12299. }
  12300. }
  12301. #if defined(USE_IPV6)
  12302. else {
  12303. char ad[50];
  12304. const char *p;
  12305. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12306. slash = 128;
  12307. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12308. n = 0;
  12309. }
  12310. }
  12311. if ((n <= 0) && no_strict) {
  12312. /* no square brackets? */
  12313. p = strchr(vec->ptr, '/');
  12314. if (p && (p < (vec->ptr + vec->len))) {
  12315. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12316. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12317. n += (int)(p - vec->ptr);
  12318. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12319. } else {
  12320. n = 0;
  12321. }
  12322. } else if (vec->len < sizeof(ad)) {
  12323. n = (int)vec->len;
  12324. slash = 128;
  12325. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12326. }
  12327. }
  12328. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12329. p = ad;
  12330. c = 0;
  12331. /* zone indexes are unsupported, at least two colons are needed */
  12332. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12333. if (*(p++) == ':') {
  12334. c++;
  12335. }
  12336. }
  12337. if ((*p == '\0') && (c >= 2)) {
  12338. struct sockaddr_in6 sin6;
  12339. unsigned int i;
  12340. /* for strict validation, an actual IPv6 argument is needed */
  12341. if (sa->sa.sa_family != AF_INET6) {
  12342. return 0;
  12343. }
  12344. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12345. /* IPv6 format */
  12346. for (i = 0; i < 16; i++) {
  12347. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12348. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12349. uint8_t mask = 0;
  12350. if (8 * i + 8 < slash) {
  12351. mask = 0xFFu;
  12352. } else if (8 * i < slash) {
  12353. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12354. }
  12355. if ((ip & mask) != net) {
  12356. return 0;
  12357. }
  12358. }
  12359. return 1;
  12360. }
  12361. }
  12362. }
  12363. }
  12364. #else
  12365. (void)no_strict;
  12366. #endif
  12367. /* malformed */
  12368. return -1;
  12369. }
  12370. static int
  12371. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12372. {
  12373. int throttle = 0;
  12374. struct vec vec, val;
  12375. char mult;
  12376. double v;
  12377. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12378. mult = ',';
  12379. if ((val.ptr == NULL)
  12380. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12381. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12382. // to an integer value, but function will not report
  12383. // conversion errors; consider using 'strtol' instead
  12384. || (v < 0)
  12385. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12386. && (mult != ','))) {
  12387. continue;
  12388. }
  12389. v *= (lowercase(&mult) == 'k')
  12390. ? 1024
  12391. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12392. if (vec.len == 1 && vec.ptr[0] == '*') {
  12393. throttle = (int)v;
  12394. } else {
  12395. int matched = parse_match_net(&vec, rsa, 0);
  12396. if (matched >= 0) {
  12397. /* a valid IP subnet */
  12398. if (matched) {
  12399. throttle = (int)v;
  12400. }
  12401. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12402. throttle = (int)v;
  12403. }
  12404. }
  12405. }
  12406. return throttle;
  12407. }
  12408. /* The mg_upload function is superseded by mg_handle_form_request. */
  12409. #include "handle_form.inl"
  12410. static int
  12411. get_first_ssl_listener_index(const struct mg_context *ctx)
  12412. {
  12413. unsigned int i;
  12414. int idx = -1;
  12415. if (ctx) {
  12416. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12417. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12418. }
  12419. }
  12420. return idx;
  12421. }
  12422. /* Return host (without port) */
  12423. static void
  12424. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12425. {
  12426. const char *host_header =
  12427. get_header(ri->http_headers, ri->num_headers, "Host");
  12428. host->ptr = NULL;
  12429. host->len = 0;
  12430. if (host_header != NULL) {
  12431. const char *pos;
  12432. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12433. * is found. */
  12434. if (*host_header == '[') {
  12435. pos = strchr(host_header, ']');
  12436. if (!pos) {
  12437. /* Malformed hostname starts with '[', but no ']' found */
  12438. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12439. return;
  12440. }
  12441. /* terminate after ']' */
  12442. host->ptr = host_header;
  12443. host->len = (size_t)(pos + 1 - host_header);
  12444. } else {
  12445. /* Otherwise, a ':' separates hostname and port number */
  12446. pos = strchr(host_header, ':');
  12447. if (pos != NULL) {
  12448. host->len = (size_t)(pos - host_header);
  12449. } else {
  12450. host->len = strlen(host_header);
  12451. }
  12452. host->ptr = host_header;
  12453. }
  12454. }
  12455. }
  12456. static int
  12457. switch_domain_context(struct mg_connection *conn)
  12458. {
  12459. struct vec host;
  12460. get_host_from_request_info(&host, &conn->request_info);
  12461. if (host.ptr) {
  12462. if (conn->ssl) {
  12463. /* This is a HTTPS connection, maybe we have a hostname
  12464. * from SNI (set in ssl_servername_callback). */
  12465. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12466. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12467. /* We are not using the default domain */
  12468. if ((strlen(sslhost) != host.len)
  12469. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12470. /* Mismatch between SNI domain and HTTP domain */
  12471. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12472. sslhost,
  12473. (int)host.len,
  12474. host.ptr);
  12475. return 0;
  12476. }
  12477. }
  12478. } else {
  12479. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12480. while (dom) {
  12481. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12482. size_t domNameLen = strlen(domName);
  12483. if ((domNameLen == host.len)
  12484. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12485. /* Found matching domain */
  12486. DEBUG_TRACE("HTTP domain %s found",
  12487. dom->config[AUTHENTICATION_DOMAIN]);
  12488. /* TODO: Check if this is a HTTP or HTTPS domain */
  12489. conn->dom_ctx = dom;
  12490. break;
  12491. }
  12492. mg_lock_context(conn->phys_ctx);
  12493. dom = dom->next;
  12494. mg_unlock_context(conn->phys_ctx);
  12495. }
  12496. }
  12497. DEBUG_TRACE("HTTP%s Host: %.*s",
  12498. conn->ssl ? "S" : "",
  12499. (int)host.len,
  12500. host.ptr);
  12501. } else {
  12502. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12503. return 1;
  12504. }
  12505. return 1;
  12506. }
  12507. static void
  12508. redirect_to_https_port(struct mg_connection *conn, int port)
  12509. {
  12510. char target_url[MG_BUF_LEN];
  12511. int truncated = 0;
  12512. const char *expect_proto =
  12513. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12514. /* Use "308 Permanent Redirect" */
  12515. int redirect_code = 308;
  12516. /* In any case, close the current connection */
  12517. conn->must_close = 1;
  12518. /* Send host, port, uri and (if it exists) ?query_string */
  12519. if (mg_construct_local_link(
  12520. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12521. < 0) {
  12522. truncated = 1;
  12523. } else if (conn->request_info.query_string != NULL) {
  12524. size_t slen1 = strlen(target_url);
  12525. size_t slen2 = strlen(conn->request_info.query_string);
  12526. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12527. target_url[slen1] = '?';
  12528. memcpy(target_url + slen1 + 1,
  12529. conn->request_info.query_string,
  12530. slen2);
  12531. target_url[slen1 + slen2 + 1] = 0;
  12532. } else {
  12533. truncated = 1;
  12534. }
  12535. }
  12536. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12537. * is used as buffer size) */
  12538. if (truncated) {
  12539. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12540. return;
  12541. }
  12542. /* Use redirect helper function */
  12543. mg_send_http_redirect(conn, target_url, redirect_code);
  12544. }
  12545. static void
  12546. mg_set_handler_type(struct mg_context *phys_ctx,
  12547. struct mg_domain_context *dom_ctx,
  12548. const char *uri,
  12549. int handler_type,
  12550. int is_delete_request,
  12551. mg_request_handler handler,
  12552. struct mg_websocket_subprotocols *subprotocols,
  12553. mg_websocket_connect_handler connect_handler,
  12554. mg_websocket_ready_handler ready_handler,
  12555. mg_websocket_data_handler data_handler,
  12556. mg_websocket_close_handler close_handler,
  12557. mg_authorization_handler auth_handler,
  12558. void *cbdata)
  12559. {
  12560. struct mg_handler_info *tmp_rh, **lastref;
  12561. size_t urilen = strlen(uri);
  12562. if (handler_type == WEBSOCKET_HANDLER) {
  12563. DEBUG_ASSERT(handler == NULL);
  12564. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12565. || ready_handler != NULL || data_handler != NULL
  12566. || close_handler != NULL);
  12567. DEBUG_ASSERT(auth_handler == NULL);
  12568. if (handler != NULL) {
  12569. return;
  12570. }
  12571. if (!is_delete_request && (connect_handler == NULL)
  12572. && (ready_handler == NULL) && (data_handler == NULL)
  12573. && (close_handler == NULL)) {
  12574. return;
  12575. }
  12576. if (auth_handler != NULL) {
  12577. return;
  12578. }
  12579. } else if (handler_type == REQUEST_HANDLER) {
  12580. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12581. && data_handler == NULL && close_handler == NULL);
  12582. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12583. DEBUG_ASSERT(auth_handler == NULL);
  12584. if ((connect_handler != NULL) || (ready_handler != NULL)
  12585. || (data_handler != NULL) || (close_handler != NULL)) {
  12586. return;
  12587. }
  12588. if (!is_delete_request && (handler == NULL)) {
  12589. return;
  12590. }
  12591. if (auth_handler != NULL) {
  12592. return;
  12593. }
  12594. } else if (handler_type == AUTH_HANDLER) {
  12595. DEBUG_ASSERT(handler == NULL);
  12596. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12597. && data_handler == NULL && close_handler == NULL);
  12598. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12599. if (handler != NULL) {
  12600. return;
  12601. }
  12602. if ((connect_handler != NULL) || (ready_handler != NULL)
  12603. || (data_handler != NULL) || (close_handler != NULL)) {
  12604. return;
  12605. }
  12606. if (!is_delete_request && (auth_handler == NULL)) {
  12607. return;
  12608. }
  12609. } else {
  12610. /* Unknown handler type. */
  12611. return;
  12612. }
  12613. if (!phys_ctx || !dom_ctx) {
  12614. /* no context available */
  12615. return;
  12616. }
  12617. mg_lock_context(phys_ctx);
  12618. /* first try to find an existing handler */
  12619. do {
  12620. lastref = &(dom_ctx->handlers);
  12621. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12622. tmp_rh = tmp_rh->next) {
  12623. if (tmp_rh->handler_type == handler_type
  12624. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12625. if (!is_delete_request) {
  12626. /* update existing handler */
  12627. if (handler_type == REQUEST_HANDLER) {
  12628. /* Wait for end of use before updating */
  12629. if (tmp_rh->refcount) {
  12630. mg_unlock_context(phys_ctx);
  12631. mg_sleep(1);
  12632. mg_lock_context(phys_ctx);
  12633. /* tmp_rh might have been freed, search again. */
  12634. break;
  12635. }
  12636. /* Ok, the handler is no more use -> Update it */
  12637. tmp_rh->handler = handler;
  12638. } else if (handler_type == WEBSOCKET_HANDLER) {
  12639. tmp_rh->subprotocols = subprotocols;
  12640. tmp_rh->connect_handler = connect_handler;
  12641. tmp_rh->ready_handler = ready_handler;
  12642. tmp_rh->data_handler = data_handler;
  12643. tmp_rh->close_handler = close_handler;
  12644. } else { /* AUTH_HANDLER */
  12645. tmp_rh->auth_handler = auth_handler;
  12646. }
  12647. tmp_rh->cbdata = cbdata;
  12648. } else {
  12649. /* remove existing handler */
  12650. if (handler_type == REQUEST_HANDLER) {
  12651. /* Wait for end of use before removing */
  12652. if (tmp_rh->refcount) {
  12653. tmp_rh->removing = 1;
  12654. mg_unlock_context(phys_ctx);
  12655. mg_sleep(1);
  12656. mg_lock_context(phys_ctx);
  12657. /* tmp_rh might have been freed, search again. */
  12658. break;
  12659. }
  12660. /* Ok, the handler is no more used */
  12661. }
  12662. *lastref = tmp_rh->next;
  12663. mg_free(tmp_rh->uri);
  12664. mg_free(tmp_rh);
  12665. }
  12666. mg_unlock_context(phys_ctx);
  12667. return;
  12668. }
  12669. lastref = &(tmp_rh->next);
  12670. }
  12671. } while (tmp_rh != NULL);
  12672. if (is_delete_request) {
  12673. /* no handler to set, this was a remove request to a non-existing
  12674. * handler */
  12675. mg_unlock_context(phys_ctx);
  12676. return;
  12677. }
  12678. tmp_rh =
  12679. (struct mg_handler_info *)mg_calloc_ctx(1,
  12680. sizeof(struct mg_handler_info),
  12681. phys_ctx);
  12682. if (tmp_rh == NULL) {
  12683. mg_unlock_context(phys_ctx);
  12684. mg_cry_ctx_internal(phys_ctx,
  12685. "%s",
  12686. "Cannot create new request handler struct, OOM");
  12687. return;
  12688. }
  12689. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12690. if (!tmp_rh->uri) {
  12691. mg_unlock_context(phys_ctx);
  12692. mg_free(tmp_rh);
  12693. mg_cry_ctx_internal(phys_ctx,
  12694. "%s",
  12695. "Cannot create new request handler struct, OOM");
  12696. return;
  12697. }
  12698. tmp_rh->uri_len = urilen;
  12699. if (handler_type == REQUEST_HANDLER) {
  12700. tmp_rh->refcount = 0;
  12701. tmp_rh->removing = 0;
  12702. tmp_rh->handler = handler;
  12703. } else if (handler_type == WEBSOCKET_HANDLER) {
  12704. tmp_rh->subprotocols = subprotocols;
  12705. tmp_rh->connect_handler = connect_handler;
  12706. tmp_rh->ready_handler = ready_handler;
  12707. tmp_rh->data_handler = data_handler;
  12708. tmp_rh->close_handler = close_handler;
  12709. } else { /* AUTH_HANDLER */
  12710. tmp_rh->auth_handler = auth_handler;
  12711. }
  12712. tmp_rh->cbdata = cbdata;
  12713. tmp_rh->handler_type = handler_type;
  12714. tmp_rh->next = NULL;
  12715. *lastref = tmp_rh;
  12716. mg_unlock_context(phys_ctx);
  12717. }
  12718. CIVETWEB_API void
  12719. mg_set_request_handler(struct mg_context *ctx,
  12720. const char *uri,
  12721. mg_request_handler handler,
  12722. void *cbdata)
  12723. {
  12724. mg_set_handler_type(ctx,
  12725. &(ctx->dd),
  12726. uri,
  12727. REQUEST_HANDLER,
  12728. handler == NULL,
  12729. handler,
  12730. NULL,
  12731. NULL,
  12732. NULL,
  12733. NULL,
  12734. NULL,
  12735. NULL,
  12736. cbdata);
  12737. }
  12738. CIVETWEB_API void
  12739. mg_set_websocket_handler(struct mg_context *ctx,
  12740. const char *uri,
  12741. mg_websocket_connect_handler connect_handler,
  12742. mg_websocket_ready_handler ready_handler,
  12743. mg_websocket_data_handler data_handler,
  12744. mg_websocket_close_handler close_handler,
  12745. void *cbdata)
  12746. {
  12747. mg_set_websocket_handler_with_subprotocols(ctx,
  12748. uri,
  12749. NULL,
  12750. connect_handler,
  12751. ready_handler,
  12752. data_handler,
  12753. close_handler,
  12754. cbdata);
  12755. }
  12756. CIVETWEB_API void
  12757. mg_set_websocket_handler_with_subprotocols(
  12758. struct mg_context *ctx,
  12759. const char *uri,
  12760. struct mg_websocket_subprotocols *subprotocols,
  12761. mg_websocket_connect_handler connect_handler,
  12762. mg_websocket_ready_handler ready_handler,
  12763. mg_websocket_data_handler data_handler,
  12764. mg_websocket_close_handler close_handler,
  12765. void *cbdata)
  12766. {
  12767. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12768. && (data_handler == NULL)
  12769. && (close_handler == NULL);
  12770. mg_set_handler_type(ctx,
  12771. &(ctx->dd),
  12772. uri,
  12773. WEBSOCKET_HANDLER,
  12774. is_delete_request,
  12775. NULL,
  12776. subprotocols,
  12777. connect_handler,
  12778. ready_handler,
  12779. data_handler,
  12780. close_handler,
  12781. NULL,
  12782. cbdata);
  12783. }
  12784. CIVETWEB_API void
  12785. mg_set_auth_handler(struct mg_context *ctx,
  12786. const char *uri,
  12787. mg_authorization_handler handler,
  12788. void *cbdata)
  12789. {
  12790. mg_set_handler_type(ctx,
  12791. &(ctx->dd),
  12792. uri,
  12793. AUTH_HANDLER,
  12794. handler == NULL,
  12795. NULL,
  12796. NULL,
  12797. NULL,
  12798. NULL,
  12799. NULL,
  12800. NULL,
  12801. handler,
  12802. cbdata);
  12803. }
  12804. static int
  12805. get_request_handler(struct mg_connection *conn,
  12806. int handler_type,
  12807. mg_request_handler *handler,
  12808. struct mg_websocket_subprotocols **subprotocols,
  12809. mg_websocket_connect_handler *connect_handler,
  12810. mg_websocket_ready_handler *ready_handler,
  12811. mg_websocket_data_handler *data_handler,
  12812. mg_websocket_close_handler *close_handler,
  12813. mg_authorization_handler *auth_handler,
  12814. void **cbdata,
  12815. struct mg_handler_info **handler_info)
  12816. {
  12817. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12818. if (request_info) {
  12819. const char *uri = request_info->local_uri;
  12820. size_t urilen = strlen(uri);
  12821. struct mg_handler_info *tmp_rh;
  12822. int step, matched;
  12823. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12824. return 0;
  12825. }
  12826. mg_lock_context(conn->phys_ctx);
  12827. for (step = 0; step < 3; step++) {
  12828. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12829. tmp_rh = tmp_rh->next) {
  12830. if (tmp_rh->handler_type != handler_type) {
  12831. continue;
  12832. }
  12833. if (step == 0) {
  12834. /* first try for an exact match */
  12835. matched = (tmp_rh->uri_len == urilen)
  12836. && (strcmp(tmp_rh->uri, uri) == 0);
  12837. } else if (step == 1) {
  12838. /* next try for a partial match, we will accept
  12839. uri/something */
  12840. matched =
  12841. (tmp_rh->uri_len < urilen)
  12842. && (uri[tmp_rh->uri_len] == '/')
  12843. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12844. } else {
  12845. /* finally try for pattern match */
  12846. matched =
  12847. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12848. }
  12849. if (matched) {
  12850. if (handler_type == WEBSOCKET_HANDLER) {
  12851. *subprotocols = tmp_rh->subprotocols;
  12852. *connect_handler = tmp_rh->connect_handler;
  12853. *ready_handler = tmp_rh->ready_handler;
  12854. *data_handler = tmp_rh->data_handler;
  12855. *close_handler = tmp_rh->close_handler;
  12856. } else if (handler_type == REQUEST_HANDLER) {
  12857. if (tmp_rh->removing) {
  12858. /* Treat as none found */
  12859. step = 2;
  12860. break;
  12861. }
  12862. *handler = tmp_rh->handler;
  12863. /* Acquire handler and give it back */
  12864. tmp_rh->refcount++;
  12865. *handler_info = tmp_rh;
  12866. } else { /* AUTH_HANDLER */
  12867. *auth_handler = tmp_rh->auth_handler;
  12868. }
  12869. *cbdata = tmp_rh->cbdata;
  12870. mg_unlock_context(conn->phys_ctx);
  12871. return 1;
  12872. }
  12873. }
  12874. }
  12875. mg_unlock_context(conn->phys_ctx);
  12876. }
  12877. return 0; /* none found */
  12878. }
  12879. /* Check if the script file is in a path, allowed for script files.
  12880. * This can be used if uploading files is possible not only for the server
  12881. * admin, and the upload mechanism does not check the file extension.
  12882. */
  12883. static int
  12884. is_in_script_path(const struct mg_connection *conn, const char *path)
  12885. {
  12886. /* TODO (Feature): Add config value for allowed script path.
  12887. * Default: All allowed. */
  12888. (void)conn;
  12889. (void)path;
  12890. return 1;
  12891. }
  12892. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12893. static int
  12894. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12895. int bits,
  12896. char *data,
  12897. size_t len,
  12898. void *cbdata)
  12899. {
  12900. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12901. if (pcallbacks->websocket_data) {
  12902. return pcallbacks->websocket_data(conn, bits, data, len);
  12903. }
  12904. /* No handler set - assume "OK" */
  12905. return 1;
  12906. }
  12907. static void
  12908. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12909. void *cbdata)
  12910. {
  12911. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12912. if (pcallbacks->connection_close) {
  12913. pcallbacks->connection_close(conn);
  12914. }
  12915. }
  12916. #endif
  12917. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12918. */
  12919. static void
  12920. release_handler_ref(struct mg_connection *conn,
  12921. struct mg_handler_info *handler_info)
  12922. {
  12923. if (handler_info != NULL) {
  12924. /* Use context lock for ref counter */
  12925. mg_lock_context(conn->phys_ctx);
  12926. handler_info->refcount--;
  12927. mg_unlock_context(conn->phys_ctx);
  12928. }
  12929. }
  12930. /* This is the heart of the Civetweb's logic.
  12931. * This function is called when the request is read, parsed and validated,
  12932. * and Civetweb must decide what action to take: serve a file, or
  12933. * a directory, or call embedded function, etcetera. */
  12934. static void
  12935. handle_request(struct mg_connection *conn)
  12936. {
  12937. struct mg_request_info *ri = &conn->request_info;
  12938. char path[UTF8_PATH_MAX];
  12939. int uri_len, ssl_index;
  12940. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12941. is_put_or_delete_request = 0, is_callback_resource = 0,
  12942. is_template_text_file = 0, is_webdav_request = 0;
  12943. int i;
  12944. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12945. mg_request_handler callback_handler = NULL;
  12946. struct mg_handler_info *handler_info = NULL;
  12947. struct mg_websocket_subprotocols *subprotocols;
  12948. mg_websocket_connect_handler ws_connect_handler = NULL;
  12949. mg_websocket_ready_handler ws_ready_handler = NULL;
  12950. mg_websocket_data_handler ws_data_handler = NULL;
  12951. mg_websocket_close_handler ws_close_handler = NULL;
  12952. void *callback_data = NULL;
  12953. mg_authorization_handler auth_handler = NULL;
  12954. void *auth_callback_data = NULL;
  12955. int handler_type;
  12956. time_t curtime = time(NULL);
  12957. char date[64];
  12958. char *tmp;
  12959. path[0] = 0;
  12960. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12961. conn->request_state = 0;
  12962. /* 1. get the request url */
  12963. /* 1.1. split into url and query string */
  12964. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12965. != NULL) {
  12966. *((char *)conn->request_info.query_string++) = '\0';
  12967. }
  12968. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12969. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12970. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12971. if (ssl_index >= 0) {
  12972. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12973. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12974. redirect_to_https_port(conn, port);
  12975. } else {
  12976. /* A http to https forward port has been specified,
  12977. * but no https port to forward to. */
  12978. mg_send_http_error(conn,
  12979. 503,
  12980. "%s",
  12981. "Error: SSL forward not configured properly");
  12982. mg_cry_internal(conn,
  12983. "%s",
  12984. "Can not redirect to SSL, no SSL port available");
  12985. }
  12986. return;
  12987. }
  12988. uri_len = (int)strlen(ri->local_uri);
  12989. /* 1.3. decode url (if config says so) */
  12990. if (should_decode_url(conn)) {
  12991. url_decode_in_place((char *)ri->local_uri);
  12992. }
  12993. /* URL decode the query-string only if explicitly set in the configuration
  12994. */
  12995. if (conn->request_info.query_string) {
  12996. if (should_decode_query_string(conn)) {
  12997. url_decode_in_place((char *)conn->request_info.query_string);
  12998. }
  12999. }
  13000. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  13001. * possible. The fact that we cleaned the URI is stored in that the
  13002. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  13003. * ri->local_uri_raw still points to memory allocated in
  13004. * worker_thread_run(). ri->local_uri is private to the request so we
  13005. * don't have to use preallocated memory here. */
  13006. tmp = mg_strdup(ri->local_uri_raw);
  13007. if (!tmp) {
  13008. /* Out of memory. We cannot do anything reasonable here. */
  13009. return;
  13010. }
  13011. remove_dot_segments(tmp);
  13012. ri->local_uri = tmp;
  13013. /* step 1. completed, the url is known now */
  13014. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13015. /* 2. if this ip has limited speed, set it for this connection */
  13016. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13017. &conn->client.rsa,
  13018. ri->local_uri);
  13019. /* 3. call a "handle everything" callback, if registered */
  13020. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13021. /* Note that since V1.7 the "begin_request" function is called
  13022. * before an authorization check. If an authorization check is
  13023. * required, use a request_handler instead. */
  13024. i = conn->phys_ctx->callbacks.begin_request(conn);
  13025. if (i > 0) {
  13026. /* callback already processed the request. Store the
  13027. return value as a status code for the access log. */
  13028. conn->status_code = i;
  13029. if (!conn->must_close) {
  13030. discard_unread_request_data(conn);
  13031. }
  13032. DEBUG_TRACE("%s", "begin_request handled request");
  13033. return;
  13034. } else if (i == 0) {
  13035. /* civetweb should process the request */
  13036. } else {
  13037. /* unspecified - may change with the next version */
  13038. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13039. return;
  13040. }
  13041. }
  13042. /* request not yet handled by a handler or redirect, so the request
  13043. * is processed here */
  13044. /* 4. Check for CORS preflight requests and handle them (if configured).
  13045. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13046. */
  13047. if (!strcmp(ri->request_method, "OPTIONS")) {
  13048. /* Send a response to CORS preflights only if
  13049. * access_control_allow_methods is not NULL and not an empty string.
  13050. * In this case, scripts can still handle CORS. */
  13051. const char *cors_meth_cfg =
  13052. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13053. const char *cors_orig_cfg =
  13054. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13055. const char *cors_origin =
  13056. get_header(ri->http_headers, ri->num_headers, "Origin");
  13057. const char *cors_acrm = get_header(ri->http_headers,
  13058. ri->num_headers,
  13059. "Access-Control-Request-Method");
  13060. /* Todo: check if cors_origin is in cors_orig_cfg.
  13061. * Or, let the client check this. */
  13062. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13063. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13064. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  13065. /* This is a valid CORS preflight, and the server is configured
  13066. * to handle it automatically. */
  13067. const char *cors_acrh =
  13068. get_header(ri->http_headers,
  13069. ri->num_headers,
  13070. "Access-Control-Request-Headers");
  13071. const char *cors_cred_cfg =
  13072. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13073. const char *cors_exphdr_cfg =
  13074. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13075. gmt_time_string(date, sizeof(date), &curtime);
  13076. mg_printf(conn,
  13077. "HTTP/1.1 200 OK\r\n"
  13078. "Date: %s\r\n"
  13079. "Access-Control-Allow-Origin: %s\r\n"
  13080. "Access-Control-Allow-Methods: %s\r\n"
  13081. "Content-Length: 0\r\n"
  13082. "Connection: %s\r\n",
  13083. date,
  13084. cors_orig_cfg,
  13085. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13086. suggest_connection_header(conn));
  13087. if (cors_cred_cfg && *cors_cred_cfg) {
  13088. mg_printf(conn,
  13089. "Access-Control-Allow-Credentials: %s\r\n",
  13090. cors_cred_cfg);
  13091. }
  13092. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13093. mg_printf(conn,
  13094. "Access-Control-Expose-Headers: %s\r\n",
  13095. cors_exphdr_cfg);
  13096. }
  13097. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13098. /* CORS request is asking for additional headers */
  13099. const char *cors_hdr_cfg =
  13100. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13101. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13102. /* Allow only if access_control_allow_headers is
  13103. * not NULL and not an empty string. If this
  13104. * configuration is set to *, allow everything.
  13105. * Otherwise this configuration must be a list
  13106. * of allowed HTTP header names. */
  13107. mg_printf(conn,
  13108. "Access-Control-Allow-Headers: %s\r\n",
  13109. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13110. : cors_hdr_cfg));
  13111. }
  13112. }
  13113. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13114. mg_printf(conn, "\r\n");
  13115. DEBUG_TRACE("%s", "OPTIONS done");
  13116. return;
  13117. }
  13118. }
  13119. /* 5. interpret the url to find out how the request must be handled
  13120. */
  13121. /* 5.1. first test, if the request targets the regular http(s)://
  13122. * protocol namespace or the websocket ws(s):// protocol namespace.
  13123. */
  13124. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13125. #if defined(USE_WEBSOCKET)
  13126. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13127. #else
  13128. handler_type = REQUEST_HANDLER;
  13129. #endif /* defined(USE_WEBSOCKET) */
  13130. if (is_websocket_request) {
  13131. HTTP1_only;
  13132. }
  13133. /* 5.2. check if the request will be handled by a callback */
  13134. if (get_request_handler(conn,
  13135. handler_type,
  13136. &callback_handler,
  13137. &subprotocols,
  13138. &ws_connect_handler,
  13139. &ws_ready_handler,
  13140. &ws_data_handler,
  13141. &ws_close_handler,
  13142. NULL,
  13143. &callback_data,
  13144. &handler_info)) {
  13145. /* 5.2.1. A callback will handle this request. All requests
  13146. * handled by a callback have to be considered as requests
  13147. * to a script resource. */
  13148. is_callback_resource = 1;
  13149. is_script_resource = 1;
  13150. is_put_or_delete_request = is_put_or_delete_method(conn);
  13151. /* Never handle a C callback according to File WebDav rules,
  13152. * even if it is a webdav method */
  13153. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13154. } else {
  13155. no_callback_resource:
  13156. /* 5.2.2. No callback is responsible for this request. The URI
  13157. * addresses a file based resource (static content or Lua/cgi
  13158. * scripts in the file system). */
  13159. is_callback_resource = 0;
  13160. interpret_uri(conn,
  13161. path,
  13162. sizeof(path),
  13163. &file.stat,
  13164. &is_found,
  13165. &is_script_resource,
  13166. &is_websocket_request,
  13167. &is_put_or_delete_request,
  13168. &is_webdav_request,
  13169. &is_template_text_file);
  13170. }
  13171. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13172. if (is_webdav_request) {
  13173. /* TODO: Do we need a config option? */
  13174. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13175. if (webdav_enable[0] != 'y') {
  13176. mg_send_http_error(conn,
  13177. 405,
  13178. "%s method not allowed",
  13179. conn->request_info.request_method);
  13180. DEBUG_TRACE("%s", "webdav rejected");
  13181. return;
  13182. }
  13183. }
  13184. /* 6. authorization check */
  13185. /* 6.1. a custom authorization handler is installed */
  13186. if (get_request_handler(conn,
  13187. AUTH_HANDLER,
  13188. NULL,
  13189. NULL,
  13190. NULL,
  13191. NULL,
  13192. NULL,
  13193. NULL,
  13194. &auth_handler,
  13195. &auth_callback_data,
  13196. NULL)) {
  13197. if (!auth_handler(conn, auth_callback_data)) {
  13198. /* Callback handler will not be used anymore. Release it */
  13199. release_handler_ref(conn, handler_info);
  13200. DEBUG_TRACE("%s", "auth handler rejected request");
  13201. return;
  13202. }
  13203. } else if (is_put_or_delete_request && !is_script_resource
  13204. && !is_callback_resource) {
  13205. HTTP1_only;
  13206. /* 6.2. this request is a PUT/DELETE to a real file */
  13207. /* 6.2.1. thus, the server must have real files */
  13208. #if defined(NO_FILES)
  13209. if (1) {
  13210. #else
  13211. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13212. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13213. #endif
  13214. /* This code path will not be called for request handlers */
  13215. DEBUG_ASSERT(handler_info == NULL);
  13216. /* This server does not have any real files, thus the
  13217. * PUT/DELETE methods are not valid. */
  13218. mg_send_http_error(conn,
  13219. 405,
  13220. "%s method not allowed",
  13221. conn->request_info.request_method);
  13222. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13223. return;
  13224. }
  13225. #if !defined(NO_FILES)
  13226. /* 6.2.2. Check if put authorization for static files is
  13227. * available.
  13228. */
  13229. if (!is_authorized_for_put(conn)) {
  13230. send_authorization_request(conn, NULL);
  13231. DEBUG_TRACE("%s", "file write needs authorization");
  13232. return;
  13233. }
  13234. #endif
  13235. } else {
  13236. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13237. * or it is a PUT or DELETE request to a resource that does not
  13238. * correspond to a file. Check authorization. */
  13239. if (!check_authorization(conn, path)) {
  13240. send_authorization_request(conn, NULL);
  13241. /* Callback handler will not be used anymore. Release it */
  13242. release_handler_ref(conn, handler_info);
  13243. DEBUG_TRACE("%s", "access authorization required");
  13244. return;
  13245. }
  13246. }
  13247. /* request is authorized or does not need authorization */
  13248. /* 7. check if there are request handlers for this uri */
  13249. if (is_callback_resource) {
  13250. HTTP1_only;
  13251. if (!is_websocket_request) {
  13252. i = callback_handler(conn, callback_data);
  13253. /* Callback handler will not be used anymore. Release it */
  13254. release_handler_ref(conn, handler_info);
  13255. if (i > 0) {
  13256. /* Do nothing, callback has served the request. Store
  13257. * then return value as status code for the log and discard
  13258. * all data from the client not used by the callback. */
  13259. conn->status_code = i;
  13260. if (!conn->must_close) {
  13261. discard_unread_request_data(conn);
  13262. }
  13263. } else {
  13264. /* The handler did NOT handle the request. */
  13265. /* Some proper reactions would be:
  13266. * a) close the connections without sending anything
  13267. * b) send a 404 not found
  13268. * c) try if there is a file matching the URI
  13269. * It would be possible to do a, b or c in the callback
  13270. * implementation, and return 1 - we cannot do anything
  13271. * here, that is not possible in the callback.
  13272. *
  13273. * TODO: What would be the best reaction here?
  13274. * (Note: The reaction may change, if there is a better
  13275. * idea.)
  13276. */
  13277. /* For the moment, use option c: We look for a proper file,
  13278. * but since a file request is not always a script resource,
  13279. * the authorization check might be different. */
  13280. callback_handler = NULL;
  13281. /* Here we are at a dead end:
  13282. * According to URI matching, a callback should be
  13283. * responsible for handling the request,
  13284. * we called it, but the callback declared itself
  13285. * not responsible.
  13286. * We use a goto here, to get out of this dead end,
  13287. * and continue with the default handling.
  13288. * A goto here is simpler and better to understand
  13289. * than some curious loop. */
  13290. goto no_callback_resource;
  13291. }
  13292. } else {
  13293. #if defined(USE_WEBSOCKET)
  13294. handle_websocket_request(conn,
  13295. path,
  13296. is_callback_resource,
  13297. subprotocols,
  13298. ws_connect_handler,
  13299. ws_ready_handler,
  13300. ws_data_handler,
  13301. ws_close_handler,
  13302. callback_data);
  13303. #endif
  13304. }
  13305. DEBUG_TRACE("%s", "websocket handling done");
  13306. return;
  13307. }
  13308. /* 8. handle websocket requests */
  13309. #if defined(USE_WEBSOCKET)
  13310. if (is_websocket_request) {
  13311. HTTP1_only;
  13312. if (is_script_resource) {
  13313. if (is_in_script_path(conn, path)) {
  13314. /* Websocket Lua script */
  13315. handle_websocket_request(conn,
  13316. path,
  13317. 0 /* Lua Script */,
  13318. NULL,
  13319. NULL,
  13320. NULL,
  13321. NULL,
  13322. NULL,
  13323. conn->phys_ctx->user_data);
  13324. } else {
  13325. /* Script was in an illegal path */
  13326. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13327. }
  13328. } else {
  13329. mg_send_http_error(conn, 404, "%s", "Not found");
  13330. }
  13331. DEBUG_TRACE("%s", "websocket script done");
  13332. return;
  13333. } else
  13334. #endif
  13335. #if defined(NO_FILES)
  13336. /* 9a. In case the server uses only callbacks, this uri is
  13337. * unknown.
  13338. * Then, all request handling ends here. */
  13339. mg_send_http_error(conn, 404, "%s", "Not Found");
  13340. #else
  13341. /* 9b. This request is either for a static file or resource handled
  13342. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13343. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13344. mg_send_http_error(conn, 404, "%s", "Not Found");
  13345. DEBUG_TRACE("%s", "no document root available");
  13346. return;
  13347. }
  13348. /* 10. Request is handled by a script */
  13349. if (is_script_resource) {
  13350. HTTP1_only;
  13351. handle_file_based_request(conn, path, &file);
  13352. DEBUG_TRACE("%s", "script handling done");
  13353. return;
  13354. }
  13355. /* Request was not handled by a callback or script. It will be
  13356. * handled by a server internal method. */
  13357. /* 11. Handle put/delete/mkcol requests */
  13358. if (is_put_or_delete_request) {
  13359. HTTP1_only;
  13360. /* 11.1. PUT method */
  13361. if (!strcmp(ri->request_method, "PUT")) {
  13362. put_file(conn, path);
  13363. DEBUG_TRACE("handling %s request to %s done",
  13364. ri->request_method,
  13365. path);
  13366. return;
  13367. }
  13368. /* 11.2. DELETE method */
  13369. if (!strcmp(ri->request_method, "DELETE")) {
  13370. delete_file(conn, path);
  13371. DEBUG_TRACE("handling %s request to %s done",
  13372. ri->request_method,
  13373. path);
  13374. return;
  13375. }
  13376. /* 11.3. MKCOL method */
  13377. if (!strcmp(ri->request_method, "MKCOL")) {
  13378. dav_mkcol(conn, path);
  13379. DEBUG_TRACE("handling %s request to %s done",
  13380. ri->request_method,
  13381. path);
  13382. return;
  13383. }
  13384. /* 11.4. MOVE method */
  13385. if (!strcmp(ri->request_method, "MOVE")) {
  13386. dav_move_file(conn, path, 0);
  13387. DEBUG_TRACE("handling %s request to %s done",
  13388. ri->request_method,
  13389. path);
  13390. return;
  13391. }
  13392. if (!strcmp(ri->request_method, "COPY")) {
  13393. dav_move_file(conn, path, 1);
  13394. DEBUG_TRACE("handling %s request to %s done",
  13395. ri->request_method,
  13396. path);
  13397. return;
  13398. }
  13399. /* 11.5. LOCK method */
  13400. if (!strcmp(ri->request_method, "LOCK")) {
  13401. dav_lock_file(conn, path);
  13402. DEBUG_TRACE("handling %s request to %s done",
  13403. ri->request_method,
  13404. path);
  13405. return;
  13406. }
  13407. /* 11.6. UNLOCK method */
  13408. if (!strcmp(ri->request_method, "UNLOCK")) {
  13409. dav_unlock_file(conn, path);
  13410. DEBUG_TRACE("handling %s request to %s done",
  13411. ri->request_method,
  13412. path);
  13413. return;
  13414. }
  13415. /* 11.7. PROPPATCH method */
  13416. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13417. dav_proppatch(conn, path);
  13418. DEBUG_TRACE("handling %s request to %s done",
  13419. ri->request_method,
  13420. path);
  13421. return;
  13422. }
  13423. /* 11.8. Other methods, e.g.: PATCH
  13424. * This method is not supported for static resources,
  13425. * only for scripts (Lua, CGI) and callbacks. */
  13426. mg_send_http_error(conn,
  13427. 405,
  13428. "%s method not allowed",
  13429. conn->request_info.request_method);
  13430. DEBUG_TRACE("method %s on %s is not supported",
  13431. ri->request_method,
  13432. path);
  13433. return;
  13434. }
  13435. /* 11. File does not exist, or it was configured that it should be
  13436. * hidden */
  13437. if (!is_found || (must_hide_file(conn, path))) {
  13438. mg_send_http_error(conn, 404, "%s", "Not found");
  13439. DEBUG_TRACE("handling %s request to %s: file not found",
  13440. ri->request_method,
  13441. path);
  13442. return;
  13443. }
  13444. /* 12. Directory uris should end with a slash */
  13445. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13446. && (ri->local_uri[uri_len - 1] != '/')) {
  13447. /* Path + server root */
  13448. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13449. char *new_path;
  13450. if (ri->query_string) {
  13451. buflen += strlen(ri->query_string);
  13452. }
  13453. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13454. if (!new_path) {
  13455. mg_send_http_error(conn, 500, "out or memory");
  13456. } else {
  13457. mg_get_request_link(conn, new_path, buflen - 1);
  13458. strcat(new_path, "/");
  13459. if (ri->query_string) {
  13460. /* Append ? and query string */
  13461. strcat(new_path, "?");
  13462. strcat(new_path, ri->query_string);
  13463. }
  13464. mg_send_http_redirect(conn, new_path, 301);
  13465. mg_free(new_path);
  13466. }
  13467. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13468. ri->request_method,
  13469. path);
  13470. return;
  13471. }
  13472. /* 13. Handle other methods than GET/HEAD */
  13473. /* 13.1. Handle PROPFIND */
  13474. if (!strcmp(ri->request_method, "PROPFIND")) {
  13475. handle_propfind(conn, path, &file.stat);
  13476. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13477. return;
  13478. }
  13479. /* 13.2. Handle OPTIONS for files */
  13480. if (!strcmp(ri->request_method, "OPTIONS")) {
  13481. /* This standard handler is only used for real files.
  13482. * Scripts should support the OPTIONS method themselves, to allow a
  13483. * maximum flexibility.
  13484. * Lua and CGI scripts may fully support CORS this way (including
  13485. * preflights). */
  13486. send_options(conn);
  13487. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13488. return;
  13489. }
  13490. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13491. if ((0 != strcmp(ri->request_method, "GET"))
  13492. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13493. mg_send_http_error(conn,
  13494. 405,
  13495. "%s method not allowed",
  13496. conn->request_info.request_method);
  13497. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13498. return;
  13499. }
  13500. /* 14. directories */
  13501. if (file.stat.is_directory) {
  13502. /* Substitute files have already been handled above. */
  13503. /* Here we can either generate and send a directory listing,
  13504. * or send an "access denied" error. */
  13505. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13506. "yes")) {
  13507. handle_directory_request(conn, path);
  13508. } else {
  13509. mg_send_http_error(conn,
  13510. 403,
  13511. "%s",
  13512. "Error: Directory listing denied");
  13513. }
  13514. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13515. return;
  13516. }
  13517. /* 15. Files with search/replace patterns: LSP and SSI */
  13518. if (is_template_text_file) {
  13519. HTTP1_only;
  13520. handle_file_based_request(conn, path, &file);
  13521. DEBUG_TRACE("handling %s request to %s done (template)",
  13522. ri->request_method,
  13523. path);
  13524. return;
  13525. }
  13526. /* 16. Static file - maybe cached */
  13527. #if !defined(NO_CACHING)
  13528. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13529. /* Send 304 "Not Modified" - this must not send any body data */
  13530. handle_not_modified_static_file_request(conn, &file);
  13531. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13532. ri->request_method,
  13533. path);
  13534. return;
  13535. }
  13536. #endif /* !NO_CACHING */
  13537. /* 17. Static file - not cached */
  13538. handle_static_file_request(conn, path, &file, NULL, NULL);
  13539. DEBUG_TRACE("handling %s request to %s done (static)",
  13540. ri->request_method,
  13541. path);
  13542. #endif /* !defined(NO_FILES) */
  13543. }
  13544. #if !defined(NO_FILESYSTEMS)
  13545. static void
  13546. handle_file_based_request(struct mg_connection *conn,
  13547. const char *path,
  13548. struct mg_file *file)
  13549. {
  13550. #if !defined(NO_CGI)
  13551. int cgi_config_idx, inc, max;
  13552. #endif
  13553. if (!conn || !conn->dom_ctx) {
  13554. return;
  13555. }
  13556. #if defined(USE_LUA)
  13557. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13558. path)
  13559. > 0) {
  13560. if (is_in_script_path(conn, path)) {
  13561. /* Lua server page: an SSI like page containing mostly plain
  13562. * html code plus some tags with server generated contents. */
  13563. handle_lsp_request(conn, path, file, NULL);
  13564. } else {
  13565. /* Script was in an illegal path */
  13566. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13567. }
  13568. return;
  13569. }
  13570. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13571. > 0) {
  13572. if (is_in_script_path(conn, path)) {
  13573. /* Lua in-server module script: a CGI like script used to
  13574. * generate the entire reply. */
  13575. mg_exec_lua_script(conn, path, NULL);
  13576. } else {
  13577. /* Script was in an illegal path */
  13578. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13579. }
  13580. return;
  13581. }
  13582. #endif
  13583. #if defined(USE_DUKTAPE)
  13584. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13585. path)
  13586. > 0) {
  13587. if (is_in_script_path(conn, path)) {
  13588. /* Call duktape to generate the page */
  13589. mg_exec_duktape_script(conn, path);
  13590. } else {
  13591. /* Script was in an illegal path */
  13592. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13593. }
  13594. return;
  13595. }
  13596. #endif
  13597. #if !defined(NO_CGI)
  13598. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13599. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13600. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13601. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13602. if (match_prefix_strlen(
  13603. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13604. path)
  13605. > 0) {
  13606. if (is_in_script_path(conn, path)) {
  13607. /* CGI scripts may support all HTTP methods */
  13608. handle_cgi_request(conn, path, cgi_config_idx);
  13609. } else {
  13610. /* Script was in an illegal path */
  13611. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13612. }
  13613. return;
  13614. }
  13615. }
  13616. }
  13617. #endif /* !NO_CGI */
  13618. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13619. if (is_in_script_path(conn, path)) {
  13620. handle_ssi_file_request(conn, path, file);
  13621. } else {
  13622. /* Script was in an illegal path */
  13623. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13624. }
  13625. return;
  13626. }
  13627. #if !defined(NO_CACHING)
  13628. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13629. /* Send 304 "Not Modified" - this must not send any body data */
  13630. handle_not_modified_static_file_request(conn, file);
  13631. return;
  13632. }
  13633. #endif /* !NO_CACHING */
  13634. handle_static_file_request(conn, path, file, NULL, NULL);
  13635. }
  13636. #endif /* NO_FILESYSTEMS */
  13637. static void
  13638. close_all_listening_sockets(struct mg_context *ctx)
  13639. {
  13640. unsigned int i;
  13641. if (!ctx) {
  13642. return;
  13643. }
  13644. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13645. closesocket(ctx->listening_sockets[i].sock);
  13646. #if defined(USE_X_DOM_SOCKET)
  13647. /* For unix domain sockets, the socket name represents a file that has
  13648. * to be deleted. */
  13649. /* See
  13650. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13651. */
  13652. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13653. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13654. IGNORE_UNUSED_RESULT(
  13655. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13656. }
  13657. #endif
  13658. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13659. }
  13660. mg_free(ctx->listening_sockets);
  13661. ctx->listening_sockets = NULL;
  13662. mg_free(ctx->listening_socket_fds);
  13663. ctx->listening_socket_fds = NULL;
  13664. }
  13665. /* Valid listening port specification is: [ip_address:]port[s]
  13666. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13667. * Examples for IPv6: [::]:80, [::1]:80,
  13668. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13669. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13670. * In order to bind to both, IPv4 and IPv6, you can either add
  13671. * both ports using 8080,[::]:8080, or the short form +8080.
  13672. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13673. * one only accepting IPv4 the other only IPv6. +8080 creates
  13674. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13675. * environment, they might work differently, or might not work
  13676. * at all - it must be tested what options work best in the
  13677. * relevant network environment.
  13678. */
  13679. static int
  13680. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13681. {
  13682. unsigned int a, b, c, d;
  13683. unsigned port;
  13684. unsigned long portUL;
  13685. int len;
  13686. const char *cb;
  13687. char *endptr;
  13688. #if defined(USE_IPV6)
  13689. char buf[100] = {0};
  13690. #endif
  13691. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13692. * Also, all-zeroes in the socket address means binding to all addresses
  13693. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13694. memset(so, 0, sizeof(*so));
  13695. so->lsa.sin.sin_family = AF_INET;
  13696. *ip_version = 0;
  13697. /* Initialize len as invalid. */
  13698. port = 0;
  13699. len = 0;
  13700. /* Test for different ways to format this string */
  13701. if (sscanf(vec->ptr,
  13702. "%u.%u.%u.%u:%u%n",
  13703. &a,
  13704. &b,
  13705. &c,
  13706. &d,
  13707. &port,
  13708. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13709. // to an integer value, but function will not report
  13710. // conversion errors; consider using 'strtol' instead
  13711. == 5) {
  13712. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13713. so->lsa.sin.sin_addr.s_addr =
  13714. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13715. so->lsa.sin.sin_port = htons((uint16_t)port);
  13716. *ip_version = 4;
  13717. #if defined(USE_IPV6)
  13718. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13719. && ((size_t)len <= vec->len)
  13720. && mg_inet_pton(
  13721. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13722. /* IPv6 address, examples: see above */
  13723. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13724. */
  13725. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13726. *ip_version = 6;
  13727. #endif
  13728. } else if ((vec->ptr[0] == '+')
  13729. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13730. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13731. // string to an integer value, but function will not
  13732. // report conversion errors; consider using 'strtol'
  13733. // instead
  13734. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13735. /* Add 1 to len for the + character we skipped before */
  13736. len++;
  13737. #if defined(USE_IPV6)
  13738. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13739. so->lsa.sin6.sin6_family = AF_INET6;
  13740. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13741. *ip_version = 4 + 6;
  13742. #else
  13743. /* Bind to IPv4 only, since IPv6 is not built in. */
  13744. so->lsa.sin.sin_port = htons((uint16_t)port);
  13745. *ip_version = 4;
  13746. #endif
  13747. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13748. && (vec->ptr != endptr)) {
  13749. len = (int)(endptr - vec->ptr);
  13750. port = (uint16_t)portUL;
  13751. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13752. so->lsa.sin.sin_port = htons((uint16_t)port);
  13753. *ip_version = 4;
  13754. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13755. /* String could be a hostname. This check algorithm
  13756. * will only work for RFC 952 compliant hostnames,
  13757. * starting with a letter, containing only letters,
  13758. * digits and hyphen ('-'). Newer specs may allow
  13759. * more, but this is not guaranteed here, since it
  13760. * may interfere with rules for port option lists. */
  13761. /* According to RFC 1035, hostnames are restricted to 255 characters
  13762. * in total (63 between two dots). */
  13763. char hostname[256];
  13764. size_t hostnlen = (size_t)(cb - vec->ptr);
  13765. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13766. /* This would be invalid in any case */
  13767. *ip_version = 0;
  13768. return 0;
  13769. }
  13770. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13771. if (mg_inet_pton(
  13772. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13773. if (sscanf(cb + 1, "%u%n", &port, &len)
  13774. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13775. // string to an integer value, but function will not
  13776. // report conversion errors; consider using 'strtol'
  13777. // instead
  13778. *ip_version = 4;
  13779. so->lsa.sin.sin_port = htons((uint16_t)port);
  13780. len += (int)(hostnlen + 1);
  13781. } else {
  13782. len = 0;
  13783. }
  13784. #if defined(USE_IPV6)
  13785. } else if (mg_inet_pton(AF_INET6,
  13786. hostname,
  13787. &so->lsa.sin6,
  13788. sizeof(so->lsa.sin6),
  13789. 1)) {
  13790. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13791. *ip_version = 6;
  13792. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13793. len += (int)(hostnlen + 1);
  13794. } else {
  13795. len = 0;
  13796. }
  13797. #endif
  13798. } else {
  13799. len = 0;
  13800. }
  13801. #if defined(USE_X_DOM_SOCKET)
  13802. } else if (vec->ptr[0] == 'x') {
  13803. /* unix (linux) domain socket */
  13804. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13805. len = vec->len;
  13806. so->lsa.sun.sun_family = AF_UNIX;
  13807. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13808. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13809. port = 0;
  13810. *ip_version = 99;
  13811. } else {
  13812. /* String too long */
  13813. len = 0;
  13814. }
  13815. #endif
  13816. } else {
  13817. /* Parsing failure. */
  13818. len = 0;
  13819. }
  13820. /* sscanf and the option splitting code ensure the following condition
  13821. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13822. * 'r' */
  13823. if ((len > 0) && (is_valid_port(port))) {
  13824. int bad_suffix = 0;
  13825. size_t i;
  13826. /* Parse any suffix character(s) after the port number */
  13827. for (i = len; i < vec->len; i++) {
  13828. unsigned char *opt = NULL;
  13829. switch (vec->ptr[i]) {
  13830. case 'o':
  13831. opt = &so->is_optional;
  13832. break;
  13833. case 'r':
  13834. opt = &so->ssl_redir;
  13835. break;
  13836. case 's':
  13837. opt = &so->is_ssl;
  13838. break;
  13839. default: /* empty */
  13840. break;
  13841. }
  13842. if ((opt) && (*opt == 0))
  13843. *opt = 1;
  13844. else {
  13845. bad_suffix = 1;
  13846. break;
  13847. }
  13848. }
  13849. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13850. return 1;
  13851. }
  13852. }
  13853. /* Reset ip_version to 0 if there is an error */
  13854. *ip_version = 0;
  13855. return 0;
  13856. }
  13857. /* Is there any SSL port in use? */
  13858. static int
  13859. is_ssl_port_used(const char *ports)
  13860. {
  13861. if (ports) {
  13862. /* There are several different allowed syntax variants:
  13863. * - "80" for a single port using every network interface
  13864. * - "localhost:80" for a single port using only localhost
  13865. * - "80,localhost:8080" for two ports, one bound to localhost
  13866. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13867. * to IPv4 localhost, one to IPv6 localhost
  13868. * - "+80" use port 80 for IPv4 and IPv6
  13869. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13870. * for both: IPv4 and IPv4
  13871. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13872. * additionally port 8080 bound to localhost connections
  13873. *
  13874. * If we just look for 's' anywhere in the string, "localhost:80"
  13875. * will be detected as SSL (false positive).
  13876. * Looking for 's' after a digit may cause false positives in
  13877. * "my24service:8080".
  13878. * Looking from 's' backward if there are only ':' and numbers
  13879. * before will not work for "24service:8080" (non SSL, port 8080)
  13880. * or "24s" (SSL, port 24).
  13881. *
  13882. * Remark: Initially hostnames were not allowed to start with a
  13883. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13884. * Section 2.1).
  13885. *
  13886. * To get this correct, the entire string must be parsed as a whole,
  13887. * reading it as a list element for element and parsing with an
  13888. * algorithm equivalent to parse_port_string.
  13889. *
  13890. * In fact, we use local interface names here, not arbitrary
  13891. * hostnames, so in most cases the only name will be "localhost".
  13892. *
  13893. * So, for now, we use this simple algorithm, that may still return
  13894. * a false positive in bizarre cases.
  13895. */
  13896. int i;
  13897. int portslen = (int)strlen(ports);
  13898. char prevIsNumber = 0;
  13899. for (i = 0; i < portslen; i++) {
  13900. if (prevIsNumber) {
  13901. int suffixCharIdx = (ports[i] == 'o')
  13902. ? (i + 1)
  13903. : i; /* allow "os" and "or" suffixes */
  13904. if (ports[suffixCharIdx] == 's'
  13905. || ports[suffixCharIdx] == 'r') {
  13906. return 1;
  13907. }
  13908. }
  13909. if (ports[i] >= '0' && ports[i] <= '9') {
  13910. prevIsNumber = 1;
  13911. } else {
  13912. prevIsNumber = 0;
  13913. }
  13914. }
  13915. }
  13916. return 0;
  13917. }
  13918. static int
  13919. set_ports_option(struct mg_context *phys_ctx)
  13920. {
  13921. const char *list;
  13922. int on = 1;
  13923. #if defined(USE_IPV6)
  13924. int off = 0;
  13925. #endif
  13926. struct vec vec;
  13927. struct socket so, *ptr;
  13928. struct mg_pollfd *pfd;
  13929. union usa usa;
  13930. socklen_t len;
  13931. int ip_version;
  13932. int portsTotal = 0;
  13933. int portsOk = 0;
  13934. const char *opt_txt;
  13935. long opt_listen_backlog;
  13936. if (!phys_ctx) {
  13937. return 0;
  13938. }
  13939. memset(&so, 0, sizeof(so));
  13940. memset(&usa, 0, sizeof(usa));
  13941. len = sizeof(usa);
  13942. list = phys_ctx->dd.config[LISTENING_PORTS];
  13943. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13944. portsTotal++;
  13945. if (!parse_port_string(&vec, &so, &ip_version)) {
  13946. mg_cry_ctx_internal(
  13947. phys_ctx,
  13948. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13949. (int)vec.len,
  13950. vec.ptr,
  13951. portsTotal,
  13952. "[IP_ADDRESS:]PORT[s|r]");
  13953. continue;
  13954. }
  13955. #if !defined(NO_SSL)
  13956. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13957. mg_cry_ctx_internal(phys_ctx,
  13958. "Cannot add SSL socket (entry %i)",
  13959. portsTotal);
  13960. continue;
  13961. }
  13962. #endif
  13963. /* Create socket. */
  13964. /* For a list of protocol numbers (e.g., TCP==6) see:
  13965. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13966. */
  13967. if ((so.sock =
  13968. socket(so.lsa.sa.sa_family,
  13969. SOCK_STREAM,
  13970. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13971. == INVALID_SOCKET) {
  13972. mg_cry_ctx_internal(phys_ctx,
  13973. "cannot create socket (entry %i)",
  13974. portsTotal);
  13975. if (so.is_optional) {
  13976. portsOk++; /* it's okay if we couldn't create a socket,
  13977. this port is optional anyway */
  13978. }
  13979. continue;
  13980. }
  13981. #if defined(_WIN32)
  13982. /* Windows SO_REUSEADDR lets many procs binds to a
  13983. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13984. * if someone already has the socket -- DTL */
  13985. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13986. * Windows might need a few seconds before
  13987. * the same port can be used again in the
  13988. * same process, so a short Sleep may be
  13989. * required between mg_stop and mg_start.
  13990. */
  13991. if (setsockopt(so.sock,
  13992. SOL_SOCKET,
  13993. SO_EXCLUSIVEADDRUSE,
  13994. (SOCK_OPT_TYPE)&on,
  13995. sizeof(on))
  13996. != 0) {
  13997. /* Set reuse option, but don't abort on errors. */
  13998. mg_cry_ctx_internal(
  13999. phys_ctx,
  14000. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  14001. portsTotal);
  14002. }
  14003. #else
  14004. if (setsockopt(so.sock,
  14005. SOL_SOCKET,
  14006. SO_REUSEADDR,
  14007. (SOCK_OPT_TYPE)&on,
  14008. sizeof(on))
  14009. != 0) {
  14010. /* Set reuse option, but don't abort on errors. */
  14011. mg_cry_ctx_internal(
  14012. phys_ctx,
  14013. "cannot set socket option SO_REUSEADDR (entry %i)",
  14014. portsTotal);
  14015. }
  14016. #endif
  14017. #if defined(USE_X_DOM_SOCKET)
  14018. if (ip_version == 99) {
  14019. /* Unix domain socket */
  14020. } else
  14021. #endif
  14022. if (ip_version > 4) {
  14023. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14024. #if defined(USE_IPV6)
  14025. if (ip_version > 6) {
  14026. if (so.lsa.sa.sa_family == AF_INET6
  14027. && setsockopt(so.sock,
  14028. IPPROTO_IPV6,
  14029. IPV6_V6ONLY,
  14030. (void *)&off,
  14031. sizeof(off))
  14032. != 0) {
  14033. /* Set IPv6 only option, but don't abort on errors. */
  14034. mg_cry_ctx_internal(phys_ctx,
  14035. "cannot set socket option "
  14036. "IPV6_V6ONLY=off (entry %i)",
  14037. portsTotal);
  14038. }
  14039. } else {
  14040. if (so.lsa.sa.sa_family == AF_INET6
  14041. && setsockopt(so.sock,
  14042. IPPROTO_IPV6,
  14043. IPV6_V6ONLY,
  14044. (void *)&on,
  14045. sizeof(on))
  14046. != 0) {
  14047. /* Set IPv6 only option, but don't abort on errors. */
  14048. mg_cry_ctx_internal(phys_ctx,
  14049. "cannot set socket option "
  14050. "IPV6_V6ONLY=on (entry %i)",
  14051. portsTotal);
  14052. }
  14053. }
  14054. #else
  14055. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14056. closesocket(so.sock);
  14057. if (so.is_optional) {
  14058. portsOk++; /* it's okay if we couldn't set the socket option,
  14059. this port is optional anyway */
  14060. }
  14061. so.sock = INVALID_SOCKET;
  14062. continue;
  14063. #endif
  14064. }
  14065. if (so.lsa.sa.sa_family == AF_INET) {
  14066. len = sizeof(so.lsa.sin);
  14067. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14068. mg_cry_ctx_internal(phys_ctx,
  14069. "cannot bind to %.*s: %d (%s)",
  14070. (int)vec.len,
  14071. vec.ptr,
  14072. (int)ERRNO,
  14073. strerror(errno));
  14074. closesocket(so.sock);
  14075. so.sock = INVALID_SOCKET;
  14076. if (so.is_optional) {
  14077. portsOk++; /* it's okay if we couldn't bind, this port is
  14078. optional anyway */
  14079. }
  14080. continue;
  14081. }
  14082. }
  14083. #if defined(USE_IPV6)
  14084. else if (so.lsa.sa.sa_family == AF_INET6) {
  14085. len = sizeof(so.lsa.sin6);
  14086. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14087. mg_cry_ctx_internal(phys_ctx,
  14088. "cannot bind to IPv6 %.*s: %d (%s)",
  14089. (int)vec.len,
  14090. vec.ptr,
  14091. (int)ERRNO,
  14092. strerror(errno));
  14093. closesocket(so.sock);
  14094. so.sock = INVALID_SOCKET;
  14095. if (so.is_optional) {
  14096. portsOk++; /* it's okay if we couldn't bind, this port is
  14097. optional anyway */
  14098. }
  14099. continue;
  14100. }
  14101. }
  14102. #endif
  14103. #if defined(USE_X_DOM_SOCKET)
  14104. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14105. len = sizeof(so.lsa.sun);
  14106. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14107. mg_cry_ctx_internal(phys_ctx,
  14108. "cannot bind to unix socket %s: %d (%s)",
  14109. so.lsa.sun.sun_path,
  14110. (int)ERRNO,
  14111. strerror(errno));
  14112. closesocket(so.sock);
  14113. so.sock = INVALID_SOCKET;
  14114. if (so.is_optional) {
  14115. portsOk++; /* it's okay if we couldn't bind, this port is
  14116. optional anyway */
  14117. }
  14118. continue;
  14119. }
  14120. }
  14121. #endif
  14122. else {
  14123. mg_cry_ctx_internal(
  14124. phys_ctx,
  14125. "cannot bind: address family not supported (entry %i)",
  14126. portsTotal);
  14127. closesocket(so.sock);
  14128. so.sock = INVALID_SOCKET;
  14129. continue;
  14130. }
  14131. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14132. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14133. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14134. mg_cry_ctx_internal(phys_ctx,
  14135. "%s value \"%s\" is invalid",
  14136. config_options[LISTEN_BACKLOG_SIZE].name,
  14137. opt_txt);
  14138. closesocket(so.sock);
  14139. so.sock = INVALID_SOCKET;
  14140. continue;
  14141. }
  14142. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14143. mg_cry_ctx_internal(phys_ctx,
  14144. "cannot listen to %.*s: %d (%s)",
  14145. (int)vec.len,
  14146. vec.ptr,
  14147. (int)ERRNO,
  14148. strerror(errno));
  14149. closesocket(so.sock);
  14150. so.sock = INVALID_SOCKET;
  14151. continue;
  14152. }
  14153. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14154. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14155. int err = (int)ERRNO;
  14156. mg_cry_ctx_internal(phys_ctx,
  14157. "call to getsockname failed %.*s: %d (%s)",
  14158. (int)vec.len,
  14159. vec.ptr,
  14160. err,
  14161. strerror(errno));
  14162. closesocket(so.sock);
  14163. so.sock = INVALID_SOCKET;
  14164. continue;
  14165. }
  14166. /* Update lsa port in case of random free ports */
  14167. #if defined(USE_IPV6)
  14168. if (so.lsa.sa.sa_family == AF_INET6) {
  14169. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14170. } else
  14171. #endif
  14172. {
  14173. so.lsa.sin.sin_port = usa.sin.sin_port;
  14174. }
  14175. if ((ptr = (struct socket *)
  14176. mg_realloc_ctx(phys_ctx->listening_sockets,
  14177. (phys_ctx->num_listening_sockets + 1)
  14178. * sizeof(phys_ctx->listening_sockets[0]),
  14179. phys_ctx))
  14180. == NULL) {
  14181. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14182. closesocket(so.sock);
  14183. so.sock = INVALID_SOCKET;
  14184. continue;
  14185. }
  14186. /* The +2 below includes the original +1 (for the socket we're about to
  14187. * add), plus another +1 for the thread_shutdown_notification_socket
  14188. * that we'll also want to poll() on so that mg_stop() can return
  14189. * quickly
  14190. */
  14191. if ((pfd = (struct mg_pollfd *)
  14192. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14193. (phys_ctx->num_listening_sockets + 2)
  14194. * sizeof(phys_ctx->listening_socket_fds[0]),
  14195. phys_ctx))
  14196. == NULL) {
  14197. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14198. closesocket(so.sock);
  14199. so.sock = INVALID_SOCKET;
  14200. mg_free(ptr);
  14201. continue;
  14202. }
  14203. set_close_on_exec(so.sock, NULL, phys_ctx);
  14204. phys_ctx->listening_sockets = ptr;
  14205. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14206. phys_ctx->listening_socket_fds = pfd;
  14207. phys_ctx->num_listening_sockets++;
  14208. portsOk++;
  14209. }
  14210. if (portsOk != portsTotal) {
  14211. close_all_listening_sockets(phys_ctx);
  14212. portsOk = 0;
  14213. }
  14214. return portsOk;
  14215. }
  14216. static const char *
  14217. header_val(const struct mg_connection *conn, const char *header)
  14218. {
  14219. const char *header_value;
  14220. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14221. return "-";
  14222. } else {
  14223. return header_value;
  14224. }
  14225. }
  14226. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14227. #include "external_log_access.inl"
  14228. #elif !defined(NO_FILESYSTEMS)
  14229. static void
  14230. log_access(const struct mg_connection *conn)
  14231. {
  14232. const struct mg_request_info *ri;
  14233. struct mg_file fi;
  14234. char date[64], src_addr[IP_ADDR_STR_LEN];
  14235. #if defined(REENTRANT_TIME)
  14236. struct tm _tm;
  14237. struct tm *tm = &_tm;
  14238. #else
  14239. struct tm *tm;
  14240. #endif
  14241. const char *referer;
  14242. const char *user_agent;
  14243. char log_buf[4096];
  14244. if (!conn || !conn->dom_ctx) {
  14245. return;
  14246. }
  14247. /* Set log message to "empty" */
  14248. log_buf[0] = 0;
  14249. #if defined(USE_LUA)
  14250. if (conn->phys_ctx->lua_bg_log_available) {
  14251. int ret;
  14252. struct mg_context *ctx = conn->phys_ctx;
  14253. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14254. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14255. /* call "log()" in Lua */
  14256. lua_getglobal(lstate, "log");
  14257. prepare_lua_request_info_inner(conn, lstate);
  14258. push_lua_response_log_data(conn, lstate);
  14259. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14260. if (ret == 0) {
  14261. int t = lua_type(lstate, -1);
  14262. if (t == LUA_TBOOLEAN) {
  14263. if (lua_toboolean(lstate, -1) == 0) {
  14264. /* log() returned false: do not log */
  14265. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14266. return;
  14267. }
  14268. /* log returned true: continue logging */
  14269. } else if (t == LUA_TSTRING) {
  14270. size_t len;
  14271. const char *txt = lua_tolstring(lstate, -1, &len);
  14272. if ((len == 0) || (*txt == 0)) {
  14273. /* log() returned empty string: do not log */
  14274. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14275. return;
  14276. }
  14277. /* Copy test from Lua into log_buf */
  14278. if (len >= sizeof(log_buf)) {
  14279. len = sizeof(log_buf) - 1;
  14280. }
  14281. memcpy(log_buf, txt, len);
  14282. log_buf[len] = 0;
  14283. }
  14284. } else {
  14285. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14286. }
  14287. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14288. }
  14289. #endif
  14290. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14291. if (mg_fopen(conn,
  14292. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14293. MG_FOPEN_MODE_APPEND,
  14294. &fi)
  14295. == 0) {
  14296. fi.access.fp = NULL;
  14297. }
  14298. } else {
  14299. fi.access.fp = NULL;
  14300. }
  14301. /* Log is written to a file and/or a callback. If both are not set,
  14302. * executing the rest of the function is pointless. */
  14303. if ((fi.access.fp == NULL)
  14304. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14305. return;
  14306. }
  14307. /* If we did not get a log message from Lua, create it here. */
  14308. if (!log_buf[0]) {
  14309. #if defined(REENTRANT_TIME)
  14310. localtime_r(&conn->conn_birth_time, tm);
  14311. #else
  14312. tm = localtime(&conn->conn_birth_time);
  14313. #endif
  14314. if (tm != NULL) {
  14315. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14316. } else {
  14317. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14318. }
  14319. ri = &conn->request_info;
  14320. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14321. referer = header_val(conn, "Referer");
  14322. user_agent = header_val(conn, "User-Agent");
  14323. mg_snprintf(conn,
  14324. NULL, /* Ignore truncation in access log */
  14325. log_buf,
  14326. sizeof(log_buf),
  14327. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14328. " %s %s",
  14329. src_addr,
  14330. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14331. date,
  14332. ri->request_method ? ri->request_method : "-",
  14333. ri->request_uri ? ri->request_uri : "-",
  14334. ri->query_string ? "?" : "",
  14335. ri->query_string ? ri->query_string : "",
  14336. ri->http_version,
  14337. conn->status_code,
  14338. conn->num_bytes_sent,
  14339. referer,
  14340. user_agent);
  14341. }
  14342. /* Here we have a log message in log_buf. Call the callback */
  14343. if (conn->phys_ctx->callbacks.log_access) {
  14344. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14345. /* do not log if callback returns non-zero */
  14346. if (fi.access.fp) {
  14347. mg_fclose(&fi.access);
  14348. }
  14349. return;
  14350. }
  14351. }
  14352. /* Store in file */
  14353. if (fi.access.fp) {
  14354. int ok = 1;
  14355. flockfile(fi.access.fp);
  14356. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14357. ok = 0;
  14358. }
  14359. if (fflush(fi.access.fp) != 0) {
  14360. ok = 0;
  14361. }
  14362. funlockfile(fi.access.fp);
  14363. if (mg_fclose(&fi.access) != 0) {
  14364. ok = 0;
  14365. }
  14366. if (!ok) {
  14367. mg_cry_internal(conn,
  14368. "Error writing log file %s",
  14369. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14370. }
  14371. }
  14372. }
  14373. #else
  14374. #error "Either enable filesystems or provide a custom log_access implementation"
  14375. #endif /* Externally provided function */
  14376. /* Verify given socket address against the ACL.
  14377. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14378. */
  14379. static int
  14380. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14381. {
  14382. int allowed, flag, matched;
  14383. struct vec vec;
  14384. if (phys_ctx) {
  14385. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14386. /* If any ACL is set, deny by default */
  14387. allowed = (list == NULL) ? '+' : '-';
  14388. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14389. flag = vec.ptr[0];
  14390. matched = -1;
  14391. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14392. vec.ptr++;
  14393. vec.len--;
  14394. matched = parse_match_net(&vec, sa, 1);
  14395. }
  14396. if (matched < 0) {
  14397. mg_cry_ctx_internal(phys_ctx,
  14398. "%s: subnet must be [+|-]IP-addr[/x]",
  14399. __func__);
  14400. return -1;
  14401. }
  14402. if (matched) {
  14403. allowed = flag;
  14404. }
  14405. }
  14406. return allowed == '+';
  14407. }
  14408. return -1;
  14409. }
  14410. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14411. static int
  14412. set_uid_option(struct mg_context *phys_ctx)
  14413. {
  14414. int success = 0;
  14415. if (phys_ctx) {
  14416. /* We are currently running as curr_uid. */
  14417. const uid_t curr_uid = getuid();
  14418. /* If set, we want to run as run_as_user. */
  14419. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14420. const struct passwd *to_pw = NULL;
  14421. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14422. /* run_as_user does not exist on the system. We can't proceed
  14423. * further. */
  14424. mg_cry_ctx_internal(phys_ctx,
  14425. "%s: unknown user [%s]",
  14426. __func__,
  14427. run_as_user);
  14428. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14429. /* There was either no request to change user, or we're already
  14430. * running as run_as_user. Nothing else to do.
  14431. */
  14432. success = 1;
  14433. } else {
  14434. /* Valid change request. */
  14435. if (setgid(to_pw->pw_gid) == -1) {
  14436. mg_cry_ctx_internal(phys_ctx,
  14437. "%s: setgid(%s): %s",
  14438. __func__,
  14439. run_as_user,
  14440. strerror(errno));
  14441. } else if (setgroups(0, NULL) == -1) {
  14442. mg_cry_ctx_internal(phys_ctx,
  14443. "%s: setgroups(): %s",
  14444. __func__,
  14445. strerror(errno));
  14446. } else if (setuid(to_pw->pw_uid) == -1) {
  14447. mg_cry_ctx_internal(phys_ctx,
  14448. "%s: setuid(%s): %s",
  14449. __func__,
  14450. run_as_user,
  14451. strerror(errno));
  14452. } else {
  14453. success = 1;
  14454. }
  14455. }
  14456. }
  14457. return success;
  14458. }
  14459. #endif /* !_WIN32 */
  14460. static void
  14461. tls_dtor(void *key)
  14462. {
  14463. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14464. /* key == pthread_getspecific(sTlsKey); */
  14465. if (tls) {
  14466. if (tls->is_master == 2) {
  14467. tls->is_master = -3; /* Mark memory as dead */
  14468. mg_free(tls);
  14469. }
  14470. }
  14471. pthread_setspecific(sTlsKey, NULL);
  14472. }
  14473. #if defined(USE_MBEDTLS)
  14474. /* Check if SSL is required.
  14475. * If so, set up ctx->ssl_ctx pointer. */
  14476. static int
  14477. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14478. {
  14479. if (!phys_ctx) {
  14480. return 0;
  14481. }
  14482. if (!dom_ctx) {
  14483. dom_ctx = &(phys_ctx->dd);
  14484. }
  14485. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14486. /* No SSL port is set. No need to setup SSL. */
  14487. return 1;
  14488. }
  14489. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14490. if (dom_ctx->ssl_ctx == NULL) {
  14491. fprintf(stderr, "ssl_ctx malloc failed\n");
  14492. return 0;
  14493. }
  14494. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14495. == 0
  14496. ? 1
  14497. : 0;
  14498. }
  14499. #elif defined(USE_GNUTLS)
  14500. /* Check if SSL is required.
  14501. * If so, set up ctx->ssl_ctx pointer. */
  14502. static int
  14503. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14504. {
  14505. if (!phys_ctx) {
  14506. return 0;
  14507. }
  14508. if (!dom_ctx) {
  14509. dom_ctx = &(phys_ctx->dd);
  14510. }
  14511. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14512. /* No SSL port is set. No need to setup SSL. */
  14513. return 1;
  14514. }
  14515. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14516. if (dom_ctx->ssl_ctx == NULL) {
  14517. fprintf(stderr, "ssl_ctx malloc failed\n");
  14518. return 0;
  14519. }
  14520. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14521. == 0
  14522. ? 1
  14523. : 0;
  14524. }
  14525. #elif !defined(NO_SSL)
  14526. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14527. struct mg_domain_context *dom_ctx,
  14528. const char *pem,
  14529. const char *chain);
  14530. static const char *ssl_error(void);
  14531. static int
  14532. refresh_trust(struct mg_connection *conn)
  14533. {
  14534. struct stat cert_buf;
  14535. int64_t t = 0;
  14536. const char *pem;
  14537. const char *chain;
  14538. int should_verify_peer;
  14539. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14540. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14541. * refresh_trust still can not work. */
  14542. return 0;
  14543. }
  14544. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14545. if (chain == NULL) {
  14546. /* pem is not NULL here */
  14547. chain = pem;
  14548. }
  14549. if (*chain == 0) {
  14550. chain = NULL;
  14551. }
  14552. if (stat(pem, &cert_buf) != -1) {
  14553. t = (int64_t)cert_buf.st_mtime;
  14554. }
  14555. mg_lock_context(conn->phys_ctx);
  14556. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14557. conn->dom_ctx->ssl_cert_last_mtime = t;
  14558. should_verify_peer = 0;
  14559. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14560. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14561. == 0) {
  14562. should_verify_peer = 1;
  14563. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14564. "optional")
  14565. == 0) {
  14566. should_verify_peer = 1;
  14567. }
  14568. }
  14569. if (should_verify_peer) {
  14570. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14571. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14572. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14573. ca_file,
  14574. ca_path)
  14575. != 1) {
  14576. mg_unlock_context(conn->phys_ctx);
  14577. mg_cry_ctx_internal(
  14578. conn->phys_ctx,
  14579. "SSL_CTX_load_verify_locations error: %s "
  14580. "ssl_verify_peer requires setting "
  14581. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14582. "present in "
  14583. "the .conf file?",
  14584. ssl_error());
  14585. return 0;
  14586. }
  14587. }
  14588. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14589. mg_unlock_context(conn->phys_ctx);
  14590. return 0;
  14591. }
  14592. }
  14593. mg_unlock_context(conn->phys_ctx);
  14594. return 1;
  14595. }
  14596. #if defined(OPENSSL_API_1_1)
  14597. #else
  14598. static pthread_mutex_t *ssl_mutexes;
  14599. #endif /* OPENSSL_API_1_1 */
  14600. static int
  14601. sslize(struct mg_connection *conn,
  14602. int (*func)(SSL *),
  14603. const struct mg_client_options *client_options)
  14604. {
  14605. int ret, err;
  14606. int short_trust;
  14607. unsigned timeout = 1024;
  14608. unsigned i;
  14609. if (!conn) {
  14610. return 0;
  14611. }
  14612. short_trust =
  14613. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14614. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14615. if (short_trust) {
  14616. int trust_ret = refresh_trust(conn);
  14617. if (!trust_ret) {
  14618. return trust_ret;
  14619. }
  14620. }
  14621. mg_lock_context(conn->phys_ctx);
  14622. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14623. mg_unlock_context(conn->phys_ctx);
  14624. if (conn->ssl == NULL) {
  14625. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14626. OPENSSL_REMOVE_THREAD_STATE();
  14627. return 0;
  14628. }
  14629. SSL_set_app_data(conn->ssl, (char *)conn);
  14630. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14631. if (ret != 1) {
  14632. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14633. SSL_free(conn->ssl);
  14634. conn->ssl = NULL;
  14635. OPENSSL_REMOVE_THREAD_STATE();
  14636. return 0;
  14637. }
  14638. if (client_options) {
  14639. if (client_options->host_name) {
  14640. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14641. }
  14642. }
  14643. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14644. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14645. /* NOTE: The loop below acts as a back-off, so we can end
  14646. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14647. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14648. if (to >= 0) {
  14649. timeout = (unsigned)to;
  14650. }
  14651. }
  14652. /* SSL functions may fail and require to be called again:
  14653. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14654. * Here "func" could be SSL_connect or SSL_accept. */
  14655. for (i = 0; i <= timeout; i += 50) {
  14656. ERR_clear_error();
  14657. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14658. ret = func(conn->ssl);
  14659. if (ret != 1) {
  14660. err = SSL_get_error(conn->ssl, ret);
  14661. if ((err == SSL_ERROR_WANT_CONNECT)
  14662. || (err == SSL_ERROR_WANT_ACCEPT)
  14663. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14664. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14665. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14666. /* Don't wait if the server is going to be stopped. */
  14667. break;
  14668. }
  14669. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14670. /* Simply retry the function call. */
  14671. mg_sleep(50);
  14672. } else {
  14673. /* Need to retry the function call "later".
  14674. * See https://linux.die.net/man/3/ssl_get_error
  14675. * This is typical for non-blocking sockets. */
  14676. struct mg_pollfd pfd[2];
  14677. int pollres;
  14678. unsigned int num_sock = 1;
  14679. pfd[0].fd = conn->client.sock;
  14680. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14681. || (err == SSL_ERROR_WANT_WRITE))
  14682. ? POLLOUT
  14683. : POLLIN;
  14684. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14685. pfd[num_sock].fd =
  14686. conn->phys_ctx->thread_shutdown_notification_socket;
  14687. pfd[num_sock].events = POLLIN;
  14688. num_sock++;
  14689. }
  14690. pollres = mg_poll(pfd,
  14691. num_sock,
  14692. 50,
  14693. &(conn->phys_ctx->stop_flag));
  14694. if (pollres < 0) {
  14695. /* Break if error occurred (-1)
  14696. * or server shutdown (-2) */
  14697. break;
  14698. }
  14699. }
  14700. } else if (err == SSL_ERROR_SYSCALL) {
  14701. /* This is an IO error. Look at errno. */
  14702. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14703. break;
  14704. } else {
  14705. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14706. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14707. break;
  14708. }
  14709. } else {
  14710. /* success */
  14711. break;
  14712. }
  14713. }
  14714. ERR_clear_error();
  14715. if (ret != 1) {
  14716. SSL_free(conn->ssl);
  14717. conn->ssl = NULL;
  14718. OPENSSL_REMOVE_THREAD_STATE();
  14719. return 0;
  14720. }
  14721. return 1;
  14722. }
  14723. /* Return OpenSSL error message (from CRYPTO lib) */
  14724. static const char *
  14725. ssl_error(void)
  14726. {
  14727. unsigned long err;
  14728. err = ERR_get_error();
  14729. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14730. }
  14731. static int
  14732. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14733. {
  14734. int i;
  14735. const char hexdigit[] = "0123456789abcdef";
  14736. if ((memlen <= 0) || (buflen <= 0)) {
  14737. return 0;
  14738. }
  14739. if (buflen < (3 * memlen)) {
  14740. return 0;
  14741. }
  14742. for (i = 0; i < memlen; i++) {
  14743. if (i > 0) {
  14744. buf[3 * i - 1] = ' ';
  14745. }
  14746. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14747. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14748. }
  14749. buf[3 * memlen - 1] = 0;
  14750. return 1;
  14751. }
  14752. static int
  14753. ssl_get_client_cert_info(const struct mg_connection *conn,
  14754. struct mg_client_cert *client_cert)
  14755. {
  14756. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14757. if (cert) {
  14758. char str_buf[1024];
  14759. unsigned char buf[256];
  14760. char *str_serial = NULL;
  14761. unsigned int ulen;
  14762. int ilen;
  14763. unsigned char *tmp_buf;
  14764. unsigned char *tmp_p;
  14765. /* Handle to algorithm used for fingerprint */
  14766. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14767. /* Get Subject and issuer */
  14768. X509_NAME *subj = X509_get_subject_name(cert);
  14769. X509_NAME *iss = X509_get_issuer_name(cert);
  14770. /* Get serial number */
  14771. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14772. /* Translate serial number to a hex string */
  14773. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14774. if (serial_bn) {
  14775. str_serial = BN_bn2hex(serial_bn);
  14776. BN_free(serial_bn);
  14777. }
  14778. client_cert->serial =
  14779. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14780. /* Translate subject and issuer to a string */
  14781. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14782. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14783. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14784. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14785. /* Calculate SHA1 fingerprint and store as a hex string */
  14786. ulen = 0;
  14787. /* ASN1_digest is deprecated. Do the calculation manually,
  14788. * using EVP_Digest. */
  14789. ilen = i2d_X509(cert, NULL);
  14790. tmp_buf = (ilen > 0)
  14791. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14792. conn->phys_ctx)
  14793. : NULL;
  14794. if (tmp_buf) {
  14795. tmp_p = tmp_buf;
  14796. (void)i2d_X509(cert, &tmp_p);
  14797. if (!EVP_Digest(
  14798. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14799. ulen = 0;
  14800. }
  14801. mg_free(tmp_buf);
  14802. }
  14803. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14804. *str_buf = 0;
  14805. }
  14806. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14807. client_cert->peer_cert = (void *)cert;
  14808. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14809. * see https://linux.die.net/man/3/bn_bn2hex */
  14810. OPENSSL_free(str_serial);
  14811. return 1;
  14812. }
  14813. return 0;
  14814. }
  14815. #if defined(OPENSSL_API_1_1)
  14816. #else
  14817. static void
  14818. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14819. {
  14820. (void)line;
  14821. (void)file;
  14822. if (mode & 1) {
  14823. /* 1 is CRYPTO_LOCK */
  14824. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14825. } else {
  14826. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14827. }
  14828. }
  14829. #endif /* OPENSSL_API_1_1 */
  14830. #if !defined(NO_SSL_DL)
  14831. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14832. static void *
  14833. load_tls_dll(char *ebuf,
  14834. size_t ebuf_len,
  14835. const char *dll_name,
  14836. struct ssl_func *sw,
  14837. int *feature_missing)
  14838. {
  14839. union {
  14840. void *p;
  14841. void (*fp)(void);
  14842. } u;
  14843. void *dll_handle;
  14844. struct ssl_func *fp;
  14845. int ok;
  14846. int truncated = 0;
  14847. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14848. mg_snprintf(NULL,
  14849. NULL, /* No truncation check for ebuf */
  14850. ebuf,
  14851. ebuf_len,
  14852. "%s: cannot load %s",
  14853. __func__,
  14854. dll_name);
  14855. return NULL;
  14856. }
  14857. ok = 1;
  14858. for (fp = sw; fp->name != NULL; fp++) {
  14859. #if defined(_WIN32)
  14860. /* GetProcAddress() returns pointer to function */
  14861. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14862. #else
  14863. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14864. * pointers to function pointers. We need to use a union to make a
  14865. * cast. */
  14866. u.p = dlsym(dll_handle, fp->name);
  14867. #endif /* _WIN32 */
  14868. /* Set pointer (might be NULL) */
  14869. fp->ptr = u.fp;
  14870. if (u.fp == NULL) {
  14871. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14872. if (feature_missing) {
  14873. feature_missing[fp->required]++;
  14874. }
  14875. if (fp->required == TLS_Mandatory) {
  14876. /* Mandatory function is missing */
  14877. if (ok) {
  14878. /* This is the first missing function.
  14879. * Create a new error message. */
  14880. mg_snprintf(NULL,
  14881. &truncated,
  14882. ebuf,
  14883. ebuf_len,
  14884. "%s: %s: cannot find %s",
  14885. __func__,
  14886. dll_name,
  14887. fp->name);
  14888. ok = 0;
  14889. } else {
  14890. /* This is yet anothermissing function.
  14891. * Append existing error message. */
  14892. size_t cur_len = strlen(ebuf);
  14893. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14894. mg_snprintf(NULL,
  14895. &truncated,
  14896. ebuf + cur_len,
  14897. ebuf_len - cur_len - 3,
  14898. ", %s",
  14899. fp->name);
  14900. if (truncated) {
  14901. /* If truncated, add "..." */
  14902. strcat(ebuf, "...");
  14903. }
  14904. }
  14905. }
  14906. }
  14907. }
  14908. }
  14909. if (!ok) {
  14910. (void)dlclose(dll_handle);
  14911. return NULL;
  14912. }
  14913. return dll_handle;
  14914. }
  14915. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14916. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14917. #endif /* NO_SSL_DL */
  14918. #if defined(SSL_ALREADY_INITIALIZED)
  14919. static volatile ptrdiff_t cryptolib_users =
  14920. 1; /* Reference counter for crypto library. */
  14921. #else
  14922. static volatile ptrdiff_t cryptolib_users =
  14923. 0; /* Reference counter for crypto library. */
  14924. #endif
  14925. static int
  14926. initialize_openssl(char *ebuf, size_t ebuf_len)
  14927. {
  14928. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14929. int i, num_locks;
  14930. size_t size;
  14931. #endif
  14932. if (ebuf_len > 0) {
  14933. ebuf[0] = 0;
  14934. }
  14935. #if !defined(NO_SSL_DL)
  14936. if (!cryptolib_dll_handle) {
  14937. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14938. cryptolib_dll_handle = load_tls_dll(
  14939. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14940. if (!cryptolib_dll_handle) {
  14941. mg_snprintf(NULL,
  14942. NULL, /* No truncation check for ebuf */
  14943. ebuf,
  14944. ebuf_len,
  14945. "%s: error loading library %s",
  14946. __func__,
  14947. CRYPTO_LIB);
  14948. DEBUG_TRACE("%s", ebuf);
  14949. return 0;
  14950. }
  14951. }
  14952. #endif /* NO_SSL_DL */
  14953. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14954. return 1;
  14955. }
  14956. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14957. /* Initialize locking callbacks, needed for thread safety.
  14958. * http://www.openssl.org/support/faq.html#PROG1
  14959. */
  14960. num_locks = CRYPTO_num_locks();
  14961. if (num_locks < 0) {
  14962. num_locks = 0;
  14963. }
  14964. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14965. /* allocate mutex array, if required */
  14966. if (num_locks == 0) {
  14967. /* No mutex array required */
  14968. ssl_mutexes = NULL;
  14969. } else {
  14970. /* Mutex array required - allocate it */
  14971. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14972. /* Check OOM */
  14973. if (ssl_mutexes == NULL) {
  14974. mg_snprintf(NULL,
  14975. NULL, /* No truncation check for ebuf */
  14976. ebuf,
  14977. ebuf_len,
  14978. "%s: cannot allocate mutexes: %s",
  14979. __func__,
  14980. ssl_error());
  14981. DEBUG_TRACE("%s", ebuf);
  14982. return 0;
  14983. }
  14984. /* initialize mutex array */
  14985. for (i = 0; i < num_locks; i++) {
  14986. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14987. mg_snprintf(NULL,
  14988. NULL, /* No truncation check for ebuf */
  14989. ebuf,
  14990. ebuf_len,
  14991. "%s: error initializing mutex %i of %i",
  14992. __func__,
  14993. i,
  14994. num_locks);
  14995. DEBUG_TRACE("%s", ebuf);
  14996. mg_free(ssl_mutexes);
  14997. return 0;
  14998. }
  14999. }
  15000. }
  15001. CRYPTO_set_locking_callback(&ssl_locking_callback);
  15002. CRYPTO_set_id_callback(&mg_current_thread_id);
  15003. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15004. #if !defined(NO_SSL_DL)
  15005. if (!ssllib_dll_handle) {
  15006. ssllib_dll_handle =
  15007. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  15008. if (!ssllib_dll_handle) {
  15009. #if !defined(OPENSSL_API_1_1)
  15010. mg_free(ssl_mutexes);
  15011. #endif
  15012. DEBUG_TRACE("%s", ebuf);
  15013. return 0;
  15014. }
  15015. }
  15016. #endif /* NO_SSL_DL */
  15017. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15018. && !defined(NO_SSL_DL)
  15019. /* Initialize SSL library */
  15020. OPENSSL_init_ssl(0, NULL);
  15021. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15022. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15023. NULL);
  15024. #else
  15025. /* Initialize SSL library */
  15026. SSL_library_init();
  15027. SSL_load_error_strings();
  15028. #endif
  15029. return 1;
  15030. }
  15031. static int
  15032. ssl_use_pem_file(struct mg_context *phys_ctx,
  15033. struct mg_domain_context *dom_ctx,
  15034. const char *pem,
  15035. const char *chain)
  15036. {
  15037. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15038. mg_cry_ctx_internal(phys_ctx,
  15039. "%s: cannot open certificate file %s: %s",
  15040. __func__,
  15041. pem,
  15042. ssl_error());
  15043. return 0;
  15044. }
  15045. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15046. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15047. mg_cry_ctx_internal(phys_ctx,
  15048. "%s: cannot open private key file %s: %s",
  15049. __func__,
  15050. pem,
  15051. ssl_error());
  15052. return 0;
  15053. }
  15054. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15055. mg_cry_ctx_internal(phys_ctx,
  15056. "%s: certificate and private key do not match: %s",
  15057. __func__,
  15058. pem);
  15059. return 0;
  15060. }
  15061. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15062. * chain files that contain private keys and certificates in
  15063. * SSL_CTX_use_certificate_chain_file.
  15064. * The CivetWeb-Server used pem-Files that contained both information.
  15065. * In order to make wolfSSL work, it is split in two files.
  15066. * One file that contains key and certificate used by the server and
  15067. * an optional chain file for the ssl stack.
  15068. */
  15069. if (chain) {
  15070. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15071. mg_cry_ctx_internal(phys_ctx,
  15072. "%s: cannot use certificate chain file %s: %s",
  15073. __func__,
  15074. chain,
  15075. ssl_error());
  15076. return 0;
  15077. }
  15078. }
  15079. return 1;
  15080. }
  15081. #if defined(OPENSSL_API_1_1)
  15082. static unsigned long
  15083. ssl_get_protocol(int version_id)
  15084. {
  15085. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15086. if (version_id > 0)
  15087. ret |= SSL_OP_NO_SSLv2;
  15088. if (version_id > 1)
  15089. ret |= SSL_OP_NO_SSLv3;
  15090. if (version_id > 2)
  15091. ret |= SSL_OP_NO_TLSv1;
  15092. if (version_id > 3)
  15093. ret |= SSL_OP_NO_TLSv1_1;
  15094. if (version_id > 4)
  15095. ret |= SSL_OP_NO_TLSv1_2;
  15096. #if defined(SSL_OP_NO_TLSv1_3)
  15097. if (version_id > 5)
  15098. ret |= SSL_OP_NO_TLSv1_3;
  15099. #endif
  15100. return ret;
  15101. }
  15102. #else
  15103. static long
  15104. ssl_get_protocol(int version_id)
  15105. {
  15106. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15107. if (version_id > 0)
  15108. ret |= SSL_OP_NO_SSLv2;
  15109. if (version_id > 1)
  15110. ret |= SSL_OP_NO_SSLv3;
  15111. if (version_id > 2)
  15112. ret |= SSL_OP_NO_TLSv1;
  15113. if (version_id > 3)
  15114. ret |= SSL_OP_NO_TLSv1_1;
  15115. if (version_id > 4)
  15116. ret |= SSL_OP_NO_TLSv1_2;
  15117. #if defined(SSL_OP_NO_TLSv1_3)
  15118. if (version_id > 5)
  15119. ret |= SSL_OP_NO_TLSv1_3;
  15120. #endif
  15121. return (long)ret;
  15122. }
  15123. #endif /* OPENSSL_API_1_1 */
  15124. /* SSL callback documentation:
  15125. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15126. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15127. * https://linux.die.net/man/3/ssl_set_info_callback */
  15128. /* Note: There is no "const" for the first argument in the documentation
  15129. * examples, however some (maybe most, but not all) headers of OpenSSL
  15130. * versions / OpenSSL compatibility layers have it. Having a different
  15131. * definition will cause a warning in C and an error in C++. Use "const SSL
  15132. * *", while automatic conversion from "SSL *" works for all compilers,
  15133. * but not other way around */
  15134. static void
  15135. ssl_info_callback(const SSL *ssl, int what, int ret)
  15136. {
  15137. (void)ret;
  15138. if (what & SSL_CB_HANDSHAKE_START) {
  15139. SSL_get_app_data(ssl);
  15140. }
  15141. if (what & SSL_CB_HANDSHAKE_DONE) {
  15142. /* TODO: check for openSSL 1.1 */
  15143. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15144. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15145. }
  15146. }
  15147. static int
  15148. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15149. {
  15150. #if defined(GCC_DIAGNOSTIC)
  15151. #pragma GCC diagnostic push
  15152. #pragma GCC diagnostic ignored "-Wcast-align"
  15153. #endif /* defined(GCC_DIAGNOSTIC) */
  15154. /* We used an aligned pointer in SSL_set_app_data */
  15155. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15156. #if defined(GCC_DIAGNOSTIC)
  15157. #pragma GCC diagnostic pop
  15158. #endif /* defined(GCC_DIAGNOSTIC) */
  15159. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15160. (void)ad;
  15161. (void)arg;
  15162. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15163. DEBUG_ASSERT(0);
  15164. return SSL_TLSEXT_ERR_NOACK;
  15165. }
  15166. conn->dom_ctx = &(conn->phys_ctx->dd);
  15167. /* Old clients (Win XP) will not support SNI. Then, there
  15168. * is no server name available in the request - we can
  15169. * only work with the default certificate.
  15170. * Multiple HTTPS hosts on one IP+port are only possible
  15171. * with a certificate containing all alternative names.
  15172. */
  15173. if ((servername == NULL) || (*servername == 0)) {
  15174. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15175. mg_lock_context(conn->phys_ctx);
  15176. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15177. mg_unlock_context(conn->phys_ctx);
  15178. return SSL_TLSEXT_ERR_NOACK;
  15179. }
  15180. DEBUG_TRACE("TLS connection to host %s", servername);
  15181. while (conn->dom_ctx) {
  15182. if (!mg_strcasecmp(servername,
  15183. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15184. /* Found matching domain */
  15185. DEBUG_TRACE("TLS domain %s found",
  15186. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15187. break;
  15188. }
  15189. mg_lock_context(conn->phys_ctx);
  15190. conn->dom_ctx = conn->dom_ctx->next;
  15191. mg_unlock_context(conn->phys_ctx);
  15192. }
  15193. if (conn->dom_ctx == NULL) {
  15194. /* Default domain */
  15195. DEBUG_TRACE("TLS default domain %s used",
  15196. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15197. conn->dom_ctx = &(conn->phys_ctx->dd);
  15198. }
  15199. mg_lock_context(conn->phys_ctx);
  15200. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15201. mg_unlock_context(conn->phys_ctx);
  15202. return SSL_TLSEXT_ERR_OK;
  15203. }
  15204. #if defined(USE_ALPN)
  15205. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15206. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15207. alpn_proto_list + 3 + 8,
  15208. NULL};
  15209. #if defined(USE_HTTP2)
  15210. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15211. alpn_proto_list + 3,
  15212. alpn_proto_list + 3 + 8,
  15213. NULL};
  15214. #endif
  15215. static int
  15216. alpn_select_cb(SSL *ssl,
  15217. const unsigned char **out,
  15218. unsigned char *outlen,
  15219. const unsigned char *in,
  15220. unsigned int inlen,
  15221. void *arg)
  15222. {
  15223. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15224. unsigned int i, j, enable_http2 = 0;
  15225. const char **alpn_proto_order = alpn_proto_order_http1;
  15226. struct mg_workerTLS *tls =
  15227. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15228. (void)ssl;
  15229. if (tls == NULL) {
  15230. /* Need to store protocol in Thread Local Storage */
  15231. /* If there is no Thread Local Storage, don't use ALPN */
  15232. return SSL_TLSEXT_ERR_NOACK;
  15233. }
  15234. #if defined(USE_HTTP2)
  15235. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15236. if (enable_http2) {
  15237. alpn_proto_order = alpn_proto_order_http2;
  15238. }
  15239. #endif
  15240. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15241. /* check all accepted protocols in this order */
  15242. const char *alpn_proto = alpn_proto_order[j];
  15243. /* search input for matching protocol */
  15244. for (i = 0; i < inlen; i++) {
  15245. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15246. *out = in + i + 1;
  15247. *outlen = in[i];
  15248. tls->alpn_proto = alpn_proto;
  15249. return SSL_TLSEXT_ERR_OK;
  15250. }
  15251. }
  15252. }
  15253. /* Nothing found */
  15254. return SSL_TLSEXT_ERR_NOACK;
  15255. }
  15256. static int
  15257. next_protos_advertised_cb(SSL *ssl,
  15258. const unsigned char **data,
  15259. unsigned int *len,
  15260. void *arg)
  15261. {
  15262. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15263. *data = (const unsigned char *)alpn_proto_list;
  15264. *len = (unsigned int)strlen((const char *)data);
  15265. (void)ssl;
  15266. (void)dom_ctx;
  15267. return SSL_TLSEXT_ERR_OK;
  15268. }
  15269. static int
  15270. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15271. {
  15272. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15273. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15274. (const unsigned char *)alpn_proto_list,
  15275. alpn_len);
  15276. if (ret != 0) {
  15277. mg_cry_ctx_internal(phys_ctx,
  15278. "SSL_CTX_set_alpn_protos error: %s",
  15279. ssl_error());
  15280. }
  15281. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15282. alpn_select_cb,
  15283. (void *)dom_ctx);
  15284. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15285. next_protos_advertised_cb,
  15286. (void *)dom_ctx);
  15287. return ret;
  15288. }
  15289. #endif
  15290. /* Setup SSL CTX as required by CivetWeb */
  15291. static int
  15292. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15293. struct mg_domain_context *dom_ctx,
  15294. const char *pem,
  15295. const char *chain)
  15296. {
  15297. int callback_ret;
  15298. int should_verify_peer;
  15299. int peer_certificate_optional;
  15300. const char *ca_path;
  15301. const char *ca_file;
  15302. int use_default_verify_paths;
  15303. int verify_depth;
  15304. struct timespec now_mt;
  15305. md5_byte_t ssl_context_id[16];
  15306. md5_state_t md5state;
  15307. int protocol_ver;
  15308. int ssl_cache_timeout;
  15309. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15310. && !defined(NO_SSL_DL)
  15311. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15312. mg_cry_ctx_internal(phys_ctx,
  15313. "SSL_CTX_new (server) error: %s",
  15314. ssl_error());
  15315. return 0;
  15316. }
  15317. #else
  15318. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15319. mg_cry_ctx_internal(phys_ctx,
  15320. "SSL_CTX_new (server) error: %s",
  15321. ssl_error());
  15322. return 0;
  15323. }
  15324. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15325. #if defined(SSL_OP_NO_TLSv1_3)
  15326. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15327. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15328. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15329. | SSL_OP_NO_TLSv1_3);
  15330. #else
  15331. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15332. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15333. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15334. #endif
  15335. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15336. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15337. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15338. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15339. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15340. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15341. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15342. #if defined(SSL_OP_NO_RENEGOTIATION)
  15343. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15344. #endif
  15345. #if !defined(NO_SSL_DL)
  15346. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15347. #endif /* NO_SSL_DL */
  15348. /* In SSL documentation examples callback defined without const
  15349. * specifier 'void (*)(SSL *, int, int)' See:
  15350. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15351. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15352. * But in the source code const SSL is used:
  15353. * 'void (*)(const SSL *, int, int)' See:
  15354. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15355. * Problem about wrong documentation described, but not resolved:
  15356. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15357. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15358. * But when compiled with modern C++ compiler, correct const should be
  15359. * provided
  15360. */
  15361. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15362. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15363. ssl_servername_callback);
  15364. /* If a callback has been specified, call it. */
  15365. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15366. ? 0
  15367. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15368. phys_ctx->user_data));
  15369. /* If callback returns 0, civetweb sets up the SSL certificate.
  15370. * If it returns 1, civetweb assumes the callback already did this.
  15371. * If it returns -1, initializing ssl fails. */
  15372. if (callback_ret < 0) {
  15373. mg_cry_ctx_internal(phys_ctx,
  15374. "SSL callback returned error: %i",
  15375. callback_ret);
  15376. return 0;
  15377. }
  15378. if (callback_ret > 0) {
  15379. /* Callback did everything. */
  15380. return 1;
  15381. }
  15382. /* If a domain callback has been specified, call it. */
  15383. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15384. ? 0
  15385. : (phys_ctx->callbacks.init_ssl_domain(
  15386. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15387. dom_ctx->ssl_ctx,
  15388. phys_ctx->user_data));
  15389. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15390. * If it returns 1, civetweb assumes the callback already did this.
  15391. * If it returns -1, initializing ssl fails. */
  15392. if (callback_ret < 0) {
  15393. mg_cry_ctx_internal(phys_ctx,
  15394. "Domain SSL callback returned error: %i",
  15395. callback_ret);
  15396. return 0;
  15397. }
  15398. if (callback_ret > 0) {
  15399. /* Domain callback did everything. */
  15400. return 1;
  15401. }
  15402. /* Use some combination of start time, domain and port as a SSL
  15403. * context ID. This should be unique on the current machine. */
  15404. md5_init(&md5state);
  15405. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15406. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15407. md5_append(&md5state,
  15408. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15409. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15410. md5_append(&md5state,
  15411. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15412. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15413. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15414. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15415. md5_finish(&md5state, ssl_context_id);
  15416. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15417. (unsigned char *)ssl_context_id,
  15418. sizeof(ssl_context_id));
  15419. if (pem != NULL) {
  15420. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15421. return 0;
  15422. }
  15423. }
  15424. /* Should we support client certificates? */
  15425. /* Default is "no". */
  15426. should_verify_peer = 0;
  15427. peer_certificate_optional = 0;
  15428. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15429. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15430. /* Yes, they are mandatory */
  15431. should_verify_peer = 1;
  15432. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15433. "optional")
  15434. == 0) {
  15435. /* Yes, they are optional */
  15436. should_verify_peer = 1;
  15437. peer_certificate_optional = 1;
  15438. }
  15439. }
  15440. use_default_verify_paths =
  15441. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15442. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15443. == 0);
  15444. if (should_verify_peer) {
  15445. ca_path = dom_ctx->config[SSL_CA_PATH];
  15446. ca_file = dom_ctx->config[SSL_CA_FILE];
  15447. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15448. != 1) {
  15449. mg_cry_ctx_internal(phys_ctx,
  15450. "SSL_CTX_load_verify_locations error: %s "
  15451. "ssl_verify_peer requires setting "
  15452. "either ssl_ca_path or ssl_ca_file. "
  15453. "Is any of them present in the "
  15454. ".conf file?",
  15455. ssl_error());
  15456. return 0;
  15457. }
  15458. if (peer_certificate_optional) {
  15459. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15460. } else {
  15461. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15462. SSL_VERIFY_PEER
  15463. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15464. NULL);
  15465. }
  15466. if (use_default_verify_paths
  15467. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15468. mg_cry_ctx_internal(phys_ctx,
  15469. "SSL_CTX_set_default_verify_paths error: %s",
  15470. ssl_error());
  15471. return 0;
  15472. }
  15473. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15474. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15475. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15476. }
  15477. }
  15478. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15479. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15480. dom_ctx->config[SSL_CIPHER_LIST])
  15481. != 1) {
  15482. mg_cry_ctx_internal(phys_ctx,
  15483. "SSL_CTX_set_cipher_list error: %s",
  15484. ssl_error());
  15485. }
  15486. }
  15487. /* SSL session caching */
  15488. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15489. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15490. : 0);
  15491. if (ssl_cache_timeout > 0) {
  15492. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15493. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15494. * default */
  15495. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15496. }
  15497. #if defined(USE_ALPN)
  15498. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15499. #if !defined(NO_SSL_DL)
  15500. if (!tls_feature_missing[TLS_ALPN])
  15501. #endif
  15502. {
  15503. init_alpn(phys_ctx, dom_ctx);
  15504. }
  15505. #endif
  15506. return 1;
  15507. }
  15508. /* Check if SSL is required.
  15509. * If so, dynamically load SSL library
  15510. * and set up ctx->ssl_ctx pointer. */
  15511. static int
  15512. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15513. {
  15514. void *ssl_ctx = 0;
  15515. int callback_ret;
  15516. const char *pem;
  15517. const char *chain;
  15518. char ebuf[128];
  15519. if (!phys_ctx) {
  15520. return 0;
  15521. }
  15522. if (!dom_ctx) {
  15523. dom_ctx = &(phys_ctx->dd);
  15524. }
  15525. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15526. /* No SSL port is set. No need to setup SSL. */
  15527. return 1;
  15528. }
  15529. /* Check for external SSL_CTX */
  15530. callback_ret =
  15531. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15532. ? 0
  15533. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15534. phys_ctx->user_data));
  15535. if (callback_ret < 0) {
  15536. /* Callback exists and returns <0: Initializing failed. */
  15537. mg_cry_ctx_internal(phys_ctx,
  15538. "external_ssl_ctx callback returned error: %i",
  15539. callback_ret);
  15540. return 0;
  15541. } else if (callback_ret > 0) {
  15542. /* Callback exists and returns >0: Initializing complete,
  15543. * civetweb should not modify the SSL context. */
  15544. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15545. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15546. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15547. return 0;
  15548. }
  15549. return 1;
  15550. }
  15551. /* If the callback does not exist or return 0, civetweb must initialize
  15552. * the SSL context. Handle "domain" callback next. */
  15553. /* Check for external domain SSL_CTX callback. */
  15554. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15555. ? 0
  15556. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15557. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15558. &ssl_ctx,
  15559. phys_ctx->user_data));
  15560. if (callback_ret < 0) {
  15561. /* Callback < 0: Error. Abort init. */
  15562. mg_cry_ctx_internal(
  15563. phys_ctx,
  15564. "external_ssl_ctx_domain callback returned error: %i",
  15565. callback_ret);
  15566. return 0;
  15567. } else if (callback_ret > 0) {
  15568. /* Callback > 0: Consider init done. */
  15569. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15570. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15571. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15572. return 0;
  15573. }
  15574. return 1;
  15575. }
  15576. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15577. * 0, CivetWeb should continue initializing SSL */
  15578. /* If PEM file is not specified and the init_ssl callbacks
  15579. * are not specified, setup will fail. */
  15580. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15581. && (phys_ctx->callbacks.init_ssl == NULL)
  15582. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15583. /* No certificate and no init_ssl callbacks:
  15584. * Essential data to set up TLS is missing.
  15585. */
  15586. mg_cry_ctx_internal(phys_ctx,
  15587. "Initializing SSL failed: -%s is not set",
  15588. config_options[SSL_CERTIFICATE].name);
  15589. return 0;
  15590. }
  15591. /* If a certificate chain is configured, use it. */
  15592. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15593. if (chain == NULL) {
  15594. /* Default: certificate chain in PEM file */
  15595. chain = pem;
  15596. }
  15597. if ((chain != NULL) && (*chain == 0)) {
  15598. /* If the chain is an empty string, don't use it. */
  15599. chain = NULL;
  15600. }
  15601. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15602. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15603. return 0;
  15604. }
  15605. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15606. }
  15607. static void
  15608. uninitialize_openssl(void)
  15609. {
  15610. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15611. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15612. /* Shutdown according to
  15613. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15614. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15615. */
  15616. CONF_modules_unload(1);
  15617. #else
  15618. int i;
  15619. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15620. /* Shutdown according to
  15621. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15622. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15623. */
  15624. CRYPTO_set_locking_callback(NULL);
  15625. CRYPTO_set_id_callback(NULL);
  15626. ENGINE_cleanup();
  15627. CONF_modules_unload(1);
  15628. ERR_free_strings();
  15629. EVP_cleanup();
  15630. CRYPTO_cleanup_all_ex_data();
  15631. OPENSSL_REMOVE_THREAD_STATE();
  15632. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15633. pthread_mutex_destroy(&ssl_mutexes[i]);
  15634. }
  15635. mg_free(ssl_mutexes);
  15636. ssl_mutexes = NULL;
  15637. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15638. }
  15639. }
  15640. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15641. #if !defined(NO_FILESYSTEMS)
  15642. static int
  15643. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15644. {
  15645. if (phys_ctx) {
  15646. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15647. const char *path;
  15648. struct mg_connection fc;
  15649. if (!dom_ctx) {
  15650. dom_ctx = &(phys_ctx->dd);
  15651. }
  15652. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15653. if ((path != NULL)
  15654. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15655. mg_cry_ctx_internal(phys_ctx,
  15656. "Cannot open %s: %s",
  15657. path,
  15658. strerror(ERRNO));
  15659. return 0;
  15660. }
  15661. return 1;
  15662. }
  15663. return 0;
  15664. }
  15665. #endif /* NO_FILESYSTEMS */
  15666. static int
  15667. set_acl_option(struct mg_context *phys_ctx)
  15668. {
  15669. union usa sa;
  15670. memset(&sa, 0, sizeof(sa));
  15671. #if defined(USE_IPV6)
  15672. sa.sin6.sin6_family = AF_INET6;
  15673. #else
  15674. sa.sin.sin_family = AF_INET;
  15675. #endif
  15676. return check_acl(phys_ctx, &sa) != -1;
  15677. }
  15678. static void
  15679. reset_per_request_attributes(struct mg_connection *conn)
  15680. {
  15681. if (!conn) {
  15682. return;
  15683. }
  15684. conn->num_bytes_sent = conn->consumed_content = 0;
  15685. conn->path_info = NULL;
  15686. conn->status_code = -1;
  15687. conn->content_len = -1;
  15688. conn->is_chunked = 0;
  15689. conn->must_close = 0;
  15690. conn->request_len = 0;
  15691. conn->request_state = 0;
  15692. conn->throttle = 0;
  15693. conn->accept_gzip = 0;
  15694. conn->response_info.content_length = conn->request_info.content_length = -1;
  15695. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15696. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15697. conn->response_info.status_text = NULL;
  15698. conn->response_info.status_code = 0;
  15699. conn->request_info.remote_user = NULL;
  15700. conn->request_info.request_method = NULL;
  15701. conn->request_info.request_uri = NULL;
  15702. /* Free cleaned local URI (if any) */
  15703. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15704. mg_free((void *)conn->request_info.local_uri);
  15705. conn->request_info.local_uri = NULL;
  15706. }
  15707. conn->request_info.local_uri = NULL;
  15708. #if defined(USE_SERVER_STATS)
  15709. conn->processing_time = 0;
  15710. #endif
  15711. }
  15712. static int
  15713. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15714. {
  15715. if ((so->lsa.sa.sa_family == AF_INET)
  15716. || (so->lsa.sa.sa_family == AF_INET6)) {
  15717. /* Only for TCP sockets */
  15718. if (setsockopt(so->sock,
  15719. IPPROTO_TCP,
  15720. TCP_NODELAY,
  15721. (SOCK_OPT_TYPE)&nodelay_on,
  15722. sizeof(nodelay_on))
  15723. != 0) {
  15724. /* Error */
  15725. return 1;
  15726. }
  15727. }
  15728. /* OK */
  15729. return 0;
  15730. }
  15731. #if !defined(__ZEPHYR__)
  15732. static void
  15733. close_socket_gracefully(struct mg_connection *conn)
  15734. {
  15735. #if defined(_WIN32)
  15736. char buf[MG_BUF_LEN];
  15737. int n;
  15738. #endif
  15739. struct linger linger;
  15740. int error_code = 0;
  15741. int linger_timeout = -2;
  15742. socklen_t opt_len = sizeof(error_code);
  15743. if (!conn) {
  15744. return;
  15745. }
  15746. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15747. * "Note that enabling a nonzero timeout on a nonblocking socket
  15748. * is not recommended.", so set it to blocking now */
  15749. set_blocking_mode(conn->client.sock);
  15750. /* Send FIN to the client */
  15751. shutdown(conn->client.sock, SHUTDOWN_WR);
  15752. #if defined(_WIN32)
  15753. /* Read and discard pending incoming data. If we do not do that and
  15754. * close
  15755. * the socket, the data in the send buffer may be discarded. This
  15756. * behaviour is seen on Windows, when client keeps sending data
  15757. * when server decides to close the connection; then when client
  15758. * does recv() it gets no data back. */
  15759. do {
  15760. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15761. } while (n > 0);
  15762. #endif
  15763. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15764. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15765. }
  15766. /* Set linger option according to configuration */
  15767. if (linger_timeout >= 0) {
  15768. /* Set linger option to avoid socket hanging out after close. This
  15769. * prevent ephemeral port exhaust problem under high QPS. */
  15770. linger.l_onoff = 1;
  15771. #if defined(_MSC_VER)
  15772. #pragma warning(push)
  15773. #pragma warning(disable : 4244)
  15774. #endif
  15775. #if defined(GCC_DIAGNOSTIC)
  15776. #pragma GCC diagnostic push
  15777. #pragma GCC diagnostic ignored "-Wconversion"
  15778. #endif
  15779. /* Data type of linger structure elements may differ,
  15780. * so we don't know what cast we need here.
  15781. * Disable type conversion warnings. */
  15782. linger.l_linger = (linger_timeout + 999) / 1000;
  15783. #if defined(GCC_DIAGNOSTIC)
  15784. #pragma GCC diagnostic pop
  15785. #endif
  15786. #if defined(_MSC_VER)
  15787. #pragma warning(pop)
  15788. #endif
  15789. } else {
  15790. linger.l_onoff = 0;
  15791. linger.l_linger = 0;
  15792. }
  15793. if (linger_timeout < -1) {
  15794. /* Default: don't configure any linger */
  15795. } else if (getsockopt(conn->client.sock,
  15796. SOL_SOCKET,
  15797. SO_ERROR,
  15798. #if defined(_WIN32) /* WinSock uses different data type here */
  15799. (char *)&error_code,
  15800. #else
  15801. &error_code,
  15802. #endif
  15803. &opt_len)
  15804. != 0) {
  15805. /* Cannot determine if socket is already closed. This should
  15806. * not occur and never did in a test. Log an error message
  15807. * and continue. */
  15808. mg_cry_internal(conn,
  15809. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15810. __func__,
  15811. strerror(ERRNO));
  15812. #if defined(_WIN32)
  15813. } else if (error_code == WSAECONNRESET) {
  15814. #else
  15815. } else if (error_code == ECONNRESET) {
  15816. #endif
  15817. /* Socket already closed by client/peer, close socket without linger
  15818. */
  15819. } else {
  15820. /* Set linger timeout */
  15821. if (setsockopt(conn->client.sock,
  15822. SOL_SOCKET,
  15823. SO_LINGER,
  15824. (char *)&linger,
  15825. sizeof(linger))
  15826. != 0) {
  15827. mg_cry_internal(
  15828. conn,
  15829. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15830. __func__,
  15831. linger.l_onoff,
  15832. linger.l_linger,
  15833. strerror(ERRNO));
  15834. }
  15835. }
  15836. /* Now we know that our FIN is ACK-ed, safe to close */
  15837. closesocket(conn->client.sock);
  15838. conn->client.sock = INVALID_SOCKET;
  15839. }
  15840. #endif
  15841. static void
  15842. close_connection(struct mg_connection *conn)
  15843. {
  15844. #if defined(USE_SERVER_STATS)
  15845. conn->conn_state = 6; /* to close */
  15846. #endif
  15847. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15848. if (conn->lua_websocket_state) {
  15849. lua_websocket_close(conn, conn->lua_websocket_state);
  15850. conn->lua_websocket_state = NULL;
  15851. }
  15852. #endif
  15853. mg_lock_connection(conn);
  15854. /* Set close flag, so keep-alive loops will stop */
  15855. conn->must_close = 1;
  15856. /* call the connection_close callback if assigned */
  15857. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15858. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15859. conn->phys_ctx->callbacks.connection_close(conn);
  15860. }
  15861. }
  15862. /* Reset user data, after close callback is called.
  15863. * Do not reuse it. If the user needs a destructor,
  15864. * it must be done in the connection_close callback. */
  15865. mg_set_user_connection_data(conn, NULL);
  15866. #if defined(USE_SERVER_STATS)
  15867. conn->conn_state = 7; /* closing */
  15868. #endif
  15869. #if defined(USE_MBEDTLS)
  15870. if (conn->ssl != NULL) {
  15871. mbed_ssl_close(conn->ssl);
  15872. conn->ssl = NULL;
  15873. }
  15874. #elif defined(USE_GNUTLS)
  15875. if (conn->ssl != NULL) {
  15876. gtls_ssl_close(conn->ssl);
  15877. conn->ssl = NULL;
  15878. }
  15879. #elif !defined(NO_SSL)
  15880. if (conn->ssl != NULL) {
  15881. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15882. */
  15883. SSL_shutdown(conn->ssl);
  15884. SSL_free(conn->ssl);
  15885. OPENSSL_REMOVE_THREAD_STATE();
  15886. conn->ssl = NULL;
  15887. }
  15888. #endif
  15889. if (conn->client.sock != INVALID_SOCKET) {
  15890. #if defined(__ZEPHYR__)
  15891. closesocket(conn->client.sock);
  15892. #else
  15893. close_socket_gracefully(conn);
  15894. #endif
  15895. conn->client.sock = INVALID_SOCKET;
  15896. }
  15897. /* call the connection_closed callback if assigned */
  15898. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15899. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15900. conn->phys_ctx->callbacks.connection_closed(conn);
  15901. }
  15902. }
  15903. mg_unlock_connection(conn);
  15904. #if defined(USE_SERVER_STATS)
  15905. conn->conn_state = 8; /* closed */
  15906. #endif
  15907. }
  15908. CIVETWEB_API void
  15909. mg_close_connection(struct mg_connection *conn)
  15910. {
  15911. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15912. return;
  15913. }
  15914. #if defined(USE_WEBSOCKET)
  15915. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15916. if (conn->in_websocket_handling) {
  15917. /* Set close flag, so the server thread can exit. */
  15918. conn->must_close = 1;
  15919. return;
  15920. }
  15921. }
  15922. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15923. unsigned int i;
  15924. /* client context: loops must end */
  15925. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15926. conn->must_close = 1;
  15927. /* We need to get the client thread out of the select/recv call
  15928. * here. */
  15929. /* Since we use a sleep quantum of some seconds to check for recv
  15930. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15931. /* join worker thread */
  15932. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15933. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15934. }
  15935. }
  15936. #endif /* defined(USE_WEBSOCKET) */
  15937. close_connection(conn);
  15938. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  15939. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15940. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15941. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15942. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15943. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15944. }
  15945. #endif
  15946. #if defined(USE_WEBSOCKET)
  15947. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15948. mg_free(conn->phys_ctx->worker_threadids);
  15949. (void)pthread_mutex_destroy(&conn->mutex);
  15950. mg_free(conn);
  15951. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15952. (void)pthread_mutex_destroy(&conn->mutex);
  15953. mg_free(conn);
  15954. }
  15955. #else
  15956. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15957. (void)pthread_mutex_destroy(&conn->mutex);
  15958. mg_free(conn);
  15959. }
  15960. #endif /* defined(USE_WEBSOCKET) */
  15961. }
  15962. static struct mg_connection *
  15963. mg_connect_client_impl(const struct mg_client_options *client_options,
  15964. int use_ssl,
  15965. struct mg_init_data *init,
  15966. struct mg_error_data *error)
  15967. {
  15968. struct mg_connection *conn = NULL;
  15969. SOCKET sock;
  15970. union usa sa;
  15971. struct sockaddr *psa;
  15972. socklen_t len;
  15973. unsigned max_req_size =
  15974. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15975. /* Size of structures, aligned to 8 bytes */
  15976. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15977. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15978. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15979. (void)init; /* TODO: Implement required options */
  15980. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15981. if (error != NULL) {
  15982. error->code = MG_ERROR_DATA_CODE_OK;
  15983. error->code_sub = 0;
  15984. if (error->text_buffer_size > 0) {
  15985. error->text[0] = 0;
  15986. }
  15987. }
  15988. if (conn == NULL) {
  15989. if (error != NULL) {
  15990. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15991. error->code_sub = (unsigned)alloc_size;
  15992. mg_snprintf(NULL,
  15993. NULL, /* No truncation check for ebuf */
  15994. error->text,
  15995. error->text_buffer_size,
  15996. "calloc(): %s",
  15997. strerror(ERRNO));
  15998. }
  15999. return NULL;
  16000. }
  16001. #if defined(GCC_DIAGNOSTIC)
  16002. #pragma GCC diagnostic push
  16003. #pragma GCC diagnostic ignored "-Wcast-align"
  16004. #endif /* defined(GCC_DIAGNOSTIC) */
  16005. /* conn_size is aligned to 8 bytes */
  16006. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  16007. #if defined(GCC_DIAGNOSTIC)
  16008. #pragma GCC diagnostic pop
  16009. #endif /* defined(GCC_DIAGNOSTIC) */
  16010. conn->buf = (((char *)conn) + conn_size + ctx_size);
  16011. conn->buf_size = (int)max_req_size;
  16012. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  16013. conn->dom_ctx = &(conn->phys_ctx->dd);
  16014. if (!connect_socket(conn->phys_ctx,
  16015. client_options->host,
  16016. client_options->port,
  16017. use_ssl,
  16018. error,
  16019. &sock,
  16020. &sa)) {
  16021. /* "error" will be set by connect_socket. */
  16022. /* free all memory and return NULL; */
  16023. mg_free(conn);
  16024. return NULL;
  16025. }
  16026. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16027. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16028. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16029. && !defined(NO_SSL_DL)
  16030. if (use_ssl
  16031. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16032. == NULL) {
  16033. if (error != NULL) {
  16034. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16035. mg_snprintf(NULL,
  16036. NULL, /* No truncation check for ebuf */
  16037. error->text,
  16038. error->text_buffer_size,
  16039. "SSL_CTX_new error: %s",
  16040. ssl_error());
  16041. }
  16042. closesocket(sock);
  16043. mg_free(conn);
  16044. return NULL;
  16045. }
  16046. #else
  16047. if (use_ssl
  16048. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16049. == NULL) {
  16050. if (error != NULL) {
  16051. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16052. mg_snprintf(NULL,
  16053. NULL, /* No truncation check for ebuf */
  16054. error->text,
  16055. error->text_buffer_size,
  16056. "SSL_CTX_new error: %s",
  16057. ssl_error());
  16058. }
  16059. closesocket(sock);
  16060. mg_free(conn);
  16061. return NULL;
  16062. }
  16063. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16064. #endif /* NO_SSL */
  16065. #if defined(USE_IPV6)
  16066. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16067. : sizeof(conn->client.rsa.sin6);
  16068. psa = (sa.sa.sa_family == AF_INET)
  16069. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16070. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16071. #else
  16072. len = sizeof(conn->client.rsa.sin);
  16073. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16074. #endif
  16075. conn->client.sock = sock;
  16076. conn->client.lsa = sa;
  16077. if (getsockname(sock, psa, &len) != 0) {
  16078. mg_cry_internal(conn,
  16079. "%s: getsockname() failed: %s",
  16080. __func__,
  16081. strerror(ERRNO));
  16082. }
  16083. conn->client.is_ssl = use_ssl ? 1 : 0;
  16084. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16085. if (error != NULL) {
  16086. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16087. error->code_sub = (unsigned)ERRNO;
  16088. mg_snprintf(NULL,
  16089. NULL, /* No truncation check for ebuf */
  16090. error->text,
  16091. error->text_buffer_size,
  16092. "Can not create mutex");
  16093. }
  16094. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16095. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16096. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16097. #endif
  16098. closesocket(sock);
  16099. mg_free(conn);
  16100. return NULL;
  16101. }
  16102. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16103. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16104. if (use_ssl) {
  16105. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16106. * SSL_CTX_set_verify call is needed to switch off server
  16107. * certificate checking, which is off by default in OpenSSL and
  16108. * on in yaSSL. */
  16109. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16110. * SSL_VERIFY_PEER, verify_ssl_server); */
  16111. if (client_options->client_cert) {
  16112. if (!ssl_use_pem_file(conn->phys_ctx,
  16113. conn->dom_ctx,
  16114. client_options->client_cert,
  16115. NULL)) {
  16116. if (error != NULL) {
  16117. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16118. mg_snprintf(NULL,
  16119. NULL, /* No truncation check for ebuf */
  16120. error->text,
  16121. error->text_buffer_size,
  16122. "Can not use SSL client certificate");
  16123. }
  16124. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16125. closesocket(sock);
  16126. mg_free(conn);
  16127. return NULL;
  16128. }
  16129. }
  16130. if (client_options->server_cert) {
  16131. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16132. client_options->server_cert,
  16133. NULL)
  16134. != 1) {
  16135. if (error != NULL) {
  16136. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16137. mg_snprintf(NULL,
  16138. NULL, /* No truncation check for ebuf */
  16139. error->text,
  16140. error->text_buffer_size,
  16141. "SSL_CTX_load_verify_locations error: %s",
  16142. ssl_error());
  16143. }
  16144. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16145. closesocket(sock);
  16146. mg_free(conn);
  16147. return NULL;
  16148. }
  16149. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16150. } else {
  16151. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16152. }
  16153. if (!sslize(conn, SSL_connect, client_options)) {
  16154. if (error != NULL) {
  16155. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16156. mg_snprintf(NULL,
  16157. NULL, /* No truncation check for ebuf */
  16158. error->text,
  16159. error->text_buffer_size,
  16160. "SSL connection error");
  16161. }
  16162. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16163. closesocket(sock);
  16164. mg_free(conn);
  16165. return NULL;
  16166. }
  16167. }
  16168. #endif
  16169. return conn;
  16170. }
  16171. CIVETWEB_API struct mg_connection *
  16172. mg_connect_client_secure(const struct mg_client_options *client_options,
  16173. char *error_buffer,
  16174. size_t error_buffer_size)
  16175. {
  16176. struct mg_init_data init;
  16177. struct mg_error_data error;
  16178. memset(&init, 0, sizeof(init));
  16179. memset(&error, 0, sizeof(error));
  16180. error.text_buffer_size = error_buffer_size;
  16181. error.text = error_buffer;
  16182. return mg_connect_client_impl(client_options, 1, &init, &error);
  16183. }
  16184. CIVETWEB_API struct mg_connection *
  16185. mg_connect_client(const char *host,
  16186. int port,
  16187. int use_ssl,
  16188. char *error_buffer,
  16189. size_t error_buffer_size)
  16190. {
  16191. struct mg_client_options opts;
  16192. struct mg_init_data init;
  16193. struct mg_error_data error;
  16194. memset(&init, 0, sizeof(init));
  16195. memset(&error, 0, sizeof(error));
  16196. error.text_buffer_size = error_buffer_size;
  16197. error.text = error_buffer;
  16198. memset(&opts, 0, sizeof(opts));
  16199. opts.host = host;
  16200. opts.port = port;
  16201. if (use_ssl) {
  16202. opts.host_name = host;
  16203. }
  16204. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16205. }
  16206. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16207. CIVETWEB_API struct mg_connection *
  16208. mg_connect_client2(const char *host,
  16209. const char *protocol,
  16210. int port,
  16211. const char *path,
  16212. struct mg_init_data *init,
  16213. struct mg_error_data *error)
  16214. {
  16215. (void)path;
  16216. int is_ssl, is_ws;
  16217. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16218. if (error != NULL) {
  16219. error->code = MG_ERROR_DATA_CODE_OK;
  16220. error->code_sub = 0;
  16221. if (error->text_buffer_size > 0) {
  16222. *error->text = 0;
  16223. }
  16224. }
  16225. if ((host == NULL) || (protocol == NULL)) {
  16226. if (error != NULL) {
  16227. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16228. mg_snprintf(NULL,
  16229. NULL, /* No truncation check for error buffers */
  16230. error->text,
  16231. error->text_buffer_size,
  16232. "%s",
  16233. "Invalid parameters");
  16234. }
  16235. return NULL;
  16236. }
  16237. /* check all known protocols */
  16238. if (!mg_strcasecmp(protocol, "http")) {
  16239. is_ssl = 0;
  16240. is_ws = 0;
  16241. } else if (!mg_strcasecmp(protocol, "https")) {
  16242. is_ssl = 1;
  16243. is_ws = 0;
  16244. #if defined(USE_WEBSOCKET)
  16245. } else if (!mg_strcasecmp(protocol, "ws")) {
  16246. is_ssl = 0;
  16247. is_ws = 1;
  16248. } else if (!mg_strcasecmp(protocol, "wss")) {
  16249. is_ssl = 1;
  16250. is_ws = 1;
  16251. #endif
  16252. } else {
  16253. if (error != NULL) {
  16254. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16255. mg_snprintf(NULL,
  16256. NULL, /* No truncation check for error buffers */
  16257. error->text,
  16258. error->text_buffer_size,
  16259. "Protocol %s not supported",
  16260. protocol);
  16261. }
  16262. return NULL;
  16263. }
  16264. /* TODO: The current implementation here just calls the old
  16265. * implementations, without using any new options. This is just a first
  16266. * step to test the new interfaces. */
  16267. #if defined(USE_WEBSOCKET)
  16268. if (is_ws) {
  16269. /* TODO: implement all options */
  16270. return mg_connect_websocket_client(
  16271. host,
  16272. port,
  16273. is_ssl,
  16274. ((error != NULL) ? error->text : NULL),
  16275. ((error != NULL) ? error->text_buffer_size : 0),
  16276. (path ? path : ""),
  16277. NULL /* TODO: origin */,
  16278. experimental_websocket_client_data_wrapper,
  16279. experimental_websocket_client_close_wrapper,
  16280. (void *)init->callbacks);
  16281. }
  16282. #else
  16283. (void)is_ws;
  16284. #endif
  16285. /* TODO: all additional options */
  16286. struct mg_client_options opts;
  16287. memset(&opts, 0, sizeof(opts));
  16288. opts.host = host;
  16289. opts.port = port;
  16290. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16291. }
  16292. #endif
  16293. static const struct {
  16294. const char *proto;
  16295. size_t proto_len;
  16296. unsigned default_port;
  16297. } abs_uri_protocols[] = {{"http://", 7, 80},
  16298. {"https://", 8, 443},
  16299. {"ws://", 5, 80},
  16300. {"wss://", 6, 443},
  16301. {NULL, 0, 0}};
  16302. /* Check if the uri is valid.
  16303. * return 0 for invalid uri,
  16304. * return 1 for *,
  16305. * return 2 for relative uri,
  16306. * return 3 for absolute uri without port,
  16307. * return 4 for absolute uri with port */
  16308. static int
  16309. get_uri_type(const char *uri)
  16310. {
  16311. int i;
  16312. const char *hostend, *portbegin;
  16313. char *portend;
  16314. unsigned long port;
  16315. /* According to the HTTP standard
  16316. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16317. * URI can be an asterisk (*) or should start with slash (relative uri),
  16318. * or it should start with the protocol (absolute uri). */
  16319. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16320. /* asterisk */
  16321. return 1;
  16322. }
  16323. /* Valid URIs according to RFC 3986
  16324. * (https://www.ietf.org/rfc/rfc3986.txt)
  16325. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16326. * and unreserved characters A-Z a-z 0-9 and -._~
  16327. * and % encoded symbols.
  16328. */
  16329. for (i = 0; uri[i] != 0; i++) {
  16330. if ((unsigned char)uri[i] < 33) {
  16331. /* control characters and spaces are invalid */
  16332. return 0;
  16333. }
  16334. /* Allow everything else here (See #894) */
  16335. }
  16336. /* A relative uri starts with a / character */
  16337. if (uri[0] == '/') {
  16338. /* relative uri */
  16339. return 2;
  16340. }
  16341. /* It could be an absolute uri: */
  16342. /* This function only checks if the uri is valid, not if it is
  16343. * addressing the current server. So civetweb can also be used
  16344. * as a proxy server. */
  16345. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16346. if (mg_strncasecmp(uri,
  16347. abs_uri_protocols[i].proto,
  16348. abs_uri_protocols[i].proto_len)
  16349. == 0) {
  16350. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16351. if (!hostend) {
  16352. return 0;
  16353. }
  16354. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16355. if (!portbegin) {
  16356. return 3;
  16357. }
  16358. port = strtoul(portbegin + 1, &portend, 10);
  16359. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16360. return 0;
  16361. }
  16362. return 4;
  16363. }
  16364. }
  16365. return 0;
  16366. }
  16367. /* Return NULL or the relative uri at the current server */
  16368. static const char *
  16369. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16370. {
  16371. const char *server_domain;
  16372. size_t server_domain_len;
  16373. size_t request_domain_len = 0;
  16374. unsigned long port = 0;
  16375. int i, auth_domain_check_enabled;
  16376. const char *hostbegin = NULL;
  16377. const char *hostend = NULL;
  16378. const char *portbegin;
  16379. char *portend;
  16380. auth_domain_check_enabled =
  16381. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16382. /* DNS is case insensitive, so use case insensitive string compare here
  16383. */
  16384. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16385. if (mg_strncasecmp(uri,
  16386. abs_uri_protocols[i].proto,
  16387. abs_uri_protocols[i].proto_len)
  16388. == 0) {
  16389. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16390. hostend = strchr(hostbegin, '/');
  16391. if (!hostend) {
  16392. return 0;
  16393. }
  16394. portbegin = strchr(hostbegin, ':');
  16395. if ((!portbegin) || (portbegin > hostend)) {
  16396. port = abs_uri_protocols[i].default_port;
  16397. request_domain_len = (size_t)(hostend - hostbegin);
  16398. } else {
  16399. port = strtoul(portbegin + 1, &portend, 10);
  16400. if ((portend != hostend) || (port <= 0)
  16401. || !is_valid_port(port)) {
  16402. return 0;
  16403. }
  16404. request_domain_len = (size_t)(portbegin - hostbegin);
  16405. }
  16406. /* protocol found, port set */
  16407. break;
  16408. }
  16409. }
  16410. if (!port) {
  16411. /* port remains 0 if the protocol is not found */
  16412. return 0;
  16413. }
  16414. /* Check if the request is directed to a different server. */
  16415. /* First check if the port is the same. */
  16416. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16417. /* Request is directed to a different port */
  16418. return 0;
  16419. }
  16420. /* Finally check if the server corresponds to the authentication
  16421. * domain of the server (the server domain).
  16422. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16423. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16424. * but do not allow substrings (like
  16425. * http://notmydomain.com/path/file.ext
  16426. * or http://mydomain.com.fake/path/file.ext).
  16427. */
  16428. if (auth_domain_check_enabled) {
  16429. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16430. server_domain_len = strlen(server_domain);
  16431. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16432. return 0;
  16433. }
  16434. if ((request_domain_len == server_domain_len)
  16435. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16436. /* Request is directed to this server - full name match. */
  16437. } else {
  16438. if (request_domain_len < (server_domain_len + 2)) {
  16439. /* Request is directed to another server: The server name
  16440. * is longer than the request name.
  16441. * Drop this case here to avoid overflows in the
  16442. * following checks. */
  16443. return 0;
  16444. }
  16445. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16446. /* Request is directed to another server: It could be a
  16447. * substring
  16448. * like notmyserver.com */
  16449. return 0;
  16450. }
  16451. if (0
  16452. != memcmp(server_domain,
  16453. hostbegin + request_domain_len - server_domain_len,
  16454. server_domain_len)) {
  16455. /* Request is directed to another server:
  16456. * The server name is different. */
  16457. return 0;
  16458. }
  16459. }
  16460. }
  16461. return hostend;
  16462. }
  16463. static int
  16464. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16465. {
  16466. if (ebuf_len > 0) {
  16467. ebuf[0] = '\0';
  16468. }
  16469. *err = 0;
  16470. reset_per_request_attributes(conn);
  16471. if (!conn) {
  16472. mg_snprintf(conn,
  16473. NULL, /* No truncation check for ebuf */
  16474. ebuf,
  16475. ebuf_len,
  16476. "%s",
  16477. "Internal error");
  16478. *err = 500;
  16479. return 0;
  16480. }
  16481. /* Set the time the request was received. This value should be used for
  16482. * timeouts. */
  16483. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16484. conn->request_len =
  16485. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16486. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16487. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16488. mg_snprintf(conn,
  16489. NULL, /* No truncation check for ebuf */
  16490. ebuf,
  16491. ebuf_len,
  16492. "%s",
  16493. "Invalid message size");
  16494. *err = 500;
  16495. return 0;
  16496. }
  16497. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16498. mg_snprintf(conn,
  16499. NULL, /* No truncation check for ebuf */
  16500. ebuf,
  16501. ebuf_len,
  16502. "%s",
  16503. "Message too large");
  16504. *err = 413;
  16505. return 0;
  16506. }
  16507. if (conn->request_len <= 0) {
  16508. if (conn->data_len > 0) {
  16509. mg_snprintf(conn,
  16510. NULL, /* No truncation check for ebuf */
  16511. ebuf,
  16512. ebuf_len,
  16513. "%s",
  16514. conn->request_len == -3 ? "Request timeout"
  16515. : "Malformed message");
  16516. *err = 400;
  16517. } else {
  16518. /* Server did not recv anything -> just close the connection */
  16519. conn->must_close = 1;
  16520. mg_snprintf(conn,
  16521. NULL, /* No truncation check for ebuf */
  16522. ebuf,
  16523. ebuf_len,
  16524. "%s",
  16525. "No data received");
  16526. *err = 0;
  16527. }
  16528. return 0;
  16529. }
  16530. return 1;
  16531. }
  16532. static int
  16533. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16534. {
  16535. const char *cl;
  16536. conn->connection_type =
  16537. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16538. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16539. return 0;
  16540. }
  16541. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16542. <= 0) {
  16543. mg_snprintf(conn,
  16544. NULL, /* No truncation check for ebuf */
  16545. ebuf,
  16546. ebuf_len,
  16547. "%s",
  16548. "Bad request");
  16549. *err = 400;
  16550. return 0;
  16551. }
  16552. /* Message is a valid request */
  16553. if (!switch_domain_context(conn)) {
  16554. mg_snprintf(conn,
  16555. NULL, /* No truncation check for ebuf */
  16556. ebuf,
  16557. ebuf_len,
  16558. "%s",
  16559. "Bad request: Host mismatch");
  16560. *err = 400;
  16561. return 0;
  16562. }
  16563. #if USE_ZLIB
  16564. if (((cl = get_header(conn->request_info.http_headers,
  16565. conn->request_info.num_headers,
  16566. "Accept-Encoding"))
  16567. != NULL)
  16568. && strstr(cl, "gzip")) {
  16569. conn->accept_gzip = 1;
  16570. }
  16571. #endif
  16572. if (((cl = get_header(conn->request_info.http_headers,
  16573. conn->request_info.num_headers,
  16574. "Transfer-Encoding"))
  16575. != NULL)
  16576. && mg_strcasecmp(cl, "identity")) {
  16577. if (mg_strcasecmp(cl, "chunked")) {
  16578. mg_snprintf(conn,
  16579. NULL, /* No truncation check for ebuf */
  16580. ebuf,
  16581. ebuf_len,
  16582. "%s",
  16583. "Bad request");
  16584. *err = 400;
  16585. return 0;
  16586. }
  16587. conn->is_chunked = 1;
  16588. conn->content_len = 0; /* not yet read */
  16589. } else if ((cl = get_header(conn->request_info.http_headers,
  16590. conn->request_info.num_headers,
  16591. "Content-Length"))
  16592. != NULL) {
  16593. /* Request has content length set */
  16594. char *endptr = NULL;
  16595. conn->content_len = strtoll(cl, &endptr, 10);
  16596. if ((endptr == cl) || (conn->content_len < 0)) {
  16597. mg_snprintf(conn,
  16598. NULL, /* No truncation check for ebuf */
  16599. ebuf,
  16600. ebuf_len,
  16601. "%s",
  16602. "Bad request");
  16603. *err = 411;
  16604. return 0;
  16605. }
  16606. /* Publish the content length back to the request info. */
  16607. conn->request_info.content_length = conn->content_len;
  16608. } else {
  16609. /* There is no exception, see RFC7230. */
  16610. conn->content_len = 0;
  16611. }
  16612. return 1;
  16613. }
  16614. /* conn is assumed to be valid in this internal function */
  16615. static int
  16616. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16617. {
  16618. const char *cl;
  16619. conn->connection_type =
  16620. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16621. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16622. return 0;
  16623. }
  16624. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16625. <= 0) {
  16626. mg_snprintf(conn,
  16627. NULL, /* No truncation check for ebuf */
  16628. ebuf,
  16629. ebuf_len,
  16630. "%s",
  16631. "Bad response");
  16632. *err = 400;
  16633. return 0;
  16634. }
  16635. /* Message is a valid response */
  16636. if (((cl = get_header(conn->response_info.http_headers,
  16637. conn->response_info.num_headers,
  16638. "Transfer-Encoding"))
  16639. != NULL)
  16640. && mg_strcasecmp(cl, "identity")) {
  16641. if (mg_strcasecmp(cl, "chunked")) {
  16642. mg_snprintf(conn,
  16643. NULL, /* No truncation check for ebuf */
  16644. ebuf,
  16645. ebuf_len,
  16646. "%s",
  16647. "Bad request");
  16648. *err = 400;
  16649. return 0;
  16650. }
  16651. conn->is_chunked = 1;
  16652. conn->content_len = 0; /* not yet read */
  16653. } else if ((cl = get_header(conn->response_info.http_headers,
  16654. conn->response_info.num_headers,
  16655. "Content-Length"))
  16656. != NULL) {
  16657. char *endptr = NULL;
  16658. conn->content_len = strtoll(cl, &endptr, 10);
  16659. if ((endptr == cl) || (conn->content_len < 0)) {
  16660. mg_snprintf(conn,
  16661. NULL, /* No truncation check for ebuf */
  16662. ebuf,
  16663. ebuf_len,
  16664. "%s",
  16665. "Bad request");
  16666. *err = 411;
  16667. return 0;
  16668. }
  16669. /* Publish the content length back to the response info. */
  16670. conn->response_info.content_length = conn->content_len;
  16671. /* TODO: check if it is still used in response_info */
  16672. conn->request_info.content_length = conn->content_len;
  16673. /* TODO: we should also consider HEAD method */
  16674. if (conn->response_info.status_code == 304) {
  16675. conn->content_len = 0;
  16676. }
  16677. } else {
  16678. /* TODO: we should also consider HEAD method */
  16679. if (((conn->response_info.status_code >= 100)
  16680. && (conn->response_info.status_code <= 199))
  16681. || (conn->response_info.status_code == 204)
  16682. || (conn->response_info.status_code == 304)) {
  16683. conn->content_len = 0;
  16684. } else {
  16685. conn->content_len = -1; /* unknown content length */
  16686. }
  16687. }
  16688. return 1;
  16689. }
  16690. CIVETWEB_API int
  16691. mg_get_response(struct mg_connection *conn,
  16692. char *ebuf,
  16693. size_t ebuf_len,
  16694. int timeout)
  16695. {
  16696. int err, ret;
  16697. char txt[32]; /* will not overflow */
  16698. char *save_timeout;
  16699. char *new_timeout;
  16700. if (ebuf_len > 0) {
  16701. ebuf[0] = '\0';
  16702. }
  16703. if (!conn) {
  16704. mg_snprintf(conn,
  16705. NULL, /* No truncation check for ebuf */
  16706. ebuf,
  16707. ebuf_len,
  16708. "%s",
  16709. "Parameter error");
  16710. return -1;
  16711. }
  16712. /* Reset the previous responses */
  16713. conn->data_len = 0;
  16714. /* Implementation of API function for HTTP clients */
  16715. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16716. if (timeout >= 0) {
  16717. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16718. new_timeout = txt;
  16719. } else {
  16720. new_timeout = NULL;
  16721. }
  16722. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16723. ret = get_response(conn, ebuf, ebuf_len, &err);
  16724. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16725. /* TODO: here, the URI is the http response code */
  16726. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16727. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16728. /* TODO (mid): Define proper return values - maybe return length?
  16729. * For the first test use <0 for error and >0 for OK */
  16730. return (ret == 0) ? -1 : +1;
  16731. }
  16732. CIVETWEB_API struct mg_connection *
  16733. mg_download(const char *host,
  16734. int port,
  16735. int use_ssl,
  16736. char *ebuf,
  16737. size_t ebuf_len,
  16738. const char *fmt,
  16739. ...)
  16740. {
  16741. struct mg_connection *conn;
  16742. va_list ap;
  16743. int i;
  16744. int reqerr;
  16745. if (ebuf_len > 0) {
  16746. ebuf[0] = '\0';
  16747. }
  16748. va_start(ap, fmt);
  16749. /* open a connection */
  16750. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16751. if (conn != NULL) {
  16752. i = mg_vprintf(conn, fmt, ap);
  16753. if (i <= 0) {
  16754. mg_snprintf(conn,
  16755. NULL, /* No truncation check for ebuf */
  16756. ebuf,
  16757. ebuf_len,
  16758. "%s",
  16759. "Error sending request");
  16760. } else {
  16761. /* make sure the buffer is clear */
  16762. conn->data_len = 0;
  16763. get_response(conn, ebuf, ebuf_len, &reqerr);
  16764. /* TODO: here, the URI is the http response code */
  16765. conn->request_info.local_uri = conn->request_info.request_uri;
  16766. }
  16767. }
  16768. /* if an error occurred, close the connection */
  16769. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16770. mg_close_connection(conn);
  16771. conn = NULL;
  16772. }
  16773. va_end(ap);
  16774. return conn;
  16775. }
  16776. struct websocket_client_thread_data {
  16777. struct mg_connection *conn;
  16778. mg_websocket_data_handler data_handler;
  16779. mg_websocket_close_handler close_handler;
  16780. void *callback_data;
  16781. };
  16782. #if defined(USE_WEBSOCKET)
  16783. #if defined(_WIN32)
  16784. static unsigned __stdcall websocket_client_thread(void *data)
  16785. #else
  16786. static void *
  16787. websocket_client_thread(void *data)
  16788. #endif
  16789. {
  16790. struct websocket_client_thread_data *cdata =
  16791. (struct websocket_client_thread_data *)data;
  16792. void *user_thread_ptr = NULL;
  16793. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16794. struct sigaction sa;
  16795. /* Ignore SIGPIPE */
  16796. memset(&sa, 0, sizeof(sa));
  16797. sa.sa_handler = SIG_IGN;
  16798. sigaction(SIGPIPE, &sa, NULL);
  16799. #endif
  16800. mg_set_thread_name("ws-clnt");
  16801. if (cdata->conn->phys_ctx) {
  16802. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16803. /* 3 indicates a websocket client thread */
  16804. /* TODO: check if conn->phys_ctx can be set */
  16805. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16806. cdata->conn->phys_ctx, 3);
  16807. }
  16808. }
  16809. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16810. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16811. if (cdata->close_handler != NULL) {
  16812. cdata->close_handler(cdata->conn, cdata->callback_data);
  16813. }
  16814. /* The websocket_client context has only this thread. If it runs out,
  16815. set the stop_flag to 2 (= "stopped"). */
  16816. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16817. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16818. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16819. 3,
  16820. user_thread_ptr);
  16821. }
  16822. mg_free((void *)cdata);
  16823. #if defined(_WIN32)
  16824. return 0;
  16825. #else
  16826. return NULL;
  16827. #endif
  16828. }
  16829. #endif
  16830. #if defined(USE_WEBSOCKET)
  16831. static void
  16832. generate_websocket_magic(char *magic25)
  16833. {
  16834. uint64_t rnd;
  16835. unsigned char buffer[2 * sizeof(rnd)];
  16836. rnd = get_random();
  16837. memcpy(buffer, &rnd, sizeof(rnd));
  16838. rnd = get_random();
  16839. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16840. size_t dst_len = 24 + 1;
  16841. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16842. }
  16843. #endif
  16844. static struct mg_connection *
  16845. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16846. int use_ssl,
  16847. char *error_buffer,
  16848. size_t error_buffer_size,
  16849. const char *path,
  16850. const char *origin,
  16851. const char *extensions,
  16852. mg_websocket_data_handler data_func,
  16853. mg_websocket_close_handler close_func,
  16854. void *user_data)
  16855. {
  16856. struct mg_connection *conn = NULL;
  16857. #if defined(USE_WEBSOCKET)
  16858. struct websocket_client_thread_data *thread_data;
  16859. char magic[32];
  16860. generate_websocket_magic(magic);
  16861. const char *host = client_options->host;
  16862. int i;
  16863. struct mg_init_data init;
  16864. struct mg_error_data error;
  16865. memset(&init, 0, sizeof(init));
  16866. memset(&error, 0, sizeof(error));
  16867. error.text_buffer_size = error_buffer_size;
  16868. error.text = error_buffer;
  16869. #if defined(__clang__)
  16870. #pragma clang diagnostic push
  16871. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16872. #endif
  16873. /* Establish the client connection and request upgrade */
  16874. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16875. /* Connection object will be null if something goes wrong */
  16876. if (conn == NULL) {
  16877. /* error_buffer should be already filled ... */
  16878. if (!error_buffer[0]) {
  16879. /* ... if not add an error message */
  16880. mg_snprintf(conn,
  16881. NULL, /* No truncation check for ebuf */
  16882. error_buffer,
  16883. error_buffer_size,
  16884. "Unexpected error");
  16885. }
  16886. return NULL;
  16887. }
  16888. if (origin != NULL) {
  16889. if (extensions != NULL) {
  16890. i = mg_printf(conn,
  16891. "GET %s HTTP/1.1\r\n"
  16892. "Host: %s\r\n"
  16893. "Upgrade: websocket\r\n"
  16894. "Connection: Upgrade\r\n"
  16895. "Sec-WebSocket-Key: %s\r\n"
  16896. "Sec-WebSocket-Version: 13\r\n"
  16897. "Sec-WebSocket-Extensions: %s\r\n"
  16898. "Origin: %s\r\n"
  16899. "\r\n",
  16900. path,
  16901. host,
  16902. magic,
  16903. extensions,
  16904. origin);
  16905. } else {
  16906. i = mg_printf(conn,
  16907. "GET %s HTTP/1.1\r\n"
  16908. "Host: %s\r\n"
  16909. "Upgrade: websocket\r\n"
  16910. "Connection: Upgrade\r\n"
  16911. "Sec-WebSocket-Key: %s\r\n"
  16912. "Sec-WebSocket-Version: 13\r\n"
  16913. "Origin: %s\r\n"
  16914. "\r\n",
  16915. path,
  16916. host,
  16917. magic,
  16918. origin);
  16919. }
  16920. } else {
  16921. if (extensions != NULL) {
  16922. i = mg_printf(conn,
  16923. "GET %s HTTP/1.1\r\n"
  16924. "Host: %s\r\n"
  16925. "Upgrade: websocket\r\n"
  16926. "Connection: Upgrade\r\n"
  16927. "Sec-WebSocket-Key: %s\r\n"
  16928. "Sec-WebSocket-Version: 13\r\n"
  16929. "Sec-WebSocket-Extensions: %s\r\n"
  16930. "\r\n",
  16931. path,
  16932. host,
  16933. magic,
  16934. extensions);
  16935. } else {
  16936. i = mg_printf(conn,
  16937. "GET %s HTTP/1.1\r\n"
  16938. "Host: %s\r\n"
  16939. "Upgrade: websocket\r\n"
  16940. "Connection: Upgrade\r\n"
  16941. "Sec-WebSocket-Key: %s\r\n"
  16942. "Sec-WebSocket-Version: 13\r\n"
  16943. "\r\n",
  16944. path,
  16945. host,
  16946. magic);
  16947. }
  16948. }
  16949. if (i <= 0) {
  16950. mg_snprintf(conn,
  16951. NULL, /* No truncation check for ebuf */
  16952. error_buffer,
  16953. error_buffer_size,
  16954. "%s",
  16955. "Error sending request");
  16956. mg_close_connection(conn);
  16957. return NULL;
  16958. }
  16959. conn->data_len = 0;
  16960. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16961. mg_close_connection(conn);
  16962. return NULL;
  16963. }
  16964. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16965. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16966. #if defined(__clang__)
  16967. #pragma clang diagnostic pop
  16968. #endif
  16969. if (conn->response_info.status_code != 101) {
  16970. /* We sent an "upgrade" request. For a correct websocket
  16971. * protocol handshake, we expect a "101 Continue" response.
  16972. * Otherwise it is a protocol violation. Maybe the HTTP
  16973. * Server does not know websockets. */
  16974. if (!*error_buffer) {
  16975. /* set an error, if not yet set */
  16976. mg_snprintf(conn,
  16977. NULL, /* No truncation check for ebuf */
  16978. error_buffer,
  16979. error_buffer_size,
  16980. "Unexpected server reply");
  16981. }
  16982. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16983. mg_close_connection(conn);
  16984. return NULL;
  16985. }
  16986. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16987. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16988. if (!thread_data) {
  16989. DEBUG_TRACE("%s\r\n", "Out of memory");
  16990. mg_close_connection(conn);
  16991. return NULL;
  16992. }
  16993. thread_data->conn = conn;
  16994. thread_data->data_handler = data_func;
  16995. thread_data->close_handler = close_func;
  16996. thread_data->callback_data = user_data;
  16997. conn->phys_ctx->worker_threadids =
  16998. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16999. if (!conn->phys_ctx->worker_threadids) {
  17000. DEBUG_TRACE("%s\r\n", "Out of memory");
  17001. mg_free(thread_data);
  17002. mg_close_connection(conn);
  17003. return NULL;
  17004. }
  17005. /* Now upgrade to ws/wss client context */
  17006. conn->phys_ctx->user_data = user_data;
  17007. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  17008. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  17009. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  17010. /* Start a thread to read the websocket client connection
  17011. * This thread will automatically stop when mg_disconnect is
  17012. * called on the client connection */
  17013. if (mg_start_thread_with_id(websocket_client_thread,
  17014. thread_data,
  17015. conn->phys_ctx->worker_threadids)
  17016. != 0) {
  17017. conn->phys_ctx->spawned_worker_threads = 0;
  17018. mg_free(thread_data);
  17019. mg_close_connection(conn);
  17020. conn = NULL;
  17021. DEBUG_TRACE("%s",
  17022. "Websocket client connect thread could not be started\r\n");
  17023. }
  17024. #else
  17025. /* Appease "unused parameter" warnings */
  17026. (void)client_options;
  17027. (void)use_ssl;
  17028. (void)error_buffer;
  17029. (void)error_buffer_size;
  17030. (void)path;
  17031. (void)origin;
  17032. (void)extensions;
  17033. (void)user_data;
  17034. (void)data_func;
  17035. (void)close_func;
  17036. #endif
  17037. return conn;
  17038. }
  17039. CIVETWEB_API struct mg_connection *
  17040. mg_connect_websocket_client(const char *host,
  17041. int port,
  17042. int use_ssl,
  17043. char *error_buffer,
  17044. size_t error_buffer_size,
  17045. const char *path,
  17046. const char *origin,
  17047. mg_websocket_data_handler data_func,
  17048. mg_websocket_close_handler close_func,
  17049. void *user_data)
  17050. {
  17051. struct mg_client_options client_options;
  17052. memset(&client_options, 0, sizeof(client_options));
  17053. client_options.host = host;
  17054. client_options.port = port;
  17055. if (use_ssl) {
  17056. client_options.host_name = host;
  17057. }
  17058. return mg_connect_websocket_client_impl(&client_options,
  17059. use_ssl,
  17060. error_buffer,
  17061. error_buffer_size,
  17062. path,
  17063. origin,
  17064. NULL,
  17065. data_func,
  17066. close_func,
  17067. user_data);
  17068. }
  17069. CIVETWEB_API struct mg_connection *
  17070. mg_connect_websocket_client_secure(
  17071. const struct mg_client_options *client_options,
  17072. char *error_buffer,
  17073. size_t error_buffer_size,
  17074. const char *path,
  17075. const char *origin,
  17076. mg_websocket_data_handler data_func,
  17077. mg_websocket_close_handler close_func,
  17078. void *user_data)
  17079. {
  17080. if (!client_options) {
  17081. return NULL;
  17082. }
  17083. return mg_connect_websocket_client_impl(client_options,
  17084. 1,
  17085. error_buffer,
  17086. error_buffer_size,
  17087. path,
  17088. origin,
  17089. NULL,
  17090. data_func,
  17091. close_func,
  17092. user_data);
  17093. }
  17094. CIVETWEB_API struct mg_connection *
  17095. mg_connect_websocket_client_extensions(const char *host,
  17096. int port,
  17097. int use_ssl,
  17098. char *error_buffer,
  17099. size_t error_buffer_size,
  17100. const char *path,
  17101. const char *origin,
  17102. const char *extensions,
  17103. mg_websocket_data_handler data_func,
  17104. mg_websocket_close_handler close_func,
  17105. void *user_data)
  17106. {
  17107. struct mg_client_options client_options;
  17108. memset(&client_options, 0, sizeof(client_options));
  17109. client_options.host = host;
  17110. client_options.port = port;
  17111. return mg_connect_websocket_client_impl(&client_options,
  17112. use_ssl,
  17113. error_buffer,
  17114. error_buffer_size,
  17115. path,
  17116. origin,
  17117. extensions,
  17118. data_func,
  17119. close_func,
  17120. user_data);
  17121. }
  17122. CIVETWEB_API struct mg_connection *
  17123. mg_connect_websocket_client_secure_extensions(
  17124. const struct mg_client_options *client_options,
  17125. char *error_buffer,
  17126. size_t error_buffer_size,
  17127. const char *path,
  17128. const char *origin,
  17129. const char *extensions,
  17130. mg_websocket_data_handler data_func,
  17131. mg_websocket_close_handler close_func,
  17132. void *user_data)
  17133. {
  17134. if (!client_options) {
  17135. return NULL;
  17136. }
  17137. return mg_connect_websocket_client_impl(client_options,
  17138. 1,
  17139. error_buffer,
  17140. error_buffer_size,
  17141. path,
  17142. origin,
  17143. extensions,
  17144. data_func,
  17145. close_func,
  17146. user_data);
  17147. }
  17148. /* Prepare connection data structure */
  17149. static void
  17150. init_connection(struct mg_connection *conn)
  17151. {
  17152. /* Is keep alive allowed by the server */
  17153. int keep_alive_enabled =
  17154. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17155. if (!keep_alive_enabled) {
  17156. conn->must_close = 1;
  17157. }
  17158. /* Important: on new connection, reset the receiving buffer. Credit
  17159. * goes to crule42. */
  17160. conn->data_len = 0;
  17161. conn->handled_requests = 0;
  17162. conn->connection_type = CONNECTION_TYPE_INVALID;
  17163. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17164. mg_set_user_connection_data(conn, NULL);
  17165. #if defined(USE_SERVER_STATS)
  17166. conn->conn_state = 2; /* init */
  17167. #endif
  17168. /* call the init_connection callback if assigned */
  17169. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17170. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17171. void *conn_data = NULL;
  17172. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17173. mg_set_user_connection_data(conn, conn_data);
  17174. }
  17175. }
  17176. }
  17177. /* Process a connection - may handle multiple requests
  17178. * using the same connection.
  17179. * Must be called with a valid connection (conn and
  17180. * conn->phys_ctx must be valid).
  17181. */
  17182. static void
  17183. process_new_connection(struct mg_connection *conn)
  17184. {
  17185. struct mg_request_info *ri = &conn->request_info;
  17186. int keep_alive, discard_len;
  17187. char ebuf[100];
  17188. const char *hostend;
  17189. int reqerr, uri_type;
  17190. #if defined(USE_SERVER_STATS)
  17191. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17192. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17193. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17194. #endif
  17195. DEBUG_TRACE("Start processing connection from %s",
  17196. conn->request_info.remote_addr);
  17197. /* Loop over multiple requests sent using the same connection
  17198. * (while "keep alive"). */
  17199. do {
  17200. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17201. conn->handled_requests + 1);
  17202. #if defined(USE_SERVER_STATS)
  17203. conn->conn_state = 3; /* ready */
  17204. #endif
  17205. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17206. /* The request sent by the client could not be understood by
  17207. * the server, or it was incomplete or a timeout. Send an
  17208. * error message and close the connection. */
  17209. if (reqerr > 0) {
  17210. DEBUG_ASSERT(ebuf[0] != '\0');
  17211. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17212. }
  17213. } else if (strcmp(ri->http_version, "1.0")
  17214. && strcmp(ri->http_version, "1.1")) {
  17215. /* HTTP/2 is not allowed here */
  17216. mg_snprintf(conn,
  17217. NULL, /* No truncation check for ebuf */
  17218. ebuf,
  17219. sizeof(ebuf),
  17220. "Bad HTTP version: [%s]",
  17221. ri->http_version);
  17222. mg_send_http_error(conn, 505, "%s", ebuf);
  17223. }
  17224. if (ebuf[0] == '\0') {
  17225. uri_type = get_uri_type(conn->request_info.request_uri);
  17226. switch (uri_type) {
  17227. case 1:
  17228. /* Asterisk */
  17229. conn->request_info.local_uri_raw = 0;
  17230. /* TODO: Deal with '*'. */
  17231. break;
  17232. case 2:
  17233. /* relative uri */
  17234. conn->request_info.local_uri_raw =
  17235. conn->request_info.request_uri;
  17236. break;
  17237. case 3:
  17238. case 4:
  17239. /* absolute uri (with/without port) */
  17240. hostend = get_rel_url_at_current_server(
  17241. conn->request_info.request_uri, conn);
  17242. if (hostend) {
  17243. conn->request_info.local_uri_raw = hostend;
  17244. } else {
  17245. conn->request_info.local_uri_raw = NULL;
  17246. }
  17247. break;
  17248. default:
  17249. mg_snprintf(conn,
  17250. NULL, /* No truncation check for ebuf */
  17251. ebuf,
  17252. sizeof(ebuf),
  17253. "Invalid URI");
  17254. mg_send_http_error(conn, 400, "%s", ebuf);
  17255. conn->request_info.local_uri_raw = NULL;
  17256. break;
  17257. }
  17258. conn->request_info.local_uri =
  17259. (char *)conn->request_info.local_uri_raw;
  17260. }
  17261. if (ebuf[0] != '\0') {
  17262. conn->protocol_type = -1;
  17263. } else {
  17264. /* HTTP/1 allows protocol upgrade */
  17265. conn->protocol_type = should_switch_to_protocol(conn);
  17266. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17267. /* This will occur, if a HTTP/1.1 request should be upgraded
  17268. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17269. * Since most (all?) major browsers only support HTTP/2 using
  17270. * ALPN, this is hard to test and very low priority.
  17271. * Deactivate it (at least for now).
  17272. */
  17273. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17274. }
  17275. }
  17276. DEBUG_TRACE("http: %s, error: %s",
  17277. (ri->http_version ? ri->http_version : "none"),
  17278. (ebuf[0] ? ebuf : "none"));
  17279. if (ebuf[0] == '\0') {
  17280. if (conn->request_info.local_uri) {
  17281. /* handle request to local server */
  17282. handle_request_stat_log(conn);
  17283. } else {
  17284. /* TODO: handle non-local request (PROXY) */
  17285. conn->must_close = 1;
  17286. }
  17287. } else {
  17288. conn->must_close = 1;
  17289. }
  17290. /* Response complete. Free header buffer */
  17291. free_buffered_response_header_list(conn);
  17292. if (ri->remote_user != NULL) {
  17293. mg_free((void *)ri->remote_user);
  17294. /* Important! When having connections with and without auth
  17295. * would cause double free and then crash */
  17296. ri->remote_user = NULL;
  17297. }
  17298. /* NOTE(lsm): order is important here. should_keep_alive() call
  17299. * is using parsed request, which will be invalid after
  17300. * memmove's below.
  17301. * Therefore, memorize should_keep_alive() result now for later
  17302. * use in loop exit condition. */
  17303. /* Enable it only if this request is completely discardable. */
  17304. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17305. && should_keep_alive(conn) && (conn->content_len >= 0)
  17306. && (conn->request_len > 0)
  17307. && ((conn->is_chunked == 4)
  17308. || (!conn->is_chunked
  17309. && ((conn->consumed_content == conn->content_len)
  17310. || ((conn->request_len + conn->content_len)
  17311. <= conn->data_len))))
  17312. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17313. if (keep_alive) {
  17314. /* Discard all buffered data for this request */
  17315. discard_len =
  17316. ((conn->request_len + conn->content_len) < conn->data_len)
  17317. ? (int)(conn->request_len + conn->content_len)
  17318. : conn->data_len;
  17319. conn->data_len -= discard_len;
  17320. if (conn->data_len > 0) {
  17321. DEBUG_TRACE("discard_len = %d", discard_len);
  17322. memmove(conn->buf,
  17323. conn->buf + discard_len,
  17324. (size_t)conn->data_len);
  17325. }
  17326. }
  17327. DEBUG_ASSERT(conn->data_len >= 0);
  17328. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17329. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17330. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17331. (long int)conn->data_len,
  17332. (long int)conn->buf_size);
  17333. break;
  17334. }
  17335. conn->handled_requests++;
  17336. } while (keep_alive);
  17337. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17338. conn->request_info.remote_addr,
  17339. difftime(time(NULL), conn->conn_birth_time));
  17340. close_connection(conn);
  17341. #if defined(USE_SERVER_STATS)
  17342. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17343. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17344. #endif
  17345. }
  17346. static int
  17347. mg_start_worker_thread(struct mg_context *ctx,
  17348. int only_if_no_idle_threads); /* forward declaration */
  17349. #if defined(ALTERNATIVE_QUEUE)
  17350. static void
  17351. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17352. {
  17353. unsigned int i;
  17354. (void)mg_start_worker_thread(
  17355. ctx, 1); /* will start a worker-thread only if there aren't currently
  17356. any idle worker-threads */
  17357. while (!ctx->stop_flag) {
  17358. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17359. /* find a free worker slot and signal it */
  17360. if (ctx->client_socks[i].in_use == 2) {
  17361. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17362. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17363. ctx->client_socks[i] = *sp;
  17364. ctx->client_socks[i].in_use = 1;
  17365. /* socket has been moved to the consumer */
  17366. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17367. (void)event_signal(ctx->client_wait_events[i]);
  17368. return;
  17369. }
  17370. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17371. }
  17372. }
  17373. /* queue is full */
  17374. mg_sleep(1);
  17375. }
  17376. /* must consume */
  17377. set_blocking_mode(sp->sock);
  17378. closesocket(sp->sock);
  17379. }
  17380. static int
  17381. consume_socket(struct mg_context *ctx,
  17382. struct socket *sp,
  17383. int thread_index,
  17384. int counter_was_preincremented)
  17385. {
  17386. DEBUG_TRACE("%s", "going idle");
  17387. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17388. if (counter_was_preincremented
  17389. == 0) { /* first call only: the master-thread pre-incremented this
  17390. before he spawned us */
  17391. ctx->idle_worker_thread_count++;
  17392. }
  17393. ctx->client_socks[thread_index].in_use = 2;
  17394. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17395. event_wait(ctx->client_wait_events[thread_index]);
  17396. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17397. *sp = ctx->client_socks[thread_index];
  17398. if (ctx->stop_flag) {
  17399. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17400. if (sp->in_use == 1) {
  17401. /* must consume */
  17402. set_blocking_mode(sp->sock);
  17403. closesocket(sp->sock);
  17404. }
  17405. return 0;
  17406. }
  17407. ctx->idle_worker_thread_count--;
  17408. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17409. if (sp->in_use == 1) {
  17410. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17411. return 1;
  17412. }
  17413. /* must not reach here */
  17414. DEBUG_ASSERT(0);
  17415. return 0;
  17416. }
  17417. #else /* ALTERNATIVE_QUEUE */
  17418. /* Worker threads take accepted socket from the queue */
  17419. static int
  17420. consume_socket(struct mg_context *ctx,
  17421. struct socket *sp,
  17422. int thread_index,
  17423. int counter_was_preincremented)
  17424. {
  17425. (void)thread_index;
  17426. DEBUG_TRACE("%s", "going idle");
  17427. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17428. if (counter_was_preincremented
  17429. == 0) { /* first call only: the master-thread pre-incremented this
  17430. before he spawned us */
  17431. ctx->idle_worker_thread_count++;
  17432. }
  17433. /* If the queue is empty, wait. We're idle at this point. */
  17434. while ((ctx->sq_head == ctx->sq_tail)
  17435. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17436. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17437. }
  17438. /* If we're stopping, sq_head may be equal to sq_tail. */
  17439. if (ctx->sq_head > ctx->sq_tail) {
  17440. /* Copy socket from the queue and increment tail */
  17441. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17442. ctx->sq_tail++;
  17443. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17444. /* Wrap pointers if needed */
  17445. while (ctx->sq_tail > ctx->sq_size) {
  17446. ctx->sq_tail -= ctx->sq_size;
  17447. ctx->sq_head -= ctx->sq_size;
  17448. }
  17449. }
  17450. (void)pthread_cond_signal(&ctx->sq_empty);
  17451. ctx->idle_worker_thread_count--;
  17452. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17453. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17454. }
  17455. /* Master thread adds accepted socket to a queue */
  17456. static void
  17457. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17458. {
  17459. int queue_filled;
  17460. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17461. queue_filled = ctx->sq_head - ctx->sq_tail;
  17462. /* If the queue is full, wait */
  17463. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17464. && (queue_filled >= ctx->sq_size)) {
  17465. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17466. #if defined(USE_SERVER_STATS)
  17467. if (queue_filled > ctx->sq_max_fill) {
  17468. ctx->sq_max_fill = queue_filled;
  17469. }
  17470. #endif
  17471. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17472. ctx->sq_blocked = 0; /* Not blocked now */
  17473. queue_filled = ctx->sq_head - ctx->sq_tail;
  17474. }
  17475. if (queue_filled < ctx->sq_size) {
  17476. /* Copy socket to the queue and increment head */
  17477. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17478. ctx->sq_head++;
  17479. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17480. }
  17481. queue_filled = ctx->sq_head - ctx->sq_tail;
  17482. #if defined(USE_SERVER_STATS)
  17483. if (queue_filled > ctx->sq_max_fill) {
  17484. ctx->sq_max_fill = queue_filled;
  17485. }
  17486. #endif
  17487. (void)pthread_cond_signal(&ctx->sq_full);
  17488. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17489. (void)mg_start_worker_thread(
  17490. ctx, 1); /* will start a worker-thread only if there aren't currently
  17491. any idle worker-threads */
  17492. }
  17493. #endif /* ALTERNATIVE_QUEUE */
  17494. static void
  17495. worker_thread_run(struct mg_connection *conn)
  17496. {
  17497. struct mg_context *ctx = conn->phys_ctx;
  17498. int thread_index;
  17499. struct mg_workerTLS tls;
  17500. int first_call_to_consume_socket = 1;
  17501. mg_set_thread_name("worker");
  17502. tls.is_master = 0;
  17503. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17504. #if defined(_WIN32)
  17505. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17506. #endif
  17507. /* Initialize thread local storage before calling any callback */
  17508. pthread_setspecific(sTlsKey, &tls);
  17509. /* Check if there is a user callback */
  17510. if (ctx->callbacks.init_thread) {
  17511. /* call init_thread for a worker thread (type 1), and store the
  17512. * return value */
  17513. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17514. } else {
  17515. /* No callback: set user pointer to NULL */
  17516. tls.user_ptr = NULL;
  17517. }
  17518. /* Connection structure has been pre-allocated */
  17519. thread_index = (int)(conn - ctx->worker_connections);
  17520. if ((thread_index < 0)
  17521. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17522. mg_cry_ctx_internal(ctx,
  17523. "Internal error: Invalid worker index %i",
  17524. thread_index);
  17525. return;
  17526. }
  17527. /* Request buffers are not pre-allocated. They are private to the
  17528. * request and do not contain any state information that might be
  17529. * of interest to anyone observing a server status. */
  17530. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17531. if (conn->buf == NULL) {
  17532. mg_cry_ctx_internal(
  17533. ctx,
  17534. "Out of memory: Cannot allocate buffer for worker %i",
  17535. thread_index);
  17536. return;
  17537. }
  17538. conn->buf_size = (int)ctx->max_request_size;
  17539. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17540. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17541. conn->request_info.user_data = ctx->user_data;
  17542. /* Allocate a mutex for this connection to allow communication both
  17543. * within the request handler and from elsewhere in the application
  17544. */
  17545. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17546. mg_free(conn->buf);
  17547. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17548. return;
  17549. }
  17550. #if defined(USE_SERVER_STATS)
  17551. conn->conn_state = 1; /* not consumed */
  17552. #endif
  17553. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17554. * signal sq_empty condvar to wake up the master waiting in
  17555. * produce_socket() */
  17556. while (consume_socket(
  17557. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17558. first_call_to_consume_socket = 0;
  17559. /* New connections must start with new protocol negotiation */
  17560. tls.alpn_proto = NULL;
  17561. #if defined(USE_SERVER_STATS)
  17562. conn->conn_close_time = 0;
  17563. #endif
  17564. conn->conn_birth_time = time(NULL);
  17565. /* Fill in IP, port info early so even if SSL setup below fails,
  17566. * error handler would have the corresponding info.
  17567. * Thanks to Johannes Winkelmann for the patch.
  17568. */
  17569. conn->request_info.remote_port =
  17570. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17571. conn->request_info.server_port =
  17572. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17573. sockaddr_to_string(conn->request_info.remote_addr,
  17574. sizeof(conn->request_info.remote_addr),
  17575. &conn->client.rsa);
  17576. DEBUG_TRACE("Incoming %sconnection from %s",
  17577. (conn->client.is_ssl ? "SSL " : ""),
  17578. conn->request_info.remote_addr);
  17579. conn->request_info.is_ssl = conn->client.is_ssl;
  17580. if (conn->client.is_ssl) {
  17581. #if defined(USE_MBEDTLS)
  17582. /* HTTPS connection */
  17583. if (mbed_ssl_accept(&(conn->ssl),
  17584. conn->dom_ctx->ssl_ctx,
  17585. (int *)&(conn->client.sock),
  17586. conn->phys_ctx)
  17587. == 0) {
  17588. /* conn->dom_ctx is set in get_request */
  17589. /* process HTTPS connection */
  17590. init_connection(conn);
  17591. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17592. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17593. process_new_connection(conn);
  17594. } else {
  17595. /* make sure the connection is cleaned up on SSL failure */
  17596. close_connection(conn);
  17597. }
  17598. #elif defined(USE_GNUTLS)
  17599. /* HTTPS connection */
  17600. if (gtls_ssl_accept(&(conn->ssl),
  17601. conn->dom_ctx->ssl_ctx,
  17602. conn->client.sock,
  17603. conn->phys_ctx)
  17604. == 0) {
  17605. /* conn->dom_ctx is set in get_request */
  17606. /* process HTTPS connection */
  17607. init_connection(conn);
  17608. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17609. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17610. process_new_connection(conn);
  17611. } else {
  17612. /* make sure the connection is cleaned up on SSL failure */
  17613. close_connection(conn);
  17614. }
  17615. #elif !defined(NO_SSL)
  17616. /* HTTPS connection */
  17617. if (sslize(conn, SSL_accept, NULL)) {
  17618. /* conn->dom_ctx is set in get_request */
  17619. /* Get SSL client certificate information (if set) */
  17620. struct mg_client_cert client_cert;
  17621. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17622. conn->request_info.client_cert = &client_cert;
  17623. }
  17624. /* process HTTPS connection */
  17625. #if defined(USE_HTTP2)
  17626. if ((tls.alpn_proto != NULL)
  17627. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17628. /* process HTTPS/2 connection */
  17629. init_connection(conn);
  17630. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17631. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17632. conn->content_len =
  17633. -1; /* content length is not predefined */
  17634. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17635. process_new_http2_connection(conn);
  17636. } else
  17637. #endif
  17638. {
  17639. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17640. init_connection(conn);
  17641. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17642. /* Start with HTTP, WS will be an "upgrade" request later */
  17643. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17644. process_new_connection(conn);
  17645. }
  17646. /* Free client certificate info */
  17647. if (conn->request_info.client_cert) {
  17648. mg_free((void *)(conn->request_info.client_cert->subject));
  17649. mg_free((void *)(conn->request_info.client_cert->issuer));
  17650. mg_free((void *)(conn->request_info.client_cert->serial));
  17651. mg_free((void *)(conn->request_info.client_cert->finger));
  17652. /* Free certificate memory */
  17653. X509_free(
  17654. (X509 *)conn->request_info.client_cert->peer_cert);
  17655. conn->request_info.client_cert->peer_cert = 0;
  17656. conn->request_info.client_cert->subject = 0;
  17657. conn->request_info.client_cert->issuer = 0;
  17658. conn->request_info.client_cert->serial = 0;
  17659. conn->request_info.client_cert->finger = 0;
  17660. conn->request_info.client_cert = 0;
  17661. }
  17662. } else {
  17663. /* make sure the connection is cleaned up on SSL failure */
  17664. close_connection(conn);
  17665. }
  17666. #endif
  17667. } else {
  17668. /* process HTTP connection */
  17669. init_connection(conn);
  17670. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17671. /* Start with HTTP, WS will be an "upgrade" request later */
  17672. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17673. process_new_connection(conn);
  17674. }
  17675. DEBUG_TRACE("%s", "Connection closed");
  17676. #if defined(USE_SERVER_STATS)
  17677. conn->conn_close_time = time(NULL);
  17678. #endif
  17679. }
  17680. /* Call exit thread user callback */
  17681. if (ctx->callbacks.exit_thread) {
  17682. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17683. }
  17684. /* delete thread local storage objects */
  17685. pthread_setspecific(sTlsKey, NULL);
  17686. #if defined(_WIN32)
  17687. CloseHandle(tls.pthread_cond_helper_mutex);
  17688. #endif
  17689. pthread_mutex_destroy(&conn->mutex);
  17690. /* Free the request buffer. */
  17691. conn->buf_size = 0;
  17692. mg_free(conn->buf);
  17693. conn->buf = NULL;
  17694. /* Free cleaned URI (if any) */
  17695. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17696. mg_free((void *)conn->request_info.local_uri);
  17697. conn->request_info.local_uri = NULL;
  17698. }
  17699. #if defined(USE_SERVER_STATS)
  17700. conn->conn_state = 9; /* done */
  17701. #endif
  17702. DEBUG_TRACE("%s", "exiting");
  17703. }
  17704. /* Threads have different return types on Windows and Unix. */
  17705. #if defined(_WIN32)
  17706. static unsigned __stdcall worker_thread(void *thread_func_param)
  17707. {
  17708. worker_thread_run((struct mg_connection *)thread_func_param);
  17709. return 0;
  17710. }
  17711. #else
  17712. static void *
  17713. worker_thread(void *thread_func_param)
  17714. {
  17715. #if !defined(__ZEPHYR__)
  17716. struct sigaction sa;
  17717. /* Ignore SIGPIPE */
  17718. memset(&sa, 0, sizeof(sa));
  17719. sa.sa_handler = SIG_IGN;
  17720. sigaction(SIGPIPE, &sa, NULL);
  17721. #endif
  17722. worker_thread_run((struct mg_connection *)thread_func_param);
  17723. return NULL;
  17724. }
  17725. #endif /* _WIN32 */
  17726. /* This is an internal function, thus all arguments are expected to be
  17727. * valid - a NULL check is not required. */
  17728. static void
  17729. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17730. {
  17731. struct socket so;
  17732. char src_addr[IP_ADDR_STR_LEN];
  17733. socklen_t len = sizeof(so.rsa);
  17734. #if !defined(__ZEPHYR__)
  17735. int on = 1;
  17736. #endif
  17737. memset(&so, 0, sizeof(so));
  17738. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17739. == INVALID_SOCKET) {
  17740. } else if (check_acl(ctx, &so.rsa) != 1) {
  17741. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17742. mg_cry_ctx_internal(ctx,
  17743. "%s: %s is not allowed to connect",
  17744. __func__,
  17745. src_addr);
  17746. closesocket(so.sock);
  17747. } else {
  17748. /* Put so socket structure into the queue */
  17749. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17750. set_close_on_exec(so.sock, NULL, ctx);
  17751. so.is_ssl = listener->is_ssl;
  17752. so.ssl_redir = listener->ssl_redir;
  17753. so.is_optional = listener->is_optional;
  17754. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17755. mg_cry_ctx_internal(ctx,
  17756. "%s: getsockname() failed: %s",
  17757. __func__,
  17758. strerror(ERRNO));
  17759. }
  17760. #if !defined(__ZEPHYR__)
  17761. if ((so.lsa.sa.sa_family == AF_INET)
  17762. || (so.lsa.sa.sa_family == AF_INET6)) {
  17763. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17764. * This is needed because if HTTP-level keep-alive
  17765. * is enabled, and client resets the connection, server won't get
  17766. * TCP FIN or RST and will keep the connection open forever. With
  17767. * TCP keep-alive, next keep-alive handshake will figure out that
  17768. * the client is down and will close the server end.
  17769. * Thanks to Igor Klopov who suggested the patch. */
  17770. if (setsockopt(so.sock,
  17771. SOL_SOCKET,
  17772. SO_KEEPALIVE,
  17773. (SOCK_OPT_TYPE)&on,
  17774. sizeof(on))
  17775. != 0) {
  17776. mg_cry_ctx_internal(
  17777. ctx,
  17778. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17779. __func__,
  17780. strerror(ERRNO));
  17781. }
  17782. }
  17783. #endif
  17784. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17785. * to effectively fill up the underlying IP packet payload and
  17786. * reduce the overhead of sending lots of small buffers. However
  17787. * this hurts the server's throughput (ie. operations per second)
  17788. * when HTTP 1.1 persistent connections are used and the responses
  17789. * are relatively small (eg. less than 1400 bytes).
  17790. */
  17791. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17792. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17793. if (set_tcp_nodelay(&so, 1) != 0) {
  17794. mg_cry_ctx_internal(
  17795. ctx,
  17796. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17797. __func__,
  17798. strerror(ERRNO));
  17799. }
  17800. }
  17801. /* The "non blocking" property should already be
  17802. * inherited from the parent socket. Set it for
  17803. * non-compliant socket implementations. */
  17804. set_non_blocking_mode(so.sock);
  17805. so.in_use = 0;
  17806. produce_socket(ctx, &so);
  17807. }
  17808. }
  17809. static void
  17810. master_thread_run(struct mg_context *ctx)
  17811. {
  17812. struct mg_workerTLS tls;
  17813. struct mg_pollfd *pfd;
  17814. unsigned int i;
  17815. unsigned int workerthreadcount;
  17816. if (!ctx || !ctx->listening_socket_fds) {
  17817. return;
  17818. }
  17819. mg_set_thread_name("master");
  17820. /* Increase priority of the master thread */
  17821. #if defined(_WIN32)
  17822. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17823. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17824. int min_prio = sched_get_priority_min(SCHED_RR);
  17825. int max_prio = sched_get_priority_max(SCHED_RR);
  17826. if ((min_prio >= 0) && (max_prio >= 0)
  17827. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17828. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17829. struct sched_param sched_param = {0};
  17830. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17831. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17832. }
  17833. #endif
  17834. /* Initialize thread local storage */
  17835. #if defined(_WIN32)
  17836. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17837. #endif
  17838. tls.is_master = 1;
  17839. pthread_setspecific(sTlsKey, &tls);
  17840. if (ctx->callbacks.init_thread) {
  17841. /* Callback for the master thread (type 0) */
  17842. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17843. } else {
  17844. tls.user_ptr = NULL;
  17845. }
  17846. /* Lua background script "start" event */
  17847. #if defined(USE_LUA)
  17848. if (ctx->lua_background_state) {
  17849. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17850. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17851. /* call "start()" in Lua */
  17852. lua_getglobal(lstate, "start");
  17853. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17854. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17855. if (ret != 0) {
  17856. struct mg_connection fc;
  17857. lua_cry(fake_connection(&fc, ctx),
  17858. ret,
  17859. lstate,
  17860. "lua_background_script",
  17861. "start");
  17862. }
  17863. } else {
  17864. lua_pop(lstate, 1);
  17865. }
  17866. /* determine if there is a "log()" function in Lua background script */
  17867. lua_getglobal(lstate, "log");
  17868. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17869. ctx->lua_bg_log_available = 1;
  17870. }
  17871. lua_pop(lstate, 1);
  17872. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17873. }
  17874. #endif
  17875. /* Server starts *now* */
  17876. ctx->start_time = time(NULL);
  17877. /* Server accept loop */
  17878. pfd = ctx->listening_socket_fds;
  17879. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17880. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17881. pfd[i].fd = ctx->listening_sockets[i].sock;
  17882. pfd[i].events = POLLIN;
  17883. }
  17884. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17885. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17886. * of listening_socket_fds[] just to hold this
  17887. */
  17888. pfd[ctx->num_listening_sockets].fd =
  17889. ctx->thread_shutdown_notification_socket;
  17890. pfd[ctx->num_listening_sockets].events = POLLIN;
  17891. if (mg_poll(pfd,
  17892. ctx->num_listening_sockets
  17893. + 1, // +1 for the thread_shutdown_notification_socket
  17894. SOCKET_TIMEOUT_QUANTUM,
  17895. &(ctx->stop_flag))
  17896. > 0) {
  17897. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17898. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17899. * successful poll, and POLLIN is defined as
  17900. * (POLLRDNORM | POLLRDBAND)
  17901. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17902. * pfd[i].revents == POLLIN. */
  17903. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17904. && (pfd[i].revents & POLLIN)) {
  17905. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17906. }
  17907. }
  17908. }
  17909. }
  17910. /* Here stop_flag is 1 - Initiate shutdown. */
  17911. DEBUG_TRACE("%s", "stopping workers");
  17912. /* Stop signal received: somebody called mg_stop. Quit. */
  17913. close_all_listening_sockets(ctx);
  17914. /* Wakeup workers that are waiting for connections to handle. */
  17915. #if defined(ALTERNATIVE_QUEUE)
  17916. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17917. event_signal(ctx->client_wait_events[i]);
  17918. }
  17919. #else
  17920. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17921. pthread_cond_broadcast(&ctx->sq_full);
  17922. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17923. #endif
  17924. /* Join all worker threads to avoid leaking threads. */
  17925. workerthreadcount = ctx->spawned_worker_threads;
  17926. for (i = 0; i < workerthreadcount; i++) {
  17927. if (ctx->worker_threadids[i] != 0) {
  17928. mg_join_thread(ctx->worker_threadids[i]);
  17929. }
  17930. }
  17931. #if defined(USE_LUA)
  17932. /* Free Lua state of lua background task */
  17933. if (ctx->lua_background_state) {
  17934. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17935. ctx->lua_bg_log_available = 0;
  17936. /* call "stop()" in Lua */
  17937. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17938. lua_getglobal(lstate, "stop");
  17939. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17940. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17941. if (ret != 0) {
  17942. struct mg_connection fc;
  17943. lua_cry(fake_connection(&fc, ctx),
  17944. ret,
  17945. lstate,
  17946. "lua_background_script",
  17947. "stop");
  17948. }
  17949. }
  17950. DEBUG_TRACE("Close Lua background state %p", lstate);
  17951. lua_close(lstate);
  17952. ctx->lua_background_state = 0;
  17953. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17954. }
  17955. #endif
  17956. DEBUG_TRACE("%s", "exiting");
  17957. /* call exit thread callback */
  17958. if (ctx->callbacks.exit_thread) {
  17959. /* Callback for the master thread (type 0) */
  17960. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17961. }
  17962. #if defined(_WIN32)
  17963. CloseHandle(tls.pthread_cond_helper_mutex);
  17964. #endif
  17965. pthread_setspecific(sTlsKey, NULL);
  17966. /* Signal mg_stop() that we're done.
  17967. * WARNING: This must be the very last thing this
  17968. * thread does, as ctx becomes invalid after this line. */
  17969. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17970. }
  17971. /* Threads have different return types on Windows and Unix. */
  17972. #if defined(_WIN32)
  17973. static unsigned __stdcall master_thread(void *thread_func_param)
  17974. {
  17975. master_thread_run((struct mg_context *)thread_func_param);
  17976. return 0;
  17977. }
  17978. #else
  17979. static void *
  17980. master_thread(void *thread_func_param)
  17981. {
  17982. #if !defined(__ZEPHYR__)
  17983. struct sigaction sa;
  17984. /* Ignore SIGPIPE */
  17985. memset(&sa, 0, sizeof(sa));
  17986. sa.sa_handler = SIG_IGN;
  17987. sigaction(SIGPIPE, &sa, NULL);
  17988. #endif
  17989. master_thread_run((struct mg_context *)thread_func_param);
  17990. return NULL;
  17991. }
  17992. #endif /* _WIN32 */
  17993. static void
  17994. free_context(struct mg_context *ctx)
  17995. {
  17996. int i;
  17997. struct mg_handler_info *tmp_rh;
  17998. if (ctx == NULL) {
  17999. return;
  18000. }
  18001. /* Call user callback */
  18002. if (ctx->callbacks.exit_context) {
  18003. ctx->callbacks.exit_context(ctx);
  18004. }
  18005. /* All threads exited, no sync is needed. Destroy thread mutex and
  18006. * condvars
  18007. */
  18008. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  18009. #if defined(ALTERNATIVE_QUEUE)
  18010. mg_free(ctx->client_socks);
  18011. if (ctx->client_wait_events != NULL) {
  18012. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  18013. event_destroy(ctx->client_wait_events[i]);
  18014. }
  18015. mg_free(ctx->client_wait_events);
  18016. }
  18017. #else
  18018. (void)pthread_cond_destroy(&ctx->sq_empty);
  18019. (void)pthread_cond_destroy(&ctx->sq_full);
  18020. mg_free(ctx->squeue);
  18021. #endif
  18022. /* Destroy other context global data structures mutex */
  18023. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18024. #if defined(USE_LUA)
  18025. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18026. #endif
  18027. /* Deallocate shutdown-triggering socket-pair */
  18028. if (ctx->user_shutdown_notification_socket >= 0) {
  18029. closesocket(ctx->user_shutdown_notification_socket);
  18030. }
  18031. if (ctx->thread_shutdown_notification_socket >= 0) {
  18032. closesocket(ctx->thread_shutdown_notification_socket);
  18033. }
  18034. /* Deallocate config parameters */
  18035. for (i = 0; i < NUM_OPTIONS; i++) {
  18036. if (ctx->dd.config[i] != NULL) {
  18037. #if defined(_MSC_VER)
  18038. #pragma warning(suppress : 6001)
  18039. #endif
  18040. mg_free(ctx->dd.config[i]);
  18041. }
  18042. }
  18043. /* Deallocate request handlers */
  18044. while (ctx->dd.handlers) {
  18045. tmp_rh = ctx->dd.handlers;
  18046. ctx->dd.handlers = tmp_rh->next;
  18047. mg_free(tmp_rh->uri);
  18048. mg_free(tmp_rh);
  18049. }
  18050. #if defined(USE_MBEDTLS)
  18051. if (ctx->dd.ssl_ctx != NULL) {
  18052. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18053. mg_free(ctx->dd.ssl_ctx);
  18054. ctx->dd.ssl_ctx = NULL;
  18055. }
  18056. #elif defined(USE_GNUTLS)
  18057. if (ctx->dd.ssl_ctx != NULL) {
  18058. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18059. mg_free(ctx->dd.ssl_ctx);
  18060. ctx->dd.ssl_ctx = NULL;
  18061. }
  18062. #elif !defined(NO_SSL)
  18063. /* Deallocate SSL context */
  18064. if (ctx->dd.ssl_ctx != NULL) {
  18065. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18066. int callback_ret =
  18067. (ctx->callbacks.external_ssl_ctx == NULL)
  18068. ? 0
  18069. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18070. if (callback_ret == 0) {
  18071. SSL_CTX_free(ctx->dd.ssl_ctx);
  18072. }
  18073. /* else: ignore error and omit SSL_CTX_free in case
  18074. * callback_ret is 1 */
  18075. }
  18076. #endif /* !NO_SSL */
  18077. /* Deallocate worker thread ID array */
  18078. mg_free(ctx->worker_threadids);
  18079. /* Deallocate worker thread ID array */
  18080. mg_free(ctx->worker_connections);
  18081. /* deallocate system name string */
  18082. mg_free(ctx->systemName);
  18083. /* Deallocate context itself */
  18084. mg_free(ctx);
  18085. }
  18086. CIVETWEB_API void
  18087. mg_stop(struct mg_context *ctx)
  18088. {
  18089. pthread_t mt;
  18090. if (!ctx) {
  18091. return;
  18092. }
  18093. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18094. * two threads is not allowed. */
  18095. mt = ctx->masterthreadid;
  18096. if (mt == 0) {
  18097. return;
  18098. }
  18099. ctx->masterthreadid = 0;
  18100. /* Set stop flag, so all threads know they have to exit. */
  18101. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18102. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18103. * immediately */
  18104. closesocket(ctx->user_shutdown_notification_socket);
  18105. ctx->user_shutdown_notification_socket =
  18106. -1; /* to avoid calling closesocket() again in free_context() */
  18107. /* Join timer thread */
  18108. #if defined(USE_TIMERS)
  18109. timers_exit(ctx);
  18110. #endif
  18111. /* Wait until everything has stopped. */
  18112. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18113. (void)mg_sleep(10);
  18114. }
  18115. /* Wait to stop master thread */
  18116. mg_join_thread(mt);
  18117. /* Close remaining Lua states */
  18118. #if defined(USE_LUA)
  18119. lua_ctx_exit(ctx);
  18120. #endif
  18121. /* Free memory */
  18122. free_context(ctx);
  18123. }
  18124. static void
  18125. get_system_name(char **sysName)
  18126. {
  18127. #if defined(_WIN32)
  18128. char name[128];
  18129. DWORD dwVersion = 0;
  18130. DWORD dwMajorVersion = 0;
  18131. DWORD dwMinorVersion = 0;
  18132. DWORD dwBuild = 0;
  18133. BOOL wowRet, isWoW = FALSE;
  18134. #if defined(_MSC_VER)
  18135. #pragma warning(push)
  18136. /* GetVersion was declared deprecated */
  18137. #pragma warning(disable : 4996)
  18138. #endif
  18139. dwVersion = GetVersion();
  18140. #if defined(_MSC_VER)
  18141. #pragma warning(pop)
  18142. #endif
  18143. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18144. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18145. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18146. (void)dwBuild;
  18147. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18148. sprintf(name,
  18149. "Windows %u.%u%s",
  18150. (unsigned)dwMajorVersion,
  18151. (unsigned)dwMinorVersion,
  18152. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18153. *sysName = mg_strdup(name);
  18154. #elif defined(__rtems__)
  18155. *sysName = mg_strdup("RTEMS");
  18156. #elif defined(__ZEPHYR__)
  18157. *sysName = mg_strdup("Zephyr OS");
  18158. #else
  18159. struct utsname name;
  18160. memset(&name, 0, sizeof(name));
  18161. uname(&name);
  18162. *sysName = mg_strdup(name.sysname);
  18163. #endif
  18164. }
  18165. static void
  18166. legacy_init(const char **options)
  18167. {
  18168. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18169. if (options) {
  18170. const char **run_options = options;
  18171. const char *optname = config_options[LISTENING_PORTS].name;
  18172. /* Try to find the "listening_ports" option */
  18173. while (*run_options) {
  18174. if (!strcmp(*run_options, optname)) {
  18175. ports_option = run_options[1];
  18176. }
  18177. run_options += 2;
  18178. }
  18179. }
  18180. if (is_ssl_port_used(ports_option)) {
  18181. /* Initialize with SSL support */
  18182. mg_init_library(MG_FEATURES_TLS);
  18183. } else {
  18184. /* Initialize without SSL support */
  18185. mg_init_library(MG_FEATURES_DEFAULT);
  18186. }
  18187. }
  18188. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18189. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18190. #define HAVE_SOCKETPAIR 1
  18191. #endif
  18192. static int
  18193. mg_socketpair(int *sockA, int *sockB)
  18194. {
  18195. int temp[2] = {-1, -1};
  18196. int asock = -1;
  18197. /** Default to unallocated */
  18198. *sockA = -1;
  18199. *sockB = -1;
  18200. #if defined(HAVE_SOCKETPAIR)
  18201. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18202. if (ret == 0) {
  18203. *sockA = temp[0];
  18204. *sockB = temp[1];
  18205. set_close_on_exec(*sockA, NULL, NULL);
  18206. set_close_on_exec(*sockB, NULL, NULL);
  18207. }
  18208. (void)asock; /* not used */
  18209. return ret;
  18210. #else
  18211. /** No socketpair() call is available, so we'll have to roll our own
  18212. * implementation */
  18213. asock = socket(PF_INET, SOCK_STREAM, 0);
  18214. if (asock >= 0) {
  18215. struct sockaddr_in addr;
  18216. struct sockaddr *pa = (struct sockaddr *)&addr;
  18217. socklen_t addrLen = sizeof(addr);
  18218. memset(&addr, 0, sizeof(addr));
  18219. addr.sin_family = AF_INET;
  18220. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18221. addr.sin_port = 0;
  18222. if ((bind(asock, pa, sizeof(addr)) == 0)
  18223. && (getsockname(asock, pa, &addrLen) == 0)
  18224. && (listen(asock, 1) == 0)) {
  18225. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18226. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18227. temp[1] = accept(asock, pa, &addrLen);
  18228. if (temp[1] >= 0) {
  18229. closesocket(asock);
  18230. *sockA = temp[0];
  18231. *sockB = temp[1];
  18232. set_close_on_exec(*sockA, NULL, NULL);
  18233. set_close_on_exec(*sockB, NULL, NULL);
  18234. return 0; /* success! */
  18235. }
  18236. }
  18237. }
  18238. }
  18239. /* Cleanup */
  18240. if (asock >= 0)
  18241. closesocket(asock);
  18242. if (temp[0] >= 0)
  18243. closesocket(temp[0]);
  18244. if (temp[1] >= 0)
  18245. closesocket(temp[1]);
  18246. return -1; /* fail! */
  18247. #endif
  18248. }
  18249. static int
  18250. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18251. {
  18252. const unsigned int i = ctx->spawned_worker_threads;
  18253. if (i >= ctx->cfg_max_worker_threads) {
  18254. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18255. threads, ever! */
  18256. }
  18257. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18258. #if defined(ALTERNATIVE_QUEUE)
  18259. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18260. #else
  18261. if ((only_if_no_idle_threads)
  18262. && (ctx->idle_worker_thread_count
  18263. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18264. #endif
  18265. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18266. return -2; /* There are idle threads available, so no need to spawn a
  18267. new worker thread now */
  18268. }
  18269. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18270. condition while the thread is starting
  18271. up */
  18272. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18273. ctx->worker_connections[i].phys_ctx = ctx;
  18274. int ret = mg_start_thread_with_id(worker_thread,
  18275. &ctx->worker_connections[i],
  18276. &ctx->worker_threadids[i]);
  18277. if (ret == 0) {
  18278. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18279. the table */
  18280. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18281. } else {
  18282. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18283. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18284. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18285. }
  18286. return ret;
  18287. }
  18288. CIVETWEB_API struct mg_context *
  18289. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18290. {
  18291. struct mg_context *ctx;
  18292. const char *name, *value, *default_value;
  18293. int idx, ok, prespawnthreadcount, workerthreadcount;
  18294. unsigned int i;
  18295. int itmp;
  18296. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18297. const char **options =
  18298. ((init != NULL) ? (init->configuration_options) : (NULL));
  18299. struct mg_workerTLS tls;
  18300. if (error != NULL) {
  18301. error->code = MG_ERROR_DATA_CODE_OK;
  18302. error->code_sub = 0;
  18303. if (error->text_buffer_size > 0) {
  18304. *error->text = 0;
  18305. }
  18306. }
  18307. if (mg_init_library_called == 0) {
  18308. /* Legacy INIT, if mg_start is called without mg_init_library.
  18309. * Note: This will cause a memory leak when unloading the library.
  18310. */
  18311. legacy_init(options);
  18312. }
  18313. if (mg_init_library_called == 0) {
  18314. if (error != NULL) {
  18315. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18316. mg_snprintf(NULL,
  18317. NULL, /* No truncation check for error buffers */
  18318. error->text,
  18319. error->text_buffer_size,
  18320. "%s",
  18321. "Library uninitialized");
  18322. }
  18323. return NULL;
  18324. }
  18325. /* Allocate context and initialize reasonable general case defaults. */
  18326. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18327. if (ctx == NULL) {
  18328. if (error != NULL) {
  18329. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18330. error->code_sub = (unsigned)sizeof(*ctx);
  18331. mg_snprintf(NULL,
  18332. NULL, /* No truncation check for error buffers */
  18333. error->text,
  18334. error->text_buffer_size,
  18335. "%s",
  18336. "Out of memory");
  18337. }
  18338. return NULL;
  18339. }
  18340. /* Random number generator will initialize at the first call */
  18341. ctx->dd.auth_nonce_mask =
  18342. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18343. /* Save started thread index to reuse in other external API calls
  18344. * For the sake of thread synchronization all non-civetweb threads
  18345. * can be considered as single external thread */
  18346. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18347. tls.is_master = -1; /* Thread calling mg_start */
  18348. tls.thread_idx = ctx->starter_thread_idx;
  18349. #if defined(_WIN32)
  18350. tls.pthread_cond_helper_mutex = NULL;
  18351. #endif
  18352. pthread_setspecific(sTlsKey, &tls);
  18353. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18354. #if !defined(ALTERNATIVE_QUEUE)
  18355. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18356. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18357. ctx->sq_blocked = 0;
  18358. #endif
  18359. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18360. #if defined(USE_LUA)
  18361. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18362. #endif
  18363. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18364. * will cause poll() to return immediately in the master-thread, so that
  18365. * mg_stop() can also return immediately.
  18366. */
  18367. ok &= (0
  18368. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18369. &ctx->thread_shutdown_notification_socket));
  18370. if (!ok) {
  18371. unsigned error_id = (unsigned)ERRNO;
  18372. const char *err_msg =
  18373. "Cannot initialize thread synchronization objects";
  18374. /* Fatal error - abort start. However, this situation should never
  18375. * occur in practice. */
  18376. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18377. if (error != NULL) {
  18378. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18379. error->code_sub = error_id;
  18380. mg_snprintf(NULL,
  18381. NULL, /* No truncation check for error buffers */
  18382. error->text,
  18383. error->text_buffer_size,
  18384. "%s",
  18385. err_msg);
  18386. }
  18387. mg_free(ctx);
  18388. pthread_setspecific(sTlsKey, NULL);
  18389. return NULL;
  18390. }
  18391. if ((init != NULL) && (init->callbacks != NULL)) {
  18392. /* Set all callbacks except exit_context. */
  18393. ctx->callbacks = *init->callbacks;
  18394. exit_callback = init->callbacks->exit_context;
  18395. /* The exit callback is activated once the context is successfully
  18396. * created. It should not be called, if an incomplete context object
  18397. * is deleted during a failed initialization. */
  18398. ctx->callbacks.exit_context = 0;
  18399. }
  18400. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18401. ctx->dd.handlers = NULL;
  18402. ctx->dd.next = NULL;
  18403. #if defined(USE_LUA)
  18404. lua_ctx_init(ctx);
  18405. #endif
  18406. /* Store options */
  18407. while (options && (name = *options++) != NULL) {
  18408. idx = get_option_index(name);
  18409. if (idx == -1) {
  18410. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18411. if (error != NULL) {
  18412. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18413. error->code_sub = (unsigned)-1;
  18414. mg_snprintf(NULL,
  18415. NULL, /* No truncation check for error buffers */
  18416. error->text,
  18417. error->text_buffer_size,
  18418. "Invalid configuration option: %s",
  18419. name);
  18420. }
  18421. free_context(ctx);
  18422. pthread_setspecific(sTlsKey, NULL);
  18423. return NULL;
  18424. } else if ((value = *options++) == NULL) {
  18425. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18426. if (error != NULL) {
  18427. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18428. error->code_sub = (unsigned)idx;
  18429. mg_snprintf(NULL,
  18430. NULL, /* No truncation check for error buffers */
  18431. error->text,
  18432. error->text_buffer_size,
  18433. "Invalid configuration option value: %s",
  18434. name);
  18435. }
  18436. free_context(ctx);
  18437. pthread_setspecific(sTlsKey, NULL);
  18438. return NULL;
  18439. }
  18440. if (ctx->dd.config[idx] != NULL) {
  18441. /* A duplicate configuration option is not an error - the last
  18442. * option value will be used. */
  18443. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18444. mg_free(ctx->dd.config[idx]);
  18445. }
  18446. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18447. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18448. }
  18449. /* Set default value if needed */
  18450. for (i = 0; config_options[i].name != NULL; i++) {
  18451. default_value = config_options[i].default_value;
  18452. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18453. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18454. }
  18455. }
  18456. /* Request size option */
  18457. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18458. if (itmp < 1024) {
  18459. mg_cry_ctx_internal(ctx,
  18460. "%s too small",
  18461. config_options[MAX_REQUEST_SIZE].name);
  18462. if (error != NULL) {
  18463. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18464. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18465. mg_snprintf(NULL,
  18466. NULL, /* No truncation check for error buffers */
  18467. error->text,
  18468. error->text_buffer_size,
  18469. "Invalid configuration option value: %s",
  18470. config_options[MAX_REQUEST_SIZE].name);
  18471. }
  18472. free_context(ctx);
  18473. pthread_setspecific(sTlsKey, NULL);
  18474. return NULL;
  18475. }
  18476. ctx->max_request_size = (unsigned)itmp;
  18477. /* Queue length */
  18478. #if !defined(ALTERNATIVE_QUEUE)
  18479. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18480. if (itmp < 1) {
  18481. mg_cry_ctx_internal(ctx,
  18482. "%s too small",
  18483. config_options[CONNECTION_QUEUE_SIZE].name);
  18484. if (error != NULL) {
  18485. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18486. error->code_sub = CONNECTION_QUEUE_SIZE;
  18487. mg_snprintf(NULL,
  18488. NULL, /* No truncation check for error buffers */
  18489. error->text,
  18490. error->text_buffer_size,
  18491. "Invalid configuration option value: %s",
  18492. config_options[CONNECTION_QUEUE_SIZE].name);
  18493. }
  18494. free_context(ctx);
  18495. pthread_setspecific(sTlsKey, NULL);
  18496. return NULL;
  18497. }
  18498. ctx->squeue =
  18499. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18500. if (ctx->squeue == NULL) {
  18501. mg_cry_ctx_internal(ctx,
  18502. "Out of memory: Cannot allocate %s",
  18503. config_options[CONNECTION_QUEUE_SIZE].name);
  18504. if (error != NULL) {
  18505. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18506. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18507. mg_snprintf(NULL,
  18508. NULL, /* No truncation check for error buffers */
  18509. error->text,
  18510. error->text_buffer_size,
  18511. "Out of memory: Cannot allocate %s",
  18512. config_options[CONNECTION_QUEUE_SIZE].name);
  18513. }
  18514. free_context(ctx);
  18515. pthread_setspecific(sTlsKey, NULL);
  18516. return NULL;
  18517. }
  18518. ctx->sq_size = itmp;
  18519. #endif
  18520. /* Worker thread count option */
  18521. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18522. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18523. if ((prespawnthreadcount < 0)
  18524. || (prespawnthreadcount > workerthreadcount)) {
  18525. prespawnthreadcount =
  18526. workerthreadcount; /* can't prespawn more than all of them! */
  18527. }
  18528. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18529. if (workerthreadcount <= 0) {
  18530. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18531. } else {
  18532. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18533. }
  18534. if (error != NULL) {
  18535. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18536. error->code_sub = NUM_THREADS;
  18537. mg_snprintf(NULL,
  18538. NULL, /* No truncation check for error buffers */
  18539. error->text,
  18540. error->text_buffer_size,
  18541. "Invalid configuration option value: %s",
  18542. config_options[NUM_THREADS].name);
  18543. }
  18544. free_context(ctx);
  18545. pthread_setspecific(sTlsKey, NULL);
  18546. return NULL;
  18547. }
  18548. /* Document root */
  18549. #if defined(NO_FILES)
  18550. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18551. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18552. if (error != NULL) {
  18553. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18554. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18555. mg_snprintf(NULL,
  18556. NULL, /* No truncation check for error buffers */
  18557. error->text,
  18558. error->text_buffer_size,
  18559. "Invalid configuration option value: %s",
  18560. config_options[DOCUMENT_ROOT].name);
  18561. }
  18562. free_context(ctx);
  18563. pthread_setspecific(sTlsKey, NULL);
  18564. return NULL;
  18565. }
  18566. #endif
  18567. get_system_name(&ctx->systemName);
  18568. #if defined(USE_LUA)
  18569. /* If a Lua background script has been configured, start it. */
  18570. ctx->lua_bg_log_available = 0;
  18571. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18572. char ebuf[256];
  18573. struct vec opt_vec;
  18574. struct vec eq_vec;
  18575. const char *sparams;
  18576. memset(ebuf, 0, sizeof(ebuf));
  18577. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18578. /* Create a Lua state, load all standard libraries and the mg table */
  18579. lua_State *state = mg_lua_context_script_prepare(
  18580. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18581. if (!state) {
  18582. mg_cry_ctx_internal(ctx,
  18583. "lua_background_script load error: %s",
  18584. ebuf);
  18585. if (error != NULL) {
  18586. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18587. mg_snprintf(NULL,
  18588. NULL, /* No truncation check for error buffers */
  18589. error->text,
  18590. error->text_buffer_size,
  18591. "Error in script %s: %s",
  18592. config_options[LUA_BACKGROUND_SCRIPT].name,
  18593. ebuf);
  18594. }
  18595. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18596. free_context(ctx);
  18597. pthread_setspecific(sTlsKey, NULL);
  18598. return NULL;
  18599. }
  18600. /* Add a table with parameters into mg.params */
  18601. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18602. if (sparams && sparams[0]) {
  18603. lua_getglobal(state, "mg");
  18604. lua_pushstring(state, "params");
  18605. lua_newtable(state);
  18606. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18607. != NULL) {
  18608. reg_llstring(
  18609. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18610. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18611. break;
  18612. }
  18613. lua_rawset(state, -3);
  18614. lua_pop(state, 1);
  18615. }
  18616. /* Call script */
  18617. state = mg_lua_context_script_run(state,
  18618. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18619. ctx,
  18620. ebuf,
  18621. sizeof(ebuf));
  18622. if (!state) {
  18623. mg_cry_ctx_internal(ctx,
  18624. "lua_background_script start error: %s",
  18625. ebuf);
  18626. if (error != NULL) {
  18627. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18628. mg_snprintf(NULL,
  18629. NULL, /* No truncation check for error buffers */
  18630. error->text,
  18631. error->text_buffer_size,
  18632. "Error in script %s: %s",
  18633. config_options[DOCUMENT_ROOT].name,
  18634. ebuf);
  18635. }
  18636. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18637. free_context(ctx);
  18638. pthread_setspecific(sTlsKey, NULL);
  18639. return NULL;
  18640. }
  18641. /* state remains valid */
  18642. ctx->lua_background_state = (void *)state;
  18643. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18644. } else {
  18645. ctx->lua_background_state = 0;
  18646. }
  18647. #endif
  18648. /* Step by step initialization of ctx - depending on build options */
  18649. #if !defined(NO_FILESYSTEMS)
  18650. if (!set_gpass_option(ctx, NULL)) {
  18651. const char *err_msg = "Invalid global password file";
  18652. /* Fatal error - abort start. */
  18653. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18654. if (error != NULL) {
  18655. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18656. mg_snprintf(NULL,
  18657. NULL, /* No truncation check for error buffers */
  18658. error->text,
  18659. error->text_buffer_size,
  18660. "%s",
  18661. err_msg);
  18662. }
  18663. free_context(ctx);
  18664. pthread_setspecific(sTlsKey, NULL);
  18665. return NULL;
  18666. }
  18667. #endif
  18668. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18669. if (!mg_sslctx_init(ctx, NULL)) {
  18670. const char *err_msg = "Error initializing SSL context";
  18671. /* Fatal error - abort start. */
  18672. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18673. if (error != NULL) {
  18674. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18675. mg_snprintf(NULL,
  18676. NULL, /* No truncation check for error buffers */
  18677. error->text,
  18678. error->text_buffer_size,
  18679. "%s",
  18680. err_msg);
  18681. }
  18682. free_context(ctx);
  18683. pthread_setspecific(sTlsKey, NULL);
  18684. return NULL;
  18685. }
  18686. #elif !defined(NO_SSL)
  18687. if (!init_ssl_ctx(ctx, NULL)) {
  18688. const char *err_msg = "Error initializing SSL context";
  18689. /* Fatal error - abort start. */
  18690. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18691. if (error != NULL) {
  18692. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  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. if (!set_ports_option(ctx)) {
  18706. const char *err_msg = "Failed to setup server ports";
  18707. /* Fatal error - abort start. */
  18708. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18709. if (error != NULL) {
  18710. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18711. mg_snprintf(NULL,
  18712. NULL, /* No truncation check for error buffers */
  18713. error->text,
  18714. error->text_buffer_size,
  18715. "%s",
  18716. err_msg);
  18717. }
  18718. free_context(ctx);
  18719. pthread_setspecific(sTlsKey, NULL);
  18720. return NULL;
  18721. }
  18722. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18723. if (!set_uid_option(ctx)) {
  18724. const char *err_msg = "Failed to run as configured user";
  18725. /* Fatal error - abort start. */
  18726. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18727. if (error != NULL) {
  18728. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18729. mg_snprintf(NULL,
  18730. NULL, /* No truncation check for error buffers */
  18731. error->text,
  18732. error->text_buffer_size,
  18733. "%s",
  18734. err_msg);
  18735. }
  18736. free_context(ctx);
  18737. pthread_setspecific(sTlsKey, NULL);
  18738. return NULL;
  18739. }
  18740. #endif
  18741. if (!set_acl_option(ctx)) {
  18742. const char *err_msg = "Failed to setup access control list";
  18743. /* Fatal error - abort start. */
  18744. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18745. if (error != NULL) {
  18746. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18747. mg_snprintf(NULL,
  18748. NULL, /* No truncation check for error buffers */
  18749. error->text,
  18750. error->text_buffer_size,
  18751. "%s",
  18752. err_msg);
  18753. }
  18754. free_context(ctx);
  18755. pthread_setspecific(sTlsKey, NULL);
  18756. return NULL;
  18757. }
  18758. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18759. ctx->worker_threadids =
  18760. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18761. sizeof(pthread_t),
  18762. ctx);
  18763. if (ctx->worker_threadids == NULL) {
  18764. const char *err_msg = "Not enough memory for worker thread ID array";
  18765. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18766. if (error != NULL) {
  18767. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18768. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18769. * (unsigned)sizeof(pthread_t);
  18770. mg_snprintf(NULL,
  18771. NULL, /* No truncation check for error buffers */
  18772. error->text,
  18773. error->text_buffer_size,
  18774. "%s",
  18775. err_msg);
  18776. }
  18777. free_context(ctx);
  18778. pthread_setspecific(sTlsKey, NULL);
  18779. return NULL;
  18780. }
  18781. ctx->worker_connections =
  18782. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18783. sizeof(struct mg_connection),
  18784. ctx);
  18785. if (ctx->worker_connections == NULL) {
  18786. const char *err_msg =
  18787. "Not enough memory for worker thread connection array";
  18788. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18789. if (error != NULL) {
  18790. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18791. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18792. * (unsigned)sizeof(struct mg_connection);
  18793. mg_snprintf(NULL,
  18794. NULL, /* No truncation check for error buffers */
  18795. error->text,
  18796. error->text_buffer_size,
  18797. "%s",
  18798. err_msg);
  18799. }
  18800. free_context(ctx);
  18801. pthread_setspecific(sTlsKey, NULL);
  18802. return NULL;
  18803. }
  18804. #if defined(ALTERNATIVE_QUEUE)
  18805. ctx->client_wait_events =
  18806. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18807. sizeof(ctx->client_wait_events[0]),
  18808. ctx);
  18809. if (ctx->client_wait_events == NULL) {
  18810. const char *err_msg = "Not enough memory for worker event array";
  18811. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18812. mg_free(ctx->worker_threadids);
  18813. if (error != NULL) {
  18814. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18815. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18816. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18817. mg_snprintf(NULL,
  18818. NULL, /* No truncation check for error buffers */
  18819. error->text,
  18820. error->text_buffer_size,
  18821. "%s",
  18822. err_msg);
  18823. }
  18824. free_context(ctx);
  18825. pthread_setspecific(sTlsKey, NULL);
  18826. return NULL;
  18827. }
  18828. ctx->client_socks =
  18829. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18830. sizeof(ctx->client_socks[0]),
  18831. ctx);
  18832. if (ctx->client_socks == NULL) {
  18833. const char *err_msg = "Not enough memory for worker socket array";
  18834. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18835. mg_free(ctx->client_wait_events);
  18836. mg_free(ctx->worker_threadids);
  18837. if (error != NULL) {
  18838. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18839. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18840. * (unsigned)sizeof(ctx->client_socks[0]);
  18841. mg_snprintf(NULL,
  18842. NULL, /* No truncation check for error buffers */
  18843. error->text,
  18844. error->text_buffer_size,
  18845. "%s",
  18846. err_msg);
  18847. }
  18848. free_context(ctx);
  18849. pthread_setspecific(sTlsKey, NULL);
  18850. return NULL;
  18851. }
  18852. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18853. ctx->client_wait_events[i] = event_create();
  18854. if (ctx->client_wait_events[i] == 0) {
  18855. const char *err_msg = "Error creating worker event %i";
  18856. mg_cry_ctx_internal(ctx, err_msg, i);
  18857. while (i > 0) {
  18858. i--;
  18859. event_destroy(ctx->client_wait_events[i]);
  18860. }
  18861. mg_free(ctx->client_socks);
  18862. mg_free(ctx->client_wait_events);
  18863. mg_free(ctx->worker_threadids);
  18864. if (error != NULL) {
  18865. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18866. error->code_sub = (unsigned)ERRNO;
  18867. mg_snprintf(NULL,
  18868. NULL, /* No truncation check for error buffers */
  18869. error->text,
  18870. error->text_buffer_size,
  18871. err_msg,
  18872. i);
  18873. }
  18874. free_context(ctx);
  18875. pthread_setspecific(sTlsKey, NULL);
  18876. return NULL;
  18877. }
  18878. }
  18879. #endif
  18880. #if defined(USE_TIMERS)
  18881. if (timers_init(ctx) != 0) {
  18882. const char *err_msg = "Error creating timers";
  18883. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18884. if (error != NULL) {
  18885. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18886. error->code_sub = (unsigned)ERRNO;
  18887. mg_snprintf(NULL,
  18888. NULL, /* No truncation check for error buffers */
  18889. error->text,
  18890. error->text_buffer_size,
  18891. "%s",
  18892. err_msg);
  18893. }
  18894. free_context(ctx);
  18895. pthread_setspecific(sTlsKey, NULL);
  18896. return NULL;
  18897. }
  18898. #endif
  18899. /* Context has been created - init user libraries */
  18900. if (ctx->callbacks.init_context) {
  18901. ctx->callbacks.init_context(ctx);
  18902. }
  18903. /* From now, the context is successfully created.
  18904. * When it is destroyed, the exit callback should be called. */
  18905. ctx->callbacks.exit_context = exit_callback;
  18906. ctx->context_type = CONTEXT_SERVER; /* server context */
  18907. /* Start worker threads */
  18908. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18909. /* worker_thread sets up the other fields */
  18910. if (mg_start_worker_thread(ctx, 0) != 0) {
  18911. long error_no = (long)ERRNO;
  18912. /* thread was not created */
  18913. if (ctx->spawned_worker_threads > 0) {
  18914. /* If the second, third, ... thread cannot be created, set a
  18915. * warning, but keep running. */
  18916. mg_cry_ctx_internal(ctx,
  18917. "Cannot start worker thread %i: error %ld",
  18918. ctx->spawned_worker_threads + 1,
  18919. error_no);
  18920. /* If the server initialization should stop here, all
  18921. * threads that have already been created must be stopped
  18922. * first, before any free_context(ctx) call.
  18923. */
  18924. } else {
  18925. /* If the first worker thread cannot be created, stop
  18926. * initialization and free the entire server context. */
  18927. mg_cry_ctx_internal(ctx,
  18928. "Cannot create threads: error %ld",
  18929. error_no);
  18930. if (error != NULL) {
  18931. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18932. error->code_sub = (unsigned)error_no;
  18933. mg_snprintf(
  18934. NULL,
  18935. NULL, /* No truncation check for error buffers */
  18936. error->text,
  18937. error->text_buffer_size,
  18938. "Cannot create first worker thread: error %ld",
  18939. error_no);
  18940. }
  18941. free_context(ctx);
  18942. pthread_setspecific(sTlsKey, NULL);
  18943. return NULL;
  18944. }
  18945. break;
  18946. }
  18947. }
  18948. /* Start master (listening) thread */
  18949. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18950. pthread_setspecific(sTlsKey, NULL);
  18951. return ctx;
  18952. }
  18953. CIVETWEB_API struct mg_context *
  18954. mg_start(const struct mg_callbacks *callbacks,
  18955. void *user_data,
  18956. const char **options)
  18957. {
  18958. struct mg_init_data init = {0};
  18959. init.callbacks = callbacks;
  18960. init.user_data = user_data;
  18961. init.configuration_options = options;
  18962. return mg_start2(&init, NULL);
  18963. }
  18964. /* Add an additional domain to an already running web server. */
  18965. CIVETWEB_API int
  18966. mg_start_domain2(struct mg_context *ctx,
  18967. const char **options,
  18968. struct mg_error_data *error)
  18969. {
  18970. const char *name;
  18971. const char *value;
  18972. const char *default_value;
  18973. struct mg_domain_context *new_dom;
  18974. struct mg_domain_context *dom;
  18975. int idx, i;
  18976. if (error != NULL) {
  18977. error->code = MG_ERROR_DATA_CODE_OK;
  18978. error->code_sub = 0;
  18979. if (error->text_buffer_size > 0) {
  18980. *error->text = 0;
  18981. }
  18982. }
  18983. if ((ctx == NULL) || (options == NULL)) {
  18984. if (error != NULL) {
  18985. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18986. mg_snprintf(NULL,
  18987. NULL, /* No truncation check for error buffers */
  18988. error->text,
  18989. error->text_buffer_size,
  18990. "%s",
  18991. "Invalid parameters");
  18992. }
  18993. return -1;
  18994. }
  18995. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18996. if (error != NULL) {
  18997. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18998. mg_snprintf(NULL,
  18999. NULL, /* No truncation check for error buffers */
  19000. error->text,
  19001. error->text_buffer_size,
  19002. "%s",
  19003. "Server already stopped");
  19004. }
  19005. return -7;
  19006. }
  19007. new_dom = (struct mg_domain_context *)
  19008. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  19009. if (!new_dom) {
  19010. /* Out of memory */
  19011. if (error != NULL) {
  19012. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  19013. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  19014. mg_snprintf(NULL,
  19015. NULL, /* No truncation check for error buffers */
  19016. error->text,
  19017. error->text_buffer_size,
  19018. "%s",
  19019. "Out or memory");
  19020. }
  19021. return -6;
  19022. }
  19023. /* Store options - TODO: unite duplicate code */
  19024. while (options && (name = *options++) != NULL) {
  19025. idx = get_option_index(name);
  19026. if (idx == -1) {
  19027. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19028. if (error != NULL) {
  19029. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19030. error->code_sub = (unsigned)-1;
  19031. mg_snprintf(NULL,
  19032. NULL, /* No truncation check for error buffers */
  19033. error->text,
  19034. error->text_buffer_size,
  19035. "Invalid option: %s",
  19036. name);
  19037. }
  19038. mg_free(new_dom);
  19039. return -2;
  19040. } else if ((value = *options++) == NULL) {
  19041. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19042. if (error != NULL) {
  19043. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19044. error->code_sub = (unsigned)idx;
  19045. mg_snprintf(NULL,
  19046. NULL, /* No truncation check for error buffers */
  19047. error->text,
  19048. error->text_buffer_size,
  19049. "Invalid option value: %s",
  19050. name);
  19051. }
  19052. mg_free(new_dom);
  19053. return -2;
  19054. }
  19055. if (new_dom->config[idx] != NULL) {
  19056. /* Duplicate option: Later values overwrite earlier ones. */
  19057. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19058. mg_free(new_dom->config[idx]);
  19059. }
  19060. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19061. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19062. }
  19063. /* Authentication domain is mandatory */
  19064. /* TODO: Maybe use a new option hostname? */
  19065. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19066. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19067. if (error != NULL) {
  19068. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19069. error->code_sub = AUTHENTICATION_DOMAIN;
  19070. mg_snprintf(NULL,
  19071. NULL, /* No truncation check for error buffers */
  19072. error->text,
  19073. error->text_buffer_size,
  19074. "Mandatory option %s missing",
  19075. config_options[AUTHENTICATION_DOMAIN].name);
  19076. }
  19077. mg_free(new_dom);
  19078. return -4;
  19079. }
  19080. /* Set default value if needed. Take the config value from
  19081. * ctx as a default value. */
  19082. for (i = 0; config_options[i].name != NULL; i++) {
  19083. default_value = ctx->dd.config[i];
  19084. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19085. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19086. }
  19087. }
  19088. new_dom->handlers = NULL;
  19089. new_dom->next = NULL;
  19090. new_dom->nonce_count = 0;
  19091. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19092. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19093. new_dom->shared_lua_websockets = NULL;
  19094. #endif
  19095. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19096. if (!init_ssl_ctx(ctx, new_dom)) {
  19097. /* Init SSL failed */
  19098. if (error != NULL) {
  19099. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19100. mg_snprintf(NULL,
  19101. NULL, /* No truncation check for error buffers */
  19102. error->text,
  19103. error->text_buffer_size,
  19104. "%s",
  19105. "Initializing SSL context failed");
  19106. }
  19107. mg_free(new_dom);
  19108. return -3;
  19109. }
  19110. #endif
  19111. /* Add element to linked list. */
  19112. mg_lock_context(ctx);
  19113. idx = 0;
  19114. dom = &(ctx->dd);
  19115. for (;;) {
  19116. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19117. dom->config[AUTHENTICATION_DOMAIN])) {
  19118. /* Domain collision */
  19119. mg_cry_ctx_internal(ctx,
  19120. "domain %s already in use",
  19121. new_dom->config[AUTHENTICATION_DOMAIN]);
  19122. if (error != NULL) {
  19123. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19124. mg_snprintf(NULL,
  19125. NULL, /* No truncation check for error buffers */
  19126. error->text,
  19127. error->text_buffer_size,
  19128. "Domain %s specified by %s is already in use",
  19129. new_dom->config[AUTHENTICATION_DOMAIN],
  19130. config_options[AUTHENTICATION_DOMAIN].name);
  19131. }
  19132. mg_free(new_dom);
  19133. mg_unlock_context(ctx);
  19134. return -5;
  19135. }
  19136. /* Count number of domains */
  19137. idx++;
  19138. if (dom->next == NULL) {
  19139. dom->next = new_dom;
  19140. break;
  19141. }
  19142. dom = dom->next;
  19143. }
  19144. mg_unlock_context(ctx);
  19145. /* Return domain number */
  19146. return idx;
  19147. }
  19148. CIVETWEB_API int
  19149. mg_start_domain(struct mg_context *ctx, const char **options)
  19150. {
  19151. return mg_start_domain2(ctx, options, NULL);
  19152. }
  19153. /* Feature check API function */
  19154. CIVETWEB_API unsigned
  19155. mg_check_feature(unsigned feature)
  19156. {
  19157. static const unsigned feature_set = 0
  19158. /* Set bits for available features according to API documentation.
  19159. * This bit mask is created at compile time, according to the active
  19160. * preprocessor defines. It is a single const value at runtime. */
  19161. #if !defined(NO_FILES)
  19162. | MG_FEATURES_FILES
  19163. #endif
  19164. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19165. | MG_FEATURES_SSL
  19166. #endif
  19167. #if !defined(NO_CGI)
  19168. | MG_FEATURES_CGI
  19169. #endif
  19170. #if defined(USE_IPV6)
  19171. | MG_FEATURES_IPV6
  19172. #endif
  19173. #if defined(USE_WEBSOCKET)
  19174. | MG_FEATURES_WEBSOCKET
  19175. #endif
  19176. #if defined(USE_LUA)
  19177. | MG_FEATURES_LUA
  19178. #endif
  19179. #if defined(USE_DUKTAPE)
  19180. | MG_FEATURES_SSJS
  19181. #endif
  19182. #if !defined(NO_CACHING)
  19183. | MG_FEATURES_CACHE
  19184. #endif
  19185. #if defined(USE_SERVER_STATS)
  19186. | MG_FEATURES_STATS
  19187. #endif
  19188. #if defined(USE_ZLIB)
  19189. | MG_FEATURES_COMPRESSION
  19190. #endif
  19191. #if defined(USE_HTTP2)
  19192. | MG_FEATURES_HTTP2
  19193. #endif
  19194. #if defined(USE_X_DOM_SOCKET)
  19195. | MG_FEATURES_X_DOMAIN_SOCKET
  19196. #endif
  19197. /* Set some extra bits not defined in the API documentation.
  19198. * These bits may change without further notice. */
  19199. #if defined(MG_LEGACY_INTERFACE)
  19200. | 0x80000000u
  19201. #endif
  19202. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19203. | 0x40000000u
  19204. #endif
  19205. #if !defined(NO_RESPONSE_BUFFERING)
  19206. | 0x20000000u
  19207. #endif
  19208. #if defined(MEMORY_DEBUGGING)
  19209. | 0x10000000u
  19210. #endif
  19211. ;
  19212. return (feature & feature_set);
  19213. }
  19214. static size_t
  19215. mg_str_append(char **dst, char *end, const char *src)
  19216. {
  19217. size_t len = strlen(src);
  19218. if (*dst != end) {
  19219. /* Append src if enough space, or close dst. */
  19220. if ((size_t)(end - *dst) > len) {
  19221. strcpy(*dst, src);
  19222. *dst += len;
  19223. } else {
  19224. *dst = end;
  19225. }
  19226. }
  19227. return len;
  19228. }
  19229. /* Get system information. It can be printed or stored by the caller.
  19230. * Return the size of available information. */
  19231. CIVETWEB_API int
  19232. mg_get_system_info(char *buffer, int buflen)
  19233. {
  19234. char *end, *append_eoobj = NULL, block[256];
  19235. size_t system_info_length = 0;
  19236. #if defined(_WIN32)
  19237. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19238. #else
  19239. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19240. #endif
  19241. if ((buffer == NULL) || (buflen < 1)) {
  19242. buflen = 0;
  19243. end = buffer;
  19244. } else {
  19245. *buffer = 0;
  19246. end = buffer + buflen;
  19247. }
  19248. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19249. /* has enough space to append eoobj */
  19250. append_eoobj = buffer;
  19251. if (end) {
  19252. end -= sizeof(eoobj) - 1;
  19253. }
  19254. }
  19255. system_info_length += mg_str_append(&buffer, end, "{");
  19256. /* Server version */
  19257. {
  19258. const char *version = mg_version();
  19259. mg_snprintf(NULL,
  19260. NULL,
  19261. block,
  19262. sizeof(block),
  19263. "%s\"version\" : \"%s\"",
  19264. eol,
  19265. version);
  19266. system_info_length += mg_str_append(&buffer, end, block);
  19267. }
  19268. /* System info */
  19269. {
  19270. #if defined(_WIN32)
  19271. DWORD dwVersion = 0;
  19272. DWORD dwMajorVersion = 0;
  19273. DWORD dwMinorVersion = 0;
  19274. SYSTEM_INFO si;
  19275. GetSystemInfo(&si);
  19276. #if defined(_MSC_VER)
  19277. #pragma warning(push)
  19278. /* GetVersion was declared deprecated */
  19279. #pragma warning(disable : 4996)
  19280. #endif
  19281. dwVersion = GetVersion();
  19282. #if defined(_MSC_VER)
  19283. #pragma warning(pop)
  19284. #endif
  19285. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19286. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19287. mg_snprintf(NULL,
  19288. NULL,
  19289. block,
  19290. sizeof(block),
  19291. ",%s\"os\" : \"Windows %u.%u\"",
  19292. eol,
  19293. (unsigned)dwMajorVersion,
  19294. (unsigned)dwMinorVersion);
  19295. system_info_length += mg_str_append(&buffer, end, block);
  19296. mg_snprintf(NULL,
  19297. NULL,
  19298. block,
  19299. sizeof(block),
  19300. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19301. eol,
  19302. (unsigned)si.wProcessorArchitecture,
  19303. (unsigned)si.dwNumberOfProcessors,
  19304. (unsigned)si.dwActiveProcessorMask);
  19305. system_info_length += mg_str_append(&buffer, end, block);
  19306. #elif defined(__rtems__)
  19307. mg_snprintf(NULL,
  19308. NULL,
  19309. block,
  19310. sizeof(block),
  19311. ",%s\"os\" : \"%s %s\"",
  19312. eol,
  19313. "RTEMS",
  19314. rtems_version());
  19315. system_info_length += mg_str_append(&buffer, end, block);
  19316. #elif defined(__ZEPHYR__)
  19317. mg_snprintf(NULL,
  19318. NULL,
  19319. block,
  19320. sizeof(block),
  19321. ",%s\"os\" : \"%s\"",
  19322. eol,
  19323. "Zephyr OS",
  19324. ZEPHYR_VERSION);
  19325. system_info_length += mg_str_append(&buffer, end, block);
  19326. #else
  19327. struct utsname name;
  19328. memset(&name, 0, sizeof(name));
  19329. uname(&name);
  19330. mg_snprintf(NULL,
  19331. NULL,
  19332. block,
  19333. sizeof(block),
  19334. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19335. eol,
  19336. name.sysname,
  19337. name.version,
  19338. name.release,
  19339. name.machine);
  19340. system_info_length += mg_str_append(&buffer, end, block);
  19341. #endif
  19342. }
  19343. /* Features */
  19344. {
  19345. mg_snprintf(NULL,
  19346. NULL,
  19347. block,
  19348. sizeof(block),
  19349. ",%s\"features\" : %lu"
  19350. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19351. eol,
  19352. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19353. eol,
  19354. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19355. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19356. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19357. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19358. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19359. : "",
  19360. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19361. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19362. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19363. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19364. system_info_length += mg_str_append(&buffer, end, block);
  19365. #if defined(USE_LUA)
  19366. mg_snprintf(NULL,
  19367. NULL,
  19368. block,
  19369. sizeof(block),
  19370. ",%s\"lua_version\" : \"%u (%s)\"",
  19371. eol,
  19372. (unsigned)LUA_VERSION_NUM,
  19373. LUA_RELEASE);
  19374. system_info_length += mg_str_append(&buffer, end, block);
  19375. #endif
  19376. #if defined(USE_DUKTAPE)
  19377. mg_snprintf(NULL,
  19378. NULL,
  19379. block,
  19380. sizeof(block),
  19381. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19382. eol,
  19383. (unsigned)DUK_VERSION / 10000,
  19384. ((unsigned)DUK_VERSION / 100) % 100,
  19385. (unsigned)DUK_VERSION % 100);
  19386. system_info_length += mg_str_append(&buffer, end, block);
  19387. #endif
  19388. }
  19389. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19390. {
  19391. #if defined(BUILD_DATE)
  19392. const char *bd = BUILD_DATE;
  19393. #else
  19394. #if defined(GCC_DIAGNOSTIC)
  19395. #if GCC_VERSION >= 40900
  19396. #pragma GCC diagnostic push
  19397. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19398. * does not work in some versions. If "BUILD_DATE" is defined to some
  19399. * string, it is used instead of __DATE__. */
  19400. #pragma GCC diagnostic ignored "-Wdate-time"
  19401. #endif
  19402. #endif
  19403. const char *bd = __DATE__;
  19404. #if defined(GCC_DIAGNOSTIC)
  19405. #if GCC_VERSION >= 40900
  19406. #pragma GCC diagnostic pop
  19407. #endif
  19408. #endif
  19409. #endif
  19410. mg_snprintf(
  19411. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19412. system_info_length += mg_str_append(&buffer, end, block);
  19413. }
  19414. /* Compiler information */
  19415. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19416. {
  19417. #if defined(_MSC_VER)
  19418. mg_snprintf(NULL,
  19419. NULL,
  19420. block,
  19421. sizeof(block),
  19422. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19423. eol,
  19424. (unsigned)_MSC_VER,
  19425. (unsigned)_MSC_FULL_VER);
  19426. system_info_length += mg_str_append(&buffer, end, block);
  19427. #elif defined(__MINGW64__)
  19428. mg_snprintf(NULL,
  19429. NULL,
  19430. block,
  19431. sizeof(block),
  19432. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19433. eol,
  19434. (unsigned)__MINGW64_VERSION_MAJOR,
  19435. (unsigned)__MINGW64_VERSION_MINOR);
  19436. system_info_length += mg_str_append(&buffer, end, block);
  19437. mg_snprintf(NULL,
  19438. NULL,
  19439. block,
  19440. sizeof(block),
  19441. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19442. eol,
  19443. (unsigned)__MINGW32_MAJOR_VERSION,
  19444. (unsigned)__MINGW32_MINOR_VERSION);
  19445. system_info_length += mg_str_append(&buffer, end, block);
  19446. #elif defined(__MINGW32__)
  19447. mg_snprintf(NULL,
  19448. NULL,
  19449. block,
  19450. sizeof(block),
  19451. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19452. eol,
  19453. (unsigned)__MINGW32_MAJOR_VERSION,
  19454. (unsigned)__MINGW32_MINOR_VERSION);
  19455. system_info_length += mg_str_append(&buffer, end, block);
  19456. #elif defined(__clang__)
  19457. mg_snprintf(NULL,
  19458. NULL,
  19459. block,
  19460. sizeof(block),
  19461. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19462. eol,
  19463. __clang_major__,
  19464. __clang_minor__,
  19465. __clang_patchlevel__,
  19466. __clang_version__);
  19467. system_info_length += mg_str_append(&buffer, end, block);
  19468. #elif defined(__GNUC__)
  19469. mg_snprintf(NULL,
  19470. NULL,
  19471. block,
  19472. sizeof(block),
  19473. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19474. eol,
  19475. (unsigned)__GNUC__,
  19476. (unsigned)__GNUC_MINOR__,
  19477. (unsigned)__GNUC_PATCHLEVEL__);
  19478. system_info_length += mg_str_append(&buffer, end, block);
  19479. #elif defined(__INTEL_COMPILER)
  19480. mg_snprintf(NULL,
  19481. NULL,
  19482. block,
  19483. sizeof(block),
  19484. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19485. eol,
  19486. (unsigned)__INTEL_COMPILER);
  19487. system_info_length += mg_str_append(&buffer, end, block);
  19488. #elif defined(__BORLANDC__)
  19489. mg_snprintf(NULL,
  19490. NULL,
  19491. block,
  19492. sizeof(block),
  19493. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19494. eol,
  19495. (unsigned)__BORLANDC__);
  19496. system_info_length += mg_str_append(&buffer, end, block);
  19497. #elif defined(__SUNPRO_C)
  19498. mg_snprintf(NULL,
  19499. NULL,
  19500. block,
  19501. sizeof(block),
  19502. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19503. eol,
  19504. (unsigned)__SUNPRO_C);
  19505. system_info_length += mg_str_append(&buffer, end, block);
  19506. #else
  19507. mg_snprintf(NULL,
  19508. NULL,
  19509. block,
  19510. sizeof(block),
  19511. ",%s\"compiler\" : \"other\"",
  19512. eol);
  19513. system_info_length += mg_str_append(&buffer, end, block);
  19514. #endif
  19515. }
  19516. /* Determine 32/64 bit data mode.
  19517. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19518. {
  19519. mg_snprintf(NULL,
  19520. NULL,
  19521. block,
  19522. sizeof(block),
  19523. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19524. "char:%u/%u, "
  19525. "ptr:%u, size:%u, time:%u\"",
  19526. eol,
  19527. (unsigned)sizeof(short),
  19528. (unsigned)sizeof(int),
  19529. (unsigned)sizeof(long),
  19530. (unsigned)sizeof(long long),
  19531. (unsigned)sizeof(float),
  19532. (unsigned)sizeof(double),
  19533. (unsigned)sizeof(long double),
  19534. (unsigned)sizeof(char),
  19535. (unsigned)sizeof(wchar_t),
  19536. (unsigned)sizeof(void *),
  19537. (unsigned)sizeof(size_t),
  19538. (unsigned)sizeof(time_t));
  19539. system_info_length += mg_str_append(&buffer, end, block);
  19540. }
  19541. /* Terminate string */
  19542. if (append_eoobj) {
  19543. strcat(append_eoobj, eoobj);
  19544. }
  19545. system_info_length += sizeof(eoobj) - 1;
  19546. return (int)system_info_length;
  19547. }
  19548. /* Get context information. It can be printed or stored by the caller.
  19549. * Return the size of available information. */
  19550. CIVETWEB_API int
  19551. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19552. {
  19553. #if defined(USE_SERVER_STATS)
  19554. char *end, *append_eoobj = NULL, block[256];
  19555. size_t context_info_length = 0;
  19556. #if defined(_WIN32)
  19557. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19558. #else
  19559. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19560. #endif
  19561. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19562. if ((buffer == NULL) || (buflen < 1)) {
  19563. buflen = 0;
  19564. end = buffer;
  19565. } else {
  19566. *buffer = 0;
  19567. end = buffer + buflen;
  19568. }
  19569. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19570. /* has enough space to append eoobj */
  19571. append_eoobj = buffer;
  19572. end -= sizeof(eoobj) - 1;
  19573. }
  19574. context_info_length += mg_str_append(&buffer, end, "{");
  19575. if (ms) { /* <-- should be always true */
  19576. /* Memory information */
  19577. int blockCount = (int)ms->blockCount;
  19578. int64_t totalMemUsed = ms->totalMemUsed;
  19579. int64_t maxMemUsed = ms->maxMemUsed;
  19580. if (totalMemUsed > maxMemUsed) {
  19581. maxMemUsed = totalMemUsed;
  19582. }
  19583. mg_snprintf(NULL,
  19584. NULL,
  19585. block,
  19586. sizeof(block),
  19587. "%s\"memory\" : {%s"
  19588. "\"blocks\" : %i,%s"
  19589. "\"used\" : %" INT64_FMT ",%s"
  19590. "\"maxUsed\" : %" INT64_FMT "%s"
  19591. "}",
  19592. eol,
  19593. eol,
  19594. blockCount,
  19595. eol,
  19596. totalMemUsed,
  19597. eol,
  19598. maxMemUsed,
  19599. eol);
  19600. context_info_length += mg_str_append(&buffer, end, block);
  19601. }
  19602. if (ctx) {
  19603. /* Declare all variables at begin of the block, to comply
  19604. * with old C standards. */
  19605. char start_time_str[64] = {0};
  19606. char now_str[64] = {0};
  19607. time_t start_time = ctx->start_time;
  19608. time_t now = time(NULL);
  19609. int64_t total_data_read, total_data_written;
  19610. int active_connections = (int)ctx->active_connections;
  19611. int max_active_connections = (int)ctx->max_active_connections;
  19612. int total_connections = (int)ctx->total_connections;
  19613. if (active_connections > max_active_connections) {
  19614. max_active_connections = active_connections;
  19615. }
  19616. if (active_connections > total_connections) {
  19617. total_connections = active_connections;
  19618. }
  19619. /* Connections information */
  19620. mg_snprintf(NULL,
  19621. NULL,
  19622. block,
  19623. sizeof(block),
  19624. ",%s\"connections\" : {%s"
  19625. "\"active\" : %i,%s"
  19626. "\"maxActive\" : %i,%s"
  19627. "\"total\" : %i%s"
  19628. "}",
  19629. eol,
  19630. eol,
  19631. active_connections,
  19632. eol,
  19633. max_active_connections,
  19634. eol,
  19635. total_connections,
  19636. eol);
  19637. context_info_length += mg_str_append(&buffer, end, block);
  19638. /* Queue information */
  19639. #if !defined(ALTERNATIVE_QUEUE)
  19640. mg_snprintf(NULL,
  19641. NULL,
  19642. block,
  19643. sizeof(block),
  19644. ",%s\"queue\" : {%s"
  19645. "\"length\" : %i,%s"
  19646. "\"filled\" : %i,%s"
  19647. "\"maxFilled\" : %i,%s"
  19648. "\"full\" : %s%s"
  19649. "}",
  19650. eol,
  19651. eol,
  19652. ctx->sq_size,
  19653. eol,
  19654. ctx->sq_head - ctx->sq_tail,
  19655. eol,
  19656. ctx->sq_max_fill,
  19657. eol,
  19658. (ctx->sq_blocked ? "true" : "false"),
  19659. eol);
  19660. context_info_length += mg_str_append(&buffer, end, block);
  19661. #endif
  19662. /* Requests information */
  19663. mg_snprintf(NULL,
  19664. NULL,
  19665. block,
  19666. sizeof(block),
  19667. ",%s\"requests\" : {%s"
  19668. "\"total\" : %lu%s"
  19669. "}",
  19670. eol,
  19671. eol,
  19672. (unsigned long)ctx->total_requests,
  19673. eol);
  19674. context_info_length += mg_str_append(&buffer, end, block);
  19675. /* Data information */
  19676. total_data_read =
  19677. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19678. total_data_written =
  19679. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19680. mg_snprintf(NULL,
  19681. NULL,
  19682. block,
  19683. sizeof(block),
  19684. ",%s\"data\" : {%s"
  19685. "\"read\" : %" INT64_FMT ",%s"
  19686. "\"written\" : %" INT64_FMT "%s"
  19687. "}",
  19688. eol,
  19689. eol,
  19690. total_data_read,
  19691. eol,
  19692. total_data_written,
  19693. eol);
  19694. context_info_length += mg_str_append(&buffer, end, block);
  19695. /* Execution time information */
  19696. gmt_time_string(start_time_str,
  19697. sizeof(start_time_str) - 1,
  19698. &start_time);
  19699. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19700. mg_snprintf(NULL,
  19701. NULL,
  19702. block,
  19703. sizeof(block),
  19704. ",%s\"time\" : {%s"
  19705. "\"uptime\" : %.0f,%s"
  19706. "\"start\" : \"%s\",%s"
  19707. "\"now\" : \"%s\"%s"
  19708. "}",
  19709. eol,
  19710. eol,
  19711. difftime(now, start_time),
  19712. eol,
  19713. start_time_str,
  19714. eol,
  19715. now_str,
  19716. eol);
  19717. context_info_length += mg_str_append(&buffer, end, block);
  19718. }
  19719. /* Terminate string */
  19720. if (append_eoobj) {
  19721. strcat(append_eoobj, eoobj);
  19722. }
  19723. context_info_length += sizeof(eoobj) - 1;
  19724. return (int)context_info_length;
  19725. #else
  19726. (void)ctx;
  19727. if ((buffer != NULL) && (buflen > 0)) {
  19728. *buffer = 0;
  19729. }
  19730. return 0;
  19731. #endif
  19732. }
  19733. CIVETWEB_API void
  19734. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19735. {
  19736. /* https://github.com/civetweb/civetweb/issues/727 */
  19737. if (conn != NULL) {
  19738. conn->must_close = 1;
  19739. }
  19740. }
  19741. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19742. /* Get connection information. It can be printed or stored by the caller.
  19743. * Return the size of available information. */
  19744. CIVETWEB_API int
  19745. mg_get_connection_info(const struct mg_context *ctx,
  19746. int idx,
  19747. char *buffer,
  19748. int buflen)
  19749. {
  19750. const struct mg_connection *conn;
  19751. const struct mg_request_info *ri;
  19752. char *end, *append_eoobj = NULL, block[256];
  19753. size_t connection_info_length = 0;
  19754. int state = 0;
  19755. const char *state_str = "unknown";
  19756. #if defined(_WIN32)
  19757. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19758. #else
  19759. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19760. #endif
  19761. if ((buffer == NULL) || (buflen < 1)) {
  19762. buflen = 0;
  19763. end = buffer;
  19764. } else {
  19765. *buffer = 0;
  19766. end = buffer + buflen;
  19767. }
  19768. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19769. /* has enough space to append eoobj */
  19770. append_eoobj = buffer;
  19771. end -= sizeof(eoobj) - 1;
  19772. }
  19773. if ((ctx == NULL) || (idx < 0)) {
  19774. /* Parameter error */
  19775. return 0;
  19776. }
  19777. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19778. /* Out of range */
  19779. return 0;
  19780. }
  19781. /* Take connection [idx]. This connection is not locked in
  19782. * any way, so some other thread might use it. */
  19783. conn = (ctx->worker_connections) + idx;
  19784. /* Initialize output string */
  19785. connection_info_length += mg_str_append(&buffer, end, "{");
  19786. /* Init variables */
  19787. ri = &(conn->request_info);
  19788. #if defined(USE_SERVER_STATS)
  19789. state = conn->conn_state;
  19790. /* State as string */
  19791. switch (state) {
  19792. case 0:
  19793. state_str = "undefined";
  19794. break;
  19795. case 1:
  19796. state_str = "not used";
  19797. break;
  19798. case 2:
  19799. state_str = "init";
  19800. break;
  19801. case 3:
  19802. state_str = "ready";
  19803. break;
  19804. case 4:
  19805. state_str = "processing";
  19806. break;
  19807. case 5:
  19808. state_str = "processed";
  19809. break;
  19810. case 6:
  19811. state_str = "to close";
  19812. break;
  19813. case 7:
  19814. state_str = "closing";
  19815. break;
  19816. case 8:
  19817. state_str = "closed";
  19818. break;
  19819. case 9:
  19820. state_str = "done";
  19821. break;
  19822. }
  19823. #endif
  19824. /* Connection info */
  19825. if ((state >= 3) && (state < 9)) {
  19826. mg_snprintf(NULL,
  19827. NULL,
  19828. block,
  19829. sizeof(block),
  19830. "%s\"connection\" : {%s"
  19831. "\"remote\" : {%s"
  19832. "\"protocol\" : \"%s\",%s"
  19833. "\"addr\" : \"%s\",%s"
  19834. "\"port\" : %u%s"
  19835. "},%s"
  19836. "\"handled_requests\" : %u%s"
  19837. "}",
  19838. eol,
  19839. eol,
  19840. eol,
  19841. get_proto_name(conn),
  19842. eol,
  19843. ri->remote_addr,
  19844. eol,
  19845. ri->remote_port,
  19846. eol,
  19847. eol,
  19848. conn->handled_requests,
  19849. eol);
  19850. connection_info_length += mg_str_append(&buffer, end, block);
  19851. }
  19852. /* Request info */
  19853. if ((state >= 4) && (state < 6)) {
  19854. mg_snprintf(NULL,
  19855. NULL,
  19856. block,
  19857. sizeof(block),
  19858. "%s%s\"request_info\" : {%s"
  19859. "\"method\" : \"%s\",%s"
  19860. "\"uri\" : \"%s\",%s"
  19861. "\"query\" : %s%s%s%s"
  19862. "}",
  19863. (connection_info_length > 1 ? "," : ""),
  19864. eol,
  19865. eol,
  19866. ri->request_method,
  19867. eol,
  19868. ri->request_uri,
  19869. eol,
  19870. ri->query_string ? "\"" : "",
  19871. ri->query_string ? ri->query_string : "null",
  19872. ri->query_string ? "\"" : "",
  19873. eol);
  19874. connection_info_length += mg_str_append(&buffer, end, block);
  19875. }
  19876. /* Execution time information */
  19877. if ((state >= 2) && (state < 9)) {
  19878. char start_time_str[64] = {0};
  19879. char close_time_str[64] = {0};
  19880. time_t start_time = conn->conn_birth_time;
  19881. time_t close_time = 0;
  19882. double time_diff;
  19883. gmt_time_string(start_time_str,
  19884. sizeof(start_time_str) - 1,
  19885. &start_time);
  19886. #if defined(USE_SERVER_STATS)
  19887. close_time = conn->conn_close_time;
  19888. #endif
  19889. if (close_time != 0) {
  19890. time_diff = difftime(close_time, start_time);
  19891. gmt_time_string(close_time_str,
  19892. sizeof(close_time_str) - 1,
  19893. &close_time);
  19894. } else {
  19895. time_t now = time(NULL);
  19896. time_diff = difftime(now, start_time);
  19897. close_time_str[0] = 0; /* or use "now" ? */
  19898. }
  19899. mg_snprintf(NULL,
  19900. NULL,
  19901. block,
  19902. sizeof(block),
  19903. "%s%s\"time\" : {%s"
  19904. "\"uptime\" : %.0f,%s"
  19905. "\"start\" : \"%s\",%s"
  19906. "\"closed\" : \"%s\"%s"
  19907. "}",
  19908. (connection_info_length > 1 ? "," : ""),
  19909. eol,
  19910. eol,
  19911. time_diff,
  19912. eol,
  19913. start_time_str,
  19914. eol,
  19915. close_time_str,
  19916. eol);
  19917. connection_info_length += mg_str_append(&buffer, end, block);
  19918. }
  19919. /* Remote user name */
  19920. if ((ri->remote_user) && (state < 9)) {
  19921. mg_snprintf(NULL,
  19922. NULL,
  19923. block,
  19924. sizeof(block),
  19925. "%s%s\"user\" : {%s"
  19926. "\"name\" : \"%s\",%s"
  19927. "}",
  19928. (connection_info_length > 1 ? "," : ""),
  19929. eol,
  19930. eol,
  19931. ri->remote_user,
  19932. eol);
  19933. connection_info_length += mg_str_append(&buffer, end, block);
  19934. }
  19935. /* Data block */
  19936. if (state >= 3) {
  19937. mg_snprintf(NULL,
  19938. NULL,
  19939. block,
  19940. sizeof(block),
  19941. "%s%s\"data\" : {%s"
  19942. "\"read\" : %" INT64_FMT ",%s"
  19943. "\"written\" : %" INT64_FMT "%s"
  19944. "}",
  19945. (connection_info_length > 1 ? "," : ""),
  19946. eol,
  19947. eol,
  19948. conn->consumed_content,
  19949. eol,
  19950. conn->num_bytes_sent,
  19951. eol);
  19952. connection_info_length += mg_str_append(&buffer, end, block);
  19953. }
  19954. /* State */
  19955. mg_snprintf(NULL,
  19956. NULL,
  19957. block,
  19958. sizeof(block),
  19959. "%s%s\"state\" : \"%s\"",
  19960. (connection_info_length > 1 ? "," : ""),
  19961. eol,
  19962. state_str);
  19963. connection_info_length += mg_str_append(&buffer, end, block);
  19964. /* Terminate string */
  19965. if (append_eoobj) {
  19966. strcat(append_eoobj, eoobj);
  19967. }
  19968. connection_info_length += sizeof(eoobj) - 1;
  19969. return (int)connection_info_length;
  19970. }
  19971. #if 0
  19972. /* Get handler information. Not fully implemented. Is it required? */
  19973. CIVETWEB_API int
  19974. mg_get_handler_info(struct mg_context *ctx,
  19975. char *buffer,
  19976. int buflen)
  19977. {
  19978. int handler_info_len = 0;
  19979. struct mg_handler_info *tmp_rh;
  19980. mg_lock_context(ctx);
  19981. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19982. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19983. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19984. }
  19985. handler_info_len += tmp_rh->uri_len;
  19986. switch (tmp_rh->handler_type) {
  19987. case REQUEST_HANDLER:
  19988. (void)tmp_rh->handler;
  19989. break;
  19990. case WEBSOCKET_HANDLER:
  19991. (void)tmp_rh->connect_handler;
  19992. (void)tmp_rh->ready_handler;
  19993. (void)tmp_rh->data_handler;
  19994. (void)tmp_rh->close_handler;
  19995. break;
  19996. case AUTH_HANDLER:
  19997. (void)tmp_rh->auth_handler;
  19998. break;
  19999. }
  20000. (void)cbdata;
  20001. }
  20002. mg_unlock_context(ctx);
  20003. return handler_info_len;
  20004. }
  20005. #endif
  20006. #endif
  20007. /* Initialize this library. This function does not need to be thread safe.
  20008. */
  20009. CIVETWEB_API unsigned
  20010. mg_init_library(unsigned features)
  20011. {
  20012. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  20013. unsigned features_inited = features_to_init;
  20014. if (mg_init_library_called <= 0) {
  20015. /* Not initialized yet */
  20016. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  20017. return 0;
  20018. }
  20019. }
  20020. mg_global_lock();
  20021. if (mg_init_library_called <= 0) {
  20022. int i;
  20023. size_t len;
  20024. #if defined(_WIN32)
  20025. int file_mutex_init = 1;
  20026. int wsa = 1;
  20027. #else
  20028. int mutexattr_init = 1;
  20029. #endif
  20030. int failed = 1;
  20031. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20032. if (key_create == 0) {
  20033. #if defined(_WIN32)
  20034. file_mutex_init =
  20035. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20036. if (file_mutex_init == 0) {
  20037. /* Start WinSock */
  20038. WSADATA data;
  20039. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20040. }
  20041. #else
  20042. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20043. if (mutexattr_init == 0) {
  20044. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20045. PTHREAD_MUTEX_RECURSIVE);
  20046. }
  20047. #endif
  20048. }
  20049. if (failed) {
  20050. #if defined(_WIN32)
  20051. if (wsa == 0) {
  20052. (void)WSACleanup();
  20053. }
  20054. if (file_mutex_init == 0) {
  20055. (void)pthread_mutex_destroy(&global_log_file_lock);
  20056. }
  20057. #else
  20058. if (mutexattr_init == 0) {
  20059. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20060. }
  20061. #endif
  20062. if (key_create == 0) {
  20063. (void)pthread_key_delete(sTlsKey);
  20064. }
  20065. mg_global_unlock();
  20066. (void)pthread_mutex_destroy(&global_lock_mutex);
  20067. return 0;
  20068. }
  20069. len = 1;
  20070. for (i = 0; http_methods[i].name != NULL; i++) {
  20071. size_t sl = strlen(http_methods[i].name);
  20072. len += sl;
  20073. if (i > 0) {
  20074. len += 2;
  20075. }
  20076. }
  20077. all_methods = (char *)mg_malloc(len);
  20078. if (!all_methods) {
  20079. /* Must never happen */
  20080. mg_global_unlock();
  20081. (void)pthread_mutex_destroy(&global_lock_mutex);
  20082. return 0;
  20083. }
  20084. all_methods[0] = 0;
  20085. for (i = 0; http_methods[i].name != NULL; i++) {
  20086. if (i > 0) {
  20087. strcat(all_methods, ", ");
  20088. strcat(all_methods, http_methods[i].name);
  20089. } else {
  20090. strcpy(all_methods, http_methods[i].name);
  20091. }
  20092. }
  20093. }
  20094. #if defined(USE_LUA)
  20095. lua_init_optional_libraries();
  20096. #endif
  20097. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20098. || defined(OPENSSL_API_3_0)) \
  20099. && !defined(NO_SSL)
  20100. if (features_to_init & MG_FEATURES_SSL) {
  20101. if (!mg_openssl_initialized) {
  20102. char ebuf[128];
  20103. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20104. mg_openssl_initialized = 1;
  20105. } else {
  20106. (void)ebuf;
  20107. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20108. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20109. }
  20110. } else {
  20111. /* ssl already initialized */
  20112. }
  20113. }
  20114. #endif
  20115. if (mg_init_library_called <= 0) {
  20116. mg_init_library_called = 1;
  20117. } else {
  20118. mg_init_library_called++;
  20119. }
  20120. mg_global_unlock();
  20121. return features_inited;
  20122. }
  20123. /* Un-initialize this library. */
  20124. CIVETWEB_API unsigned
  20125. mg_exit_library(void)
  20126. {
  20127. if (mg_init_library_called <= 0) {
  20128. return 0;
  20129. }
  20130. mg_global_lock();
  20131. mg_init_library_called--;
  20132. if (mg_init_library_called == 0) {
  20133. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20134. if (mg_openssl_initialized) {
  20135. uninitialize_openssl();
  20136. mg_openssl_initialized = 0;
  20137. }
  20138. #endif
  20139. #if defined(_WIN32)
  20140. (void)WSACleanup();
  20141. (void)pthread_mutex_destroy(&global_log_file_lock);
  20142. #else
  20143. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20144. #endif
  20145. (void)pthread_key_delete(sTlsKey);
  20146. #if defined(USE_LUA)
  20147. lua_exit_optional_libraries();
  20148. #endif
  20149. mg_free(all_methods);
  20150. all_methods = NULL;
  20151. mg_global_unlock();
  20152. (void)pthread_mutex_destroy(&global_lock_mutex);
  20153. return 1;
  20154. }
  20155. mg_global_unlock();
  20156. return 1;
  20157. }
  20158. /* End of civetweb.c */