civetweb.c 622 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270
  1. /* Copyright (c) 2013-2025 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_FILESYSTEMS = 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 stderr
  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. REPLACE_ASTERISK_WITH_ORIGIN,
  1771. ACCESS_CONTROL_ALLOW_ORIGIN,
  1772. ACCESS_CONTROL_ALLOW_METHODS,
  1773. ACCESS_CONTROL_ALLOW_HEADERS,
  1774. ACCESS_CONTROL_EXPOSE_HEADERS,
  1775. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1776. ERROR_PAGES,
  1777. #if !defined(NO_CACHING)
  1778. STATIC_FILE_MAX_AGE,
  1779. STATIC_FILE_CACHE_CONTROL,
  1780. #endif
  1781. #if !defined(NO_SSL)
  1782. STRICT_HTTPS_MAX_AGE,
  1783. #endif
  1784. ADDITIONAL_HEADER,
  1785. ALLOW_INDEX_SCRIPT_SUB_RES,
  1786. NUM_OPTIONS
  1787. };
  1788. /* Config option name, config types, default value.
  1789. * Must be in the same order as the enum const above.
  1790. */
  1791. static const struct mg_option config_options[] = {
  1792. /* Once for each server */
  1793. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1794. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1795. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1796. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1797. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1798. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1799. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1800. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1801. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1802. #if defined(__linux__)
  1803. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1804. #endif
  1805. #if defined(_WIN32)
  1806. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1807. #endif
  1808. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1809. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1810. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1811. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1812. #if defined(USE_WEBSOCKET)
  1813. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1814. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1815. #endif
  1816. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1817. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1818. #if defined(USE_LUA)
  1819. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1820. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1821. #endif
  1822. #if defined(USE_HTTP2)
  1823. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1824. #endif
  1825. /* Once for each domain */
  1826. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1827. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1828. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1829. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1830. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1831. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1832. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1834. #if defined(USE_TIMERS)
  1835. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1836. #endif
  1837. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1838. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1839. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1840. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1841. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1842. #if defined(USE_TIMERS)
  1843. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1844. #endif
  1845. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1846. #if defined(USE_4_CGI)
  1847. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1848. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1849. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1850. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1851. #if defined(USE_TIMERS)
  1852. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1853. #endif
  1854. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1855. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1856. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1858. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1859. #if defined(USE_TIMERS)
  1860. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1861. #endif
  1862. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1863. #endif
  1864. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1865. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1866. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1867. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1868. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1869. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1870. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1871. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1872. {"index_files",
  1873. MG_CONFIG_TYPE_STRING_LIST,
  1874. #if defined(USE_LUA)
  1875. "index.xhtml,index.html,index.htm,"
  1876. "index.lp,index.lsp,index.lua,index.cgi,"
  1877. "index.shtml,index.php"},
  1878. #else
  1879. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1880. #endif
  1881. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1882. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1883. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1884. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1885. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1886. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1887. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1888. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1889. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1890. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1891. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1892. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1893. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1894. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1895. * as a minimum in 2020 */
  1896. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1897. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1898. #if defined(USE_LUA)
  1899. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1900. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1901. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1902. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1903. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1904. #endif
  1905. #endif
  1906. #if defined(USE_DUKTAPE)
  1907. /* The support for duktape is still in alpha version state.
  1908. * The name of this config option might change. */
  1909. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1910. #endif
  1911. #if defined(USE_WEBSOCKET)
  1912. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1913. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1914. #endif
  1915. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1916. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1917. #endif
  1918. {"replace_asterisk_with_origin", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1919. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1920. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1921. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1922. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1923. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1924. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1925. #if !defined(NO_CACHING)
  1926. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1927. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1928. #endif
  1929. #if !defined(NO_SSL)
  1930. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1931. #endif
  1932. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1933. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1934. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1935. /* Check if the config_options and the corresponding enum have compatible
  1936. * sizes. */
  1937. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1938. == (NUM_OPTIONS + 1),
  1939. "config_options and enum not sync");
  1940. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1941. struct mg_handler_info {
  1942. /* Name/Pattern of the URI. */
  1943. char *uri;
  1944. size_t uri_len;
  1945. /* handler type */
  1946. int handler_type;
  1947. /* Handler for http/https or requests. */
  1948. mg_request_handler handler;
  1949. unsigned int refcount;
  1950. int removing;
  1951. /* Handler for ws/wss (websocket) requests. */
  1952. mg_websocket_connect_handler connect_handler;
  1953. mg_websocket_ready_handler ready_handler;
  1954. mg_websocket_data_handler data_handler;
  1955. mg_websocket_close_handler close_handler;
  1956. /* accepted subprotocols for ws/wss requests. */
  1957. struct mg_websocket_subprotocols *subprotocols;
  1958. /* Handler for authorization requests */
  1959. mg_authorization_handler auth_handler;
  1960. /* User supplied argument for the handler function. */
  1961. void *cbdata;
  1962. /* next handler in a linked list */
  1963. struct mg_handler_info *next;
  1964. };
  1965. enum {
  1966. CONTEXT_INVALID,
  1967. CONTEXT_SERVER,
  1968. CONTEXT_HTTP_CLIENT,
  1969. CONTEXT_WS_CLIENT
  1970. };
  1971. struct mg_domain_context {
  1972. SSL_CTX *ssl_ctx; /* SSL context */
  1973. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1974. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1975. int64_t ssl_cert_last_mtime;
  1976. /* Server nonce */
  1977. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1978. unsigned long nonce_count; /* Used nonces, used for authentication */
  1979. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1980. /* linked list of shared lua websockets */
  1981. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1982. #endif
  1983. /* Linked list of domains */
  1984. struct mg_domain_context *next;
  1985. };
  1986. /* Stop flag can be "volatile" or require a lock.
  1987. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1988. * states a read operation for int is always atomic. */
  1989. #if defined(STOP_FLAG_NEEDS_LOCK)
  1990. typedef ptrdiff_t volatile stop_flag_t;
  1991. static int
  1992. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1993. {
  1994. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1995. return (sf == 0);
  1996. }
  1997. static int
  1998. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1999. {
  2000. stop_flag_t sf = mg_atomic_add(f, 0);
  2001. return (sf == 2);
  2002. }
  2003. static void
  2004. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  2005. {
  2006. stop_flag_t sf = 0;
  2007. do {
  2008. sf = mg_atomic_compare_and_swap(f,
  2009. __atomic_load_n(f, __ATOMIC_SEQ_CST),
  2010. v);
  2011. } while (sf != v);
  2012. }
  2013. #else /* STOP_FLAG_NEEDS_LOCK */
  2014. typedef int volatile stop_flag_t;
  2015. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  2016. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  2017. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  2018. #endif /* STOP_FLAG_NEEDS_LOCK */
  2019. #if !defined(NUM_WEBDAV_LOCKS)
  2020. #define NUM_WEBDAV_LOCKS 10
  2021. #endif
  2022. #if !defined(LOCK_DURATION_S)
  2023. #define LOCK_DURATION_S 60
  2024. #endif
  2025. struct twebdav_lock {
  2026. uint64_t locktime;
  2027. char token[33];
  2028. char path[UTF8_PATH_MAX * 2];
  2029. char user[UTF8_PATH_MAX * 2];
  2030. };
  2031. struct mg_context {
  2032. /* Part 1 - Physical context:
  2033. * This holds threads, ports, timeouts, ...
  2034. * set for the entire server, independent from the
  2035. * addressed hostname.
  2036. */
  2037. /* Connection related */
  2038. int context_type; /* See CONTEXT_* above */
  2039. struct socket *listening_sockets;
  2040. struct mg_pollfd *listening_socket_fds;
  2041. unsigned int num_listening_sockets;
  2042. struct mg_connection *worker_connections; /* The connection struct, pre-
  2043. * allocated for each worker */
  2044. #if defined(USE_SERVER_STATS)
  2045. volatile ptrdiff_t active_connections;
  2046. volatile ptrdiff_t max_active_connections;
  2047. volatile ptrdiff_t total_connections;
  2048. volatile ptrdiff_t total_requests;
  2049. volatile int64_t total_data_read;
  2050. volatile int64_t total_data_written;
  2051. #endif
  2052. /* Thread related */
  2053. stop_flag_t stop_flag; /* Should we stop event loop */
  2054. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2055. pthread_t masterthreadid; /* The master thread ID */
  2056. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2057. allowed to create, total */
  2058. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2059. exist (modified by master thread) */
  2060. unsigned int
  2061. idle_worker_thread_count; /* How many worker-threads are currently
  2062. sitting around with nothing to do */
  2063. /* Access to this value MUST be synchronized by thread_mutex */
  2064. pthread_t *worker_threadids; /* The worker thread IDs */
  2065. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2066. /* Connection to thread dispatching */
  2067. #if defined(ALTERNATIVE_QUEUE)
  2068. struct socket *client_socks;
  2069. void **client_wait_events;
  2070. #else
  2071. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2072. worker thread */
  2073. volatile int sq_head; /* Head of the socket queue */
  2074. volatile int sq_tail; /* Tail of the socket queue */
  2075. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2076. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2077. volatile int sq_blocked; /* Status information: sq is full */
  2078. int sq_size; /* No of elements in socket queue */
  2079. #if defined(USE_SERVER_STATS)
  2080. int sq_max_fill;
  2081. #endif /* USE_SERVER_STATS */
  2082. #endif /* ALTERNATIVE_QUEUE */
  2083. /* Memory related */
  2084. unsigned int max_request_size; /* The max request size */
  2085. #if defined(USE_SERVER_STATS)
  2086. struct mg_memory_stat ctx_memory;
  2087. #endif
  2088. /* WebDAV lock structures */
  2089. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2090. /* Operating system related */
  2091. char *systemName; /* What operating system is running */
  2092. time_t start_time; /* Server start time, used for authentication
  2093. * and for diagnstics. */
  2094. #if defined(USE_TIMERS)
  2095. struct ttimers *timers;
  2096. #endif
  2097. /* Lua specific: Background operations and shared websockets */
  2098. #if defined(USE_LUA)
  2099. void *lua_background_state; /* lua_State (here as void *) */
  2100. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2101. int lua_bg_log_available; /* Use Lua background state for access log */
  2102. #endif
  2103. int user_shutdown_notification_socket; /* mg_stop() will close this
  2104. socket... */
  2105. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2106. to return immediately */
  2107. /* Server nonce */
  2108. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2109. * ssl_cert_last_mtime, nonce_count, and
  2110. * next (linked list) */
  2111. /* Server callbacks */
  2112. struct mg_callbacks callbacks; /* User-defined callback function */
  2113. void *user_data; /* User-defined data */
  2114. /* Part 2 - Logical domain:
  2115. * This holds hostname, TLS certificate, document root, ...
  2116. * set for a domain hosted at the server.
  2117. * There may be multiple domains hosted at one physical server.
  2118. * The default domain "dd" is the first element of a list of
  2119. * domains.
  2120. */
  2121. struct mg_domain_context dd; /* default domain */
  2122. };
  2123. #if defined(USE_SERVER_STATS)
  2124. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2125. static struct mg_memory_stat *
  2126. get_memory_stat(struct mg_context *ctx)
  2127. {
  2128. if (ctx) {
  2129. return &(ctx->ctx_memory);
  2130. }
  2131. return &mg_common_memory;
  2132. }
  2133. #endif
  2134. enum {
  2135. CONNECTION_TYPE_INVALID = 0,
  2136. CONNECTION_TYPE_REQUEST = 1,
  2137. CONNECTION_TYPE_RESPONSE = 2
  2138. };
  2139. enum {
  2140. PROTOCOL_TYPE_HTTP1 = 0,
  2141. PROTOCOL_TYPE_WEBSOCKET = 1,
  2142. PROTOCOL_TYPE_HTTP2 = 2
  2143. };
  2144. #if defined(USE_HTTP2)
  2145. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2146. #define HTTP2_DYN_TABLE_SIZE (256)
  2147. #endif
  2148. struct mg_http2_connection {
  2149. uint32_t stream_id;
  2150. uint32_t dyn_table_size;
  2151. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2152. };
  2153. #endif
  2154. struct mg_connection {
  2155. int connection_type; /* see CONNECTION_TYPE_* above */
  2156. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2157. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2158. fully sent */
  2159. #if defined(USE_HTTP2)
  2160. struct mg_http2_connection http2;
  2161. #endif
  2162. struct mg_request_info request_info;
  2163. struct mg_response_info response_info;
  2164. struct mg_context *phys_ctx;
  2165. struct mg_domain_context *dom_ctx;
  2166. #if defined(USE_SERVER_STATS)
  2167. int conn_state; /* 0 = undef, numerical value may change in different
  2168. * versions. For the current definition, see
  2169. * mg_get_connection_info_impl */
  2170. #endif
  2171. SSL *ssl; /* SSL descriptor */
  2172. struct socket client; /* Connected client */
  2173. time_t conn_birth_time; /* Time (wall clock) when connection was
  2174. * established */
  2175. #if defined(USE_SERVER_STATS)
  2176. time_t conn_close_time; /* Time (wall clock) when connection was
  2177. * closed (or 0 if still open) */
  2178. double processing_time; /* Processing time for one request. */
  2179. #endif
  2180. struct timespec req_time; /* Time (since system start) when the request
  2181. * was received */
  2182. int64_t num_bytes_sent; /* Total bytes sent to client */
  2183. int64_t content_len; /* How many bytes of content can be read
  2184. * !is_chunked: Content-Length header value
  2185. * or -1 (until connection closed,
  2186. * not allowed for a request)
  2187. * is_chunked: >= 0, appended gradually
  2188. */
  2189. int64_t consumed_content; /* How many bytes of content have been read */
  2190. int is_chunked; /* Transfer-Encoding is chunked:
  2191. * 0 = not chunked,
  2192. * 1 = chunked, not yet, or some data read,
  2193. * 2 = chunked, has error,
  2194. * 3 = chunked, all data read except trailer,
  2195. * 4 = chunked, all data read
  2196. */
  2197. char *buf; /* Buffer for received data */
  2198. char *path_info; /* PATH_INFO part of the URL */
  2199. int must_close; /* 1 if connection must be closed */
  2200. int accept_gzip; /* 1 if gzip encoding is accepted */
  2201. int in_error_handler; /* 1 if in handler for user defined error
  2202. * pages */
  2203. #if defined(USE_WEBSOCKET)
  2204. int in_websocket_handling; /* 1 if in read_websocket */
  2205. #endif
  2206. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2207. && defined(MG_EXPERIMENTAL_INTERFACES)
  2208. /* Parameters for websocket data compression according to rfc7692 */
  2209. int websocket_deflate_server_max_windows_bits;
  2210. int websocket_deflate_client_max_windows_bits;
  2211. int websocket_deflate_server_no_context_takeover;
  2212. int websocket_deflate_client_no_context_takeover;
  2213. int websocket_deflate_initialized;
  2214. int websocket_deflate_flush;
  2215. z_stream websocket_deflate_state;
  2216. z_stream websocket_inflate_state;
  2217. #endif
  2218. int handled_requests; /* Number of requests handled by this connection
  2219. */
  2220. int buf_size; /* Buffer size */
  2221. int request_len; /* Size of the request + headers in a buffer */
  2222. int data_len; /* Total size of data in a buffer */
  2223. int status_code; /* HTTP reply status code, e.g. 200 */
  2224. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2225. * throttle */
  2226. time_t last_throttle_time; /* Last time throttled data was sent */
  2227. int last_throttle_bytes; /* Bytes sent this second */
  2228. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2229. * atomic transmissions for websockets */
  2230. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2231. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2232. #endif
  2233. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2234. * for quick access */
  2235. };
  2236. /* Directory entry */
  2237. struct de {
  2238. char *file_name;
  2239. struct mg_file_stat file;
  2240. };
  2241. #define mg_cry_internal(conn, fmt, ...) \
  2242. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2243. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2244. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2245. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2246. struct mg_context *ctx,
  2247. const char *func,
  2248. unsigned line,
  2249. const char *fmt,
  2250. ...) PRINTF_ARGS(5, 6);
  2251. #if !defined(NO_THREAD_NAME)
  2252. #if defined(_WIN32) && defined(_MSC_VER)
  2253. /* Set the thread name for debugging purposes in Visual Studio
  2254. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2255. */
  2256. #pragma pack(push, 8)
  2257. typedef struct tagTHREADNAME_INFO {
  2258. DWORD dwType; /* Must be 0x1000. */
  2259. LPCSTR szName; /* Pointer to name (in user addr space). */
  2260. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2261. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2262. } THREADNAME_INFO;
  2263. #pragma pack(pop)
  2264. #elif defined(__linux__)
  2265. #include <sys/prctl.h>
  2266. #include <sys/sendfile.h>
  2267. #if defined(ALTERNATIVE_QUEUE)
  2268. #include <sys/eventfd.h>
  2269. #endif /* ALTERNATIVE_QUEUE */
  2270. #if defined(ALTERNATIVE_QUEUE)
  2271. static void *
  2272. event_create(void)
  2273. {
  2274. int evhdl = eventfd(0, EFD_CLOEXEC);
  2275. int *ret;
  2276. if (evhdl == -1) {
  2277. /* Linux uses -1 on error, Windows NULL. */
  2278. /* However, Linux does not return 0 on success either. */
  2279. return 0;
  2280. }
  2281. ret = (int *)mg_malloc(sizeof(int));
  2282. if (ret) {
  2283. *ret = evhdl;
  2284. } else {
  2285. (void)close(evhdl);
  2286. }
  2287. return (void *)ret;
  2288. }
  2289. static int
  2290. event_wait(void *eventhdl)
  2291. {
  2292. uint64_t u;
  2293. int evhdl, s;
  2294. if (!eventhdl) {
  2295. /* error */
  2296. return 0;
  2297. }
  2298. evhdl = *(int *)eventhdl;
  2299. s = (int)read(evhdl, &u, sizeof(u));
  2300. if (s != sizeof(u)) {
  2301. /* error */
  2302. return 0;
  2303. }
  2304. (void)u; /* the value is not required */
  2305. return 1;
  2306. }
  2307. static int
  2308. event_signal(void *eventhdl)
  2309. {
  2310. uint64_t u = 1;
  2311. int evhdl, s;
  2312. if (!eventhdl) {
  2313. /* error */
  2314. return 0;
  2315. }
  2316. evhdl = *(int *)eventhdl;
  2317. s = (int)write(evhdl, &u, sizeof(u));
  2318. if (s != sizeof(u)) {
  2319. /* error */
  2320. return 0;
  2321. }
  2322. return 1;
  2323. }
  2324. static void
  2325. event_destroy(void *eventhdl)
  2326. {
  2327. int evhdl;
  2328. if (!eventhdl) {
  2329. /* error */
  2330. return;
  2331. }
  2332. evhdl = *(int *)eventhdl;
  2333. close(evhdl);
  2334. mg_free(eventhdl);
  2335. }
  2336. #endif
  2337. #endif
  2338. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2339. struct posix_event {
  2340. pthread_mutex_t mutex;
  2341. pthread_cond_t cond;
  2342. int signaled;
  2343. };
  2344. static void *
  2345. event_create(void)
  2346. {
  2347. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2348. if (ret == 0) {
  2349. /* out of memory */
  2350. return 0;
  2351. }
  2352. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2353. /* pthread mutex not available */
  2354. mg_free(ret);
  2355. return 0;
  2356. }
  2357. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2358. /* pthread cond not available */
  2359. pthread_mutex_destroy(&(ret->mutex));
  2360. mg_free(ret);
  2361. return 0;
  2362. }
  2363. ret->signaled = 0;
  2364. return (void *)ret;
  2365. }
  2366. static int
  2367. event_wait(void *eventhdl)
  2368. {
  2369. struct posix_event *ev = (struct posix_event *)eventhdl;
  2370. pthread_mutex_lock(&(ev->mutex));
  2371. while (!ev->signaled) {
  2372. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2373. }
  2374. ev->signaled = 0;
  2375. pthread_mutex_unlock(&(ev->mutex));
  2376. return 1;
  2377. }
  2378. static int
  2379. event_signal(void *eventhdl)
  2380. {
  2381. struct posix_event *ev = (struct posix_event *)eventhdl;
  2382. pthread_mutex_lock(&(ev->mutex));
  2383. pthread_cond_signal(&(ev->cond));
  2384. ev->signaled = 1;
  2385. pthread_mutex_unlock(&(ev->mutex));
  2386. return 1;
  2387. }
  2388. static void
  2389. event_destroy(void *eventhdl)
  2390. {
  2391. struct posix_event *ev = (struct posix_event *)eventhdl;
  2392. pthread_cond_destroy(&(ev->cond));
  2393. pthread_mutex_destroy(&(ev->mutex));
  2394. mg_free(ev);
  2395. }
  2396. #endif
  2397. static void
  2398. mg_set_thread_name(const char *name)
  2399. {
  2400. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2401. mg_snprintf(
  2402. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2403. #if defined(_WIN32)
  2404. #if defined(_MSC_VER)
  2405. /* Windows and Visual Studio Compiler */
  2406. __try {
  2407. THREADNAME_INFO info;
  2408. info.dwType = 0x1000;
  2409. info.szName = threadName;
  2410. info.dwThreadID = ~0U;
  2411. info.dwFlags = 0;
  2412. RaiseException(0x406D1388,
  2413. 0,
  2414. sizeof(info) / sizeof(ULONG_PTR),
  2415. (ULONG_PTR *)&info);
  2416. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2417. }
  2418. #elif defined(__MINGW32__)
  2419. /* No option known to set thread name for MinGW known */
  2420. #endif
  2421. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2422. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2423. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2424. #if defined(__MACH__) && defined(__APPLE__)
  2425. /* OS X only current thread name can be changed */
  2426. (void)pthread_setname_np(threadName);
  2427. #else
  2428. (void)pthread_setname_np(pthread_self(), threadName);
  2429. #endif
  2430. #elif defined(__linux__)
  2431. /* On Linux we can use the prctl function.
  2432. * When building for Linux Standard Base (LSB) use
  2433. * NO_THREAD_NAME. However, thread names are a big
  2434. * help for debugging, so the stadard is to set them.
  2435. */
  2436. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2437. #endif
  2438. }
  2439. #else /* !defined(NO_THREAD_NAME) */
  2440. static void
  2441. mg_set_thread_name(const char *threadName)
  2442. {
  2443. }
  2444. #endif
  2445. CIVETWEB_API const struct mg_option *
  2446. mg_get_valid_options(void)
  2447. {
  2448. return config_options;
  2449. }
  2450. /* Do not open file (unused) */
  2451. #define MG_FOPEN_MODE_NONE (0)
  2452. /* Open file for read only access */
  2453. #define MG_FOPEN_MODE_READ (1)
  2454. /* Open file for writing, create and overwrite */
  2455. #define MG_FOPEN_MODE_WRITE (2)
  2456. /* Open file for writing, create and append */
  2457. #define MG_FOPEN_MODE_APPEND (4)
  2458. static int
  2459. is_file_opened(const struct mg_file_access *fileacc)
  2460. {
  2461. if (!fileacc) {
  2462. return 0;
  2463. }
  2464. return (fileacc->fp != NULL);
  2465. }
  2466. #if !defined(NO_FILESYSTEMS)
  2467. static int mg_stat(const struct mg_connection *conn,
  2468. const char *path,
  2469. struct mg_file_stat *filep);
  2470. /* Reject files with special characters (for Windows) */
  2471. static int
  2472. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2473. {
  2474. const uint8_t *c = (const uint8_t *)path;
  2475. (void)conn; /* not used */
  2476. if ((c == NULL) || (c[0] == 0)) {
  2477. /* Null pointer or empty path --> suspicious */
  2478. return 1;
  2479. }
  2480. #if defined(_WIN32)
  2481. while (*c) {
  2482. if (*c < 32) {
  2483. /* Control character */
  2484. return 1;
  2485. }
  2486. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2487. /* stdin/stdout redirection character */
  2488. return 1;
  2489. }
  2490. if ((*c == '*') || (*c == '?')) {
  2491. /* Wildcard character */
  2492. return 1;
  2493. }
  2494. if (*c == '"') {
  2495. /* Windows quotation */
  2496. return 1;
  2497. }
  2498. c++;
  2499. }
  2500. #endif
  2501. /* Nothing suspicious found */
  2502. return 0;
  2503. }
  2504. /* mg_fopen will open a file either in memory or on the disk.
  2505. * The input parameter path is a string in UTF-8 encoding.
  2506. * The input parameter mode is MG_FOPEN_MODE_*
  2507. * On success, fp will be set in the output struct mg_file.
  2508. * All status members will also be set.
  2509. * The function returns 1 on success, 0 on error. */
  2510. static int
  2511. mg_fopen(const struct mg_connection *conn,
  2512. const char *path,
  2513. int mode,
  2514. struct mg_file *filep)
  2515. {
  2516. int found;
  2517. if (!filep) {
  2518. return 0;
  2519. }
  2520. filep->access.fp = NULL;
  2521. if (mg_path_suspicious(conn, path)) {
  2522. return 0;
  2523. }
  2524. /* filep is initialized in mg_stat: all fields with memset to,
  2525. * some fields like size and modification date with values */
  2526. found = mg_stat(conn, path, &(filep->stat));
  2527. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2528. /* file does not exist and will not be created */
  2529. return 0;
  2530. }
  2531. #if defined(_WIN32)
  2532. {
  2533. wchar_t wbuf[UTF16_PATH_MAX];
  2534. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2535. switch (mode) {
  2536. case MG_FOPEN_MODE_READ:
  2537. filep->access.fp = _wfopen(wbuf, L"rb");
  2538. break;
  2539. case MG_FOPEN_MODE_WRITE:
  2540. filep->access.fp = _wfopen(wbuf, L"wb");
  2541. break;
  2542. case MG_FOPEN_MODE_APPEND:
  2543. filep->access.fp = _wfopen(wbuf, L"ab");
  2544. break;
  2545. }
  2546. }
  2547. #else
  2548. /* Linux et al already use unicode. No need to convert. */
  2549. switch (mode) {
  2550. case MG_FOPEN_MODE_READ:
  2551. filep->access.fp = fopen(path, "r");
  2552. break;
  2553. case MG_FOPEN_MODE_WRITE:
  2554. filep->access.fp = fopen(path, "w");
  2555. break;
  2556. case MG_FOPEN_MODE_APPEND:
  2557. filep->access.fp = fopen(path, "a");
  2558. break;
  2559. }
  2560. #endif
  2561. if (!found) {
  2562. /* File did not exist before fopen was called.
  2563. * Maybe it has been created now. Get stat info
  2564. * like creation time now. */
  2565. found = mg_stat(conn, path, &(filep->stat));
  2566. (void)found;
  2567. }
  2568. /* return OK if file is opened */
  2569. return (filep->access.fp != NULL);
  2570. }
  2571. /* return 0 on success, just like fclose */
  2572. static int
  2573. mg_fclose(struct mg_file_access *fileacc)
  2574. {
  2575. int ret = -1;
  2576. if (fileacc != NULL) {
  2577. if (fileacc->fp != NULL) {
  2578. ret = fclose(fileacc->fp);
  2579. }
  2580. /* reset all members of fileacc */
  2581. memset(fileacc, 0, sizeof(*fileacc));
  2582. }
  2583. return ret;
  2584. }
  2585. #endif /* NO_FILESYSTEMS */
  2586. static void
  2587. mg_strlcpy(char *dst, const char *src, size_t n)
  2588. {
  2589. for (; *src != '\0' && n > 1; n--) {
  2590. *dst++ = *src++;
  2591. }
  2592. *dst = '\0';
  2593. }
  2594. static int
  2595. lowercase(const char *s)
  2596. {
  2597. return tolower((unsigned char)*s);
  2598. }
  2599. CIVETWEB_API int
  2600. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2601. {
  2602. int diff = 0;
  2603. if (len > 0) {
  2604. do {
  2605. diff = lowercase(s1++) - lowercase(s2++);
  2606. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2607. }
  2608. return diff;
  2609. }
  2610. CIVETWEB_API int
  2611. mg_strcasecmp(const char *s1, const char *s2)
  2612. {
  2613. int diff;
  2614. do {
  2615. diff = lowercase(s1++) - lowercase(s2++);
  2616. } while (diff == 0 && s1[-1] != '\0');
  2617. return diff;
  2618. }
  2619. static char *
  2620. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2621. {
  2622. char *p;
  2623. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2624. * defined */
  2625. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2626. mg_strlcpy(p, ptr, len + 1);
  2627. }
  2628. return p;
  2629. }
  2630. static char *
  2631. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2632. {
  2633. return mg_strndup_ctx(str, strlen(str), ctx);
  2634. }
  2635. static char *
  2636. mg_strdup(const char *str)
  2637. {
  2638. return mg_strndup_ctx(str, strlen(str), NULL);
  2639. }
  2640. static const char *
  2641. mg_strcasestr(const char *big_str, const char *small_str)
  2642. {
  2643. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2644. if (big_len >= small_len) {
  2645. for (i = 0; i <= (big_len - small_len); i++) {
  2646. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2647. return big_str + i;
  2648. }
  2649. }
  2650. }
  2651. return NULL;
  2652. }
  2653. /* Return null terminated string of given maximum length.
  2654. * Report errors if length is exceeded. */
  2655. static void
  2656. mg_vsnprintf(const struct mg_connection *conn,
  2657. int *truncated,
  2658. char *buf,
  2659. size_t buflen,
  2660. const char *fmt,
  2661. va_list ap)
  2662. {
  2663. int n, ok;
  2664. if (buflen == 0) {
  2665. if (truncated) {
  2666. *truncated = 1;
  2667. }
  2668. return;
  2669. }
  2670. #if defined(__clang__)
  2671. #pragma clang diagnostic push
  2672. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2673. /* Using fmt as a non-literal is intended here, since it is mostly called
  2674. * indirectly by mg_snprintf */
  2675. #endif
  2676. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2677. ok = (n >= 0) && ((size_t)n < buflen);
  2678. #if defined(__clang__)
  2679. #pragma clang diagnostic pop
  2680. #endif
  2681. if (ok) {
  2682. if (truncated) {
  2683. *truncated = 0;
  2684. }
  2685. } else {
  2686. if (truncated) {
  2687. *truncated = 1;
  2688. }
  2689. mg_cry_internal(conn,
  2690. "truncating vsnprintf buffer: [%.*s]",
  2691. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2692. buf);
  2693. n = (int)buflen - 1;
  2694. }
  2695. buf[n] = '\0';
  2696. }
  2697. static void
  2698. mg_snprintf(const struct mg_connection *conn,
  2699. int *truncated,
  2700. char *buf,
  2701. size_t buflen,
  2702. const char *fmt,
  2703. ...)
  2704. {
  2705. va_list ap;
  2706. va_start(ap, fmt);
  2707. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2708. va_end(ap);
  2709. }
  2710. static int
  2711. get_option_index(const char *name)
  2712. {
  2713. int i;
  2714. for (i = 0; config_options[i].name != NULL; i++) {
  2715. if (strcmp(config_options[i].name, name) == 0) {
  2716. return i;
  2717. }
  2718. }
  2719. return -1;
  2720. }
  2721. CIVETWEB_API const char *
  2722. mg_get_option(const struct mg_context *ctx, const char *name)
  2723. {
  2724. int i;
  2725. if ((i = get_option_index(name)) == -1) {
  2726. return NULL;
  2727. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2728. return "";
  2729. } else {
  2730. return ctx->dd.config[i];
  2731. }
  2732. }
  2733. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2734. CIVETWEB_API struct mg_context *
  2735. mg_get_context(const struct mg_connection *conn)
  2736. {
  2737. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2738. }
  2739. CIVETWEB_API void *
  2740. mg_get_user_data(const struct mg_context *ctx)
  2741. {
  2742. return (ctx == NULL) ? NULL : ctx->user_data;
  2743. }
  2744. CIVETWEB_API void *
  2745. mg_get_user_context_data(const struct mg_connection *conn)
  2746. {
  2747. return mg_get_user_data(mg_get_context(conn));
  2748. }
  2749. CIVETWEB_API void *
  2750. mg_get_thread_pointer(const struct mg_connection *conn)
  2751. {
  2752. /* both methods should return the same pointer */
  2753. if (conn) {
  2754. /* quick access, in case conn is known */
  2755. return conn->tls_user_ptr;
  2756. } else {
  2757. /* otherwise get pointer from thread local storage (TLS) */
  2758. struct mg_workerTLS *tls =
  2759. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2760. return tls->user_ptr;
  2761. }
  2762. }
  2763. CIVETWEB_API void
  2764. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2765. {
  2766. if (const_conn != NULL) {
  2767. /* Const cast, since "const struct mg_connection *" does not mean
  2768. * the connection object is not modified. Here "const" is used,
  2769. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2770. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2771. conn->request_info.conn_data = data;
  2772. }
  2773. }
  2774. CIVETWEB_API void *
  2775. mg_get_user_connection_data(const struct mg_connection *conn)
  2776. {
  2777. if (conn != NULL) {
  2778. return conn->request_info.conn_data;
  2779. }
  2780. return NULL;
  2781. }
  2782. CIVETWEB_API int
  2783. mg_get_server_ports(const struct mg_context *ctx,
  2784. int size,
  2785. struct mg_server_port *ports)
  2786. {
  2787. int i, cnt = 0;
  2788. if (size <= 0) {
  2789. return -1;
  2790. }
  2791. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2792. if (!ctx) {
  2793. return -1;
  2794. }
  2795. if (!ctx->listening_sockets) {
  2796. return -1;
  2797. }
  2798. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2799. ports[cnt].port =
  2800. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2801. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2802. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2803. ports[cnt].is_optional = ctx->listening_sockets[i].is_optional;
  2804. ports[cnt].is_bound = ctx->listening_sockets[i].sock != INVALID_SOCKET;
  2805. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2806. /* IPv4 */
  2807. ports[cnt].protocol = 1;
  2808. cnt++;
  2809. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2810. /* IPv6 */
  2811. ports[cnt].protocol = 3;
  2812. cnt++;
  2813. }
  2814. }
  2815. return cnt;
  2816. }
  2817. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2818. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2819. #endif
  2820. static void
  2821. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2822. {
  2823. buf[0] = '\0';
  2824. if (!usa) {
  2825. return;
  2826. }
  2827. if (usa->sa.sa_family == AF_INET) {
  2828. getnameinfo(&usa->sa,
  2829. sizeof(usa->sin),
  2830. buf,
  2831. (unsigned)len,
  2832. NULL,
  2833. 0,
  2834. NI_NUMERICHOST);
  2835. }
  2836. #if defined(USE_IPV6)
  2837. else if (usa->sa.sa_family == AF_INET6) {
  2838. getnameinfo(&usa->sa,
  2839. sizeof(usa->sin6),
  2840. buf,
  2841. (unsigned)len,
  2842. NULL,
  2843. 0,
  2844. NI_NUMERICHOST);
  2845. }
  2846. #endif
  2847. #if defined(USE_X_DOM_SOCKET)
  2848. else if (usa->sa.sa_family == AF_UNIX) {
  2849. /* TODO: Define a remote address for unix domain sockets.
  2850. * This code will always return "localhost", identical to http+tcp:
  2851. getnameinfo(&usa->sa,
  2852. sizeof(usa->sun),
  2853. buf,
  2854. (unsigned)len,
  2855. NULL,
  2856. 0,
  2857. NI_NUMERICHOST);
  2858. */
  2859. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2860. }
  2861. #endif
  2862. }
  2863. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2864. * included in all responses other than 100, 101, 5xx. */
  2865. static void
  2866. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2867. {
  2868. #if !defined(REENTRANT_TIME)
  2869. struct tm *tm;
  2870. tm = ((t != NULL) ? gmtime(t) : NULL);
  2871. if (tm != NULL) {
  2872. #else
  2873. struct tm _tm;
  2874. struct tm *tm = &_tm;
  2875. if (t != NULL) {
  2876. gmtime_r(t, tm);
  2877. #endif
  2878. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2879. } else {
  2880. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2881. }
  2882. }
  2883. /* difftime for struct timespec. Return value is in seconds. */
  2884. static double
  2885. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2886. {
  2887. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2888. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2889. }
  2890. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2891. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2892. const char *func,
  2893. unsigned line,
  2894. const char *fmt,
  2895. va_list ap);
  2896. #include "external_mg_cry_internal_impl.inl"
  2897. #elif !defined(NO_FILESYSTEMS)
  2898. /* Print error message to the opened error log stream. */
  2899. static void
  2900. mg_cry_internal_impl(const struct mg_connection *conn,
  2901. const char *func,
  2902. unsigned line,
  2903. const char *fmt,
  2904. va_list ap)
  2905. {
  2906. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2907. struct mg_file fi;
  2908. time_t timestamp;
  2909. /* Unused, in the RELEASE build */
  2910. (void)func;
  2911. (void)line;
  2912. #if defined(GCC_DIAGNOSTIC)
  2913. #pragma GCC diagnostic push
  2914. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2915. #endif
  2916. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2917. #if defined(GCC_DIAGNOSTIC)
  2918. #pragma GCC diagnostic pop
  2919. #endif
  2920. buf[sizeof(buf) - 1] = 0;
  2921. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2922. if (!conn) {
  2923. fputs(buf, stderr);
  2924. return;
  2925. }
  2926. /* Do not lock when getting the callback value, here and below.
  2927. * I suppose this is fine, since function cannot disappear in the
  2928. * same way string option can. */
  2929. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2930. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2931. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2932. if (mg_fopen(conn,
  2933. conn->dom_ctx->config[ERROR_LOG_FILE],
  2934. MG_FOPEN_MODE_APPEND,
  2935. &fi)
  2936. == 0) {
  2937. fi.access.fp = NULL;
  2938. }
  2939. } else {
  2940. fi.access.fp = NULL;
  2941. }
  2942. if (fi.access.fp != NULL) {
  2943. flockfile(fi.access.fp);
  2944. timestamp = time(NULL);
  2945. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2946. fprintf(fi.access.fp,
  2947. "[%010lu] [error] [client %s] ",
  2948. (unsigned long)timestamp,
  2949. src_addr);
  2950. if (conn->request_info.request_method != NULL) {
  2951. fprintf(fi.access.fp,
  2952. "%s %s: ",
  2953. conn->request_info.request_method,
  2954. conn->request_info.request_uri
  2955. ? conn->request_info.request_uri
  2956. : "");
  2957. }
  2958. fprintf(fi.access.fp, "%s", buf);
  2959. fputc('\n', fi.access.fp);
  2960. fflush(fi.access.fp);
  2961. funlockfile(fi.access.fp);
  2962. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2963. * mg_cry here anyway ;-) */
  2964. }
  2965. }
  2966. }
  2967. #else
  2968. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2969. #endif /* Externally provided function */
  2970. /* Construct fake connection structure. Used for logging, if connection
  2971. * is not applicable at the moment of logging. */
  2972. static struct mg_connection *
  2973. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2974. {
  2975. static const struct mg_connection conn_zero = {0};
  2976. *fc = conn_zero;
  2977. fc->phys_ctx = ctx;
  2978. fc->dom_ctx = &(ctx->dd);
  2979. return fc;
  2980. }
  2981. static void
  2982. mg_cry_internal_wrap(const struct mg_connection *conn,
  2983. struct mg_context *ctx,
  2984. const char *func,
  2985. unsigned line,
  2986. const char *fmt,
  2987. ...)
  2988. {
  2989. va_list ap;
  2990. va_start(ap, fmt);
  2991. if (!conn && ctx) {
  2992. struct mg_connection fc;
  2993. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2994. } else {
  2995. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2996. }
  2997. va_end(ap);
  2998. }
  2999. CIVETWEB_API void
  3000. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3001. {
  3002. va_list ap;
  3003. va_start(ap, fmt);
  3004. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3005. va_end(ap);
  3006. }
  3007. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3008. CIVETWEB_API const char *
  3009. mg_version(void)
  3010. {
  3011. return CIVETWEB_VERSION;
  3012. }
  3013. CIVETWEB_API const struct mg_request_info *
  3014. mg_get_request_info(const struct mg_connection *conn)
  3015. {
  3016. if (!conn) {
  3017. return NULL;
  3018. }
  3019. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3020. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3021. char txt[16];
  3022. struct mg_workerTLS *tls =
  3023. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3024. sprintf(txt, "%03i", conn->response_info.status_code);
  3025. if (strlen(txt) == 3) {
  3026. memcpy(tls->txtbuf, txt, 4);
  3027. } else {
  3028. strcpy(tls->txtbuf, "ERR");
  3029. }
  3030. ((struct mg_connection *)conn)->request_info.local_uri =
  3031. tls->txtbuf; /* use thread safe buffer */
  3032. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3033. tls->txtbuf; /* use the same thread safe buffer */
  3034. ((struct mg_connection *)conn)->request_info.request_uri =
  3035. tls->txtbuf; /* use the same thread safe buffer */
  3036. ((struct mg_connection *)conn)->request_info.num_headers =
  3037. conn->response_info.num_headers;
  3038. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3039. conn->response_info.http_headers,
  3040. sizeof(conn->response_info.http_headers));
  3041. } else
  3042. #endif
  3043. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3044. return NULL;
  3045. }
  3046. return &conn->request_info;
  3047. }
  3048. CIVETWEB_API const struct mg_response_info *
  3049. mg_get_response_info(const struct mg_connection *conn)
  3050. {
  3051. if (!conn) {
  3052. return NULL;
  3053. }
  3054. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3055. return NULL;
  3056. }
  3057. return &conn->response_info;
  3058. }
  3059. static const char *
  3060. get_proto_name(const struct mg_connection *conn)
  3061. {
  3062. #if defined(__clang__)
  3063. #pragma clang diagnostic push
  3064. #pragma clang diagnostic ignored "-Wunreachable-code"
  3065. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3066. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3067. * unreachable, but splitting into four different #ifdef clauses here is
  3068. * more complicated.
  3069. */
  3070. #endif
  3071. const struct mg_request_info *ri = &conn->request_info;
  3072. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3073. ? (ri->is_ssl ? "wss" : "ws")
  3074. : (ri->is_ssl ? "https" : "http"));
  3075. return proto;
  3076. #if defined(__clang__)
  3077. #pragma clang diagnostic pop
  3078. #endif
  3079. }
  3080. static int
  3081. mg_construct_local_link(const struct mg_connection *conn,
  3082. char *buf,
  3083. size_t buflen,
  3084. const char *define_proto,
  3085. int define_port,
  3086. const char *define_uri)
  3087. {
  3088. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3089. return -1;
  3090. } else {
  3091. int i, j;
  3092. int truncated = 0;
  3093. const struct mg_request_info *ri = &conn->request_info;
  3094. const char *proto =
  3095. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3096. const char *uri =
  3097. (define_uri != NULL)
  3098. ? define_uri
  3099. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3100. int port = (define_port > 0) ? define_port : ri->server_port;
  3101. int default_port = 80;
  3102. char *uri_encoded;
  3103. size_t uri_encoded_len;
  3104. if (uri == NULL) {
  3105. return -1;
  3106. }
  3107. uri_encoded_len = strlen(uri) * 3 + 1;
  3108. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3109. if (uri_encoded == NULL) {
  3110. return -1;
  3111. }
  3112. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3113. /* Directory separator should be preserved. */
  3114. for (i = j = 0; uri_encoded[i]; j++) {
  3115. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3116. uri_encoded[j] = '/';
  3117. i += 3;
  3118. } else {
  3119. uri_encoded[j] = uri_encoded[i++];
  3120. }
  3121. }
  3122. uri_encoded[j] = '\0';
  3123. #if defined(USE_X_DOM_SOCKET)
  3124. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3125. /* TODO: Define and document a link for UNIX domain sockets. */
  3126. /* There seems to be no official standard for this.
  3127. * Common uses seem to be "httpunix://", "http.unix://" or
  3128. * "http+unix://" as a protocol definition string, followed by
  3129. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3130. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3131. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3132. * "" (completely skipping the server name part). In any case, the
  3133. * last part is the server local path. */
  3134. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3135. mg_snprintf(conn,
  3136. &truncated,
  3137. buf,
  3138. buflen,
  3139. "%s.unix://%s%s",
  3140. proto,
  3141. server_name,
  3142. ri->local_uri);
  3143. default_port = 0;
  3144. mg_free(uri_encoded);
  3145. return 0;
  3146. }
  3147. #endif
  3148. if (define_proto) {
  3149. /* If we got a protocol name, use the default port accordingly. */
  3150. if ((0 == strcmp(define_proto, "https"))
  3151. || (0 == strcmp(define_proto, "wss"))) {
  3152. default_port = 443;
  3153. }
  3154. } else if (ri->is_ssl) {
  3155. /* If we did not get a protocol name, use TLS as default if it is
  3156. * already used. */
  3157. default_port = 443;
  3158. }
  3159. {
  3160. #if defined(USE_IPV6)
  3161. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3162. #endif
  3163. int auth_domain_check_enabled =
  3164. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3165. && (!mg_strcasecmp(
  3166. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3167. const char *server_domain =
  3168. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3169. char portstr[16];
  3170. char server_ip[48];
  3171. if (port != default_port) {
  3172. sprintf(portstr, ":%u", (unsigned)port);
  3173. } else {
  3174. portstr[0] = 0;
  3175. }
  3176. if (!auth_domain_check_enabled || !server_domain) {
  3177. sockaddr_to_string(server_ip,
  3178. sizeof(server_ip),
  3179. &conn->client.lsa);
  3180. server_domain = server_ip;
  3181. }
  3182. mg_snprintf(conn,
  3183. &truncated,
  3184. buf,
  3185. buflen,
  3186. #if defined(USE_IPV6)
  3187. "%s://%s%s%s%s%s",
  3188. proto,
  3189. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3190. server_domain,
  3191. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3192. #else
  3193. "%s://%s%s%s",
  3194. proto,
  3195. server_domain,
  3196. #endif
  3197. portstr,
  3198. uri_encoded);
  3199. mg_free(uri_encoded);
  3200. if (truncated) {
  3201. return -1;
  3202. }
  3203. return 0;
  3204. }
  3205. }
  3206. }
  3207. CIVETWEB_API int
  3208. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3209. {
  3210. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3211. }
  3212. /* Skip the characters until one of the delimiters characters found.
  3213. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3214. * Advance pointer to buffer to the next word. Return found 0-terminated
  3215. * word.
  3216. * Delimiters can be quoted with quotechar. */
  3217. static char *
  3218. skip_quoted(char **buf,
  3219. const char *delimiters,
  3220. const char *whitespace,
  3221. char quotechar)
  3222. {
  3223. char *p, *begin_word, *end_word, *end_whitespace;
  3224. begin_word = *buf;
  3225. end_word = begin_word + strcspn(begin_word, delimiters);
  3226. /* Check for quotechar */
  3227. if (end_word > begin_word) {
  3228. p = end_word - 1;
  3229. while (*p == quotechar) {
  3230. /* While the delimiter is quoted, look for the next delimiter. */
  3231. /* This happens, e.g., in calls from parse_auth_header,
  3232. * if the user name contains a " character. */
  3233. /* If there is anything beyond end_word, copy it. */
  3234. if (*end_word != '\0') {
  3235. size_t end_off = strcspn(end_word + 1, delimiters);
  3236. memmove(p, end_word, end_off + 1);
  3237. p += end_off; /* p must correspond to end_word - 1 */
  3238. end_word += end_off + 1;
  3239. } else {
  3240. *p = '\0';
  3241. break;
  3242. }
  3243. }
  3244. for (p++; p < end_word; p++) {
  3245. *p = '\0';
  3246. }
  3247. }
  3248. if (*end_word == '\0') {
  3249. *buf = end_word;
  3250. } else {
  3251. #if defined(GCC_DIAGNOSTIC)
  3252. /* Disable spurious conversion warning for GCC */
  3253. #pragma GCC diagnostic push
  3254. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3255. #endif /* defined(GCC_DIAGNOSTIC) */
  3256. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3257. #if defined(GCC_DIAGNOSTIC)
  3258. #pragma GCC diagnostic pop
  3259. #endif /* defined(GCC_DIAGNOSTIC) */
  3260. for (p = end_word; p < end_whitespace; p++) {
  3261. *p = '\0';
  3262. }
  3263. *buf = end_whitespace;
  3264. }
  3265. return begin_word;
  3266. }
  3267. /* Return HTTP header value, or NULL if not found. */
  3268. static const char *
  3269. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3270. {
  3271. int i;
  3272. for (i = 0; i < num_hdr; i++) {
  3273. if (!mg_strcasecmp(name, hdr[i].name)) {
  3274. return hdr[i].value;
  3275. }
  3276. }
  3277. return NULL;
  3278. }
  3279. /* Retrieve requested HTTP header multiple values, and return the number of
  3280. * found occurrences */
  3281. static int
  3282. get_req_headers(const struct mg_request_info *ri,
  3283. const char *name,
  3284. const char **output,
  3285. int output_max_size)
  3286. {
  3287. int i;
  3288. int cnt = 0;
  3289. if (ri) {
  3290. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3291. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3292. output[cnt++] = ri->http_headers[i].value;
  3293. }
  3294. }
  3295. }
  3296. return cnt;
  3297. }
  3298. CIVETWEB_API const char *
  3299. mg_get_header(const struct mg_connection *conn, const char *name)
  3300. {
  3301. if (!conn) {
  3302. return NULL;
  3303. }
  3304. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3305. return get_header(conn->request_info.http_headers,
  3306. conn->request_info.num_headers,
  3307. name);
  3308. }
  3309. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3310. return get_header(conn->response_info.http_headers,
  3311. conn->response_info.num_headers,
  3312. name);
  3313. }
  3314. return NULL;
  3315. }
  3316. static const char *
  3317. get_http_version(const struct mg_connection *conn)
  3318. {
  3319. if (!conn) {
  3320. return NULL;
  3321. }
  3322. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3323. return conn->request_info.http_version;
  3324. }
  3325. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3326. return conn->response_info.http_version;
  3327. }
  3328. return NULL;
  3329. }
  3330. /* A helper function for traversing a comma separated list of values.
  3331. * It returns a list pointer shifted to the next value, or NULL if the end
  3332. * of the list found.
  3333. * Value is stored in val vector. If value has form "x=y", then eq_val
  3334. * vector is initialized to point to the "y" part, and val vector length
  3335. * is adjusted to point only to "x". */
  3336. static const char *
  3337. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3338. {
  3339. int end;
  3340. reparse:
  3341. if (val == NULL || list == NULL || *list == '\0') {
  3342. /* End of the list */
  3343. return NULL;
  3344. }
  3345. /* Skip over leading LWS */
  3346. while (*list == ' ' || *list == '\t')
  3347. list++;
  3348. val->ptr = list;
  3349. if ((list = strchr(val->ptr, ',')) != NULL) {
  3350. /* Comma found. Store length and shift the list ptr */
  3351. val->len = ((size_t)(list - val->ptr));
  3352. list++;
  3353. } else {
  3354. /* This value is the last one */
  3355. list = val->ptr + strlen(val->ptr);
  3356. val->len = ((size_t)(list - val->ptr));
  3357. }
  3358. /* Adjust length for trailing LWS */
  3359. end = (int)val->len - 1;
  3360. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3361. end--;
  3362. val->len = (size_t)(end) + (size_t)(1);
  3363. if (val->len == 0) {
  3364. /* Ignore any empty entries. */
  3365. goto reparse;
  3366. }
  3367. if (eq_val != NULL) {
  3368. /* Value has form "x=y", adjust pointers and lengths
  3369. * so that val points to "x", and eq_val points to "y". */
  3370. eq_val->len = 0;
  3371. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3372. if (eq_val->ptr != NULL) {
  3373. eq_val->ptr++; /* Skip over '=' character */
  3374. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3375. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3376. }
  3377. }
  3378. return list;
  3379. }
  3380. /* A helper function for checking if a comma separated list of values
  3381. * contains
  3382. * the given option (case insensitvely).
  3383. * 'header' can be NULL, in which case false is returned. */
  3384. static int
  3385. header_has_option(const char *header, const char *option)
  3386. {
  3387. struct vec opt_vec;
  3388. struct vec eq_vec;
  3389. DEBUG_ASSERT(option != NULL);
  3390. DEBUG_ASSERT(option[0] != '\0');
  3391. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3392. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Sorting function implemented in a separate file */
  3398. #include "sort.inl"
  3399. /* Pattern matching has been reimplemented in a new file */
  3400. #include "match.inl"
  3401. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3402. * This function must tolerate situations when connection info is not
  3403. * set up, for example if request parsing failed. */
  3404. static int
  3405. should_keep_alive(const struct mg_connection *conn)
  3406. {
  3407. const char *http_version;
  3408. const char *header;
  3409. /* First satisfy needs of the server */
  3410. if ((conn == NULL) || conn->must_close) {
  3411. /* Close, if civetweb framework needs to close */
  3412. return 0;
  3413. }
  3414. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3415. /* Close, if keep alive is not enabled */
  3416. return 0;
  3417. }
  3418. /* Check explicit wish of the client */
  3419. header = mg_get_header(conn, "Connection");
  3420. if (header) {
  3421. /* If there is a connection header from the client, obey */
  3422. if (header_has_option(header, "keep-alive")) {
  3423. return 1;
  3424. }
  3425. return 0;
  3426. }
  3427. /* Use default of the standard */
  3428. http_version = get_http_version(conn);
  3429. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3430. /* HTTP 1.1 default is keep alive */
  3431. return 1;
  3432. }
  3433. /* HTTP 1.0 (and earlier) default is to close the connection */
  3434. return 0;
  3435. }
  3436. static int
  3437. should_decode_url(const struct mg_connection *conn)
  3438. {
  3439. if (!conn || !conn->dom_ctx) {
  3440. return 0;
  3441. }
  3442. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3443. }
  3444. static int
  3445. should_decode_query_string(const struct mg_connection *conn)
  3446. {
  3447. if (!conn || !conn->dom_ctx) {
  3448. return 0;
  3449. }
  3450. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3451. == 0);
  3452. }
  3453. static const char *
  3454. suggest_connection_header(const struct mg_connection *conn)
  3455. {
  3456. return should_keep_alive(conn) ? "keep-alive" : "close";
  3457. }
  3458. #include "response.inl"
  3459. static void
  3460. send_no_cache_header(struct mg_connection *conn)
  3461. {
  3462. /* Send all current and obsolete cache opt-out directives. */
  3463. mg_response_header_add(conn,
  3464. "Cache-Control",
  3465. "no-cache, no-store, "
  3466. "must-revalidate, private, max-age=0",
  3467. -1);
  3468. mg_response_header_add(conn, "Expires", "0", -1);
  3469. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3470. /* Obsolete, but still send it for HTTP/1.0 */
  3471. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3472. }
  3473. }
  3474. static void
  3475. send_static_cache_header(struct mg_connection *conn)
  3476. {
  3477. #if !defined(NO_CACHING)
  3478. int max_age;
  3479. char val[64];
  3480. const char *cache_control =
  3481. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3482. /* If there is a full cache-control option configured,0 use it */
  3483. if (cache_control != NULL) {
  3484. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3485. return;
  3486. }
  3487. /* Read the server config to check how long a file may be cached.
  3488. * The configuration is in seconds. */
  3489. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3490. if (max_age <= 0) {
  3491. /* 0 means "do not cache". All values <0 are reserved
  3492. * and may be used differently in the future. */
  3493. /* If a file should not be cached, do not only send
  3494. * max-age=0, but also pragmas and Expires headers. */
  3495. send_no_cache_header(conn);
  3496. return;
  3497. }
  3498. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3499. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3500. /* See also https://www.mnot.net/cache_docs/ */
  3501. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3502. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3503. * leap
  3504. * year to 31622400 seconds. For the moment, we just send whatever has
  3505. * been configured, still the behavior for >1 year should be considered
  3506. * as undefined. */
  3507. mg_snprintf(
  3508. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3509. mg_response_header_add(conn, "Cache-Control", val, -1);
  3510. #else /* NO_CACHING */
  3511. send_no_cache_header(conn);
  3512. #endif /* !NO_CACHING */
  3513. }
  3514. static void
  3515. send_additional_header(struct mg_connection *conn)
  3516. {
  3517. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3518. #if !defined(NO_SSL)
  3519. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3520. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3521. if (max_age >= 0) {
  3522. char val[64];
  3523. mg_snprintf(conn,
  3524. NULL,
  3525. val,
  3526. sizeof(val),
  3527. "max-age=%lu",
  3528. (unsigned long)max_age);
  3529. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3530. }
  3531. }
  3532. #endif
  3533. // Content-Security-Policy
  3534. if (header && header[0]) {
  3535. mg_response_header_add_lines(conn, header);
  3536. }
  3537. }
  3538. static void
  3539. send_cors_header(struct mg_connection *conn)
  3540. {
  3541. const char *origin_hdr = mg_get_header(conn, "Origin");
  3542. const char *cors_orig_cfg =
  3543. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3544. const char *cors_cred_cfg =
  3545. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3546. const char *cors_hdr_cfg =
  3547. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3548. const char *cors_exphdr_cfg =
  3549. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3550. const char *cors_meth_cfg =
  3551. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3552. const char *cors_repl_asterisk_with_orig_cfg =
  3553. conn->dom_ctx->config[REPLACE_ASTERISK_WITH_ORIGIN];
  3554. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr
  3555. && cors_repl_asterisk_with_orig_cfg
  3556. && *cors_repl_asterisk_with_orig_cfg) {
  3557. int cors_repl_asterisk_with_orig =
  3558. mg_strcasecmp(cors_repl_asterisk_with_orig_cfg, "yes");
  3559. /* Cross-origin resource sharing (CORS), see
  3560. * http://www.html5rocks.com/en/tutorials/cors/,
  3561. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3562. * CORS preflight is not supported for files. */
  3563. if (cors_repl_asterisk_with_orig == 0 && cors_orig_cfg[0] == '*') {
  3564. mg_response_header_add(conn,
  3565. "Access-Control-Allow-Origin",
  3566. origin_hdr,
  3567. -1);
  3568. } else {
  3569. mg_response_header_add(conn,
  3570. "Access-Control-Allow-Origin",
  3571. cors_orig_cfg,
  3572. -1);
  3573. }
  3574. }
  3575. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3576. /* Cross-origin resource sharing (CORS), see
  3577. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3578. */
  3579. mg_response_header_add(conn,
  3580. "Access-Control-Allow-Credentials",
  3581. cors_cred_cfg,
  3582. -1);
  3583. }
  3584. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3585. mg_response_header_add(conn,
  3586. "Access-Control-Allow-Headers",
  3587. cors_hdr_cfg,
  3588. -1);
  3589. }
  3590. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3591. mg_response_header_add(conn,
  3592. "Access-Control-Expose-Headers",
  3593. cors_exphdr_cfg,
  3594. -1);
  3595. }
  3596. if (cors_meth_cfg && *cors_meth_cfg) {
  3597. mg_response_header_add(conn,
  3598. "Access-Control-Allow-Methods",
  3599. cors_meth_cfg,
  3600. -1);
  3601. }
  3602. }
  3603. #if !defined(NO_FILESYSTEMS)
  3604. static void handle_file_based_request(struct mg_connection *conn,
  3605. const char *path,
  3606. struct mg_file *filep);
  3607. #endif /* NO_FILESYSTEMS */
  3608. CIVETWEB_API const char *
  3609. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3610. {
  3611. /* See IANA HTTP status code assignment:
  3612. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3613. */
  3614. switch (response_code) {
  3615. /* RFC2616 Section 10.1 - Informational 1xx */
  3616. case 100:
  3617. return "Continue"; /* RFC2616 Section 10.1.1 */
  3618. case 101:
  3619. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3620. case 102:
  3621. return "Processing"; /* RFC2518 Section 10.1 */
  3622. /* RFC2616 Section 10.2 - Successful 2xx */
  3623. case 200:
  3624. return "OK"; /* RFC2616 Section 10.2.1 */
  3625. case 201:
  3626. return "Created"; /* RFC2616 Section 10.2.2 */
  3627. case 202:
  3628. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3629. case 203:
  3630. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3631. case 204:
  3632. return "No Content"; /* RFC2616 Section 10.2.5 */
  3633. case 205:
  3634. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3635. case 206:
  3636. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3637. case 207:
  3638. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3639. */
  3640. case 208:
  3641. return "Already Reported"; /* RFC5842 Section 7.1 */
  3642. case 226:
  3643. return "IM used"; /* RFC3229 Section 10.4.1 */
  3644. /* RFC2616 Section 10.3 - Redirection 3xx */
  3645. case 300:
  3646. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3647. case 301:
  3648. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3649. case 302:
  3650. return "Found"; /* RFC2616 Section 10.3.3 */
  3651. case 303:
  3652. return "See Other"; /* RFC2616 Section 10.3.4 */
  3653. case 304:
  3654. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3655. case 305:
  3656. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3657. case 307:
  3658. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3659. case 308:
  3660. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3661. /* RFC2616 Section 10.4 - Client Error 4xx */
  3662. case 400:
  3663. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3664. case 401:
  3665. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3666. case 402:
  3667. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3668. case 403:
  3669. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3670. case 404:
  3671. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3672. case 405:
  3673. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3674. case 406:
  3675. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3676. case 407:
  3677. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3678. case 408:
  3679. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3680. case 409:
  3681. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3682. case 410:
  3683. return "Gone"; /* RFC2616 Section 10.4.11 */
  3684. case 411:
  3685. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3686. case 412:
  3687. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3688. case 413:
  3689. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3690. case 414:
  3691. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3692. case 415:
  3693. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3694. case 416:
  3695. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3696. */
  3697. case 417:
  3698. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3699. case 421:
  3700. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3701. case 422:
  3702. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3703. * Section 11.2 */
  3704. case 423:
  3705. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3706. case 424:
  3707. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3708. * Section 11.4 */
  3709. case 426:
  3710. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3711. case 428:
  3712. return "Precondition Required"; /* RFC 6585, Section 3 */
  3713. case 429:
  3714. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3715. case 431:
  3716. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3717. case 451:
  3718. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3719. * Section 3 */
  3720. /* RFC2616 Section 10.5 - Server Error 5xx */
  3721. case 500:
  3722. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3723. case 501:
  3724. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3725. case 502:
  3726. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3727. case 503:
  3728. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3729. case 504:
  3730. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3731. case 505:
  3732. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3733. case 506:
  3734. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3735. case 507:
  3736. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3737. * Section 11.5 */
  3738. case 508:
  3739. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3740. case 510:
  3741. return "Not Extended"; /* RFC 2774, Section 7 */
  3742. case 511:
  3743. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3744. /* Other status codes, not shown in the IANA HTTP status code
  3745. * assignment.
  3746. * E.g., "de facto" standards due to common use, ... */
  3747. case 418:
  3748. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3749. case 419:
  3750. return "Authentication Timeout"; /* common use */
  3751. case 420:
  3752. return "Enhance Your Calm"; /* common use */
  3753. case 440:
  3754. return "Login Timeout"; /* common use */
  3755. case 509:
  3756. return "Bandwidth Limit Exceeded"; /* common use */
  3757. default:
  3758. /* This error code is unknown. This should not happen. */
  3759. if (conn) {
  3760. mg_cry_internal(conn,
  3761. "Unknown HTTP response code: %u",
  3762. response_code);
  3763. }
  3764. /* Return at least a category according to RFC 2616 Section 10. */
  3765. if (response_code >= 100 && response_code < 200) {
  3766. /* Unknown informational status code */
  3767. return "Information";
  3768. }
  3769. if (response_code >= 200 && response_code < 300) {
  3770. /* Unknown success code */
  3771. return "Success";
  3772. }
  3773. if (response_code >= 300 && response_code < 400) {
  3774. /* Unknown redirection code */
  3775. return "Redirection";
  3776. }
  3777. if (response_code >= 400 && response_code < 500) {
  3778. /* Unknown request error code */
  3779. return "Client Error";
  3780. }
  3781. if (response_code >= 500 && response_code < 600) {
  3782. /* Unknown server error code */
  3783. return "Server Error";
  3784. }
  3785. /* Response code not even within reasonable range */
  3786. return "";
  3787. }
  3788. }
  3789. static int
  3790. mg_send_http_error_impl(struct mg_connection *conn,
  3791. int status,
  3792. const char *fmt,
  3793. va_list args)
  3794. {
  3795. char errmsg_buf[MG_BUF_LEN];
  3796. va_list ap;
  3797. int has_body;
  3798. #if !defined(NO_FILESYSTEMS)
  3799. char path_buf[UTF8_PATH_MAX];
  3800. int len, i, page_handler_found, scope, truncated;
  3801. const char *error_handler = NULL;
  3802. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3803. const char *error_page_file_ext, *tstr;
  3804. #endif /* NO_FILESYSTEMS */
  3805. int handled_by_callback = 0;
  3806. if ((conn == NULL) || (fmt == NULL)) {
  3807. return -2;
  3808. }
  3809. /* Set status (for log) */
  3810. conn->status_code = status;
  3811. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3812. has_body = ((status > 199) && (status != 204) && (status != 304));
  3813. /* Prepare message in buf, if required */
  3814. if (has_body
  3815. || (!conn->in_error_handler
  3816. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3817. /* Store error message in errmsg_buf */
  3818. va_copy(ap, args);
  3819. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3820. va_end(ap);
  3821. /* In a debug build, print all html errors */
  3822. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3823. }
  3824. /* If there is a http_error callback, call it.
  3825. * But don't do it recursively, if callback calls mg_send_http_error again.
  3826. */
  3827. if (!conn->in_error_handler
  3828. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3829. /* Mark in_error_handler to avoid recursion and call user callback. */
  3830. conn->in_error_handler = 1;
  3831. handled_by_callback =
  3832. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3833. == 0);
  3834. conn->in_error_handler = 0;
  3835. }
  3836. if (!handled_by_callback) {
  3837. /* Check for recursion */
  3838. if (conn->in_error_handler) {
  3839. DEBUG_TRACE(
  3840. "Recursion when handling error %u - fall back to default",
  3841. status);
  3842. #if !defined(NO_FILESYSTEMS)
  3843. } else {
  3844. /* Send user defined error pages, if defined */
  3845. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3846. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3847. page_handler_found = 0;
  3848. if (error_handler != NULL) {
  3849. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3850. switch (scope) {
  3851. case 1: /* Handler for specific error, e.g. 404 error */
  3852. mg_snprintf(conn,
  3853. &truncated,
  3854. path_buf,
  3855. sizeof(path_buf) - 32,
  3856. "%serror%03u.",
  3857. error_handler,
  3858. status);
  3859. break;
  3860. case 2: /* Handler for error group, e.g., 5xx error
  3861. * handler
  3862. * for all server errors (500-599) */
  3863. mg_snprintf(conn,
  3864. &truncated,
  3865. path_buf,
  3866. sizeof(path_buf) - 32,
  3867. "%serror%01uxx.",
  3868. error_handler,
  3869. status / 100);
  3870. break;
  3871. default: /* Handler for all errors */
  3872. mg_snprintf(conn,
  3873. &truncated,
  3874. path_buf,
  3875. sizeof(path_buf) - 32,
  3876. "%serror.",
  3877. error_handler);
  3878. break;
  3879. }
  3880. /* String truncation in buf may only occur if
  3881. * error_handler is too long. This string is
  3882. * from the config, not from a client. */
  3883. (void)truncated;
  3884. /* The following code is redundant, but it should avoid
  3885. * false positives in static source code analyzers and
  3886. * vulnerability scanners.
  3887. */
  3888. path_buf[sizeof(path_buf) - 32] = 0;
  3889. len = (int)strlen(path_buf);
  3890. if (len > (int)sizeof(path_buf) - 32) {
  3891. len = (int)sizeof(path_buf) - 32;
  3892. }
  3893. /* Start with the file extension from the configuration. */
  3894. tstr = strchr(error_page_file_ext, '.');
  3895. while (tstr) {
  3896. for (i = 1;
  3897. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3898. i++) {
  3899. /* buffer overrun is not possible here, since
  3900. * (i < 32) && (len < sizeof(path_buf) - 32)
  3901. * ==> (i + len) < sizeof(path_buf) */
  3902. path_buf[len + i - 1] = tstr[i];
  3903. }
  3904. /* buffer overrun is not possible here, since
  3905. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3906. * ==> (i + len) <= sizeof(path_buf) */
  3907. path_buf[len + i - 1] = 0;
  3908. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3909. DEBUG_TRACE("Check error page %s - found",
  3910. path_buf);
  3911. page_handler_found = 1;
  3912. break;
  3913. }
  3914. DEBUG_TRACE("Check error page %s - not found",
  3915. path_buf);
  3916. /* Continue with the next file extension from the
  3917. * configuration (if there is a next one). */
  3918. tstr = strchr(tstr + i, '.');
  3919. }
  3920. }
  3921. }
  3922. if (page_handler_found) {
  3923. conn->in_error_handler = 1;
  3924. handle_file_based_request(conn, path_buf, &error_page_file);
  3925. conn->in_error_handler = 0;
  3926. return 0;
  3927. }
  3928. #endif /* NO_FILESYSTEMS */
  3929. }
  3930. /* No custom error page. Send default error page. */
  3931. conn->must_close = 1;
  3932. mg_response_header_start(conn, status);
  3933. send_no_cache_header(conn);
  3934. send_additional_header(conn);
  3935. send_cors_header(conn);
  3936. if (has_body) {
  3937. mg_response_header_add(conn,
  3938. "Content-Type",
  3939. "text/plain; charset=utf-8",
  3940. -1);
  3941. }
  3942. mg_response_header_send(conn);
  3943. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3944. if (has_body) {
  3945. /* For other errors, send a generic error message. */
  3946. const char *status_text = mg_get_response_code_text(conn, status);
  3947. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3948. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3949. } else {
  3950. /* No body allowed. Close the connection. */
  3951. DEBUG_TRACE("Error %i", status);
  3952. }
  3953. }
  3954. return 0;
  3955. }
  3956. CIVETWEB_API int
  3957. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3958. {
  3959. va_list ap;
  3960. int ret;
  3961. va_start(ap, fmt);
  3962. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3963. va_end(ap);
  3964. return ret;
  3965. }
  3966. CIVETWEB_API int
  3967. mg_send_http_ok(struct mg_connection *conn,
  3968. const char *mime_type,
  3969. long long content_length)
  3970. {
  3971. if ((mime_type == NULL) || (*mime_type == 0)) {
  3972. /* No content type defined: default to text/html */
  3973. mime_type = "text/html";
  3974. }
  3975. mg_response_header_start(conn, 200);
  3976. send_no_cache_header(conn);
  3977. send_additional_header(conn);
  3978. send_cors_header(conn);
  3979. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3980. if (content_length < 0) {
  3981. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3982. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3983. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3984. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3985. }
  3986. } else {
  3987. char len[32];
  3988. int trunc = 0;
  3989. mg_snprintf(conn,
  3990. &trunc,
  3991. len,
  3992. sizeof(len),
  3993. "%" UINT64_FMT,
  3994. (uint64_t)content_length);
  3995. if (!trunc) {
  3996. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3997. * !trunc is always true */
  3998. mg_response_header_add(conn, "Content-Length", len, -1);
  3999. }
  4000. }
  4001. mg_response_header_send(conn);
  4002. return 0;
  4003. }
  4004. CIVETWEB_API int
  4005. mg_send_http_redirect(struct mg_connection *conn,
  4006. const char *target_url,
  4007. int redirect_code)
  4008. {
  4009. /* Send a 30x redirect response.
  4010. *
  4011. * Redirect types (status codes):
  4012. *
  4013. * Status | Perm/Temp | Method | Version
  4014. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4015. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4016. * 303 | temporary | always use GET | HTTP/1.1
  4017. * 307 | temporary | always keep method | HTTP/1.1
  4018. * 308 | permanent | always keep method | HTTP/1.1
  4019. */
  4020. #if defined(MG_SEND_REDIRECT_BODY)
  4021. char redirect_body[MG_BUF_LEN];
  4022. size_t content_len = 0;
  4023. char content_len_text[32];
  4024. #endif
  4025. /* In case redirect_code=0, use 307. */
  4026. if (redirect_code == 0) {
  4027. redirect_code = 307;
  4028. }
  4029. /* In case redirect_code is none of the above, return error. */
  4030. if ((redirect_code != 301) && (redirect_code != 302)
  4031. && (redirect_code != 303) && (redirect_code != 307)
  4032. && (redirect_code != 308)) {
  4033. /* Parameter error */
  4034. return -2;
  4035. }
  4036. /* If target_url is not defined, redirect to "/". */
  4037. if ((target_url == NULL) || (*target_url == 0)) {
  4038. target_url = "/";
  4039. }
  4040. #if defined(MG_SEND_REDIRECT_BODY)
  4041. /* TODO: condition name? */
  4042. /* Prepare a response body with a hyperlink.
  4043. *
  4044. * According to RFC2616 (and RFC1945 before):
  4045. * Unless the request method was HEAD, the entity of the
  4046. * response SHOULD contain a short hypertext note with a hyperlink to
  4047. * the new URI(s).
  4048. *
  4049. * However, this response body is not useful in M2M communication.
  4050. * Probably the original reason in the RFC was, clients not supporting
  4051. * a 30x HTTP redirect could still show the HTML page and let the user
  4052. * press the link. Since current browsers support 30x HTTP, the additional
  4053. * HTML body does not seem to make sense anymore.
  4054. *
  4055. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4056. * but it only notes:
  4057. * The server's response payload usually contains a short
  4058. * hypertext note with a hyperlink to the new URI(s).
  4059. *
  4060. * Deactivated by default. If you need the 30x body, set the define.
  4061. */
  4062. mg_snprintf(
  4063. conn,
  4064. NULL /* ignore truncation */,
  4065. redirect_body,
  4066. sizeof(redirect_body),
  4067. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4068. redirect_text,
  4069. target_url,
  4070. target_url);
  4071. content_len = strlen(reply);
  4072. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4073. #endif
  4074. /* Send all required headers */
  4075. mg_response_header_start(conn, redirect_code);
  4076. mg_response_header_add(conn, "Location", target_url, -1);
  4077. if ((redirect_code == 301) || (redirect_code == 308)) {
  4078. /* Permanent redirect */
  4079. send_static_cache_header(conn);
  4080. } else {
  4081. /* Temporary redirect */
  4082. send_no_cache_header(conn);
  4083. }
  4084. send_additional_header(conn);
  4085. send_cors_header(conn);
  4086. #if defined(MG_SEND_REDIRECT_BODY)
  4087. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4088. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4089. #else
  4090. mg_response_header_add(conn, "Content-Length", "0", 1);
  4091. #endif
  4092. mg_response_header_send(conn);
  4093. #if defined(MG_SEND_REDIRECT_BODY)
  4094. /* Send response body */
  4095. /* ... unless it is a HEAD request */
  4096. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4097. ret = mg_write(conn, redirect_body, content_len);
  4098. }
  4099. #endif
  4100. return 1;
  4101. }
  4102. #if defined(_WIN32)
  4103. /* Create substitutes for POSIX functions in Win32. */
  4104. #if defined(GCC_DIAGNOSTIC)
  4105. /* Show no warning in case system functions are not used. */
  4106. #pragma GCC diagnostic push
  4107. #pragma GCC diagnostic ignored "-Wunused-function"
  4108. #endif
  4109. static int
  4110. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4111. {
  4112. (void)unused;
  4113. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4114. InitializeCriticalSection(&mutex->sec);
  4115. return 0;
  4116. }
  4117. static int
  4118. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4119. {
  4120. DeleteCriticalSection(&mutex->sec);
  4121. return 0;
  4122. }
  4123. static int
  4124. pthread_mutex_lock(pthread_mutex_t *mutex)
  4125. {
  4126. EnterCriticalSection(&mutex->sec);
  4127. return 0;
  4128. }
  4129. static int
  4130. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4131. {
  4132. LeaveCriticalSection(&mutex->sec);
  4133. return 0;
  4134. }
  4135. FUNCTION_MAY_BE_UNUSED
  4136. static int
  4137. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4138. {
  4139. (void)unused;
  4140. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4141. cv->waiting_thread = NULL;
  4142. return 0;
  4143. }
  4144. FUNCTION_MAY_BE_UNUSED
  4145. static int
  4146. pthread_cond_timedwait(pthread_cond_t *cv,
  4147. pthread_mutex_t *mutex,
  4148. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4149. {
  4150. struct mg_workerTLS **ptls,
  4151. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4152. int ok;
  4153. uint64_t nsnow, nswaitabs;
  4154. int64_t nswaitrel;
  4155. DWORD mswaitrel;
  4156. pthread_mutex_lock(&cv->threadIdSec);
  4157. /* Add this thread to cv's waiting list */
  4158. ptls = &cv->waiting_thread;
  4159. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4160. ;
  4161. tls->next_waiting_thread = NULL;
  4162. *ptls = tls;
  4163. pthread_mutex_unlock(&cv->threadIdSec);
  4164. if (abstime) {
  4165. nsnow = mg_get_current_time_ns();
  4166. nswaitabs =
  4167. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4168. nswaitrel = nswaitabs - nsnow;
  4169. if (nswaitrel < 0) {
  4170. nswaitrel = 0;
  4171. }
  4172. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4173. } else {
  4174. mswaitrel = (DWORD)INFINITE;
  4175. }
  4176. pthread_mutex_unlock(mutex);
  4177. ok = (WAIT_OBJECT_0
  4178. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4179. if (!ok) {
  4180. ok = 1;
  4181. pthread_mutex_lock(&cv->threadIdSec);
  4182. ptls = &cv->waiting_thread;
  4183. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4184. if (*ptls == tls) {
  4185. *ptls = tls->next_waiting_thread;
  4186. ok = 0;
  4187. break;
  4188. }
  4189. }
  4190. pthread_mutex_unlock(&cv->threadIdSec);
  4191. if (ok) {
  4192. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4193. (DWORD)INFINITE);
  4194. }
  4195. }
  4196. /* This thread has been removed from cv's waiting list */
  4197. pthread_mutex_lock(mutex);
  4198. return ok ? 0 : -1;
  4199. }
  4200. FUNCTION_MAY_BE_UNUSED
  4201. static int
  4202. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4203. {
  4204. return pthread_cond_timedwait(cv, mutex, NULL);
  4205. }
  4206. FUNCTION_MAY_BE_UNUSED
  4207. static int
  4208. pthread_cond_signal(pthread_cond_t *cv)
  4209. {
  4210. HANDLE wkup = NULL;
  4211. BOOL ok = FALSE;
  4212. pthread_mutex_lock(&cv->threadIdSec);
  4213. if (cv->waiting_thread) {
  4214. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4215. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4216. ok = SetEvent(wkup);
  4217. DEBUG_ASSERT(ok);
  4218. }
  4219. pthread_mutex_unlock(&cv->threadIdSec);
  4220. return ok ? 0 : 1;
  4221. }
  4222. FUNCTION_MAY_BE_UNUSED
  4223. static int
  4224. pthread_cond_broadcast(pthread_cond_t *cv)
  4225. {
  4226. pthread_mutex_lock(&cv->threadIdSec);
  4227. while (cv->waiting_thread) {
  4228. pthread_cond_signal(cv);
  4229. }
  4230. pthread_mutex_unlock(&cv->threadIdSec);
  4231. return 0;
  4232. }
  4233. FUNCTION_MAY_BE_UNUSED
  4234. static int
  4235. pthread_cond_destroy(pthread_cond_t *cv)
  4236. {
  4237. pthread_mutex_lock(&cv->threadIdSec);
  4238. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4239. pthread_mutex_unlock(&cv->threadIdSec);
  4240. pthread_mutex_destroy(&cv->threadIdSec);
  4241. return 0;
  4242. }
  4243. #if defined(ALTERNATIVE_QUEUE)
  4244. FUNCTION_MAY_BE_UNUSED
  4245. static void *
  4246. event_create(void)
  4247. {
  4248. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4249. }
  4250. FUNCTION_MAY_BE_UNUSED
  4251. static int
  4252. event_wait(void *eventhdl)
  4253. {
  4254. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4255. return (res == WAIT_OBJECT_0);
  4256. }
  4257. FUNCTION_MAY_BE_UNUSED
  4258. static int
  4259. event_signal(void *eventhdl)
  4260. {
  4261. return (int)SetEvent((HANDLE)eventhdl);
  4262. }
  4263. FUNCTION_MAY_BE_UNUSED
  4264. static void
  4265. event_destroy(void *eventhdl)
  4266. {
  4267. CloseHandle((HANDLE)eventhdl);
  4268. }
  4269. #endif
  4270. #if defined(GCC_DIAGNOSTIC)
  4271. /* Enable unused function warning again */
  4272. #pragma GCC diagnostic pop
  4273. #endif
  4274. /* For Windows, change all slashes to backslashes in path names. */
  4275. static void
  4276. change_slashes_to_backslashes(char *path)
  4277. {
  4278. int i;
  4279. for (i = 0; path[i] != '\0'; i++) {
  4280. if (path[i] == '/') {
  4281. path[i] = '\\';
  4282. }
  4283. /* remove double backslash (check i > 0 to preserve UNC paths,
  4284. * like \\server\file.txt) */
  4285. if ((i > 0) && (path[i] == '\\')) {
  4286. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4287. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4288. }
  4289. }
  4290. }
  4291. }
  4292. static int
  4293. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4294. {
  4295. int diff;
  4296. do {
  4297. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4298. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4299. s1++;
  4300. s2++;
  4301. } while ((diff == 0) && (s1[-1] != L'\0'));
  4302. return diff;
  4303. }
  4304. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4305. * wbuf and wbuf_len is a target buffer and its length. */
  4306. static void
  4307. path_to_unicode(const struct mg_connection *conn,
  4308. const char *path,
  4309. wchar_t *wbuf,
  4310. size_t wbuf_len)
  4311. {
  4312. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4313. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4314. DWORD long_len, err;
  4315. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4316. mg_strlcpy(buf, path, sizeof(buf));
  4317. change_slashes_to_backslashes(buf);
  4318. /* Convert to Unicode and back. If doubly-converted string does not
  4319. * match the original, something is fishy, reject. */
  4320. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4321. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4322. WideCharToMultiByte(
  4323. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4324. if (strcmp(buf, buf2) != 0) {
  4325. wbuf[0] = L'\0';
  4326. }
  4327. /* Windows file systems are not case sensitive, but you can still use
  4328. * uppercase and lowercase letters (on all modern file systems).
  4329. * The server can check if the URI uses the same upper/lowercase
  4330. * letters an the file system, effectively making Windows servers
  4331. * case sensitive (like Linux servers are). It is still not possible
  4332. * to use two files with the same name in different cases on Windows
  4333. * (like /a and /A) - this would be possible in Linux.
  4334. * As a default, Windows is not case sensitive, but the case sensitive
  4335. * file name check can be activated by an additional configuration. */
  4336. if (conn) {
  4337. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4338. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4339. "yes")) {
  4340. /* Use case sensitive compare function */
  4341. fcompare = wcscmp;
  4342. }
  4343. }
  4344. (void)conn; /* conn is currently unused */
  4345. /* Only accept a full file path, not a Windows short (8.3) path. */
  4346. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4347. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4348. if (long_len == 0) {
  4349. err = GetLastError();
  4350. if (err == ERROR_FILE_NOT_FOUND) {
  4351. /* File does not exist. This is not always a problem here. */
  4352. return;
  4353. }
  4354. }
  4355. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4356. /* Short name is used. */
  4357. wbuf[0] = L'\0';
  4358. }
  4359. }
  4360. #if !defined(NO_FILESYSTEMS)
  4361. /* Get file information, return 1 if file exists, 0 if not */
  4362. static int
  4363. mg_stat(const struct mg_connection *conn,
  4364. const char *path,
  4365. struct mg_file_stat *filep)
  4366. {
  4367. wchar_t wbuf[UTF16_PATH_MAX];
  4368. WIN32_FILE_ATTRIBUTE_DATA info;
  4369. time_t creation_time;
  4370. size_t len;
  4371. if (!filep) {
  4372. return 0;
  4373. }
  4374. memset(filep, 0, sizeof(*filep));
  4375. if (mg_path_suspicious(conn, path)) {
  4376. return 0;
  4377. }
  4378. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4379. /* Windows happily opens files with some garbage at the end of file name.
  4380. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4381. * "a.cgi", despite one would expect an error back. */
  4382. len = strlen(path);
  4383. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4384. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4385. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4386. filep->last_modified =
  4387. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4388. info.ftLastWriteTime.dwHighDateTime);
  4389. /* On Windows, the file creation time can be higher than the
  4390. * modification time, e.g. when a file is copied.
  4391. * Since the Last-Modified timestamp is used for caching
  4392. * it should be based on the most recent timestamp. */
  4393. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4394. info.ftCreationTime.dwHighDateTime);
  4395. if (creation_time > filep->last_modified) {
  4396. filep->last_modified = creation_time;
  4397. }
  4398. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4399. return 1;
  4400. }
  4401. return 0;
  4402. }
  4403. #endif
  4404. static int
  4405. mg_remove(const struct mg_connection *conn, const char *path)
  4406. {
  4407. wchar_t wbuf[UTF16_PATH_MAX];
  4408. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4409. return DeleteFileW(wbuf) ? 0 : -1;
  4410. }
  4411. static int
  4412. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4413. {
  4414. wchar_t wbuf[UTF16_PATH_MAX];
  4415. (void)mode;
  4416. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4417. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4418. }
  4419. /* Create substitutes for POSIX functions in Win32. */
  4420. #if defined(GCC_DIAGNOSTIC)
  4421. /* Show no warning in case system functions are not used. */
  4422. #pragma GCC diagnostic push
  4423. #pragma GCC diagnostic ignored "-Wunused-function"
  4424. #endif
  4425. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4426. FUNCTION_MAY_BE_UNUSED
  4427. static DIR *
  4428. mg_opendir(const struct mg_connection *conn, const char *name)
  4429. {
  4430. DIR *dir = NULL;
  4431. wchar_t wpath[UTF16_PATH_MAX];
  4432. DWORD attrs;
  4433. if (name == NULL) {
  4434. SetLastError(ERROR_BAD_ARGUMENTS);
  4435. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4436. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4437. } else {
  4438. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4439. attrs = GetFileAttributesW(wpath);
  4440. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4441. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4442. (void)wcscat(wpath, L"\\*");
  4443. dir->handle = FindFirstFileW(wpath, &dir->info);
  4444. dir->result.d_name[0] = '\0';
  4445. } else {
  4446. mg_free(dir);
  4447. dir = NULL;
  4448. }
  4449. }
  4450. return dir;
  4451. }
  4452. FUNCTION_MAY_BE_UNUSED
  4453. static int
  4454. mg_closedir(DIR *dir)
  4455. {
  4456. int result = 0;
  4457. if (dir != NULL) {
  4458. if (dir->handle != INVALID_HANDLE_VALUE)
  4459. result = FindClose(dir->handle) ? 0 : -1;
  4460. mg_free(dir);
  4461. } else {
  4462. result = -1;
  4463. SetLastError(ERROR_BAD_ARGUMENTS);
  4464. }
  4465. return result;
  4466. }
  4467. FUNCTION_MAY_BE_UNUSED
  4468. static struct dirent *
  4469. mg_readdir(DIR *dir)
  4470. {
  4471. struct dirent *result = 0;
  4472. if (dir) {
  4473. if (dir->handle != INVALID_HANDLE_VALUE) {
  4474. result = &dir->result;
  4475. (void)WideCharToMultiByte(CP_UTF8,
  4476. 0,
  4477. dir->info.cFileName,
  4478. -1,
  4479. result->d_name,
  4480. sizeof(result->d_name),
  4481. NULL,
  4482. NULL);
  4483. if (!FindNextFileW(dir->handle, &dir->info)) {
  4484. (void)FindClose(dir->handle);
  4485. dir->handle = INVALID_HANDLE_VALUE;
  4486. }
  4487. } else {
  4488. SetLastError(ERROR_FILE_NOT_FOUND);
  4489. }
  4490. } else {
  4491. SetLastError(ERROR_BAD_ARGUMENTS);
  4492. }
  4493. return result;
  4494. }
  4495. #if !defined(HAVE_POLL)
  4496. #undef POLLIN
  4497. #undef POLLPRI
  4498. #undef POLLOUT
  4499. #undef POLLERR
  4500. #define POLLIN (1) /* Data ready - read will not block. */
  4501. #define POLLPRI (2) /* Priority data ready. */
  4502. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4503. #define POLLERR (8) /* Error event */
  4504. FUNCTION_MAY_BE_UNUSED
  4505. static int
  4506. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4507. {
  4508. struct timeval tv;
  4509. fd_set rset;
  4510. fd_set wset;
  4511. fd_set eset;
  4512. unsigned int i;
  4513. int result;
  4514. SOCKET maxfd = 0;
  4515. memset(&tv, 0, sizeof(tv));
  4516. tv.tv_sec = milliseconds / 1000;
  4517. tv.tv_usec = (milliseconds % 1000) * 1000;
  4518. FD_ZERO(&rset);
  4519. FD_ZERO(&wset);
  4520. FD_ZERO(&eset);
  4521. for (i = 0; i < n; i++) {
  4522. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4523. if (pfd[i].events & POLLIN) {
  4524. FD_SET(pfd[i].fd, &rset);
  4525. }
  4526. if (pfd[i].events & POLLOUT) {
  4527. FD_SET(pfd[i].fd, &wset);
  4528. }
  4529. /* Check for errors for any FD in the set */
  4530. FD_SET(pfd[i].fd, &eset);
  4531. }
  4532. pfd[i].revents = 0;
  4533. if (pfd[i].fd > maxfd) {
  4534. maxfd = pfd[i].fd;
  4535. }
  4536. }
  4537. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4538. for (i = 0; i < n; i++) {
  4539. if (FD_ISSET(pfd[i].fd, &rset)) {
  4540. pfd[i].revents |= POLLIN;
  4541. }
  4542. if (FD_ISSET(pfd[i].fd, &wset)) {
  4543. pfd[i].revents |= POLLOUT;
  4544. }
  4545. if (FD_ISSET(pfd[i].fd, &eset)) {
  4546. pfd[i].revents |= POLLERR;
  4547. }
  4548. }
  4549. }
  4550. /* We should subtract the time used in select from remaining
  4551. * "milliseconds", in particular if called from mg_poll with a
  4552. * timeout quantum.
  4553. * Unfortunately, the remaining time is not stored in "tv" in all
  4554. * implementations, so the result in "tv" must be considered undefined.
  4555. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4556. return result;
  4557. }
  4558. #endif /* HAVE_POLL */
  4559. #if defined(GCC_DIAGNOSTIC)
  4560. /* Enable unused function warning again */
  4561. #pragma GCC diagnostic pop
  4562. #endif
  4563. static void
  4564. set_close_on_exec(SOCKET sock,
  4565. const struct mg_connection *conn /* may be null */,
  4566. struct mg_context *ctx /* may be null */)
  4567. {
  4568. (void)conn; /* Unused. */
  4569. (void)ctx;
  4570. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4571. }
  4572. CIVETWEB_API int
  4573. mg_start_thread(mg_thread_func_t f, void *p)
  4574. {
  4575. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4576. /* Compile-time option to control stack size, e.g.
  4577. * -DUSE_STACK_SIZE=16384
  4578. */
  4579. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4580. == ((uintptr_t)(-1L)))
  4581. ? -1
  4582. : 0);
  4583. #else
  4584. return (
  4585. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4586. ? -1
  4587. : 0);
  4588. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4589. }
  4590. /* Start a thread storing the thread context. */
  4591. static int
  4592. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4593. void *p,
  4594. pthread_t *threadidptr)
  4595. {
  4596. uintptr_t uip;
  4597. HANDLE threadhandle;
  4598. int result = -1;
  4599. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4600. threadhandle = (HANDLE)uip;
  4601. if ((uip != 0) && (threadidptr != NULL)) {
  4602. *threadidptr = threadhandle;
  4603. result = 0;
  4604. }
  4605. return result;
  4606. }
  4607. /* Wait for a thread to finish. */
  4608. static int
  4609. mg_join_thread(pthread_t threadid)
  4610. {
  4611. int result;
  4612. DWORD dwevent;
  4613. result = -1;
  4614. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4615. if (dwevent == WAIT_FAILED) {
  4616. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4617. } else {
  4618. if (dwevent == WAIT_OBJECT_0) {
  4619. CloseHandle(threadid);
  4620. result = 0;
  4621. }
  4622. }
  4623. return result;
  4624. }
  4625. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4626. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4627. /* Create substitutes for POSIX functions in Win32. */
  4628. #if defined(GCC_DIAGNOSTIC)
  4629. /* Show no warning in case system functions are not used. */
  4630. #pragma GCC diagnostic push
  4631. #pragma GCC diagnostic ignored "-Wunused-function"
  4632. #endif
  4633. FUNCTION_MAY_BE_UNUSED
  4634. static HANDLE
  4635. dlopen(const char *dll_name, int flags)
  4636. {
  4637. wchar_t wbuf[UTF16_PATH_MAX];
  4638. (void)flags;
  4639. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4640. return LoadLibraryW(wbuf);
  4641. }
  4642. FUNCTION_MAY_BE_UNUSED
  4643. static int
  4644. dlclose(void *handle)
  4645. {
  4646. int result;
  4647. if (FreeLibrary((HMODULE)handle) != 0) {
  4648. result = 0;
  4649. } else {
  4650. result = -1;
  4651. }
  4652. return result;
  4653. }
  4654. #if defined(GCC_DIAGNOSTIC)
  4655. /* Enable unused function warning again */
  4656. #pragma GCC diagnostic pop
  4657. #endif
  4658. #endif
  4659. #if !defined(NO_CGI)
  4660. #define SIGKILL (0)
  4661. static int
  4662. kill(pid_t pid, int sig_num)
  4663. {
  4664. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4665. (void)CloseHandle((HANDLE)pid);
  4666. return 0;
  4667. }
  4668. #if !defined(WNOHANG)
  4669. #define WNOHANG (1)
  4670. #endif
  4671. static pid_t
  4672. waitpid(pid_t pid, int *status, int flags)
  4673. {
  4674. DWORD timeout = INFINITE;
  4675. DWORD waitres;
  4676. (void)status; /* Currently not used by any client here */
  4677. if ((flags | WNOHANG) == WNOHANG) {
  4678. timeout = 0;
  4679. }
  4680. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4681. if (waitres == WAIT_OBJECT_0) {
  4682. return pid;
  4683. }
  4684. if (waitres == WAIT_TIMEOUT) {
  4685. return 0;
  4686. }
  4687. return (pid_t)-1;
  4688. }
  4689. static void
  4690. trim_trailing_whitespaces(char *s)
  4691. {
  4692. char *e = s + strlen(s);
  4693. while ((e > s) && isspace((unsigned char)e[-1])) {
  4694. *(--e) = '\0';
  4695. }
  4696. }
  4697. static pid_t
  4698. spawn_process(struct mg_connection *conn,
  4699. const char *prog,
  4700. char *envblk,
  4701. char *envp[],
  4702. int fdin[2],
  4703. int fdout[2],
  4704. int fderr[2],
  4705. const char *dir,
  4706. int cgi_config_idx)
  4707. {
  4708. HANDLE me;
  4709. char *interp;
  4710. char *interp_arg = 0;
  4711. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4712. int truncated;
  4713. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4714. STARTUPINFOA si;
  4715. PROCESS_INFORMATION pi = {0};
  4716. (void)envp;
  4717. memset(&si, 0, sizeof(si));
  4718. si.cb = sizeof(si);
  4719. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4720. si.wShowWindow = SW_HIDE;
  4721. me = GetCurrentProcess();
  4722. DuplicateHandle(me,
  4723. (HANDLE)_get_osfhandle(fdin[0]),
  4724. me,
  4725. &si.hStdInput,
  4726. 0,
  4727. TRUE,
  4728. DUPLICATE_SAME_ACCESS);
  4729. DuplicateHandle(me,
  4730. (HANDLE)_get_osfhandle(fdout[1]),
  4731. me,
  4732. &si.hStdOutput,
  4733. 0,
  4734. TRUE,
  4735. DUPLICATE_SAME_ACCESS);
  4736. DuplicateHandle(me,
  4737. (HANDLE)_get_osfhandle(fderr[1]),
  4738. me,
  4739. &si.hStdError,
  4740. 0,
  4741. TRUE,
  4742. DUPLICATE_SAME_ACCESS);
  4743. /* Mark handles that should not be inherited. See
  4744. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4745. */
  4746. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4747. HANDLE_FLAG_INHERIT,
  4748. 0);
  4749. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4750. HANDLE_FLAG_INHERIT,
  4751. 0);
  4752. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4753. HANDLE_FLAG_INHERIT,
  4754. 0);
  4755. /* First check, if there is a CGI interpreter configured for all CGI
  4756. * scripts. */
  4757. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4758. if (interp != NULL) {
  4759. /* If there is a configured interpreter, check for additional arguments
  4760. */
  4761. interp_arg =
  4762. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4763. } else {
  4764. /* Otherwise, the interpreter must be stated in the first line of the
  4765. * CGI script file, after a #! (shebang) mark. */
  4766. buf[0] = buf[1] = '\0';
  4767. /* Get the full script path */
  4768. mg_snprintf(
  4769. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4770. if (truncated) {
  4771. pi.hProcess = (pid_t)-1;
  4772. goto spawn_cleanup;
  4773. }
  4774. /* Open the script file, to read the first line */
  4775. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4776. /* Read the first line of the script into the buffer */
  4777. mg_fgets(buf, sizeof(buf), &file);
  4778. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4779. buf[sizeof(buf) - 1] = '\0';
  4780. }
  4781. if ((buf[0] == '#') && (buf[1] == '!')) {
  4782. trim_trailing_whitespaces(buf + 2);
  4783. } else {
  4784. buf[2] = '\0';
  4785. }
  4786. interp = buf + 2;
  4787. }
  4788. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4789. if (interp[0] != '\0') {
  4790. /* This is an interpreted script file. We must call the interpreter. */
  4791. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4792. mg_snprintf(conn,
  4793. &truncated,
  4794. cmdline,
  4795. sizeof(cmdline),
  4796. "\"%s\" %s \"%s\\%s\"",
  4797. interp,
  4798. interp_arg,
  4799. full_dir,
  4800. prog);
  4801. } else {
  4802. mg_snprintf(conn,
  4803. &truncated,
  4804. cmdline,
  4805. sizeof(cmdline),
  4806. "\"%s\" \"%s\\%s\"",
  4807. interp,
  4808. full_dir,
  4809. prog);
  4810. }
  4811. } else {
  4812. /* This is (probably) a compiled program. We call it directly. */
  4813. mg_snprintf(conn,
  4814. &truncated,
  4815. cmdline,
  4816. sizeof(cmdline),
  4817. "\"%s\\%s\"",
  4818. full_dir,
  4819. prog);
  4820. }
  4821. if (truncated) {
  4822. pi.hProcess = (pid_t)-1;
  4823. goto spawn_cleanup;
  4824. }
  4825. DEBUG_TRACE("Running [%s]", cmdline);
  4826. if (CreateProcessA(NULL,
  4827. cmdline,
  4828. NULL,
  4829. NULL,
  4830. TRUE,
  4831. CREATE_NEW_PROCESS_GROUP,
  4832. envblk,
  4833. NULL,
  4834. &si,
  4835. &pi)
  4836. == 0) {
  4837. mg_cry_internal(
  4838. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4839. pi.hProcess = (pid_t)-1;
  4840. /* goto spawn_cleanup; */
  4841. }
  4842. spawn_cleanup:
  4843. (void)CloseHandle(si.hStdOutput);
  4844. (void)CloseHandle(si.hStdError);
  4845. (void)CloseHandle(si.hStdInput);
  4846. if (pi.hThread != NULL) {
  4847. (void)CloseHandle(pi.hThread);
  4848. }
  4849. return (pid_t)pi.hProcess;
  4850. }
  4851. #endif /* !NO_CGI */
  4852. static int
  4853. set_blocking_mode(SOCKET sock)
  4854. {
  4855. unsigned long non_blocking = 0;
  4856. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4857. }
  4858. static int
  4859. set_non_blocking_mode(SOCKET sock)
  4860. {
  4861. unsigned long non_blocking = 1;
  4862. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4863. }
  4864. #else
  4865. #if !defined(NO_FILESYSTEMS)
  4866. static int
  4867. mg_stat(const struct mg_connection *conn,
  4868. const char *path,
  4869. struct mg_file_stat *filep)
  4870. {
  4871. struct stat st;
  4872. if (!filep) {
  4873. return 0;
  4874. }
  4875. memset(filep, 0, sizeof(*filep));
  4876. if (mg_path_suspicious(conn, path)) {
  4877. return 0;
  4878. }
  4879. if (0 == stat(path, &st)) {
  4880. filep->size = (uint64_t)(st.st_size);
  4881. filep->last_modified = st.st_mtime;
  4882. filep->is_directory = S_ISDIR(st.st_mode);
  4883. return 1;
  4884. }
  4885. return 0;
  4886. }
  4887. #endif /* NO_FILESYSTEMS */
  4888. static void
  4889. set_close_on_exec(int fd,
  4890. const struct mg_connection *conn /* may be null */,
  4891. struct mg_context *ctx /* may be null */)
  4892. {
  4893. #if defined(__ZEPHYR__)
  4894. (void)fd;
  4895. (void)conn;
  4896. (void)ctx;
  4897. #else
  4898. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4899. if (conn || ctx) {
  4900. struct mg_connection fc;
  4901. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4902. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4903. __func__,
  4904. strerror(ERRNO));
  4905. }
  4906. }
  4907. #endif
  4908. }
  4909. CIVETWEB_API int
  4910. mg_start_thread(mg_thread_func_t func, void *param)
  4911. {
  4912. pthread_t thread_id;
  4913. pthread_attr_t attr;
  4914. int result;
  4915. (void)pthread_attr_init(&attr);
  4916. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4917. #if defined(__ZEPHYR__)
  4918. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4919. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4920. /* Compile-time option to control stack size,
  4921. * e.g. -DUSE_STACK_SIZE=16384 */
  4922. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4923. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4924. result = pthread_create(&thread_id, &attr, func, param);
  4925. pthread_attr_destroy(&attr);
  4926. return result;
  4927. }
  4928. /* Start a thread storing the thread context. */
  4929. static int
  4930. mg_start_thread_with_id(mg_thread_func_t func,
  4931. void *param,
  4932. pthread_t *threadidptr)
  4933. {
  4934. pthread_t thread_id;
  4935. pthread_attr_t attr;
  4936. int result;
  4937. (void)pthread_attr_init(&attr);
  4938. #if defined(__ZEPHYR__)
  4939. pthread_attr_setstack(&attr,
  4940. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4941. ZEPHYR_STACK_SIZE);
  4942. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4943. /* Compile-time option to control stack size,
  4944. * e.g. -DUSE_STACK_SIZE=16384 */
  4945. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4946. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4947. result = pthread_create(&thread_id, &attr, func, param);
  4948. pthread_attr_destroy(&attr);
  4949. if ((result == 0) && (threadidptr != NULL)) {
  4950. *threadidptr = thread_id;
  4951. }
  4952. return result;
  4953. }
  4954. /* Wait for a thread to finish. */
  4955. static int
  4956. mg_join_thread(pthread_t threadid)
  4957. {
  4958. int result;
  4959. result = pthread_join(threadid, NULL);
  4960. return result;
  4961. }
  4962. #if !defined(NO_CGI)
  4963. static pid_t
  4964. spawn_process(struct mg_connection *conn,
  4965. const char *prog,
  4966. char *envblk,
  4967. char *envp[],
  4968. int fdin[2],
  4969. int fdout[2],
  4970. int fderr[2],
  4971. const char *dir,
  4972. int cgi_config_idx)
  4973. {
  4974. pid_t pid;
  4975. const char *interp;
  4976. (void)envblk;
  4977. if ((pid = fork()) == -1) {
  4978. /* Parent */
  4979. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4980. } else if (pid != 0) {
  4981. /* Make sure children close parent-side descriptors.
  4982. * The caller will close the child-side immediately. */
  4983. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4984. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4985. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4986. } else {
  4987. /* Child */
  4988. if (chdir(dir) != 0) {
  4989. mg_cry_internal(
  4990. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4991. } else if (dup2(fdin[0], 0) == -1) {
  4992. mg_cry_internal(conn,
  4993. "%s: dup2(%d, 0): %s",
  4994. __func__,
  4995. fdin[0],
  4996. strerror(ERRNO));
  4997. } else if (dup2(fdout[1], 1) == -1) {
  4998. mg_cry_internal(conn,
  4999. "%s: dup2(%d, 1): %s",
  5000. __func__,
  5001. fdout[1],
  5002. strerror(ERRNO));
  5003. } else if (dup2(fderr[1], 2) == -1) {
  5004. mg_cry_internal(conn,
  5005. "%s: dup2(%d, 2): %s",
  5006. __func__,
  5007. fderr[1],
  5008. strerror(ERRNO));
  5009. } else {
  5010. struct sigaction sa;
  5011. /* Keep stderr and stdout in two different pipes.
  5012. * Stdout will be sent back to the client,
  5013. * stderr should go into a server error log. */
  5014. (void)close(fdin[0]);
  5015. (void)close(fdout[1]);
  5016. (void)close(fderr[1]);
  5017. /* Close write end fdin and read end fdout and fderr */
  5018. (void)close(fdin[1]);
  5019. (void)close(fdout[0]);
  5020. (void)close(fderr[0]);
  5021. /* After exec, all signal handlers are restored to their default
  5022. * values, with one exception of SIGCHLD. According to
  5023. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5024. * will leave unchanged after exec if it was set to be ignored.
  5025. * Restore it to default action. */
  5026. memset(&sa, 0, sizeof(sa));
  5027. sa.sa_handler = SIG_DFL;
  5028. sigaction(SIGCHLD, &sa, NULL);
  5029. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5030. if (interp == NULL) {
  5031. /* no interpreter configured, call the program directly */
  5032. (void)execle(prog, prog, NULL, envp);
  5033. mg_cry_internal(conn,
  5034. "%s: execle(%s): %s",
  5035. __func__,
  5036. prog,
  5037. strerror(ERRNO));
  5038. } else {
  5039. /* call the configured interpreter */
  5040. const char *interp_args =
  5041. conn->dom_ctx
  5042. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5043. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5044. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5045. } else {
  5046. (void)execle(interp, interp, prog, NULL, envp);
  5047. }
  5048. mg_cry_internal(conn,
  5049. "%s: execle(%s %s): %s",
  5050. __func__,
  5051. interp,
  5052. prog,
  5053. strerror(ERRNO));
  5054. }
  5055. }
  5056. exit(EXIT_FAILURE);
  5057. }
  5058. return pid;
  5059. }
  5060. #endif /* !NO_CGI */
  5061. static int
  5062. set_non_blocking_mode(SOCKET sock)
  5063. {
  5064. int flags = fcntl(sock, F_GETFL, 0);
  5065. if (flags < 0) {
  5066. return -1;
  5067. }
  5068. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5069. return -1;
  5070. }
  5071. return 0;
  5072. }
  5073. static int
  5074. set_blocking_mode(SOCKET sock)
  5075. {
  5076. int flags = fcntl(sock, F_GETFL, 0);
  5077. if (flags < 0) {
  5078. return -1;
  5079. }
  5080. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5081. return -1;
  5082. }
  5083. return 0;
  5084. }
  5085. #endif /* _WIN32 / else */
  5086. /* End of initial operating system specific define block. */
  5087. /* Get a random number (independent of C rand function) */
  5088. static uint64_t
  5089. get_random(void)
  5090. {
  5091. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5092. static uint64_t lcg = 0; /* Linear congruential generator */
  5093. uint64_t now = mg_get_current_time_ns();
  5094. if (lfsr == 0) {
  5095. /* lfsr will be only 0 if has not been initialized,
  5096. * so this code is called only once. */
  5097. lfsr = mg_get_current_time_ns();
  5098. lcg = mg_get_current_time_ns();
  5099. } else {
  5100. /* Get the next step of both random number generators. */
  5101. lfsr = (lfsr >> 1)
  5102. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5103. << 63);
  5104. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5105. }
  5106. /* Combining two pseudo-random number generators and a high resolution
  5107. * part
  5108. * of the current server time will make it hard (impossible?) to guess
  5109. * the
  5110. * next number. */
  5111. return (lfsr ^ lcg ^ now);
  5112. }
  5113. static int
  5114. mg_poll(struct mg_pollfd *pfd,
  5115. unsigned int n,
  5116. int milliseconds,
  5117. const stop_flag_t *stop_flag)
  5118. {
  5119. /* Call poll, but only for a maximum time of a few seconds.
  5120. * This will allow to stop the server after some seconds, instead
  5121. * of having to wait for a long socket timeout. */
  5122. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5123. int check_pollerr = 0;
  5124. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5125. /* If we wait for only one file descriptor, wait on error as well */
  5126. pfd[0].events |= POLLERR;
  5127. check_pollerr = 1;
  5128. }
  5129. do {
  5130. int result;
  5131. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5132. /* Shut down signal */
  5133. return -2;
  5134. }
  5135. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5136. ms_now = milliseconds;
  5137. }
  5138. result = poll(pfd, n, ms_now);
  5139. if (result != 0) {
  5140. int err = ERRNO;
  5141. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5142. /* Poll returned either success (1) or error (-1).
  5143. * Forward both to the caller. */
  5144. if ((check_pollerr)
  5145. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5146. == POLLERR)) {
  5147. /* One and only file descriptor returned error */
  5148. return -1;
  5149. }
  5150. return result;
  5151. }
  5152. }
  5153. /* Poll returned timeout (0). */
  5154. if (milliseconds > 0) {
  5155. milliseconds -= ms_now;
  5156. }
  5157. } while (milliseconds > 0);
  5158. /* timeout: return 0 */
  5159. return 0;
  5160. }
  5161. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5162. * descriptor.
  5163. * Return value:
  5164. * >=0 .. number of bytes successfully written
  5165. * -1 .. timeout
  5166. * -2 .. error
  5167. */
  5168. static int
  5169. push_inner(struct mg_context *ctx,
  5170. FILE *fp,
  5171. SOCKET sock,
  5172. SSL *ssl,
  5173. const char *buf,
  5174. int len,
  5175. double timeout)
  5176. {
  5177. uint64_t start = 0, now = 0, timeout_ns = 0;
  5178. int n, err;
  5179. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5180. #if defined(_WIN32)
  5181. typedef int len_t;
  5182. #else
  5183. typedef size_t len_t;
  5184. #endif
  5185. if (timeout > 0) {
  5186. now = mg_get_current_time_ns();
  5187. start = now;
  5188. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5189. }
  5190. if (ctx == NULL) {
  5191. return -2;
  5192. }
  5193. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5194. if (ssl) {
  5195. return -2;
  5196. }
  5197. #endif
  5198. /* Try to read until it succeeds, fails, times out, or the server
  5199. * shuts down. */
  5200. for (;;) {
  5201. #if defined(USE_MBEDTLS)
  5202. if (ssl != NULL) {
  5203. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5204. if (n <= 0) {
  5205. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5206. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5207. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5208. n = 0;
  5209. } else {
  5210. fprintf(stderr, "SSL write failed, error %d\n", n);
  5211. return -2;
  5212. }
  5213. } else {
  5214. err = 0;
  5215. }
  5216. } else
  5217. #elif defined(USE_GNUTLS)
  5218. if (ssl != NULL) {
  5219. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t)len);
  5220. if (n < 0) {
  5221. fprintf(stderr,
  5222. "SSL write failed (%d): %s",
  5223. n,
  5224. gnutls_strerror(n));
  5225. return -2;
  5226. } else {
  5227. err = 0;
  5228. }
  5229. } else
  5230. #elif !defined(NO_SSL)
  5231. if (ssl != NULL) {
  5232. ERR_clear_error();
  5233. n = SSL_write(ssl, buf, len);
  5234. if (n <= 0) {
  5235. err = SSL_get_error(ssl, n);
  5236. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5237. err = ERRNO;
  5238. } else if ((err == SSL_ERROR_WANT_READ)
  5239. || (err == SSL_ERROR_WANT_WRITE)) {
  5240. n = 0;
  5241. } else {
  5242. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5243. ERR_clear_error();
  5244. return -2;
  5245. }
  5246. ERR_clear_error();
  5247. } else {
  5248. err = 0;
  5249. }
  5250. } else
  5251. #endif
  5252. if (fp != NULL) {
  5253. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5254. if (ferror(fp)) {
  5255. n = -1;
  5256. err = ERRNO;
  5257. } else {
  5258. err = 0;
  5259. }
  5260. } else {
  5261. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5262. err = (n < 0) ? ERRNO : 0;
  5263. if (ERROR_TRY_AGAIN(err)) {
  5264. err = 0;
  5265. n = 0;
  5266. }
  5267. if (n < 0) {
  5268. /* shutdown of the socket at client side */
  5269. return -2;
  5270. }
  5271. }
  5272. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5273. return -2;
  5274. }
  5275. if ((n > 0) || ((n == 0) && (len == 0))) {
  5276. /* some data has been read, or no data was requested */
  5277. return n;
  5278. }
  5279. if (n < 0) {
  5280. /* socket error - check errno */
  5281. DEBUG_TRACE("send() failed, error %d", err);
  5282. /* TODO (mid): error handling depending on the error code.
  5283. * These codes are different between Windows and Linux.
  5284. * Currently there is no problem with failing send calls,
  5285. * if there is a reproducible situation, it should be
  5286. * investigated in detail.
  5287. */
  5288. return -2;
  5289. }
  5290. /* Only in case n=0 (timeout), repeat calling the write function */
  5291. /* If send failed, wait before retry */
  5292. if (fp != NULL) {
  5293. /* For files, just wait a fixed time.
  5294. * Maybe it helps, maybe not. */
  5295. mg_sleep(5);
  5296. } else {
  5297. /* For sockets, wait for the socket using poll */
  5298. struct mg_pollfd pfd[2];
  5299. int pollres;
  5300. unsigned int num_sock = 1;
  5301. pfd[0].fd = sock;
  5302. pfd[0].events = POLLOUT;
  5303. if (ctx->context_type == CONTEXT_SERVER) {
  5304. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5305. pfd[num_sock].events = POLLIN;
  5306. num_sock++;
  5307. }
  5308. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5309. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5310. return -2;
  5311. }
  5312. if (pollres > 0) {
  5313. continue;
  5314. }
  5315. }
  5316. if (timeout > 0) {
  5317. now = mg_get_current_time_ns();
  5318. if ((now - start) > timeout_ns) {
  5319. /* Timeout */
  5320. break;
  5321. }
  5322. }
  5323. }
  5324. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5325. used */
  5326. return -1;
  5327. }
  5328. static int
  5329. push_all(struct mg_context *ctx,
  5330. FILE *fp,
  5331. SOCKET sock,
  5332. SSL *ssl,
  5333. const char *buf,
  5334. int len)
  5335. {
  5336. double timeout = -1.0;
  5337. int n, nwritten = 0;
  5338. if (ctx == NULL) {
  5339. return -1;
  5340. }
  5341. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5342. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5343. }
  5344. if (timeout <= 0.0) {
  5345. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5346. / 1000.0;
  5347. }
  5348. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5349. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5350. if (n < 0) {
  5351. if (nwritten == 0) {
  5352. nwritten = -1; /* Propagate the error */
  5353. }
  5354. break;
  5355. } else if (n == 0) {
  5356. break; /* No more data to write */
  5357. } else {
  5358. nwritten += n;
  5359. len -= n;
  5360. }
  5361. }
  5362. return nwritten;
  5363. }
  5364. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5365. * Return value:
  5366. * >=0 .. number of bytes successfully read
  5367. * -1 .. timeout
  5368. * -2 .. error
  5369. */
  5370. static int
  5371. pull_inner(FILE *fp,
  5372. struct mg_connection *conn,
  5373. char *buf,
  5374. int len,
  5375. double timeout)
  5376. {
  5377. int nread, err = 0;
  5378. #if defined(_WIN32)
  5379. typedef int len_t;
  5380. #else
  5381. typedef size_t len_t;
  5382. #endif
  5383. /* We need an additional wait loop around this, because in some cases
  5384. * with TLSwe may get data from the socket but not from SSL_read.
  5385. * In this case we need to repeat at least once.
  5386. */
  5387. if (fp != NULL) {
  5388. /* Use read() instead of fread(), because if we're reading from the
  5389. * CGI pipe, fread() may block until IO buffer is filled up. We
  5390. * cannot afford to block and must pass all read bytes immediately
  5391. * to the client. */
  5392. nread = (int)read(fileno(fp), buf, (size_t)len);
  5393. err = (nread < 0) ? ERRNO : 0;
  5394. if ((nread == 0) && (len > 0)) {
  5395. /* Should get data, but got EOL */
  5396. return -2;
  5397. }
  5398. #if defined(USE_MBEDTLS)
  5399. } else if (conn->ssl != NULL) {
  5400. struct mg_pollfd pfd[2];
  5401. int to_read;
  5402. int pollres;
  5403. unsigned int num_sock = 1;
  5404. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5405. if (to_read > 0) {
  5406. /* We already know there is no more data buffered in conn->buf
  5407. * but there is more available in the SSL layer. So don't poll
  5408. * conn->client.sock yet. */
  5409. pollres = 1;
  5410. if (to_read > len)
  5411. to_read = len;
  5412. } else {
  5413. pfd[0].fd = conn->client.sock;
  5414. pfd[0].events = POLLIN;
  5415. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5416. pfd[num_sock].fd =
  5417. conn->phys_ctx->thread_shutdown_notification_socket;
  5418. pfd[num_sock].events = POLLIN;
  5419. num_sock++;
  5420. }
  5421. to_read = len;
  5422. pollres = mg_poll(pfd,
  5423. num_sock,
  5424. (int)(timeout * 1000.0),
  5425. &(conn->phys_ctx->stop_flag));
  5426. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5427. return -2;
  5428. }
  5429. }
  5430. if (pollres > 0) {
  5431. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5432. if (nread <= 0) {
  5433. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5434. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5435. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5436. nread = 0;
  5437. } else {
  5438. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5439. return -2;
  5440. }
  5441. } else {
  5442. err = 0;
  5443. }
  5444. } else if (pollres < 0) {
  5445. /* Error */
  5446. return -2;
  5447. } else {
  5448. /* pollres = 0 means timeout */
  5449. nread = 0;
  5450. }
  5451. #elif defined(USE_GNUTLS)
  5452. } else if (conn->ssl != NULL) {
  5453. struct mg_pollfd pfd[2];
  5454. size_t to_read;
  5455. int pollres;
  5456. unsigned int num_sock = 1;
  5457. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5458. if (to_read > 0) {
  5459. /* We already know there is no more data buffered in conn->buf
  5460. * but there is more available in the SSL layer. So don't poll
  5461. * conn->client.sock yet. */
  5462. pollres = 1;
  5463. if (to_read > (size_t)len)
  5464. to_read = (size_t)len;
  5465. } else {
  5466. pfd[0].fd = conn->client.sock;
  5467. pfd[0].events = POLLIN;
  5468. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5469. pfd[num_sock].fd =
  5470. conn->phys_ctx->thread_shutdown_notification_socket;
  5471. pfd[num_sock].events = POLLIN;
  5472. num_sock++;
  5473. }
  5474. to_read = (size_t)len;
  5475. pollres = mg_poll(pfd,
  5476. num_sock,
  5477. (int)(timeout * 1000.0),
  5478. &(conn->phys_ctx->stop_flag));
  5479. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5480. return -2;
  5481. }
  5482. }
  5483. if (pollres > 0) {
  5484. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5485. if (nread < 0) {
  5486. fprintf(stderr,
  5487. "SSL read failed (%d): %s",
  5488. nread,
  5489. gnutls_strerror(nread));
  5490. return -2;
  5491. } else {
  5492. err = 0;
  5493. }
  5494. } else if (pollres < 0) {
  5495. /* Error */
  5496. return -2;
  5497. } else {
  5498. /* pollres = 0 means timeout */
  5499. nread = 0;
  5500. }
  5501. #elif !defined(NO_SSL)
  5502. } else if (conn->ssl != NULL) {
  5503. int ssl_pending;
  5504. struct mg_pollfd pfd[2];
  5505. int pollres;
  5506. unsigned int num_sock = 1;
  5507. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5508. /* We already know there is no more data buffered in conn->buf
  5509. * but there is more available in the SSL layer. So don't poll
  5510. * conn->client.sock yet. */
  5511. if (ssl_pending > len) {
  5512. ssl_pending = len;
  5513. }
  5514. pollres = 1;
  5515. } else {
  5516. pfd[0].fd = conn->client.sock;
  5517. pfd[0].events = POLLIN;
  5518. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5519. pfd[num_sock].fd =
  5520. conn->phys_ctx->thread_shutdown_notification_socket;
  5521. pfd[num_sock].events = POLLIN;
  5522. num_sock++;
  5523. }
  5524. pollres = mg_poll(pfd,
  5525. num_sock,
  5526. (int)(timeout * 1000.0),
  5527. &(conn->phys_ctx->stop_flag));
  5528. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5529. return -2;
  5530. }
  5531. }
  5532. if (pollres > 0) {
  5533. ERR_clear_error();
  5534. nread =
  5535. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5536. if (nread <= 0) {
  5537. err = SSL_get_error(conn->ssl, nread);
  5538. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5539. err = ERRNO;
  5540. } else if ((err == SSL_ERROR_WANT_READ)
  5541. || (err == SSL_ERROR_WANT_WRITE)) {
  5542. nread = 0;
  5543. } else {
  5544. /* All errors should return -2 */
  5545. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5546. ERR_clear_error();
  5547. return -2;
  5548. }
  5549. ERR_clear_error();
  5550. } else {
  5551. err = 0;
  5552. }
  5553. } else if (pollres < 0) {
  5554. /* Error */
  5555. return -2;
  5556. } else {
  5557. /* pollres = 0 means timeout */
  5558. nread = 0;
  5559. }
  5560. #endif
  5561. } else {
  5562. struct mg_pollfd pfd[2];
  5563. int pollres;
  5564. unsigned int num_sock = 1;
  5565. pfd[0].fd = conn->client.sock;
  5566. pfd[0].events = POLLIN;
  5567. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5568. pfd[num_sock].fd =
  5569. conn->phys_ctx->thread_shutdown_notification_socket;
  5570. pfd[num_sock].events = POLLIN;
  5571. num_sock++;
  5572. }
  5573. pollres = mg_poll(pfd,
  5574. num_sock,
  5575. (int)(timeout * 1000.0),
  5576. &(conn->phys_ctx->stop_flag));
  5577. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5578. return -2;
  5579. }
  5580. if (pollres > 0) {
  5581. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5582. err = (nread < 0) ? ERRNO : 0;
  5583. if (nread <= 0) {
  5584. /* shutdown of the socket at client side */
  5585. return -2;
  5586. }
  5587. } else if (pollres < 0) {
  5588. /* error calling poll */
  5589. return -2;
  5590. } else {
  5591. /* pollres = 0 means timeout */
  5592. nread = 0;
  5593. }
  5594. }
  5595. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5596. return -2;
  5597. }
  5598. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5599. /* some data has been read, or no data was requested */
  5600. return nread;
  5601. }
  5602. if (nread < 0) {
  5603. /* socket error - check errno */
  5604. #if defined(_WIN32)
  5605. if (err == WSAEWOULDBLOCK) {
  5606. /* TODO (low): check if this is still required */
  5607. /* standard case if called from close_socket_gracefully */
  5608. return -2;
  5609. } else if (err == WSAETIMEDOUT) {
  5610. /* TODO (low): check if this is still required */
  5611. /* timeout is handled by the while loop */
  5612. return 0;
  5613. } else if (err == WSAECONNABORTED) {
  5614. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5615. return -2;
  5616. } else {
  5617. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5618. return -2;
  5619. }
  5620. #else
  5621. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5622. * if the timeout is reached and if the socket was set to non-
  5623. * blocking in close_socket_gracefully, so we can not distinguish
  5624. * here. We have to wait for the timeout in both cases for now.
  5625. */
  5626. if (ERROR_TRY_AGAIN(err)) {
  5627. /* TODO (low): check if this is still required */
  5628. /* EAGAIN/EWOULDBLOCK:
  5629. * standard case if called from close_socket_gracefully
  5630. * => should return -1 */
  5631. /* or timeout occurred
  5632. * => the code must stay in the while loop */
  5633. /* EINTR can be generated on a socket with a timeout set even
  5634. * when SA_RESTART is effective for all relevant signals
  5635. * (see signal(7)).
  5636. * => stay in the while loop */
  5637. } else {
  5638. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5639. return -2;
  5640. }
  5641. #endif
  5642. }
  5643. /* Timeout occurred, but no data available. */
  5644. return -1;
  5645. }
  5646. static int
  5647. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5648. {
  5649. int n, nread = 0;
  5650. double timeout = -1.0;
  5651. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5652. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5653. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5654. }
  5655. if (timeout <= 0.0) {
  5656. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5657. / 1000.0;
  5658. }
  5659. start_time = mg_get_current_time_ns();
  5660. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5661. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5662. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5663. if (n == -2) {
  5664. if (nread == 0) {
  5665. nread = -1; /* Propagate the error */
  5666. }
  5667. break;
  5668. } else if (n == -1) {
  5669. /* timeout */
  5670. if (timeout >= 0.0) {
  5671. now = mg_get_current_time_ns();
  5672. if ((now - start_time) <= timeout_ns) {
  5673. continue;
  5674. }
  5675. }
  5676. break;
  5677. } else if (n == 0) {
  5678. break; /* No more data to read */
  5679. } else {
  5680. nread += n;
  5681. len -= n;
  5682. }
  5683. }
  5684. return nread;
  5685. }
  5686. static void
  5687. discard_unread_request_data(struct mg_connection *conn)
  5688. {
  5689. char buf[MG_BUF_LEN];
  5690. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5691. ;
  5692. }
  5693. static int
  5694. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5695. {
  5696. int64_t content_len, n, buffered_len, nread;
  5697. int64_t len64 =
  5698. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5699. * int, we may not read more
  5700. * bytes */
  5701. const char *body;
  5702. if (conn == NULL) {
  5703. return 0;
  5704. }
  5705. /* If Content-Length is not set for a response with body data,
  5706. * we do not know in advance how much data should be read. */
  5707. content_len = conn->content_len;
  5708. if (content_len < 0) {
  5709. /* The body data is completed when the connection is closed. */
  5710. content_len = INT64_MAX;
  5711. }
  5712. nread = 0;
  5713. if (conn->consumed_content < content_len) {
  5714. /* Adjust number of bytes to read. */
  5715. int64_t left_to_read = content_len - conn->consumed_content;
  5716. if (left_to_read < len64) {
  5717. /* Do not read more than the total content length of the
  5718. * request.
  5719. */
  5720. len64 = left_to_read;
  5721. }
  5722. /* Return buffered data */
  5723. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5724. - conn->consumed_content;
  5725. if (buffered_len > 0) {
  5726. if (len64 < buffered_len) {
  5727. buffered_len = len64;
  5728. }
  5729. body = conn->buf + conn->request_len + conn->consumed_content;
  5730. memcpy(buf, body, (size_t)buffered_len);
  5731. len64 -= buffered_len;
  5732. conn->consumed_content += buffered_len;
  5733. nread += buffered_len;
  5734. buf = (char *)buf + buffered_len;
  5735. }
  5736. /* We have returned all buffered data. Read new data from the remote
  5737. * socket.
  5738. */
  5739. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5740. conn->consumed_content += n;
  5741. nread += n;
  5742. } else {
  5743. nread = ((nread > 0) ? nread : n);
  5744. }
  5745. }
  5746. return (int)nread;
  5747. }
  5748. /* Forward declarations */
  5749. static void handle_request(struct mg_connection *);
  5750. static void log_access(const struct mg_connection *);
  5751. /* Handle request, update statistics and call access log */
  5752. static void
  5753. handle_request_stat_log(struct mg_connection *conn)
  5754. {
  5755. #if defined(USE_SERVER_STATS)
  5756. struct timespec tnow;
  5757. conn->conn_state = 4; /* processing */
  5758. #endif
  5759. handle_request(conn);
  5760. #if defined(USE_SERVER_STATS)
  5761. conn->conn_state = 5; /* processed */
  5762. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5763. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5764. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5765. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5766. conn->num_bytes_sent);
  5767. #endif
  5768. DEBUG_TRACE("%s", "handle_request done");
  5769. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5770. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5771. DEBUG_TRACE("%s", "end_request callback done");
  5772. }
  5773. log_access(conn);
  5774. }
  5775. #if defined(USE_HTTP2)
  5776. #if defined(NO_SSL)
  5777. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5778. #endif
  5779. #define USE_ALPN
  5780. #include "http2.inl"
  5781. /* Not supported with HTTP/2 */
  5782. #define HTTP1_only \
  5783. { \
  5784. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5785. http2_must_use_http1(conn); \
  5786. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5787. return; \
  5788. } \
  5789. }
  5790. #else
  5791. #define HTTP1_only
  5792. #endif
  5793. CIVETWEB_API int
  5794. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5795. {
  5796. if (len > INT_MAX) {
  5797. len = INT_MAX;
  5798. }
  5799. if (conn == NULL) {
  5800. return 0;
  5801. }
  5802. if (conn->is_chunked) {
  5803. size_t all_read = 0;
  5804. while (len > 0) {
  5805. if (conn->is_chunked >= 3) {
  5806. /* No more data left to read */
  5807. return 0;
  5808. }
  5809. if (conn->is_chunked != 1) {
  5810. /* Has error */
  5811. return -1;
  5812. }
  5813. if (conn->consumed_content != conn->content_len) {
  5814. /* copy from the current chunk */
  5815. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5816. if (read_ret < 1) {
  5817. /* read error */
  5818. conn->is_chunked = 2;
  5819. return -1;
  5820. }
  5821. all_read += (size_t)read_ret;
  5822. len -= (size_t)read_ret;
  5823. if (conn->consumed_content == conn->content_len) {
  5824. /* Add data bytes in the current chunk have been read,
  5825. * so we are expecting \r\n now. */
  5826. char x[2];
  5827. conn->content_len += 2;
  5828. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5829. || (x[1] != '\n')) {
  5830. /* Protocol violation */
  5831. conn->is_chunked = 2;
  5832. return -1;
  5833. }
  5834. }
  5835. } else {
  5836. /* fetch a new chunk */
  5837. size_t i;
  5838. char lenbuf[64];
  5839. char *end = NULL;
  5840. unsigned long chunkSize = 0;
  5841. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5842. conn->content_len++;
  5843. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5844. lenbuf[i] = 0;
  5845. }
  5846. if ((i > 0) && (lenbuf[i] == ';')) {
  5847. // chunk extension --> skip chars until next CR
  5848. //
  5849. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5850. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5851. //
  5852. // chunk = chunk-size [ chunk-extension ] CRLF
  5853. // chunk-data CRLF
  5854. // ...
  5855. // chunk-extension= *( ";" chunk-ext-name [ "="
  5856. // chunk-ext-val ] )
  5857. do
  5858. ++conn->content_len;
  5859. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5860. && lenbuf[i] != '\r');
  5861. }
  5862. if ((i > 0) && (lenbuf[i] == '\r')
  5863. && (lenbuf[i - 1] != '\r')) {
  5864. continue;
  5865. }
  5866. if ((i > 1) && (lenbuf[i] == '\n')
  5867. && (lenbuf[i - 1] == '\r')) {
  5868. lenbuf[i + 1] = 0;
  5869. chunkSize = strtoul(lenbuf, &end, 16);
  5870. if (chunkSize == 0) {
  5871. /* regular end of content */
  5872. conn->is_chunked = 3;
  5873. }
  5874. break;
  5875. }
  5876. if (!isxdigit((unsigned char)lenbuf[i])) {
  5877. /* illegal character for chunk length */
  5878. conn->is_chunked = 2;
  5879. return -1;
  5880. }
  5881. }
  5882. if ((end == NULL) || (*end != '\r')) {
  5883. /* chunksize not set correctly */
  5884. conn->is_chunked = 2;
  5885. return -1;
  5886. }
  5887. if (conn->is_chunked == 3) {
  5888. /* try discarding trailer for keep-alive */
  5889. // We found the last chunk (length 0) including the
  5890. // CRLF that terminates that chunk. Now follows a possibly
  5891. // empty trailer and a final CRLF.
  5892. //
  5893. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5894. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5895. //
  5896. // Chunked-Body = *chunk
  5897. // last-chunk
  5898. // trailer
  5899. // CRLF
  5900. // ...
  5901. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5902. // ...
  5903. // trailer = *(entity-header CRLF)
  5904. int crlf_count = 2; // one CRLF already determined
  5905. while (crlf_count < 4 && conn->is_chunked == 3) {
  5906. ++conn->content_len;
  5907. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5908. if ((crlf_count == 0 || crlf_count == 2)) {
  5909. if (lenbuf[0] == '\r')
  5910. ++crlf_count;
  5911. else
  5912. crlf_count = 0;
  5913. } else {
  5914. // previous character was a CR
  5915. // --> next character must be LF
  5916. if (lenbuf[0] == '\n')
  5917. ++crlf_count;
  5918. else
  5919. conn->is_chunked = 2;
  5920. }
  5921. } else
  5922. // premature end of trailer
  5923. conn->is_chunked = 2;
  5924. }
  5925. if (conn->is_chunked == 2)
  5926. return -1;
  5927. else
  5928. conn->is_chunked = 4;
  5929. break;
  5930. }
  5931. /* append a new chunk */
  5932. conn->content_len += (int64_t)chunkSize;
  5933. }
  5934. }
  5935. return (int)all_read;
  5936. }
  5937. return mg_read_inner(conn, buf, len);
  5938. }
  5939. CIVETWEB_API int
  5940. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5941. {
  5942. time_t now;
  5943. int n, total, allowed;
  5944. if (conn == NULL) {
  5945. return 0;
  5946. }
  5947. if (len > INT_MAX) {
  5948. return -1;
  5949. }
  5950. /* Mark connection as "data sent" */
  5951. conn->request_state = 10;
  5952. #if defined(USE_HTTP2)
  5953. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5954. http2_data_frame_head(conn, len, 0);
  5955. }
  5956. #endif
  5957. if (conn->throttle > 0) {
  5958. if ((now = time(NULL)) != conn->last_throttle_time) {
  5959. conn->last_throttle_time = now;
  5960. conn->last_throttle_bytes = 0;
  5961. }
  5962. allowed = conn->throttle - conn->last_throttle_bytes;
  5963. if (allowed > (int)len) {
  5964. allowed = (int)len;
  5965. }
  5966. total = push_all(conn->phys_ctx,
  5967. NULL,
  5968. conn->client.sock,
  5969. conn->ssl,
  5970. (const char *)buf,
  5971. allowed);
  5972. if (total == allowed) {
  5973. buf = (const char *)buf + total;
  5974. conn->last_throttle_bytes += total;
  5975. while ((total < (int)len)
  5976. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5977. allowed = (conn->throttle > ((int)len - total))
  5978. ? (int)len - total
  5979. : conn->throttle;
  5980. n = push_all(conn->phys_ctx,
  5981. NULL,
  5982. conn->client.sock,
  5983. conn->ssl,
  5984. (const char *)buf,
  5985. allowed);
  5986. if (n != allowed) {
  5987. break;
  5988. }
  5989. sleep(1);
  5990. conn->last_throttle_bytes = allowed;
  5991. conn->last_throttle_time = time(NULL);
  5992. buf = (const char *)buf + n;
  5993. total += n;
  5994. }
  5995. }
  5996. } else {
  5997. total = push_all(conn->phys_ctx,
  5998. NULL,
  5999. conn->client.sock,
  6000. conn->ssl,
  6001. (const char *)buf,
  6002. (int)len);
  6003. }
  6004. if (total > 0) {
  6005. conn->num_bytes_sent += total;
  6006. }
  6007. return total;
  6008. }
  6009. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6010. CIVETWEB_API int
  6011. mg_send_chunk(struct mg_connection *conn,
  6012. const char *chunk,
  6013. unsigned int chunk_len)
  6014. {
  6015. char lenbuf[16];
  6016. size_t lenbuf_len;
  6017. int ret;
  6018. int t;
  6019. /* First store the length information in a text buffer. */
  6020. sprintf(lenbuf, "%x\r\n", chunk_len);
  6021. lenbuf_len = strlen(lenbuf);
  6022. /* Then send length information, chunk and terminating \r\n. */
  6023. ret = mg_write(conn, lenbuf, lenbuf_len);
  6024. if (ret != (int)lenbuf_len) {
  6025. return -1;
  6026. }
  6027. t = ret;
  6028. ret = mg_write(conn, chunk, chunk_len);
  6029. if (ret != (int)chunk_len) {
  6030. return -1;
  6031. }
  6032. t += ret;
  6033. ret = mg_write(conn, "\r\n", 2);
  6034. if (ret != 2) {
  6035. return -1;
  6036. }
  6037. t += ret;
  6038. return t;
  6039. }
  6040. #if defined(GCC_DIAGNOSTIC)
  6041. /* This block forwards format strings to printf implementations,
  6042. * so we need to disable the format-nonliteral warning. */
  6043. #pragma GCC diagnostic push
  6044. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6045. #endif
  6046. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6047. static int
  6048. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6049. {
  6050. va_list ap_copy;
  6051. size_t size = MG_BUF_LEN / 4;
  6052. int len = -1;
  6053. *buf = NULL;
  6054. while (len < 0) {
  6055. if (*buf) {
  6056. mg_free(*buf);
  6057. }
  6058. size *= 4;
  6059. *buf = (char *)mg_malloc(size);
  6060. if (!*buf) {
  6061. break;
  6062. }
  6063. va_copy(ap_copy, ap);
  6064. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6065. va_end(ap_copy);
  6066. (*buf)[size - 1] = 0;
  6067. }
  6068. return len;
  6069. }
  6070. /* Print message to buffer. If buffer is large enough to hold the message,
  6071. * return buffer. If buffer is to small, allocate large enough buffer on
  6072. * heap,
  6073. * and return allocated buffer. */
  6074. static int
  6075. alloc_vprintf(char **out_buf,
  6076. char *prealloc_buf,
  6077. size_t prealloc_size,
  6078. const char *fmt,
  6079. va_list ap)
  6080. {
  6081. va_list ap_copy;
  6082. int len;
  6083. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6084. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6085. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6086. * Therefore, we make two passes: on first pass, get required message
  6087. * length.
  6088. * On second pass, actually print the message. */
  6089. va_copy(ap_copy, ap);
  6090. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6091. va_end(ap_copy);
  6092. if (len < 0) {
  6093. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6094. * Switch to alternative code path that uses incremental
  6095. * allocations.
  6096. */
  6097. va_copy(ap_copy, ap);
  6098. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6099. va_end(ap_copy);
  6100. } else if ((size_t)(len) >= prealloc_size) {
  6101. /* The pre-allocated buffer not large enough. */
  6102. /* Allocate a new buffer. */
  6103. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6104. if (!*out_buf) {
  6105. /* Allocation failed. Return -1 as "out of memory" error. */
  6106. return -1;
  6107. }
  6108. /* Buffer allocation successful. Store the string there. */
  6109. va_copy(ap_copy, ap);
  6110. IGNORE_UNUSED_RESULT(
  6111. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6112. va_end(ap_copy);
  6113. } else {
  6114. /* The pre-allocated buffer is large enough.
  6115. * Use it to store the string and return the address. */
  6116. va_copy(ap_copy, ap);
  6117. IGNORE_UNUSED_RESULT(
  6118. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6119. va_end(ap_copy);
  6120. *out_buf = prealloc_buf;
  6121. }
  6122. return len;
  6123. }
  6124. static int
  6125. alloc_printf(char **out_buf, const char *fmt, ...)
  6126. {
  6127. va_list ap;
  6128. int result;
  6129. va_start(ap, fmt);
  6130. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6131. va_end(ap);
  6132. return result;
  6133. }
  6134. #if defined(GCC_DIAGNOSTIC)
  6135. /* Enable format-nonliteral warning again. */
  6136. #pragma GCC diagnostic pop
  6137. #endif
  6138. static int
  6139. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6140. {
  6141. char mem[MG_BUF_LEN];
  6142. char *buf = NULL;
  6143. int len;
  6144. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6145. len = mg_write(conn, buf, (size_t)len);
  6146. }
  6147. if (buf != mem) {
  6148. mg_free(buf);
  6149. }
  6150. return len;
  6151. }
  6152. CIVETWEB_API int
  6153. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6154. {
  6155. va_list ap;
  6156. int result;
  6157. va_start(ap, fmt);
  6158. result = mg_vprintf(conn, fmt, ap);
  6159. va_end(ap);
  6160. return result;
  6161. }
  6162. CIVETWEB_API int
  6163. mg_url_decode(const char *src,
  6164. int src_len,
  6165. char *dst,
  6166. int dst_len,
  6167. int is_form_url_encoded)
  6168. {
  6169. int i, j, a, b;
  6170. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6171. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6172. if ((i < src_len - 2) && (src[i] == '%')
  6173. && isxdigit((unsigned char)src[i + 1])
  6174. && isxdigit((unsigned char)src[i + 2])) {
  6175. a = tolower((unsigned char)src[i + 1]);
  6176. b = tolower((unsigned char)src[i + 2]);
  6177. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6178. i += 2;
  6179. } else if (is_form_url_encoded && (src[i] == '+')) {
  6180. dst[j] = ' ';
  6181. } else if ((unsigned char)src[i] <= ' ') {
  6182. return -1; /* invalid character */
  6183. } else {
  6184. dst[j] = src[i];
  6185. }
  6186. }
  6187. #undef HEXTOI
  6188. dst[j] = '\0'; /* Null-terminate the destination */
  6189. return (i >= src_len) ? j : -1;
  6190. }
  6191. /* form url decoding of an entire string */
  6192. static void
  6193. url_decode_in_place(char *buf)
  6194. {
  6195. int len = (int)strlen(buf);
  6196. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6197. }
  6198. CIVETWEB_API int
  6199. mg_get_var(const char *data,
  6200. size_t data_len,
  6201. const char *name,
  6202. char *dst,
  6203. size_t dst_len)
  6204. {
  6205. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6206. }
  6207. CIVETWEB_API int
  6208. mg_get_var2(const char *data,
  6209. size_t data_len,
  6210. const char *name,
  6211. char *dst,
  6212. size_t dst_len,
  6213. size_t occurrence)
  6214. {
  6215. const char *p, *e, *s;
  6216. size_t name_len;
  6217. int len;
  6218. if ((dst == NULL) || (dst_len == 0)) {
  6219. len = -2;
  6220. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6221. len = -1;
  6222. dst[0] = '\0';
  6223. } else {
  6224. name_len = strlen(name);
  6225. e = data + data_len;
  6226. len = -1;
  6227. dst[0] = '\0';
  6228. /* data is "var1=val1&var2=val2...". Find variable first */
  6229. for (p = data; p + name_len < e; p++) {
  6230. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6231. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6232. /* Point p to variable value */
  6233. p += name_len + 1;
  6234. /* Point s to the end of the value */
  6235. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6236. if (s == NULL) {
  6237. s = e;
  6238. }
  6239. DEBUG_ASSERT(s >= p);
  6240. if (s < p) {
  6241. return -3;
  6242. }
  6243. /* Decode variable into destination buffer */
  6244. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6245. /* Redirect error code from -1 to -2 (destination buffer too
  6246. * small). */
  6247. if (len == -1) {
  6248. len = -2;
  6249. }
  6250. break;
  6251. }
  6252. }
  6253. }
  6254. return len;
  6255. }
  6256. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6257. CIVETWEB_API int
  6258. mg_split_form_urlencoded(char *data,
  6259. struct mg_header *form_fields,
  6260. unsigned num_form_fields)
  6261. {
  6262. char *b;
  6263. int i;
  6264. int num = 0;
  6265. if (data == NULL) {
  6266. /* parameter error */
  6267. return -1;
  6268. }
  6269. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6270. /* determine the number of expected fields */
  6271. if (data[0] == 0) {
  6272. return 0;
  6273. }
  6274. /* count number of & to return the number of key-value-pairs */
  6275. num = 1;
  6276. while (*data) {
  6277. if (*data == '&') {
  6278. num++;
  6279. }
  6280. data++;
  6281. }
  6282. return num;
  6283. }
  6284. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6285. /* parameter error */
  6286. return -1;
  6287. }
  6288. for (i = 0; i < (int)num_form_fields; i++) {
  6289. /* extract key-value pairs from input data */
  6290. while ((*data == ' ') || (*data == '\t')) {
  6291. /* skip initial spaces */
  6292. data++;
  6293. }
  6294. if (*data == 0) {
  6295. /* end of string reached */
  6296. break;
  6297. }
  6298. form_fields[num].name = data;
  6299. /* find & or = */
  6300. b = data;
  6301. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6302. b++;
  6303. }
  6304. if (*b == 0) {
  6305. /* last key without value */
  6306. form_fields[num].value = NULL;
  6307. } else if (*b == '&') {
  6308. /* mid key without value */
  6309. form_fields[num].value = NULL;
  6310. } else {
  6311. /* terminate string */
  6312. *b = 0;
  6313. /* value starts after '=' */
  6314. data = b + 1;
  6315. form_fields[num].value = data;
  6316. }
  6317. /* new field is stored */
  6318. num++;
  6319. /* find a next key */
  6320. b = strchr(data, '&');
  6321. if (b == 0) {
  6322. /* no more data */
  6323. break;
  6324. } else {
  6325. /* terminate value of last field at '&' */
  6326. *b = 0;
  6327. /* next key-value-pairs starts after '&' */
  6328. data = b + 1;
  6329. }
  6330. }
  6331. /* Decode all values */
  6332. for (i = 0; i < num; i++) {
  6333. if (form_fields[i].name) {
  6334. url_decode_in_place((char *)form_fields[i].name);
  6335. }
  6336. if (form_fields[i].value) {
  6337. url_decode_in_place((char *)form_fields[i].value);
  6338. }
  6339. }
  6340. /* return number of fields found */
  6341. return num;
  6342. }
  6343. /* HCP24: some changes to compare whole var_name */
  6344. CIVETWEB_API int
  6345. mg_get_cookie(const char *cookie_header,
  6346. const char *var_name,
  6347. char *dst,
  6348. size_t dst_size)
  6349. {
  6350. const char *s, *p, *end;
  6351. int name_len, len = -1;
  6352. if ((dst == NULL) || (dst_size == 0)) {
  6353. return -2;
  6354. }
  6355. dst[0] = '\0';
  6356. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6357. return -1;
  6358. }
  6359. name_len = (int)strlen(var_name);
  6360. end = s + strlen(s);
  6361. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6362. if (s[name_len] == '=') {
  6363. /* HCP24: now check is it a substring or a full cookie name */
  6364. if ((s == cookie_header) || (s[-1] == ' ')) {
  6365. s += name_len + 1;
  6366. if ((p = strchr(s, ' ')) == NULL) {
  6367. p = end;
  6368. }
  6369. if (p[-1] == ';') {
  6370. p--;
  6371. }
  6372. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6373. s++;
  6374. p--;
  6375. }
  6376. if ((size_t)(p - s) < dst_size) {
  6377. len = (int)(p - s);
  6378. mg_strlcpy(dst, s, (size_t)len + 1);
  6379. } else {
  6380. len = -3;
  6381. }
  6382. break;
  6383. }
  6384. }
  6385. }
  6386. return len;
  6387. }
  6388. CIVETWEB_API int
  6389. mg_base64_encode(const unsigned char *src,
  6390. size_t src_len,
  6391. char *dst,
  6392. size_t *dst_len)
  6393. {
  6394. static const char *b64 =
  6395. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6396. size_t i, j;
  6397. int a, b, c;
  6398. if (dst_len != NULL) {
  6399. /* Expected length including 0 termination: */
  6400. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6401. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6402. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6403. if (*dst_len < expected_len) {
  6404. if (*dst_len > 0) {
  6405. dst[0] = '\0';
  6406. }
  6407. *dst_len = expected_len;
  6408. return 0;
  6409. }
  6410. }
  6411. for (i = j = 0; i < src_len; i += 3) {
  6412. a = src[i];
  6413. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6414. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6415. dst[j++] = b64[a >> 2];
  6416. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6417. if (i + 1 < src_len) {
  6418. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6419. }
  6420. if (i + 2 < src_len) {
  6421. dst[j++] = b64[c & 63];
  6422. }
  6423. }
  6424. while (j % 4 != 0) {
  6425. dst[j++] = '=';
  6426. }
  6427. dst[j++] = '\0';
  6428. if (dst_len != NULL) {
  6429. *dst_len = (size_t)j;
  6430. }
  6431. /* Return -1 for "OK" */
  6432. return -1;
  6433. }
  6434. static unsigned char
  6435. b64reverse(char letter)
  6436. {
  6437. if ((letter >= 'A') && (letter <= 'Z')) {
  6438. return (unsigned char)(letter - 'A');
  6439. }
  6440. if ((letter >= 'a') && (letter <= 'z')) {
  6441. return (unsigned char)(letter - 'a' + 26);
  6442. }
  6443. if ((letter >= '0') && (letter <= '9')) {
  6444. return (unsigned char)(letter - '0' + 52);
  6445. }
  6446. if (letter == '+') {
  6447. return 62;
  6448. }
  6449. if (letter == '/') {
  6450. return 63;
  6451. }
  6452. if (letter == '=') {
  6453. return 255; /* normal end */
  6454. }
  6455. return 254; /* error */
  6456. }
  6457. CIVETWEB_API int
  6458. mg_base64_decode(const char *src,
  6459. size_t src_len,
  6460. unsigned char *dst,
  6461. size_t *dst_len)
  6462. {
  6463. size_t i;
  6464. unsigned char a, b, c, d;
  6465. size_t dst_len_limit = (size_t)-1;
  6466. size_t dst_len_used = 0;
  6467. if (dst_len != NULL) {
  6468. dst_len_limit = *dst_len;
  6469. *dst_len = 0;
  6470. }
  6471. for (i = 0; i < src_len; i += 4) {
  6472. /* Read 4 characters from BASE64 string */
  6473. a = b64reverse(src[i]);
  6474. if (a >= 254) {
  6475. return (int)i;
  6476. }
  6477. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6478. if (b >= 254) {
  6479. return (int)i + 1;
  6480. }
  6481. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6482. if (c == 254) {
  6483. return (int)i + 2;
  6484. }
  6485. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6486. if (d == 254) {
  6487. return (int)i + 3;
  6488. }
  6489. /* Add first (of 3) decoded character */
  6490. if (dst_len_used < dst_len_limit) {
  6491. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6492. + (unsigned char)(b >> 4));
  6493. }
  6494. dst_len_used++;
  6495. if (c != 255) {
  6496. if (dst_len_used < dst_len_limit) {
  6497. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6498. + (unsigned char)(c >> 2));
  6499. }
  6500. dst_len_used++;
  6501. if (d != 255) {
  6502. if (dst_len_used < dst_len_limit) {
  6503. dst[dst_len_used] =
  6504. (unsigned char)((unsigned char)(c << 6) + d);
  6505. }
  6506. dst_len_used++;
  6507. }
  6508. }
  6509. }
  6510. /* Add terminating zero */
  6511. if (dst_len_used < dst_len_limit) {
  6512. dst[dst_len_used] = '\0';
  6513. }
  6514. dst_len_used++;
  6515. if (dst_len != NULL) {
  6516. *dst_len = dst_len_used;
  6517. }
  6518. if (dst_len_used > dst_len_limit) {
  6519. /* Out of memory */
  6520. return 0;
  6521. }
  6522. /* Return -1 for "OK" */
  6523. return -1;
  6524. }
  6525. static int
  6526. is_put_or_delete_method(const struct mg_connection *conn)
  6527. {
  6528. if (conn) {
  6529. const char *s = conn->request_info.request_method;
  6530. if (s != NULL) {
  6531. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6532. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6533. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6534. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6535. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6536. || !strcmp(s, "COPY"));
  6537. }
  6538. }
  6539. return 0;
  6540. }
  6541. static int
  6542. is_civetweb_webdav_method(const struct mg_connection *conn)
  6543. {
  6544. /* Note: Here we only have to identify the WebDav methods that need special
  6545. * handling in the CivetWeb code - not all methods used in WebDav. In
  6546. * particular, methods used on directories (when using Windows Explorer as
  6547. * WebDav client).
  6548. */
  6549. if (conn) {
  6550. const char *s = conn->request_info.request_method;
  6551. if (s != NULL) {
  6552. /* These are the civetweb builtin DAV methods */
  6553. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6554. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6555. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6556. }
  6557. }
  6558. return 0;
  6559. }
  6560. #if !defined(NO_FILES)
  6561. static int
  6562. extention_matches_script(
  6563. struct mg_connection *conn, /* in: request (must be valid) */
  6564. const char *filename /* in: filename (must be valid) */
  6565. )
  6566. {
  6567. #if !defined(NO_CGI)
  6568. int cgi_config_idx, inc, max;
  6569. #endif
  6570. #if defined(USE_LUA)
  6571. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6572. filename)
  6573. > 0) {
  6574. return 1;
  6575. }
  6576. #endif
  6577. #if defined(USE_DUKTAPE)
  6578. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6579. filename)
  6580. > 0) {
  6581. return 1;
  6582. }
  6583. #endif
  6584. #if !defined(NO_CGI)
  6585. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6586. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6587. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6588. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6589. && (match_prefix_strlen(
  6590. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6591. filename)
  6592. > 0)) {
  6593. return 1;
  6594. }
  6595. }
  6596. #endif
  6597. /* filename and conn could be unused, if all preocessor conditions
  6598. * are false (no script language supported). */
  6599. (void)filename;
  6600. (void)conn;
  6601. return 0;
  6602. }
  6603. static int
  6604. extention_matches_template_text(
  6605. struct mg_connection *conn, /* in: request (must be valid) */
  6606. const char *filename /* in: filename (must be valid) */
  6607. )
  6608. {
  6609. #if defined(USE_LUA)
  6610. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6611. filename)
  6612. > 0) {
  6613. return 1;
  6614. }
  6615. #endif
  6616. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6617. > 0) {
  6618. return 1;
  6619. }
  6620. return 0;
  6621. }
  6622. /* For given directory path, substitute it to valid index file.
  6623. * Return 1 if index file has been found, 0 if not found.
  6624. * If the file is found, it's stats is returned in stp. */
  6625. static int
  6626. substitute_index_file_aux(struct mg_connection *conn,
  6627. char *path,
  6628. size_t path_len,
  6629. struct mg_file_stat *filestat)
  6630. {
  6631. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6632. struct vec filename_vec;
  6633. size_t n = strlen(path);
  6634. int found = 0;
  6635. /* The 'path' given to us points to the directory. Remove all trailing
  6636. * directory separator characters from the end of the path, and
  6637. * then append single directory separator character. */
  6638. while ((n > 0) && (path[n - 1] == '/')) {
  6639. n--;
  6640. }
  6641. path[n] = '/';
  6642. /* Traverse index files list. For each entry, append it to the given
  6643. * path and see if the file exists. If it exists, break the loop */
  6644. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6645. /* Ignore too long entries that may overflow path buffer */
  6646. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6647. continue;
  6648. }
  6649. /* Prepare full path to the index file */
  6650. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6651. /* Does it exist? */
  6652. if (mg_stat(conn, path, filestat)) {
  6653. /* Yes it does, break the loop */
  6654. found = 1;
  6655. break;
  6656. }
  6657. }
  6658. /* If no index file exists, restore directory path */
  6659. if (!found) {
  6660. path[n] = '\0';
  6661. }
  6662. return found;
  6663. }
  6664. /* Same as above, except if the first try fails and a fallback-root is
  6665. * configured, we'll try there also */
  6666. static int
  6667. substitute_index_file(struct mg_connection *conn,
  6668. char *path,
  6669. size_t path_len,
  6670. struct mg_file_stat *filestat)
  6671. {
  6672. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6673. if (ret == 0) {
  6674. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6675. const char *fallback_root_prefix =
  6676. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6677. if ((root_prefix) && (fallback_root_prefix)) {
  6678. const size_t root_prefix_len = strlen(root_prefix);
  6679. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6680. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6681. side effects if we fail */
  6682. size_t sub_path_len;
  6683. const size_t fallback_root_prefix_len =
  6684. strlen(fallback_root_prefix);
  6685. const char *sub_path = path + root_prefix_len;
  6686. while (*sub_path == '/') {
  6687. sub_path++;
  6688. }
  6689. sub_path_len = strlen(sub_path);
  6690. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6691. < sizeof(scratch_path))) {
  6692. /* The concatenations below are all safe because we
  6693. * pre-verified string lengths above */
  6694. char *nul;
  6695. strcpy(scratch_path, fallback_root_prefix);
  6696. nul = strchr(scratch_path, '\0');
  6697. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6698. *nul++ = '/';
  6699. *nul = '\0';
  6700. }
  6701. strcat(scratch_path, sub_path);
  6702. if (substitute_index_file_aux(conn,
  6703. scratch_path,
  6704. sizeof(scratch_path),
  6705. filestat)) {
  6706. mg_strlcpy(path, scratch_path, path_len);
  6707. return 1;
  6708. }
  6709. }
  6710. }
  6711. }
  6712. }
  6713. return ret;
  6714. }
  6715. #endif
  6716. static void
  6717. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6718. char *filename, /* out: filename */
  6719. size_t filename_buf_len, /* in: size of filename buffer */
  6720. struct mg_file_stat *filestat, /* out: file status structure */
  6721. int *is_found, /* out: file found (directly) */
  6722. int *is_script_resource, /* out: handled by a script? */
  6723. int *is_websocket_request, /* out: websocket connection? */
  6724. int *is_put_or_delete_request, /* out: put/delete a file? */
  6725. int *is_webdav_request, /* out: webdav request? */
  6726. int *is_template_text /* out: SSI file or LSP file? */
  6727. )
  6728. {
  6729. char const *accept_encoding;
  6730. #if !defined(NO_FILES)
  6731. const char *uri = conn->request_info.local_uri;
  6732. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6733. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6734. NULL};
  6735. int fileExists = 0;
  6736. const char *rewrite;
  6737. struct vec a, b;
  6738. ptrdiff_t match_len;
  6739. char gz_path[UTF8_PATH_MAX];
  6740. int truncated;
  6741. int i;
  6742. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6743. char *tmp_str;
  6744. size_t tmp_str_len, sep_pos;
  6745. int allow_substitute_script_subresources;
  6746. #endif
  6747. #else
  6748. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6749. #endif
  6750. /* Step 1: Set all initially unknown outputs to zero */
  6751. memset(filestat, 0, sizeof(*filestat));
  6752. *filename = 0;
  6753. *is_found = 0;
  6754. *is_script_resource = 0;
  6755. *is_template_text = 0;
  6756. /* Step 2: Classify the request method */
  6757. /* Step 2a: Check if the request attempts to modify the file system */
  6758. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6759. /* Step 2b: Check if the request uses WebDav method that requires special
  6760. * handling */
  6761. *is_webdav_request = is_civetweb_webdav_method(conn);
  6762. /* Step 3: Check if it is a websocket request, and modify the document
  6763. * root if required */
  6764. #if defined(USE_WEBSOCKET)
  6765. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6766. #if !defined(NO_FILES)
  6767. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6768. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6769. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6770. }
  6771. #endif /* !NO_FILES */
  6772. #else /* USE_WEBSOCKET */
  6773. *is_websocket_request = 0;
  6774. #endif /* USE_WEBSOCKET */
  6775. /* Step 4: Check if gzip encoded response is allowed */
  6776. conn->accept_gzip = 0;
  6777. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6778. if (strstr(accept_encoding, "gzip") != NULL) {
  6779. conn->accept_gzip = 1;
  6780. }
  6781. }
  6782. #if !defined(NO_FILES)
  6783. /* Step 5: If there is no root directory, don't look for files. */
  6784. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6785. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6786. * config is not required. */
  6787. if (roots[0] == NULL) {
  6788. /* all file related outputs have already been set to 0, just return
  6789. */
  6790. return;
  6791. }
  6792. for (i = 0; roots[i] != NULL; i++) {
  6793. /* Step 6: Determine the local file path from the root path and the
  6794. * request uri. */
  6795. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6796. * part of the path one byte on the right. */
  6797. truncated = 0;
  6798. mg_snprintf(conn,
  6799. &truncated,
  6800. filename,
  6801. filename_buf_len - 1,
  6802. "%s%s",
  6803. roots[i],
  6804. uri);
  6805. if (truncated) {
  6806. goto interpret_cleanup;
  6807. }
  6808. /* Step 7: URI rewriting */
  6809. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6810. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6811. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6812. mg_snprintf(conn,
  6813. &truncated,
  6814. filename,
  6815. filename_buf_len - 1,
  6816. "%.*s%s",
  6817. (int)b.len,
  6818. b.ptr,
  6819. uri + match_len);
  6820. break;
  6821. }
  6822. }
  6823. if (truncated) {
  6824. goto interpret_cleanup;
  6825. }
  6826. /* Step 8: Check if the file exists at the server */
  6827. /* Local file path and name, corresponding to requested URI
  6828. * is now stored in "filename" variable. */
  6829. if (mg_stat(conn, filename, filestat)) {
  6830. fileExists = 1;
  6831. break;
  6832. }
  6833. }
  6834. if (fileExists) {
  6835. int uri_len = (int)strlen(uri);
  6836. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6837. /* 8.1: File exists. */
  6838. *is_found = 1;
  6839. /* 8.2: Check if it is a script type. */
  6840. if (extention_matches_script(conn, filename)) {
  6841. /* The request addresses a CGI resource, Lua script or
  6842. * server-side javascript.
  6843. * The URI corresponds to the script itself (like
  6844. * /path/script.cgi), and there is no additional resource
  6845. * path (like /path/script.cgi/something).
  6846. * Requests that modify (replace or delete) a resource, like
  6847. * PUT and DELETE requests, should replace/delete the script
  6848. * file.
  6849. * Requests that read or write from/to a resource, like GET and
  6850. * POST requests, should call the script and return the
  6851. * generated response. */
  6852. *is_script_resource = (!*is_put_or_delete_request);
  6853. }
  6854. /* 8.3: Check for SSI and LSP files */
  6855. if (extention_matches_template_text(conn, filename)) {
  6856. /* Same as above, but for *.lsp and *.shtml files. */
  6857. /* A "template text" is a file delivered directly to the client,
  6858. * but with some text tags replaced by dynamic content.
  6859. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6860. * (LP, LSP) file. */
  6861. *is_template_text = (!*is_put_or_delete_request);
  6862. }
  6863. /* 8.4: If the request target is a directory, there could be
  6864. * a substitute file (index.html, index.cgi, ...). */
  6865. /* But do not substitute a directory for a WebDav request */
  6866. if (filestat->is_directory && is_uri_end_slash
  6867. && (!*is_webdav_request)) {
  6868. /* Use a local copy here, since substitute_index_file will
  6869. * change the content of the file status */
  6870. struct mg_file_stat tmp_filestat;
  6871. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6872. if (substitute_index_file(
  6873. conn, filename, filename_buf_len, &tmp_filestat)) {
  6874. /* Substitute file found. Copy stat to the output, then
  6875. * check if the file is a script file */
  6876. *filestat = tmp_filestat;
  6877. if (extention_matches_script(conn, filename)) {
  6878. /* Substitute file is a script file */
  6879. *is_script_resource = 1;
  6880. } else if (extention_matches_template_text(conn, filename)) {
  6881. /* Substitute file is a LSP or SSI file */
  6882. *is_template_text = 1;
  6883. } else {
  6884. /* Substitute file is a regular file */
  6885. *is_script_resource = 0;
  6886. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6887. }
  6888. }
  6889. /* If there is no substitute file, the server could return
  6890. * a directory listing in a later step */
  6891. }
  6892. return;
  6893. }
  6894. /* Step 9: Check for zipped files: */
  6895. /* If we can't find the actual file, look for the file
  6896. * with the same name but a .gz extension. If we find it,
  6897. * use that and set the gzipped flag in the file struct
  6898. * to indicate that the response need to have the content-
  6899. * encoding: gzip header.
  6900. * We can only do this if the browser declares support. */
  6901. if (conn->accept_gzip) {
  6902. mg_snprintf(
  6903. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6904. if (truncated) {
  6905. goto interpret_cleanup;
  6906. }
  6907. if (mg_stat(conn, gz_path, filestat)) {
  6908. if (filestat) {
  6909. filestat->is_gzipped = 1;
  6910. *is_found = 1;
  6911. }
  6912. /* Currently gz files can not be scripts. */
  6913. return;
  6914. }
  6915. }
  6916. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6917. /* Step 10: Script resources may handle sub-resources */
  6918. /* Support PATH_INFO for CGI scripts. */
  6919. tmp_str_len = strlen(filename);
  6920. tmp_str =
  6921. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6922. if (!tmp_str) {
  6923. /* Out of memory */
  6924. goto interpret_cleanup;
  6925. }
  6926. memcpy(tmp_str, filename, tmp_str_len + 1);
  6927. /* Check config, if index scripts may have sub-resources */
  6928. allow_substitute_script_subresources =
  6929. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6930. "yes");
  6931. if (*is_webdav_request) {
  6932. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6933. * PROPFIND for their subresources? */
  6934. /* allow_substitute_script_subresources = 0; */
  6935. }
  6936. sep_pos = tmp_str_len;
  6937. while (sep_pos > 0) {
  6938. sep_pos--;
  6939. if (tmp_str[sep_pos] == '/') {
  6940. int is_script = 0, does_exist = 0;
  6941. tmp_str[sep_pos] = 0;
  6942. if (tmp_str[0]) {
  6943. is_script = extention_matches_script(conn, tmp_str);
  6944. does_exist = mg_stat(conn, tmp_str, filestat);
  6945. }
  6946. if (does_exist && is_script) {
  6947. filename[sep_pos] = 0;
  6948. memmove(filename + sep_pos + 2,
  6949. filename + sep_pos + 1,
  6950. strlen(filename + sep_pos + 1) + 1);
  6951. conn->path_info = filename + sep_pos + 1;
  6952. filename[sep_pos + 1] = '/';
  6953. *is_script_resource = 1;
  6954. *is_found = 1;
  6955. break;
  6956. }
  6957. if (allow_substitute_script_subresources) {
  6958. if (substitute_index_file(
  6959. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6960. /* some intermediate directory has an index file */
  6961. if (extention_matches_script(conn, tmp_str)) {
  6962. size_t script_name_len = strlen(tmp_str);
  6963. /* subres_name read before this memory locatio will be
  6964. overwritten */
  6965. char *subres_name = filename + sep_pos;
  6966. size_t subres_name_len = strlen(subres_name);
  6967. DEBUG_TRACE("Substitute script %s serving path %s",
  6968. tmp_str,
  6969. filename);
  6970. /* this index file is a script */
  6971. if ((script_name_len + subres_name_len + 2)
  6972. >= filename_buf_len) {
  6973. mg_free(tmp_str);
  6974. goto interpret_cleanup;
  6975. }
  6976. conn->path_info =
  6977. filename + script_name_len + 1; /* new target */
  6978. memmove(conn->path_info, subres_name, subres_name_len);
  6979. conn->path_info[subres_name_len] = 0;
  6980. memcpy(filename, tmp_str, script_name_len + 1);
  6981. *is_script_resource = 1;
  6982. *is_found = 1;
  6983. break;
  6984. } else {
  6985. DEBUG_TRACE("Substitute file %s serving path %s",
  6986. tmp_str,
  6987. filename);
  6988. /* non-script files will not have sub-resources */
  6989. filename[sep_pos] = 0;
  6990. conn->path_info = 0;
  6991. *is_script_resource = 0;
  6992. *is_found = 0;
  6993. break;
  6994. }
  6995. }
  6996. }
  6997. tmp_str[sep_pos] = '/';
  6998. }
  6999. }
  7000. mg_free(tmp_str);
  7001. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  7002. #endif /* !defined(NO_FILES) */
  7003. return;
  7004. #if !defined(NO_FILES)
  7005. /* Reset all outputs */
  7006. interpret_cleanup:
  7007. memset(filestat, 0, sizeof(*filestat));
  7008. *filename = 0;
  7009. *is_found = 0;
  7010. *is_script_resource = 0;
  7011. *is_websocket_request = 0;
  7012. *is_put_or_delete_request = 0;
  7013. #endif /* !defined(NO_FILES) */
  7014. }
  7015. /* Check whether full request is buffered. Return:
  7016. * -1 if request or response is malformed
  7017. * 0 if request or response is not yet fully buffered
  7018. * >0 actual request length, including last \r\n\r\n */
  7019. static int
  7020. get_http_header_len(const char *buf, int buflen)
  7021. {
  7022. int i;
  7023. for (i = 0; i < buflen; i++) {
  7024. /* Do an unsigned comparison in some conditions below */
  7025. const unsigned char c = (unsigned char)buf[i];
  7026. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7027. && !isprint(c)) {
  7028. /* abort scan as soon as one malformed character is found */
  7029. return -1;
  7030. }
  7031. if (i < buflen - 1) {
  7032. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7033. /* Two newline, no carriage return - not standard compliant,
  7034. * but it should be accepted */
  7035. return i + 2;
  7036. }
  7037. }
  7038. if (i < buflen - 3) {
  7039. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7040. && (buf[i + 3] == '\n')) {
  7041. /* Two \r\n - standard compliant */
  7042. return i + 4;
  7043. }
  7044. }
  7045. }
  7046. return 0;
  7047. }
  7048. #if !defined(NO_CACHING)
  7049. /* Convert month to the month number. Return -1 on error, or month number */
  7050. static int
  7051. get_month_index(const char *s)
  7052. {
  7053. size_t i;
  7054. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7055. if (!strcmp(s, month_names[i])) {
  7056. return (int)i;
  7057. }
  7058. }
  7059. return -1;
  7060. }
  7061. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7062. static time_t
  7063. parse_date_string(const char *datetime)
  7064. {
  7065. char month_str[32] = {0};
  7066. int second, minute, hour, day, month, year;
  7067. time_t result = (time_t)0;
  7068. struct tm tm;
  7069. if ((sscanf(datetime,
  7070. "%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. || (sscanf(datetime,
  7088. "%*3s, %d %3s %d %d:%d:%d",
  7089. &day,
  7090. month_str,
  7091. &year,
  7092. &hour,
  7093. &minute,
  7094. &second)
  7095. == 6)
  7096. || (sscanf(datetime,
  7097. "%d-%3s-%d %d:%d:%d",
  7098. &day,
  7099. month_str,
  7100. &year,
  7101. &hour,
  7102. &minute,
  7103. &second)
  7104. == 6)) {
  7105. month = get_month_index(month_str);
  7106. if ((month >= 0) && (year >= 1970)) {
  7107. memset(&tm, 0, sizeof(tm));
  7108. tm.tm_year = year - 1900;
  7109. tm.tm_mon = month;
  7110. tm.tm_mday = day;
  7111. tm.tm_hour = hour;
  7112. tm.tm_min = minute;
  7113. tm.tm_sec = second;
  7114. result = timegm(&tm);
  7115. }
  7116. }
  7117. return result;
  7118. }
  7119. #endif /* !NO_CACHING */
  7120. /* Pre-process URIs according to RFC + protect against directory disclosure
  7121. * attacks by removing '..', excessive '/' and '\' characters */
  7122. static void
  7123. remove_dot_segments(char *inout)
  7124. {
  7125. /* Windows backend protection
  7126. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7127. * in URI by slash */
  7128. char *out_end = inout;
  7129. char *in = inout;
  7130. if (!in) {
  7131. /* Param error. */
  7132. return;
  7133. }
  7134. while (*in) {
  7135. if (*in == '\\') {
  7136. *in = '/';
  7137. }
  7138. in++;
  7139. }
  7140. /* Algorithm "remove_dot_segments" from
  7141. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7142. /* Step 1:
  7143. * The input buffer is initialized.
  7144. * The output buffer is initialized to the empty string.
  7145. */
  7146. in = inout;
  7147. /* Step 2:
  7148. * While the input buffer is not empty, loop as follows:
  7149. */
  7150. /* Less than out_end of the inout buffer is used as output, so keep
  7151. * condition: out_end <= in */
  7152. while (*in) {
  7153. /* Step 2a:
  7154. * If the input buffer begins with a prefix of "../" or "./",
  7155. * then remove that prefix from the input buffer;
  7156. */
  7157. if (!strncmp(in, "../", 3)) {
  7158. in += 3;
  7159. } else if (!strncmp(in, "./", 2)) {
  7160. in += 2;
  7161. }
  7162. /* otherwise */
  7163. /* Step 2b:
  7164. * if the input buffer begins with a prefix of "/./" or "/.",
  7165. * where "." is a complete path segment, then replace that
  7166. * prefix with "/" in the input buffer;
  7167. */
  7168. else if (!strncmp(in, "/./", 3)) {
  7169. in += 2;
  7170. } else if (!strcmp(in, "/.")) {
  7171. in[1] = 0;
  7172. }
  7173. /* otherwise */
  7174. /* Step 2c:
  7175. * if the input buffer begins with a prefix of "/../" or "/..",
  7176. * where ".." is a complete path segment, then replace that
  7177. * prefix with "/" in the input buffer and remove the last
  7178. * segment and its preceding "/" (if any) from the output
  7179. * buffer;
  7180. */
  7181. else if (!strncmp(in, "/../", 4)) {
  7182. in += 3;
  7183. if (inout != out_end) {
  7184. /* remove last segment */
  7185. do {
  7186. out_end--;
  7187. } while ((inout != out_end) && (*out_end != '/'));
  7188. }
  7189. } else if (!strcmp(in, "/..")) {
  7190. in[1] = 0;
  7191. if (inout != out_end) {
  7192. /* remove last segment */
  7193. do {
  7194. out_end--;
  7195. } while ((inout != out_end) && (*out_end != '/'));
  7196. }
  7197. }
  7198. /* otherwise */
  7199. /* Step 2d:
  7200. * if the input buffer consists only of "." or "..", then remove
  7201. * that from the input buffer;
  7202. */
  7203. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7204. *in = 0;
  7205. }
  7206. /* otherwise */
  7207. /* Step 2e:
  7208. * move the first path segment in the input buffer to the end of
  7209. * the output buffer, including the initial "/" character (if
  7210. * any) and any subsequent characters up to, but not including,
  7211. * the next "/" character or the end of the input buffer.
  7212. */
  7213. else {
  7214. do {
  7215. *out_end = *in;
  7216. out_end++;
  7217. in++;
  7218. } while ((*in != 0) && (*in != '/'));
  7219. }
  7220. }
  7221. /* Step 3:
  7222. * Finally, the output buffer is returned as the result of
  7223. * remove_dot_segments.
  7224. */
  7225. /* Terminate output */
  7226. *out_end = 0;
  7227. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7228. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7229. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7230. * or "//" anymore.
  7231. */
  7232. out_end = in = inout;
  7233. while (*in) {
  7234. if (*in == '.') {
  7235. /* remove . at the end or preceding of / */
  7236. char *in_ahead = in;
  7237. do {
  7238. in_ahead++;
  7239. } while (*in_ahead == '.');
  7240. if (*in_ahead == '/') {
  7241. in = in_ahead;
  7242. if ((out_end != inout) && (out_end[-1] == '/')) {
  7243. /* remove generated // */
  7244. out_end--;
  7245. }
  7246. } else if (*in_ahead == 0) {
  7247. in = in_ahead;
  7248. } else {
  7249. do {
  7250. *out_end++ = '.';
  7251. in++;
  7252. } while (in != in_ahead);
  7253. }
  7254. } else if (*in == '/') {
  7255. /* replace // by / */
  7256. *out_end++ = '/';
  7257. do {
  7258. in++;
  7259. } while (*in == '/');
  7260. } else {
  7261. *out_end++ = *in;
  7262. in++;
  7263. }
  7264. }
  7265. *out_end = 0;
  7266. }
  7267. static const struct {
  7268. const char *extension;
  7269. size_t ext_len;
  7270. const char *mime_type;
  7271. } builtin_mime_types[] = {
  7272. /* IANA registered MIME types
  7273. * (http://www.iana.org/assignments/media-types)
  7274. * application types */
  7275. {".bin", 4, "application/octet-stream"},
  7276. {".cer", 4, "application/pkix-cert"},
  7277. {".crl", 4, "application/pkix-crl"},
  7278. {".crt", 4, "application/pkix-cert"},
  7279. {".deb", 4, "application/octet-stream"},
  7280. {".dmg", 4, "application/octet-stream"},
  7281. {".dll", 4, "application/octet-stream"},
  7282. {".doc", 4, "application/msword"},
  7283. {".eps", 4, "application/postscript"},
  7284. {".exe", 4, "application/octet-stream"},
  7285. {".iso", 4, "application/octet-stream"},
  7286. {".js", 3, "application/javascript"},
  7287. {".json", 5, "application/json"},
  7288. {".mjs", 4, "application/javascript"},
  7289. {".msi", 4, "application/octet-stream"},
  7290. {".pem", 4, "application/x-pem-file"},
  7291. {".pdf", 4, "application/pdf"},
  7292. {".ps", 3, "application/postscript"},
  7293. {".rtf", 4, "application/rtf"},
  7294. {".wasm", 5, "application/wasm"},
  7295. {".xhtml", 6, "application/xhtml+xml"},
  7296. {".xsl", 4, "application/xml"},
  7297. {".xslt", 5, "application/xml"},
  7298. /* fonts */
  7299. {".ttf", 4, "application/font-sfnt"},
  7300. {".cff", 4, "application/font-sfnt"},
  7301. {".otf", 4, "application/font-sfnt"},
  7302. {".aat", 4, "application/font-sfnt"},
  7303. {".sil", 4, "application/font-sfnt"},
  7304. {".pfr", 4, "application/font-tdpfr"},
  7305. {".woff", 5, "application/font-woff"},
  7306. {".woff2", 6, "application/font-woff2"},
  7307. /* audio */
  7308. {".mp3", 4, "audio/mpeg"},
  7309. {".oga", 4, "audio/ogg"},
  7310. {".ogg", 4, "audio/ogg"},
  7311. /* image */
  7312. {".gif", 4, "image/gif"},
  7313. {".ief", 4, "image/ief"},
  7314. {".jpeg", 5, "image/jpeg"},
  7315. {".jpg", 4, "image/jpeg"},
  7316. {".jpm", 4, "image/jpm"},
  7317. {".jpx", 4, "image/jpx"},
  7318. {".png", 4, "image/png"},
  7319. {".svg", 4, "image/svg+xml"},
  7320. {".tif", 4, "image/tiff"},
  7321. {".tiff", 5, "image/tiff"},
  7322. /* model */
  7323. {".wrl", 4, "model/vrml"},
  7324. /* text */
  7325. {".css", 4, "text/css"},
  7326. {".csv", 4, "text/csv"},
  7327. {".htm", 4, "text/html"},
  7328. {".html", 5, "text/html"},
  7329. {".sgm", 4, "text/sgml"},
  7330. {".shtm", 5, "text/html"},
  7331. {".shtml", 6, "text/html"},
  7332. {".txt", 4, "text/plain"},
  7333. {".xml", 4, "text/xml"},
  7334. /* video */
  7335. {".mov", 4, "video/quicktime"},
  7336. {".mp4", 4, "video/mp4"},
  7337. {".mpeg", 5, "video/mpeg"},
  7338. {".mpg", 4, "video/mpeg"},
  7339. {".ogv", 4, "video/ogg"},
  7340. {".qt", 3, "video/quicktime"},
  7341. /* not registered types
  7342. * (http://reference.sitepoint.com/html/mime-types-full,
  7343. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7344. {".arj", 4, "application/x-arj-compressed"},
  7345. {".gz", 3, "application/x-gunzip"},
  7346. {".rar", 4, "application/x-arj-compressed"},
  7347. {".swf", 4, "application/x-shockwave-flash"},
  7348. {".tar", 4, "application/x-tar"},
  7349. {".tgz", 4, "application/x-tar-gz"},
  7350. {".torrent", 8, "application/x-bittorrent"},
  7351. {".ppt", 4, "application/x-mspowerpoint"},
  7352. {".xls", 4, "application/x-msexcel"},
  7353. {".zip", 4, "application/x-zip-compressed"},
  7354. {".aac",
  7355. 4,
  7356. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7357. {".flac", 5, "audio/flac"},
  7358. {".aif", 4, "audio/x-aif"},
  7359. {".m3u", 4, "audio/x-mpegurl"},
  7360. {".mid", 4, "audio/x-midi"},
  7361. {".ra", 3, "audio/x-pn-realaudio"},
  7362. {".ram", 4, "audio/x-pn-realaudio"},
  7363. {".wav", 4, "audio/x-wav"},
  7364. {".bmp", 4, "image/bmp"},
  7365. {".ico", 4, "image/x-icon"},
  7366. {".pct", 4, "image/x-pct"},
  7367. {".pict", 5, "image/pict"},
  7368. {".rgb", 4, "image/x-rgb"},
  7369. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7370. {".asf", 4, "video/x-ms-asf"},
  7371. {".avi", 4, "video/x-msvideo"},
  7372. {".m4v", 4, "video/x-m4v"},
  7373. {NULL, 0, NULL}};
  7374. CIVETWEB_API const char *
  7375. mg_get_builtin_mime_type(const char *path)
  7376. {
  7377. const char *ext;
  7378. size_t i, path_len;
  7379. path_len = strlen(path);
  7380. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7381. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7382. if ((path_len > builtin_mime_types[i].ext_len)
  7383. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7384. return builtin_mime_types[i].mime_type;
  7385. }
  7386. }
  7387. return "text/plain";
  7388. }
  7389. /* Look at the "path" extension and figure what mime type it has.
  7390. * Store mime type in the vector. */
  7391. static void
  7392. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7393. {
  7394. struct vec ext_vec, mime_vec;
  7395. const char *list, *ext;
  7396. size_t path_len;
  7397. path_len = strlen(path);
  7398. if ((conn == NULL) || (vec == NULL)) {
  7399. if (vec != NULL) {
  7400. memset(vec, '\0', sizeof(struct vec));
  7401. }
  7402. return;
  7403. }
  7404. /* Scan user-defined mime types first, in case user wants to
  7405. * override default mime types. */
  7406. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7407. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7408. /* ext now points to the path suffix */
  7409. ext = path + path_len - ext_vec.len;
  7410. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7411. *vec = mime_vec;
  7412. return;
  7413. }
  7414. }
  7415. vec->ptr = mg_get_builtin_mime_type(path);
  7416. vec->len = strlen(vec->ptr);
  7417. }
  7418. /* Stringify binary data. Output buffer must be twice as big as input,
  7419. * because each byte takes 2 bytes in string representation */
  7420. static void
  7421. bin2str(char *to, const unsigned char *p, size_t len)
  7422. {
  7423. static const char *hex = "0123456789abcdef";
  7424. for (; len--; p++) {
  7425. *to++ = hex[p[0] >> 4];
  7426. *to++ = hex[p[0] & 0x0f];
  7427. }
  7428. *to = '\0';
  7429. }
  7430. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7431. */
  7432. CIVETWEB_API char *
  7433. mg_md5(char buf[33], ...)
  7434. {
  7435. md5_byte_t hash[16];
  7436. const char *p;
  7437. va_list ap;
  7438. md5_state_t ctx;
  7439. md5_init(&ctx);
  7440. va_start(ap, buf);
  7441. while ((p = va_arg(ap, const char *)) != NULL) {
  7442. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7443. }
  7444. va_end(ap);
  7445. md5_finish(&ctx, hash);
  7446. bin2str(buf, hash, sizeof(hash));
  7447. return buf;
  7448. }
  7449. /* Check the user's password, return 1 if OK */
  7450. static int
  7451. check_password_digest(const char *method,
  7452. const char *ha1,
  7453. const char *uri,
  7454. const char *nonce,
  7455. const char *nc,
  7456. const char *cnonce,
  7457. const char *qop,
  7458. const char *response)
  7459. {
  7460. char ha2[32 + 1], expected_response[32 + 1];
  7461. /* Some of the parameters may be NULL */
  7462. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7463. || (qop == NULL) || (response == NULL)) {
  7464. return 0;
  7465. }
  7466. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7467. if (strlen(response) != 32) {
  7468. return 0;
  7469. }
  7470. mg_md5(ha2, method, ":", uri, NULL);
  7471. mg_md5(expected_response,
  7472. ha1,
  7473. ":",
  7474. nonce,
  7475. ":",
  7476. nc,
  7477. ":",
  7478. cnonce,
  7479. ":",
  7480. qop,
  7481. ":",
  7482. ha2,
  7483. NULL);
  7484. return mg_strcasecmp(response, expected_response) == 0;
  7485. }
  7486. #if !defined(NO_FILESYSTEMS)
  7487. /* Use the global passwords file, if specified by auth_gpass option,
  7488. * or search for .htpasswd in the requested directory. */
  7489. static void
  7490. open_auth_file(struct mg_connection *conn,
  7491. const char *path,
  7492. struct mg_file *filep)
  7493. {
  7494. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7495. char name[UTF8_PATH_MAX];
  7496. const char *p, *e,
  7497. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7498. int truncated;
  7499. if (gpass != NULL) {
  7500. /* Use global passwords file */
  7501. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7502. #if defined(DEBUG)
  7503. /* Use mg_cry_internal here, since gpass has been
  7504. * configured. */
  7505. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7506. #endif
  7507. }
  7508. /* Important: using local struct mg_file to test path for
  7509. * is_directory flag. If filep is used, mg_stat() makes it
  7510. * appear as if auth file was opened.
  7511. * TODO(mid): Check if this is still required after rewriting
  7512. * mg_stat */
  7513. } else if (mg_stat(conn, path, &filep->stat)
  7514. && filep->stat.is_directory) {
  7515. mg_snprintf(conn,
  7516. &truncated,
  7517. name,
  7518. sizeof(name),
  7519. "%s/%s",
  7520. path,
  7521. PASSWORDS_FILE_NAME);
  7522. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7523. #if defined(DEBUG)
  7524. /* Don't use mg_cry_internal here, but only a trace, since
  7525. * this is a typical case. It will occur for every directory
  7526. * without a password file. */
  7527. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7528. #endif
  7529. }
  7530. } else {
  7531. /* Try to find .htpasswd in requested directory. */
  7532. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7533. if (e[0] == '/') {
  7534. break;
  7535. }
  7536. }
  7537. mg_snprintf(conn,
  7538. &truncated,
  7539. name,
  7540. sizeof(name),
  7541. "%.*s/%s",
  7542. (int)(e - p),
  7543. p,
  7544. PASSWORDS_FILE_NAME);
  7545. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7546. #if defined(DEBUG)
  7547. /* Don't use mg_cry_internal here, but only a trace, since
  7548. * this is a typical case. It will occur for every directory
  7549. * without a password file. */
  7550. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7551. #endif
  7552. }
  7553. }
  7554. }
  7555. }
  7556. #endif /* NO_FILESYSTEMS */
  7557. /* Parsed Authorization header */
  7558. struct auth_header {
  7559. char *user;
  7560. int type; /* 1 = basic, 2 = digest */
  7561. char *plain_password; /* Basic only */
  7562. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7563. };
  7564. /* Return 1 on success. Always initializes the auth_header structure. */
  7565. static int
  7566. parse_auth_header(struct mg_connection *conn,
  7567. char *buf,
  7568. size_t buf_size,
  7569. struct auth_header *auth_header)
  7570. {
  7571. char *name, *value, *s;
  7572. const char *ah;
  7573. uint64_t nonce;
  7574. if (!auth_header || !conn) {
  7575. return 0;
  7576. }
  7577. (void)memset(auth_header, 0, sizeof(*auth_header));
  7578. ah = mg_get_header(conn, "Authorization");
  7579. if (ah == NULL) {
  7580. /* No Authorization header at all */
  7581. return 0;
  7582. }
  7583. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7584. /* Basic Auth (we never asked for this, but some client may send it) */
  7585. char *split;
  7586. const char *userpw_b64 = ah + 6;
  7587. size_t userpw_b64_len = strlen(userpw_b64);
  7588. size_t buf_len_r = buf_size;
  7589. if (mg_base64_decode(
  7590. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7591. != -1) {
  7592. return 0; /* decode error */
  7593. }
  7594. split = strchr(buf, ':');
  7595. if (!split) {
  7596. return 0; /* Format error */
  7597. }
  7598. /* Separate string at ':' */
  7599. *split = 0;
  7600. /* User name is before ':', Password is after ':' */
  7601. auth_header->user = buf;
  7602. auth_header->type = 1;
  7603. auth_header->plain_password = split + 1;
  7604. return 1;
  7605. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7606. /* Digest Auth ... implemented below */
  7607. auth_header->type = 2;
  7608. } else {
  7609. /* Unknown or invalid Auth method */
  7610. return 0;
  7611. }
  7612. /* Make modifiable copy of the auth header */
  7613. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7614. s = buf;
  7615. /* Parse authorization header */
  7616. for (;;) {
  7617. /* Gobble initial spaces */
  7618. while (isspace((unsigned char)*s)) {
  7619. s++;
  7620. }
  7621. name = skip_quoted(&s, "=", " ", 0);
  7622. /* Value is either quote-delimited, or ends at first comma or space.
  7623. */
  7624. if (s[0] == '\"') {
  7625. s++;
  7626. value = skip_quoted(&s, "\"", " ", '\\');
  7627. if (s[0] == ',') {
  7628. s++;
  7629. }
  7630. } else {
  7631. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7632. * uses spaces */
  7633. }
  7634. if (*name == '\0') {
  7635. break;
  7636. }
  7637. if (!strcmp(name, "username")) {
  7638. auth_header->user = value;
  7639. } else if (!strcmp(name, "cnonce")) {
  7640. auth_header->cnonce = value;
  7641. } else if (!strcmp(name, "response")) {
  7642. auth_header->response = value;
  7643. } else if (!strcmp(name, "uri")) {
  7644. auth_header->uri = value;
  7645. } else if (!strcmp(name, "qop")) {
  7646. auth_header->qop = value;
  7647. } else if (!strcmp(name, "nc")) {
  7648. auth_header->nc = value;
  7649. } else if (!strcmp(name, "nonce")) {
  7650. auth_header->nonce = value;
  7651. }
  7652. }
  7653. #if !defined(NO_NONCE_CHECK)
  7654. /* Read the nonce from the response. */
  7655. if (auth_header->nonce == NULL) {
  7656. return 0;
  7657. }
  7658. s = NULL;
  7659. nonce = strtoull(auth_header->nonce, &s, 10);
  7660. if ((s == NULL) || (*s != 0)) {
  7661. return 0;
  7662. }
  7663. /* Convert the nonce from the client to a number. */
  7664. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7665. /* The converted number corresponds to the time the nounce has been
  7666. * created. This should not be earlier than the server start. */
  7667. /* Server side nonce check is valuable in all situations but one:
  7668. * if the server restarts frequently, but the client should not see
  7669. * that, so the server should accept nonces from previous starts. */
  7670. /* However, the reasonable default is to not accept a nonce from a
  7671. * previous start, so if anyone changed the access rights between
  7672. * two restarts, a new login is required. */
  7673. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7674. /* nonce is from a previous start of the server and no longer valid
  7675. * (replay attack?) */
  7676. return 0;
  7677. }
  7678. /* Check if the nonce is too high, so it has not (yet) been used by the
  7679. * server. */
  7680. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7681. + conn->dom_ctx->nonce_count)) {
  7682. return 0;
  7683. }
  7684. #else
  7685. (void)nonce;
  7686. #endif
  7687. return (auth_header->user != NULL);
  7688. }
  7689. static const char *
  7690. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7691. {
  7692. if (!filep) {
  7693. return NULL;
  7694. }
  7695. if (filep->access.fp != NULL) {
  7696. return fgets(buf, (int)size, filep->access.fp);
  7697. } else {
  7698. return NULL;
  7699. }
  7700. }
  7701. /* Define the initial recursion depth for procesesing htpasswd files that
  7702. * include other htpasswd
  7703. * (or even the same) files. It is not difficult to provide a file or files
  7704. * s.t. they force civetweb
  7705. * to infinitely recurse and then crash.
  7706. */
  7707. #define INITIAL_DEPTH 9
  7708. #if INITIAL_DEPTH <= 0
  7709. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7710. #endif
  7711. #if !defined(NO_FILESYSTEMS)
  7712. struct read_auth_file_struct {
  7713. struct mg_connection *conn;
  7714. struct auth_header auth_header;
  7715. const char *domain;
  7716. char buf[256 + 256 + 40];
  7717. const char *f_user;
  7718. const char *f_domain;
  7719. const char *f_ha1;
  7720. };
  7721. static int
  7722. read_auth_file(struct mg_file *filep,
  7723. struct read_auth_file_struct *workdata,
  7724. int depth)
  7725. {
  7726. int is_authorized = 0;
  7727. struct mg_file fp;
  7728. size_t l;
  7729. if (!filep || !workdata || (0 == depth)) {
  7730. return 0;
  7731. }
  7732. /* Loop over passwords file */
  7733. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7734. l = strlen(workdata->buf);
  7735. while (l > 0) {
  7736. if (isspace((unsigned char)workdata->buf[l - 1])
  7737. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7738. l--;
  7739. workdata->buf[l] = 0;
  7740. } else
  7741. break;
  7742. }
  7743. if (l < 1) {
  7744. continue;
  7745. }
  7746. workdata->f_user = workdata->buf;
  7747. if (workdata->f_user[0] == ':') {
  7748. /* user names may not contain a ':' and may not be empty,
  7749. * so lines starting with ':' may be used for a special purpose
  7750. */
  7751. if (workdata->f_user[1] == '#') {
  7752. /* :# is a comment */
  7753. continue;
  7754. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7755. if (mg_fopen(workdata->conn,
  7756. workdata->f_user + 9,
  7757. MG_FOPEN_MODE_READ,
  7758. &fp)) {
  7759. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7760. (void)mg_fclose(
  7761. &fp.access); /* ignore error on read only file */
  7762. /* No need to continue processing files once we have a
  7763. * match, since nothing will reset it back
  7764. * to 0.
  7765. */
  7766. if (is_authorized) {
  7767. return is_authorized;
  7768. }
  7769. } else {
  7770. mg_cry_internal(workdata->conn,
  7771. "%s: cannot open authorization file: %s",
  7772. __func__,
  7773. workdata->buf);
  7774. }
  7775. continue;
  7776. }
  7777. /* everything is invalid for the moment (might change in the
  7778. * future) */
  7779. mg_cry_internal(workdata->conn,
  7780. "%s: syntax error in authorization file: %s",
  7781. __func__,
  7782. workdata->buf);
  7783. continue;
  7784. }
  7785. workdata->f_domain = strchr(workdata->f_user, ':');
  7786. if (workdata->f_domain == NULL) {
  7787. mg_cry_internal(workdata->conn,
  7788. "%s: syntax error in authorization file: %s",
  7789. __func__,
  7790. workdata->buf);
  7791. continue;
  7792. }
  7793. *(char *)(workdata->f_domain) = 0;
  7794. (workdata->f_domain)++;
  7795. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7796. if (workdata->f_ha1 == NULL) {
  7797. mg_cry_internal(workdata->conn,
  7798. "%s: syntax error in authorization file: %s",
  7799. __func__,
  7800. workdata->buf);
  7801. continue;
  7802. }
  7803. *(char *)(workdata->f_ha1) = 0;
  7804. (workdata->f_ha1)++;
  7805. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7806. && !strcmp(workdata->domain, workdata->f_domain)) {
  7807. switch (workdata->auth_header.type) {
  7808. case 1: /* Basic */
  7809. {
  7810. char md5[33];
  7811. mg_md5(md5,
  7812. workdata->f_user,
  7813. ":",
  7814. workdata->domain,
  7815. ":",
  7816. workdata->auth_header.plain_password,
  7817. NULL);
  7818. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7819. }
  7820. case 2: /* Digest */
  7821. return check_password_digest(
  7822. workdata->conn->request_info.request_method,
  7823. workdata->f_ha1,
  7824. workdata->auth_header.uri,
  7825. workdata->auth_header.nonce,
  7826. workdata->auth_header.nc,
  7827. workdata->auth_header.cnonce,
  7828. workdata->auth_header.qop,
  7829. workdata->auth_header.response);
  7830. default: /* None/Other/Unknown */
  7831. return 0;
  7832. }
  7833. }
  7834. }
  7835. return is_authorized;
  7836. }
  7837. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7838. static int
  7839. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7840. {
  7841. struct read_auth_file_struct workdata;
  7842. char buf[MG_BUF_LEN];
  7843. if (!conn || !conn->dom_ctx) {
  7844. return 0;
  7845. }
  7846. memset(&workdata, 0, sizeof(workdata));
  7847. workdata.conn = conn;
  7848. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7849. return 0;
  7850. }
  7851. /* CGI needs it as REMOTE_USER */
  7852. conn->request_info.remote_user =
  7853. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7854. if (realm) {
  7855. workdata.domain = realm;
  7856. } else {
  7857. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7858. }
  7859. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7860. }
  7861. /* Public function to check http digest authentication header */
  7862. CIVETWEB_API int
  7863. mg_check_digest_access_authentication(struct mg_connection *conn,
  7864. const char *realm,
  7865. const char *filename)
  7866. {
  7867. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7868. int auth;
  7869. if (!conn || !filename) {
  7870. return -1;
  7871. }
  7872. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7873. return -2;
  7874. }
  7875. auth = authorize(conn, &file, realm);
  7876. mg_fclose(&file.access);
  7877. return auth;
  7878. }
  7879. #endif /* NO_FILESYSTEMS */
  7880. /* Return 1 if request is authorised, 0 otherwise. */
  7881. static int
  7882. check_authorization(struct mg_connection *conn, const char *path)
  7883. {
  7884. #if !defined(NO_FILESYSTEMS)
  7885. char fname[UTF8_PATH_MAX];
  7886. struct vec uri_vec, filename_vec;
  7887. const char *list;
  7888. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7889. int authorized = 1, truncated;
  7890. if (!conn || !conn->dom_ctx) {
  7891. return 0;
  7892. }
  7893. list = conn->dom_ctx->config[PROTECT_URI];
  7894. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7895. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7896. mg_snprintf(conn,
  7897. &truncated,
  7898. fname,
  7899. sizeof(fname),
  7900. "%.*s",
  7901. (int)filename_vec.len,
  7902. filename_vec.ptr);
  7903. if (truncated
  7904. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7905. mg_cry_internal(conn,
  7906. "%s: cannot open %s: %s",
  7907. __func__,
  7908. fname,
  7909. strerror(errno));
  7910. }
  7911. break;
  7912. }
  7913. }
  7914. if (!is_file_opened(&file.access)) {
  7915. open_auth_file(conn, path, &file);
  7916. }
  7917. if (is_file_opened(&file.access)) {
  7918. authorized = authorize(conn, &file, NULL);
  7919. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7920. }
  7921. return authorized;
  7922. #else
  7923. (void)conn;
  7924. (void)path;
  7925. return 1;
  7926. #endif /* NO_FILESYSTEMS */
  7927. }
  7928. /* Internal function. Assumes conn is valid */
  7929. static void
  7930. send_authorization_request(struct mg_connection *conn, const char *realm)
  7931. {
  7932. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7933. int trunc = 0;
  7934. char buf[128];
  7935. if (!realm) {
  7936. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7937. }
  7938. mg_lock_context(conn->phys_ctx);
  7939. nonce += conn->dom_ctx->nonce_count;
  7940. ++conn->dom_ctx->nonce_count;
  7941. mg_unlock_context(conn->phys_ctx);
  7942. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7943. conn->must_close = 1;
  7944. /* Create 401 response */
  7945. mg_response_header_start(conn, 401);
  7946. send_no_cache_header(conn);
  7947. send_additional_header(conn);
  7948. mg_response_header_add(conn, "Content-Length", "0", -1);
  7949. /* Content for "WWW-Authenticate" header */
  7950. mg_snprintf(conn,
  7951. &trunc,
  7952. buf,
  7953. sizeof(buf),
  7954. "Digest qop=\"auth\", realm=\"%s\", "
  7955. "nonce=\"%" UINT64_FMT "\"",
  7956. realm,
  7957. nonce);
  7958. if (!trunc) {
  7959. /* !trunc should always be true */
  7960. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7961. }
  7962. /* Send all headers */
  7963. mg_response_header_send(conn);
  7964. }
  7965. /* Interface function. Parameters are provided by the user, so do
  7966. * at least some basic checks.
  7967. */
  7968. CIVETWEB_API int
  7969. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7970. const char *realm)
  7971. {
  7972. if (conn && conn->dom_ctx) {
  7973. send_authorization_request(conn, realm);
  7974. return 0;
  7975. }
  7976. return -1;
  7977. }
  7978. #if !defined(NO_FILES)
  7979. static int
  7980. is_authorized_for_put(struct mg_connection *conn)
  7981. {
  7982. int ret = 0;
  7983. if (conn) {
  7984. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7985. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7986. if (passfile != NULL
  7987. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7988. ret = authorize(conn, &file, NULL);
  7989. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7990. }
  7991. }
  7992. DEBUG_TRACE("file write authorization: %i", ret);
  7993. return ret;
  7994. }
  7995. #endif
  7996. CIVETWEB_API int
  7997. mg_modify_passwords_file_ha1(const char *fname,
  7998. const char *domain,
  7999. const char *user,
  8000. const char *ha1)
  8001. {
  8002. int found = 0, i, result = 1;
  8003. char line[512], u[256], d[256], h[256];
  8004. struct stat st = {0};
  8005. FILE *fp = NULL;
  8006. char *temp_file = NULL;
  8007. int temp_file_offs = 0;
  8008. /* Regard empty password as no password - remove user record. */
  8009. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  8010. ha1 = NULL;
  8011. }
  8012. /* Other arguments must not be empty */
  8013. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8014. return 0;
  8015. }
  8016. /* Using the given file format, user name and domain must not contain
  8017. * the ':' character */
  8018. if (strchr(user, ':') != NULL) {
  8019. return 0;
  8020. }
  8021. if (strchr(domain, ':') != NULL) {
  8022. return 0;
  8023. }
  8024. /* Do not allow control characters like newline in user name and domain.
  8025. * Do not allow excessively long names either. */
  8026. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  8027. if (iscntrl((unsigned char)user[i])) {
  8028. return 0;
  8029. }
  8030. }
  8031. if (user[i]) {
  8032. return 0; /* user name too long */
  8033. }
  8034. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8035. if (iscntrl((unsigned char)domain[i])) {
  8036. return 0;
  8037. }
  8038. }
  8039. if (domain[i]) {
  8040. return 0; /* domain name too long */
  8041. }
  8042. /* The maximum length of the path to the password file is limited */
  8043. if (strlen(fname) >= UTF8_PATH_MAX) {
  8044. return 0;
  8045. }
  8046. /* Check if the file exists, and get file size */
  8047. if (0 == stat(fname, &st)) {
  8048. int temp_buf_len;
  8049. if (st.st_size > 10485760) {
  8050. /* Some funster provided a >10 MB text file */
  8051. return 0;
  8052. }
  8053. /* Add enough space for one more line */
  8054. temp_buf_len = (int)st.st_size + 1024;
  8055. /* Allocate memory (instead of using a temporary file) */
  8056. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8057. if (!temp_file) {
  8058. /* Out of memory */
  8059. return 0;
  8060. }
  8061. /* File exists. Read it into a memory buffer. */
  8062. fp = fopen(fname, "r");
  8063. if (fp == NULL) {
  8064. /* Cannot read file. No permission? */
  8065. mg_free(temp_file);
  8066. return 0;
  8067. }
  8068. /* Read content and store in memory */
  8069. while ((fgets(line, sizeof(line), fp) != NULL)
  8070. && ((temp_file_offs + 600) < temp_buf_len)) {
  8071. /* file format is "user:domain:hash\n" */
  8072. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8073. continue;
  8074. }
  8075. u[255] = 0;
  8076. d[255] = 0;
  8077. h[255] = 0;
  8078. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8079. /* Found the user: change the password hash or drop the user
  8080. */
  8081. if ((ha1 != NULL) && (!found)) {
  8082. i = sprintf(temp_file + temp_file_offs,
  8083. "%s:%s:%s\n",
  8084. user,
  8085. domain,
  8086. ha1);
  8087. if (i < 1) {
  8088. fclose(fp);
  8089. mg_free(temp_file);
  8090. return 0;
  8091. }
  8092. temp_file_offs += i;
  8093. }
  8094. found = 1;
  8095. } else {
  8096. /* Copy existing user, including password hash */
  8097. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8098. if (i < 1) {
  8099. fclose(fp);
  8100. mg_free(temp_file);
  8101. return 0;
  8102. }
  8103. temp_file_offs += i;
  8104. }
  8105. }
  8106. fclose(fp);
  8107. }
  8108. /* Create new file */
  8109. fp = fopen(fname, "w");
  8110. if (!fp) {
  8111. mg_free(temp_file);
  8112. return 0;
  8113. }
  8114. #if !defined(_WIN32)
  8115. /* On Linux & co., restrict file read/write permissions to the owner */
  8116. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8117. result = 0;
  8118. }
  8119. #endif
  8120. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8121. /* Store buffered content of old file */
  8122. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8123. != (size_t)temp_file_offs) {
  8124. result = 0;
  8125. }
  8126. }
  8127. /* If new user, just add it */
  8128. if ((ha1 != NULL) && (!found)) {
  8129. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8130. result = 0;
  8131. }
  8132. }
  8133. /* All data written */
  8134. if (fclose(fp) != 0) {
  8135. result = 0;
  8136. }
  8137. mg_free(temp_file);
  8138. return result;
  8139. }
  8140. CIVETWEB_API int
  8141. mg_modify_passwords_file(const char *fname,
  8142. const char *domain,
  8143. const char *user,
  8144. const char *pass)
  8145. {
  8146. char ha1buf[33];
  8147. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8148. return 0;
  8149. }
  8150. if ((pass == NULL) || (pass[0] == 0)) {
  8151. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8152. }
  8153. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8154. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8155. }
  8156. static int
  8157. is_valid_port(unsigned long port)
  8158. {
  8159. return (port <= 0xffff);
  8160. }
  8161. static int
  8162. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8163. {
  8164. struct addrinfo hints, *res, *ressave;
  8165. int func_ret = 0;
  8166. int gai_ret;
  8167. memset(&hints, 0, sizeof(struct addrinfo));
  8168. hints.ai_family = af;
  8169. if (!resolve_src) {
  8170. hints.ai_flags = AI_NUMERICHOST;
  8171. }
  8172. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8173. if (gai_ret != 0) {
  8174. /* gai_strerror could be used to convert gai_ret to a string */
  8175. /* POSIX return values: see
  8176. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8177. */
  8178. /* Windows return values: see
  8179. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8180. */
  8181. return 0;
  8182. }
  8183. ressave = res;
  8184. while (res) {
  8185. if ((dstlen >= (size_t)res->ai_addrlen)
  8186. && (res->ai_addr->sa_family == af)) {
  8187. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8188. func_ret = 1;
  8189. }
  8190. res = res->ai_next;
  8191. }
  8192. freeaddrinfo(ressave);
  8193. return func_ret;
  8194. }
  8195. static int
  8196. connect_socket(
  8197. struct mg_context *ctx /* may be NULL */,
  8198. const char *host,
  8199. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8200. int use_ssl, /* 0 or 1 */
  8201. struct mg_error_data *error,
  8202. SOCKET *sock /* output: socket, must not be NULL */,
  8203. union usa *sa /* output: socket address, must not be NULL */
  8204. )
  8205. {
  8206. int ip_ver = 0;
  8207. int conn_ret = -1;
  8208. int sockerr = 0;
  8209. *sock = INVALID_SOCKET;
  8210. memset(sa, 0, sizeof(*sa));
  8211. if (host == NULL) {
  8212. if (error != NULL) {
  8213. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8214. mg_snprintf(NULL,
  8215. NULL, /* No truncation check for ebuf */
  8216. error->text,
  8217. error->text_buffer_size,
  8218. "%s",
  8219. "NULL host");
  8220. }
  8221. return 0;
  8222. }
  8223. #if defined(USE_X_DOM_SOCKET)
  8224. if (port == -99) {
  8225. /* Unix domain socket */
  8226. size_t hostlen = strlen(host);
  8227. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8228. if (error != NULL) {
  8229. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8230. mg_snprintf(NULL,
  8231. NULL, /* No truncation check for ebuf */
  8232. error->text,
  8233. error->text_buffer_size,
  8234. "%s",
  8235. "host length exceeds limit");
  8236. }
  8237. return 0;
  8238. }
  8239. } else
  8240. #endif
  8241. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8242. if (error != NULL) {
  8243. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8244. mg_snprintf(NULL,
  8245. NULL, /* No truncation check for ebuf */
  8246. error->text,
  8247. error->text_buffer_size,
  8248. "%s",
  8249. "invalid port");
  8250. }
  8251. return 0;
  8252. }
  8253. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) \
  8254. && !defined(NO_SSL_DL)
  8255. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8256. if (use_ssl && (TLS_client_method == NULL)) {
  8257. if (error != NULL) {
  8258. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8259. mg_snprintf(NULL,
  8260. NULL, /* No truncation check for ebuf */
  8261. error->text,
  8262. error->text_buffer_size,
  8263. "%s",
  8264. "SSL is not initialized");
  8265. }
  8266. return 0;
  8267. }
  8268. #else
  8269. if (use_ssl && (SSLv23_client_method == NULL)) {
  8270. if (error != 0) {
  8271. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8272. mg_snprintf(NULL,
  8273. NULL, /* No truncation check for ebuf */
  8274. error->text,
  8275. error->text_buffer_size,
  8276. "%s",
  8277. "SSL is not initialized");
  8278. }
  8279. return 0;
  8280. }
  8281. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8282. #else
  8283. (void)use_ssl;
  8284. #endif /* NO SSL */
  8285. #if defined(USE_X_DOM_SOCKET)
  8286. if (port == -99) {
  8287. size_t hostlen = strlen(host);
  8288. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8289. ip_ver = -99;
  8290. sa->sun.sun_family = AF_UNIX;
  8291. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8292. memcpy(sa->sun.sun_path, host, hostlen);
  8293. } else
  8294. #endif
  8295. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8296. sa->sin.sin_port = htons((uint16_t)port);
  8297. ip_ver = 4;
  8298. #if defined(USE_IPV6)
  8299. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8300. sa->sin6.sin6_port = htons((uint16_t)port);
  8301. ip_ver = 6;
  8302. } else if (host[0] == '[') {
  8303. /* While getaddrinfo on Windows will work with [::1],
  8304. * getaddrinfo on Linux only works with ::1 (without []). */
  8305. size_t l = strlen(host + 1);
  8306. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8307. if (h) {
  8308. h[l - 1] = 0;
  8309. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8310. sa->sin6.sin6_port = htons((uint16_t)port);
  8311. ip_ver = 6;
  8312. }
  8313. mg_free(h);
  8314. }
  8315. #endif
  8316. }
  8317. if (ip_ver == 0) {
  8318. if (error != NULL) {
  8319. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8320. mg_snprintf(NULL,
  8321. NULL, /* No truncation check for ebuf */
  8322. error->text,
  8323. error->text_buffer_size,
  8324. "%s",
  8325. "host not found");
  8326. }
  8327. return 0;
  8328. }
  8329. if (ip_ver == 4) {
  8330. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8331. }
  8332. #if defined(USE_IPV6)
  8333. else if (ip_ver == 6) {
  8334. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8335. }
  8336. #endif
  8337. #if defined(USE_X_DOM_SOCKET)
  8338. else if (ip_ver == -99) {
  8339. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8340. }
  8341. #endif
  8342. if (*sock == INVALID_SOCKET) {
  8343. if (error != NULL) {
  8344. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8345. error->code_sub = (unsigned)ERRNO;
  8346. mg_snprintf(NULL,
  8347. NULL, /* No truncation check for ebuf */
  8348. error->text,
  8349. error->text_buffer_size,
  8350. "socket(): %s",
  8351. strerror(ERRNO));
  8352. }
  8353. return 0;
  8354. }
  8355. if (0 != set_non_blocking_mode(*sock)) {
  8356. if (error != NULL) {
  8357. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8358. error->code_sub = (unsigned)ERRNO;
  8359. mg_snprintf(NULL,
  8360. NULL, /* No truncation check for ebuf */
  8361. error->text,
  8362. error->text_buffer_size,
  8363. "Cannot set socket to non-blocking: %s",
  8364. strerror(ERRNO));
  8365. }
  8366. closesocket(*sock);
  8367. *sock = INVALID_SOCKET;
  8368. return 0;
  8369. }
  8370. set_close_on_exec(*sock, NULL, ctx);
  8371. if (ip_ver == 4) {
  8372. /* connected with IPv4 */
  8373. conn_ret = connect(*sock,
  8374. (struct sockaddr *)((void *)&sa->sin),
  8375. sizeof(sa->sin));
  8376. }
  8377. #if defined(USE_IPV6)
  8378. else if (ip_ver == 6) {
  8379. /* connected with IPv6 */
  8380. conn_ret = connect(*sock,
  8381. (struct sockaddr *)((void *)&sa->sin6),
  8382. sizeof(sa->sin6));
  8383. }
  8384. #endif
  8385. #if defined(USE_X_DOM_SOCKET)
  8386. else if (ip_ver == -99) {
  8387. /* connected to domain socket */
  8388. conn_ret = connect(*sock,
  8389. (struct sockaddr *)((void *)&sa->sun),
  8390. sizeof(sa->sun));
  8391. }
  8392. #endif
  8393. if (conn_ret != 0) {
  8394. sockerr = ERRNO;
  8395. }
  8396. #if defined(_WIN32)
  8397. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8398. #else
  8399. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8400. #endif
  8401. /* Data for getsockopt */
  8402. void *psockerr = &sockerr;
  8403. int ret;
  8404. #if defined(_WIN32)
  8405. int len = (int)sizeof(sockerr);
  8406. #else
  8407. socklen_t len = (socklen_t)sizeof(sockerr);
  8408. #endif
  8409. /* Data for poll */
  8410. struct mg_pollfd pfd[2];
  8411. int pollres;
  8412. int ms_wait = 10000; /* 10 second timeout */
  8413. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8414. unsigned int num_sock = 1; /* use one or two sockets */
  8415. /* For a non-blocking socket, the connect sequence is:
  8416. * 1) call connect (will not block)
  8417. * 2) wait until the socket is ready for writing (select or poll)
  8418. * 3) check connection state with getsockopt
  8419. */
  8420. pfd[0].fd = *sock;
  8421. pfd[0].events = POLLOUT;
  8422. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8423. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8424. pfd[num_sock].events = POLLIN;
  8425. num_sock++;
  8426. }
  8427. pollres =
  8428. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8429. if (pollres != 1) {
  8430. /* Not connected */
  8431. if (error != NULL) {
  8432. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8433. mg_snprintf(NULL,
  8434. NULL, /* No truncation check for ebuf */
  8435. error->text,
  8436. error->text_buffer_size,
  8437. "connect(%s:%d): timeout",
  8438. host,
  8439. port);
  8440. }
  8441. closesocket(*sock);
  8442. *sock = INVALID_SOCKET;
  8443. return 0;
  8444. }
  8445. #if defined(_WIN32)
  8446. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8447. #else
  8448. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8449. #endif
  8450. if ((ret == 0) && (sockerr == 0)) {
  8451. conn_ret = 0;
  8452. }
  8453. }
  8454. if (conn_ret != 0) {
  8455. /* Not connected */
  8456. if (error != NULL) {
  8457. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8458. error->code_sub = (unsigned)ERRNO;
  8459. mg_snprintf(NULL,
  8460. NULL, /* No truncation check for ebuf */
  8461. error->text,
  8462. error->text_buffer_size,
  8463. "connect(%s:%d): error %s",
  8464. host,
  8465. port,
  8466. strerror(sockerr));
  8467. }
  8468. closesocket(*sock);
  8469. *sock = INVALID_SOCKET;
  8470. return 0;
  8471. }
  8472. return 1;
  8473. }
  8474. CIVETWEB_API int
  8475. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8476. {
  8477. static const char *dont_escape = "._-$,;~()";
  8478. static const char *hex = "0123456789abcdef";
  8479. char *pos = dst;
  8480. const char *end = dst + dst_len - 1;
  8481. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8482. if (isalnum((unsigned char)*src)
  8483. || (strchr(dont_escape, *src) != NULL)) {
  8484. *pos = *src;
  8485. } else if (pos + 2 < end) {
  8486. pos[0] = '%';
  8487. pos[1] = hex[(unsigned char)*src >> 4];
  8488. pos[2] = hex[(unsigned char)*src & 0xf];
  8489. pos += 2;
  8490. } else {
  8491. break;
  8492. }
  8493. }
  8494. *pos = '\0';
  8495. return (*src == '\0') ? (int)(pos - dst) : -1;
  8496. }
  8497. /* Return 0 on success, non-zero if an error occurs. */
  8498. static int
  8499. print_dir_entry(struct mg_connection *conn, struct de *de)
  8500. {
  8501. size_t namesize, escsize, i;
  8502. char *href, *esc, *p;
  8503. char size[64], mod[64];
  8504. #if defined(REENTRANT_TIME)
  8505. struct tm _tm;
  8506. struct tm *tm = &_tm;
  8507. #else
  8508. struct tm *tm;
  8509. #endif
  8510. /* Estimate worst case size for encoding and escaping */
  8511. namesize = strlen(de->file_name) + 1;
  8512. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8513. href = (char *)mg_malloc(namesize * 3 + escsize);
  8514. if (href == NULL) {
  8515. return -1;
  8516. }
  8517. mg_url_encode(de->file_name, href, namesize * 3);
  8518. esc = NULL;
  8519. if (escsize > 0) {
  8520. /* HTML escaping needed */
  8521. esc = href + namesize * 3;
  8522. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8523. mg_strlcpy(p, de->file_name + i, 2);
  8524. if (*p == '&') {
  8525. strcpy(p, "&amp;");
  8526. } else if (*p == '<') {
  8527. strcpy(p, "&lt;");
  8528. } else if (*p == '>') {
  8529. strcpy(p, "&gt;");
  8530. }
  8531. }
  8532. }
  8533. if (de->file.is_directory) {
  8534. mg_snprintf(conn,
  8535. NULL, /* Buffer is big enough */
  8536. size,
  8537. sizeof(size),
  8538. "%s",
  8539. "[DIRECTORY]");
  8540. } else {
  8541. /* We use (signed) cast below because MSVC 6 compiler cannot
  8542. * convert unsigned __int64 to double. Sigh. */
  8543. if (de->file.size < 1024) {
  8544. mg_snprintf(conn,
  8545. NULL, /* Buffer is big enough */
  8546. size,
  8547. sizeof(size),
  8548. "%d",
  8549. (int)de->file.size);
  8550. } else if (de->file.size < 0x100000) {
  8551. mg_snprintf(conn,
  8552. NULL, /* Buffer is big enough */
  8553. size,
  8554. sizeof(size),
  8555. "%.1fk",
  8556. (double)de->file.size / 1024.0);
  8557. } else if (de->file.size < 0x40000000) {
  8558. mg_snprintf(conn,
  8559. NULL, /* Buffer is big enough */
  8560. size,
  8561. sizeof(size),
  8562. "%.1fM",
  8563. (double)de->file.size / 1048576);
  8564. } else {
  8565. mg_snprintf(conn,
  8566. NULL, /* Buffer is big enough */
  8567. size,
  8568. sizeof(size),
  8569. "%.1fG",
  8570. (double)de->file.size / 1073741824);
  8571. }
  8572. }
  8573. /* Note: mg_snprintf will not cause a buffer overflow above.
  8574. * So, string truncation checks are not required here. */
  8575. #if defined(REENTRANT_TIME)
  8576. localtime_r(&de->file.last_modified, tm);
  8577. #else
  8578. tm = localtime(&de->file.last_modified);
  8579. #endif
  8580. if (tm != NULL) {
  8581. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8582. } else {
  8583. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8584. }
  8585. mg_printf(conn,
  8586. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8587. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8588. href,
  8589. de->file.is_directory ? "/" : "",
  8590. esc ? esc : de->file_name,
  8591. de->file.is_directory ? "/" : "",
  8592. mod,
  8593. size);
  8594. mg_free(href);
  8595. return 0;
  8596. }
  8597. /* This function is called from send_directory() and used for
  8598. * sorting directory entries by size, name, or modification time. */
  8599. static int
  8600. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8601. {
  8602. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8603. if (p1 && p2) {
  8604. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8605. int cmp_result = 0;
  8606. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8607. query_string = "n";
  8608. }
  8609. /* Sort Directories vs Files */
  8610. if (a->file.is_directory && !b->file.is_directory) {
  8611. return -1; /* Always put directories on top */
  8612. } else if (!a->file.is_directory && b->file.is_directory) {
  8613. return 1; /* Always put directories on top */
  8614. }
  8615. /* Sort by size or date */
  8616. if (*query_string == 's') {
  8617. cmp_result = (a->file.size == b->file.size)
  8618. ? 0
  8619. : ((a->file.size > b->file.size) ? 1 : -1);
  8620. } else if (*query_string == 'd') {
  8621. cmp_result =
  8622. (a->file.last_modified == b->file.last_modified)
  8623. ? 0
  8624. : ((a->file.last_modified > b->file.last_modified) ? 1
  8625. : -1);
  8626. }
  8627. /* Sort by name:
  8628. * if (*query_string == 'n') ...
  8629. * but also sort files of same size/date by name as secondary criterion.
  8630. */
  8631. if (cmp_result == 0) {
  8632. cmp_result = strcmp(a->file_name, b->file_name);
  8633. }
  8634. /* For descending order, invert result */
  8635. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8636. }
  8637. return 0;
  8638. }
  8639. static int
  8640. must_hide_file(struct mg_connection *conn, const char *path)
  8641. {
  8642. if (conn && conn->dom_ctx) {
  8643. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8644. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8645. return (match_prefix_strlen(pw_pattern, path) > 0)
  8646. || (match_prefix_strlen(pattern, path) > 0);
  8647. }
  8648. return 0;
  8649. }
  8650. #if !defined(NO_FILESYSTEMS)
  8651. static int
  8652. scan_directory(struct mg_connection *conn,
  8653. const char *dir,
  8654. void *data,
  8655. int (*cb)(struct de *, void *))
  8656. {
  8657. char path[UTF8_PATH_MAX];
  8658. struct dirent *dp;
  8659. DIR *dirp;
  8660. struct de de;
  8661. int truncated;
  8662. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8663. return 0;
  8664. } else {
  8665. while ((dp = mg_readdir(dirp)) != NULL) {
  8666. /* Do not show current dir and hidden files */
  8667. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8668. || must_hide_file(conn, dp->d_name)) {
  8669. continue;
  8670. }
  8671. mg_snprintf(
  8672. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8673. /* If we don't memset stat structure to zero, mtime will have
  8674. * garbage and strftime() will segfault later on in
  8675. * print_dir_entry(). memset is required only if mg_stat()
  8676. * fails. For more details, see
  8677. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8678. memset(&de.file, 0, sizeof(de.file));
  8679. if (truncated) {
  8680. /* If the path is not complete, skip processing. */
  8681. continue;
  8682. }
  8683. if (!mg_stat(conn, path, &de.file)) {
  8684. mg_cry_internal(conn,
  8685. "%s: mg_stat(%s) failed: %s",
  8686. __func__,
  8687. path,
  8688. strerror(ERRNO));
  8689. }
  8690. de.file_name = dp->d_name;
  8691. if (cb(&de, data)) {
  8692. /* stopped */
  8693. break;
  8694. }
  8695. }
  8696. (void)mg_closedir(dirp);
  8697. }
  8698. return 1;
  8699. }
  8700. #endif /* NO_FILESYSTEMS */
  8701. #if !defined(NO_FILES)
  8702. static int
  8703. remove_directory(struct mg_connection *conn, const char *dir)
  8704. {
  8705. char path[UTF8_PATH_MAX];
  8706. struct dirent *dp;
  8707. DIR *dirp;
  8708. struct de de;
  8709. int truncated;
  8710. int ok = 1;
  8711. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8712. return 0;
  8713. } else {
  8714. while ((dp = mg_readdir(dirp)) != NULL) {
  8715. /* Do not show current dir (but show hidden files as they will
  8716. * also be removed) */
  8717. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8718. continue;
  8719. }
  8720. mg_snprintf(
  8721. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8722. /* If we don't memset stat structure to zero, mtime will have
  8723. * garbage and strftime() will segfault later on in
  8724. * print_dir_entry(). memset is required only if mg_stat()
  8725. * fails. For more details, see
  8726. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8727. memset(&de.file, 0, sizeof(de.file));
  8728. if (truncated) {
  8729. /* Do not delete anything shorter */
  8730. ok = 0;
  8731. continue;
  8732. }
  8733. if (!mg_stat(conn, path, &de.file)) {
  8734. mg_cry_internal(conn,
  8735. "%s: mg_stat(%s) failed: %s",
  8736. __func__,
  8737. path,
  8738. strerror(ERRNO));
  8739. ok = 0;
  8740. }
  8741. if (de.file.is_directory) {
  8742. if (remove_directory(conn, path) == 0) {
  8743. ok = 0;
  8744. }
  8745. } else {
  8746. /* This will fail file is the file is in memory */
  8747. if (mg_remove(conn, path) == 0) {
  8748. ok = 0;
  8749. }
  8750. }
  8751. }
  8752. (void)mg_closedir(dirp);
  8753. IGNORE_UNUSED_RESULT(rmdir(dir));
  8754. }
  8755. return ok;
  8756. }
  8757. #endif
  8758. struct dir_scan_data {
  8759. struct de *entries;
  8760. size_t num_entries;
  8761. size_t arr_size;
  8762. };
  8763. #if !defined(NO_FILESYSTEMS)
  8764. static int
  8765. dir_scan_callback(struct de *de, void *data)
  8766. {
  8767. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8768. struct de *entries = dsd->entries;
  8769. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8770. /* Here "entries" is a temporary pointer and can be replaced,
  8771. * "dsd->entries" is the original pointer */
  8772. entries =
  8773. (struct de *)mg_realloc(entries,
  8774. dsd->arr_size * 2 * sizeof(entries[0]));
  8775. if (entries == NULL) {
  8776. /* stop scan */
  8777. return 1;
  8778. }
  8779. dsd->entries = entries;
  8780. dsd->arr_size *= 2;
  8781. }
  8782. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8783. if (entries[dsd->num_entries].file_name == NULL) {
  8784. /* stop scan */
  8785. return 1;
  8786. }
  8787. entries[dsd->num_entries].file = de->file;
  8788. dsd->num_entries++;
  8789. return 0;
  8790. }
  8791. static void
  8792. handle_directory_request(struct mg_connection *conn, const char *dir)
  8793. {
  8794. size_t i;
  8795. int sort_direction;
  8796. struct dir_scan_data data = {NULL, 0, 128};
  8797. char date[64], *esc, *p;
  8798. const char *title;
  8799. time_t curtime = time(NULL);
  8800. if (!conn) {
  8801. return;
  8802. }
  8803. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8804. mg_send_http_error(conn,
  8805. 500,
  8806. "Error: Cannot open directory\nopendir(%s): %s",
  8807. dir,
  8808. strerror(ERRNO));
  8809. return;
  8810. }
  8811. gmt_time_string(date, sizeof(date), &curtime);
  8812. esc = NULL;
  8813. title = conn->request_info.local_uri;
  8814. if (title[strcspn(title, "&<>")]) {
  8815. /* HTML escaping needed */
  8816. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8817. if (esc) {
  8818. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8819. mg_strlcpy(p, title + i, 2);
  8820. if (*p == '&') {
  8821. strcpy(p, "&amp;");
  8822. } else if (*p == '<') {
  8823. strcpy(p, "&lt;");
  8824. } else if (*p == '>') {
  8825. strcpy(p, "&gt;");
  8826. }
  8827. }
  8828. } else {
  8829. title = "";
  8830. }
  8831. }
  8832. sort_direction = ((conn->request_info.query_string != NULL)
  8833. && (conn->request_info.query_string[0] != '\0')
  8834. && (conn->request_info.query_string[1] == 'd'))
  8835. ? 'a'
  8836. : 'd';
  8837. conn->must_close = 1;
  8838. /* Create 200 OK response */
  8839. mg_response_header_start(conn, 200);
  8840. send_static_cache_header(conn);
  8841. send_additional_header(conn);
  8842. mg_response_header_add(conn,
  8843. "Content-Type",
  8844. "text/html; charset=utf-8",
  8845. -1);
  8846. /* Send all headers */
  8847. mg_response_header_send(conn);
  8848. /* Body */
  8849. mg_printf(conn,
  8850. "<!DOCTYPE html>"
  8851. "<html><head><title>Index of %s</title>"
  8852. "<style>th {text-align: left;}</style></head>"
  8853. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8854. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8855. "<th><a href=\"?d%c\">Modified</a></th>"
  8856. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8857. "<tr><td colspan=\"3\"><hr></td></tr>",
  8858. esc ? esc : title,
  8859. esc ? esc : title,
  8860. sort_direction,
  8861. sort_direction,
  8862. sort_direction);
  8863. mg_free(esc);
  8864. /* Print first entry - link to a parent directory */
  8865. mg_printf(conn,
  8866. "<tr><td><a href=\"%s\">%s</a></td>"
  8867. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8868. "..",
  8869. "Parent directory",
  8870. "-",
  8871. "-");
  8872. /* Sort and print directory entries */
  8873. if (data.entries != NULL) {
  8874. mg_sort(data.entries,
  8875. data.num_entries,
  8876. sizeof(data.entries[0]),
  8877. compare_dir_entries,
  8878. (void *)conn->request_info.query_string);
  8879. for (i = 0; i < data.num_entries; i++) {
  8880. print_dir_entry(conn, &data.entries[i]);
  8881. mg_free(data.entries[i].file_name);
  8882. }
  8883. mg_free(data.entries);
  8884. }
  8885. mg_printf(conn, "%s", "</table></pre></body></html>");
  8886. conn->status_code = 200;
  8887. }
  8888. #endif /* NO_FILESYSTEMS */
  8889. /* Send len bytes from the opened file to the client. */
  8890. static void
  8891. send_file_data(struct mg_connection *conn,
  8892. struct mg_file *filep,
  8893. int64_t offset,
  8894. int64_t len,
  8895. int no_buffering)
  8896. {
  8897. char buf[MG_BUF_LEN];
  8898. int to_read, num_read, num_written;
  8899. int64_t size;
  8900. if (!filep || !conn) {
  8901. return;
  8902. }
  8903. /* Sanity check the offset */
  8904. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8905. : (int64_t)(filep->stat.size);
  8906. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8907. if (len > 0 && filep->access.fp != NULL) {
  8908. /* file stored on disk */
  8909. #if defined(__linux__)
  8910. /* sendfile is only available for Linux */
  8911. if ((conn->ssl == 0) && (conn->throttle == 0)
  8912. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8913. "yes"))) {
  8914. off_t sf_offs = (off_t)offset;
  8915. ssize_t sf_sent;
  8916. int sf_file = fileno(filep->access.fp);
  8917. int loop_cnt = 0;
  8918. do {
  8919. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8920. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8921. size_t sf_tosend =
  8922. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8923. sf_sent =
  8924. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8925. if (sf_sent > 0) {
  8926. len -= sf_sent;
  8927. offset += sf_sent;
  8928. } else if (loop_cnt == 0) {
  8929. /* This file can not be sent using sendfile.
  8930. * This might be the case for pseudo-files in the
  8931. * /sys/ and /proc/ file system.
  8932. * Use the regular user mode copy code instead. */
  8933. break;
  8934. } else if (sf_sent == 0) {
  8935. /* No error, but 0 bytes sent. May be EOF? */
  8936. return;
  8937. }
  8938. loop_cnt++;
  8939. } while ((len > 0) && (sf_sent >= 0));
  8940. if (sf_sent > 0) {
  8941. return; /* OK */
  8942. }
  8943. /* sf_sent<0 means error, thus fall back to the classic way */
  8944. /* This is always the case, if sf_file is not a "normal" file,
  8945. * e.g., for sending data from the output of a CGI process. */
  8946. offset = (int64_t)sf_offs;
  8947. }
  8948. #endif
  8949. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8950. mg_cry_internal(conn,
  8951. "%s: fseeko() failed: %s",
  8952. __func__,
  8953. strerror(ERRNO));
  8954. mg_send_http_error(
  8955. conn,
  8956. 500,
  8957. "%s",
  8958. "Error: Unable to access file at requested position.");
  8959. } else {
  8960. while (len > 0) {
  8961. /* Calculate how much to read from the file into the buffer. */
  8962. /* If no_buffering is set, we should not wait until the
  8963. * CGI->Server buffer is filled, but send everything
  8964. * immediately. In theory buffering could be turned off using
  8965. * setbuf(filep->access.fp, NULL);
  8966. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8967. * but in practice this does not work. A "Linux only" solution
  8968. * may be to use select(). The only portable way is to read byte
  8969. * by byte, but this is quite inefficient from a performance
  8970. * point of view. */
  8971. to_read = no_buffering ? 1 : sizeof(buf);
  8972. if ((int64_t)to_read > len) {
  8973. to_read = (int)len;
  8974. }
  8975. /* Read from file, exit the loop on error */
  8976. if ((num_read = pull_inner(filep->access.fp,
  8977. NULL,
  8978. buf,
  8979. to_read,
  8980. /* unused */ 0.0))
  8981. <= 0) {
  8982. break;
  8983. }
  8984. /* Send read bytes to the client, exit the loop on error */
  8985. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8986. != num_read) {
  8987. break;
  8988. }
  8989. /* Both read and were successful, adjust counters */
  8990. len -= num_written;
  8991. }
  8992. }
  8993. }
  8994. }
  8995. static int
  8996. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8997. {
  8998. return sscanf(header,
  8999. "bytes=%" INT64_FMT "-%" INT64_FMT,
  9000. a,
  9001. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  9002. // to an integer value, but function will not report
  9003. // conversion errors; consider using 'strtol' instead
  9004. }
  9005. static void
  9006. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  9007. {
  9008. if ((filestat != NULL) && (buf != NULL)) {
  9009. mg_snprintf(NULL,
  9010. NULL, /* All calls to construct_etag use 64 byte buffer */
  9011. buf,
  9012. buf_len,
  9013. "\"%lx.%" INT64_FMT "\"",
  9014. (unsigned long)filestat->last_modified,
  9015. filestat->size);
  9016. }
  9017. }
  9018. static void
  9019. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  9020. {
  9021. if (filep != NULL && filep->fp != NULL) {
  9022. #if defined(_WIN32)
  9023. (void)conn; /* Unused. */
  9024. #else
  9025. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  9026. mg_cry_internal(conn,
  9027. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  9028. __func__,
  9029. strerror(ERRNO));
  9030. }
  9031. #endif
  9032. }
  9033. }
  9034. #if defined(USE_ZLIB)
  9035. #include "mod_zlib.inl"
  9036. #endif
  9037. #if !defined(NO_FILESYSTEMS)
  9038. static void
  9039. handle_static_file_request(struct mg_connection *conn,
  9040. const char *path,
  9041. struct mg_file *filep,
  9042. const char *mime_type,
  9043. const char *additional_headers)
  9044. {
  9045. char lm[64], etag[64];
  9046. char range[128]; /* large enough, so there will be no overflow */
  9047. const char *range_hdr;
  9048. int64_t cl, r1, r2;
  9049. struct vec mime_vec;
  9050. int n, truncated;
  9051. char gz_path[UTF8_PATH_MAX];
  9052. const char *encoding = 0;
  9053. int is_head_request;
  9054. #if defined(USE_ZLIB)
  9055. /* Compression is allowed, unless there is a reason not to use
  9056. * compression. If the file is already compressed, too small or a
  9057. * "range" request was made, on the fly compression is not possible. */
  9058. int allow_on_the_fly_compression = 1;
  9059. #endif
  9060. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9061. return;
  9062. }
  9063. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9064. if (mime_type == NULL) {
  9065. get_mime_type(conn, path, &mime_vec);
  9066. } else {
  9067. mime_vec.ptr = mime_type;
  9068. mime_vec.len = strlen(mime_type);
  9069. }
  9070. if (filep->stat.size > INT64_MAX) {
  9071. mg_send_http_error(conn,
  9072. 500,
  9073. "Error: File size is too large to send\n%" INT64_FMT,
  9074. filep->stat.size);
  9075. return;
  9076. }
  9077. cl = (int64_t)filep->stat.size;
  9078. conn->status_code = 200;
  9079. range[0] = '\0';
  9080. #if defined(USE_ZLIB)
  9081. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9082. * it's important to rewrite the filename after resolving
  9083. * the mime type from it, to preserve the actual file's type */
  9084. if (!conn->accept_gzip) {
  9085. allow_on_the_fly_compression = 0;
  9086. }
  9087. #endif
  9088. /* Check if there is a range header */
  9089. range_hdr = mg_get_header(conn, "Range");
  9090. /* For gzipped files, add *.gz */
  9091. if (filep->stat.is_gzipped) {
  9092. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9093. if (truncated) {
  9094. mg_send_http_error(conn,
  9095. 500,
  9096. "Error: Path of zipped file too long (%s)",
  9097. path);
  9098. return;
  9099. }
  9100. path = gz_path;
  9101. encoding = "gzip";
  9102. #if defined(USE_ZLIB)
  9103. /* File is already compressed. No "on the fly" compression. */
  9104. allow_on_the_fly_compression = 0;
  9105. #endif
  9106. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9107. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9108. struct mg_file_stat file_stat;
  9109. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9110. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9111. && !file_stat.is_directory) {
  9112. file_stat.is_gzipped = 1;
  9113. filep->stat = file_stat;
  9114. cl = (int64_t)filep->stat.size;
  9115. path = gz_path;
  9116. encoding = "gzip";
  9117. #if defined(USE_ZLIB)
  9118. /* File is already compressed. No "on the fly" compression. */
  9119. allow_on_the_fly_compression = 0;
  9120. #endif
  9121. }
  9122. }
  9123. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9124. mg_send_http_error(conn,
  9125. 500,
  9126. "Error: Cannot open file\nfopen(%s): %s",
  9127. path,
  9128. strerror(ERRNO));
  9129. return;
  9130. }
  9131. fclose_on_exec(&filep->access, conn);
  9132. /* If "Range" request was made: parse header, send only selected part
  9133. * of the file. */
  9134. r1 = r2 = 0;
  9135. if ((range_hdr != NULL)
  9136. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9137. && (r2 >= 0)) {
  9138. /* actually, range requests don't play well with a pre-gzipped
  9139. * file (since the range is specified in the uncompressed space) */
  9140. if (filep->stat.is_gzipped) {
  9141. mg_send_http_error(
  9142. conn,
  9143. 416, /* 416 = Range Not Satisfiable */
  9144. "%s",
  9145. "Error: Range requests in gzipped files are not supported");
  9146. (void)mg_fclose(
  9147. &filep->access); /* ignore error on read only file */
  9148. return;
  9149. }
  9150. conn->status_code = 206;
  9151. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9152. mg_snprintf(conn,
  9153. NULL, /* range buffer is big enough */
  9154. range,
  9155. sizeof(range),
  9156. "bytes "
  9157. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9158. r1,
  9159. r1 + cl - 1,
  9160. filep->stat.size);
  9161. #if defined(USE_ZLIB)
  9162. /* Do not compress ranges. */
  9163. allow_on_the_fly_compression = 0;
  9164. #endif
  9165. }
  9166. /* Do not compress small files. Small files do not benefit from file
  9167. * compression, but there is still some overhead. */
  9168. #if defined(USE_ZLIB)
  9169. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9170. /* File is below the size limit. */
  9171. allow_on_the_fly_compression = 0;
  9172. }
  9173. #endif
  9174. /* Prepare Etag, and Last-Modified headers. */
  9175. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9176. construct_etag(etag, sizeof(etag), &filep->stat);
  9177. /* Create 2xx (200, 206) response */
  9178. mg_response_header_start(conn, conn->status_code);
  9179. send_static_cache_header(conn);
  9180. send_additional_header(conn);
  9181. send_cors_header(conn);
  9182. mg_response_header_add(conn,
  9183. "Content-Type",
  9184. mime_vec.ptr,
  9185. (int)mime_vec.len);
  9186. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9187. mg_response_header_add(conn, "Etag", etag, -1);
  9188. #if defined(USE_ZLIB)
  9189. /* On the fly compression allowed */
  9190. if (allow_on_the_fly_compression) {
  9191. /* For on the fly compression, we don't know the content size in
  9192. * advance, so we have to use chunked encoding */
  9193. encoding = "gzip";
  9194. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9195. /* HTTP/2 is always using "chunks" (frames) */
  9196. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9197. }
  9198. } else
  9199. #endif
  9200. {
  9201. /* Without on-the-fly compression, we know the content-length
  9202. * and we can use ranges (with on-the-fly compression we cannot).
  9203. * So we send these response headers only in this case. */
  9204. char len[32];
  9205. int trunc = 0;
  9206. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9207. if (!trunc) {
  9208. mg_response_header_add(conn, "Content-Length", len, -1);
  9209. }
  9210. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9211. }
  9212. if (encoding) {
  9213. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9214. }
  9215. if (range[0] != 0) {
  9216. mg_response_header_add(conn, "Content-Range", range, -1);
  9217. }
  9218. /* The code above does not add any header starting with X- to make
  9219. * sure no one of the additional_headers is included twice */
  9220. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9221. mg_response_header_add_lines(conn, additional_headers);
  9222. }
  9223. /* Send all headers */
  9224. mg_response_header_send(conn);
  9225. if (!is_head_request) {
  9226. #if defined(USE_ZLIB)
  9227. if (allow_on_the_fly_compression) {
  9228. /* Compress and send */
  9229. send_compressed_data(conn, filep);
  9230. } else
  9231. #endif
  9232. {
  9233. /* Send file directly */
  9234. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9235. }
  9236. }
  9237. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9238. }
  9239. CIVETWEB_API int
  9240. mg_send_file_body(struct mg_connection *conn, const char *path)
  9241. {
  9242. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9243. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9244. return -1;
  9245. }
  9246. fclose_on_exec(&file.access, conn);
  9247. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9248. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9249. return 0; /* >= 0 for OK */
  9250. }
  9251. #endif /* NO_FILESYSTEMS */
  9252. #if !defined(NO_CACHING)
  9253. /* Return True if we should reply 304 Not Modified. */
  9254. static int
  9255. is_not_modified(const struct mg_connection *conn,
  9256. const struct mg_file_stat *filestat)
  9257. {
  9258. char etag[64];
  9259. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9260. const char *inm = mg_get_header(conn, "If-None-Match");
  9261. construct_etag(etag, sizeof(etag), filestat);
  9262. if (inm) {
  9263. return !mg_strcasecmp(etag, inm);
  9264. }
  9265. if (ims) {
  9266. return (filestat->last_modified <= parse_date_string(ims));
  9267. }
  9268. return 0;
  9269. }
  9270. static void
  9271. handle_not_modified_static_file_request(struct mg_connection *conn,
  9272. struct mg_file *filep)
  9273. {
  9274. char lm[64], etag[64];
  9275. if ((conn == NULL) || (filep == NULL)) {
  9276. return;
  9277. }
  9278. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9279. construct_etag(etag, sizeof(etag), &filep->stat);
  9280. /* Create 304 "not modified" response */
  9281. mg_response_header_start(conn, 304);
  9282. send_static_cache_header(conn);
  9283. send_additional_header(conn);
  9284. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9285. mg_response_header_add(conn, "Etag", etag, -1);
  9286. /* Send all headers */
  9287. mg_response_header_send(conn);
  9288. }
  9289. #endif
  9290. #if !defined(NO_FILESYSTEMS)
  9291. CIVETWEB_API void
  9292. mg_send_file(struct mg_connection *conn, const char *path)
  9293. {
  9294. mg_send_mime_file2(conn, path, NULL, NULL);
  9295. }
  9296. CIVETWEB_API void
  9297. mg_send_mime_file(struct mg_connection *conn,
  9298. const char *path,
  9299. const char *mime_type)
  9300. {
  9301. mg_send_mime_file2(conn, path, mime_type, NULL);
  9302. }
  9303. CIVETWEB_API void
  9304. mg_send_mime_file2(struct mg_connection *conn,
  9305. const char *path,
  9306. const char *mime_type,
  9307. const char *additional_headers)
  9308. {
  9309. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9310. if (!conn) {
  9311. /* No conn */
  9312. return;
  9313. }
  9314. if (mg_stat(conn, path, &file.stat)) {
  9315. #if !defined(NO_CACHING)
  9316. if (is_not_modified(conn, &file.stat)) {
  9317. /* Send 304 "Not Modified" - this must not send any body data */
  9318. handle_not_modified_static_file_request(conn, &file);
  9319. } else
  9320. #endif /* NO_CACHING */
  9321. if (file.stat.is_directory) {
  9322. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9323. "yes")) {
  9324. handle_directory_request(conn, path);
  9325. } else {
  9326. mg_send_http_error(conn,
  9327. 403,
  9328. "%s",
  9329. "Error: Directory listing denied");
  9330. }
  9331. } else {
  9332. handle_static_file_request(
  9333. conn, path, &file, mime_type, additional_headers);
  9334. }
  9335. } else {
  9336. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9337. }
  9338. }
  9339. /* For a given PUT path, create all intermediate subdirectories.
  9340. * Return 0 if the path itself is a directory.
  9341. * Return 1 if the path leads to a file.
  9342. * Return -1 for if the path is too long.
  9343. * Return -2 if path can not be created.
  9344. */
  9345. static int
  9346. put_dir(struct mg_connection *conn, const char *path)
  9347. {
  9348. char buf[UTF8_PATH_MAX];
  9349. const char *s, *p;
  9350. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9351. size_t len;
  9352. int res = 1;
  9353. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9354. len = (size_t)(p - path);
  9355. if (len >= sizeof(buf)) {
  9356. /* path too long */
  9357. res = -1;
  9358. break;
  9359. }
  9360. memcpy(buf, path, len);
  9361. buf[len] = '\0';
  9362. /* Try to create intermediate directory */
  9363. DEBUG_TRACE("mkdir(%s)", buf);
  9364. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9365. /* path does not exist and can not be created */
  9366. res = -2;
  9367. break;
  9368. }
  9369. /* Is path itself a directory? */
  9370. if (p[1] == '\0') {
  9371. res = 0;
  9372. }
  9373. }
  9374. return res;
  9375. }
  9376. static void
  9377. remove_bad_file(const struct mg_connection *conn, const char *path)
  9378. {
  9379. int r = mg_remove(conn, path);
  9380. if (r != 0) {
  9381. mg_cry_internal(conn,
  9382. "%s: Cannot remove invalid file %s",
  9383. __func__,
  9384. path);
  9385. }
  9386. }
  9387. CIVETWEB_API long long
  9388. mg_store_body(struct mg_connection *conn, const char *path)
  9389. {
  9390. char buf[MG_BUF_LEN];
  9391. long long len = 0;
  9392. int ret, n;
  9393. struct mg_file fi;
  9394. if (conn->consumed_content != 0) {
  9395. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9396. return -11;
  9397. }
  9398. ret = put_dir(conn, path);
  9399. if (ret < 0) {
  9400. /* -1 for path too long,
  9401. * -2 for path can not be created. */
  9402. return ret;
  9403. }
  9404. if (ret != 1) {
  9405. /* Return 0 means, path itself is a directory. */
  9406. return 0;
  9407. }
  9408. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9409. return -12;
  9410. }
  9411. ret = mg_read(conn, buf, sizeof(buf));
  9412. while (ret > 0) {
  9413. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9414. if (n != ret) {
  9415. (void)mg_fclose(
  9416. &fi.access); /* File is bad and will be removed anyway. */
  9417. remove_bad_file(conn, path);
  9418. return -13;
  9419. }
  9420. len += ret;
  9421. ret = mg_read(conn, buf, sizeof(buf));
  9422. }
  9423. /* File is open for writing. If fclose fails, there was probably an
  9424. * error flushing the buffer to disk, so the file on disk might be
  9425. * broken. Delete it and return an error to the caller. */
  9426. if (mg_fclose(&fi.access) != 0) {
  9427. remove_bad_file(conn, path);
  9428. return -14;
  9429. }
  9430. return len;
  9431. }
  9432. #endif /* NO_FILESYSTEMS */
  9433. /* Parse a buffer:
  9434. * Forward the string pointer till the end of a word, then
  9435. * terminate it and forward till the begin of the next word.
  9436. */
  9437. static int
  9438. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9439. {
  9440. /* Forward until a space is found - use isgraph here */
  9441. /* Extended ASCII characters are also treated as word characters. */
  9442. /* See http://www.cplusplus.com/reference/cctype/ */
  9443. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9444. (*ppw)++;
  9445. }
  9446. /* Check end of word */
  9447. if (eol) {
  9448. /* must be a end of line */
  9449. if ((**ppw != '\r') && (**ppw != '\n')) {
  9450. return -1;
  9451. }
  9452. } else {
  9453. /* must be a end of a word, but not a line */
  9454. if (**ppw != ' ') {
  9455. return -1;
  9456. }
  9457. }
  9458. /* Terminate and forward to the next word */
  9459. do {
  9460. **ppw = 0;
  9461. (*ppw)++;
  9462. } while (isspace((unsigned char)**ppw));
  9463. /* Check after term */
  9464. if (!eol) {
  9465. /* if it's not the end of line, there must be a next word */
  9466. if (!isgraph((unsigned char)**ppw)) {
  9467. return -1;
  9468. }
  9469. }
  9470. /* ok */
  9471. return 1;
  9472. }
  9473. /* Parse HTTP headers from the given buffer, advance buf pointer
  9474. * to the point where parsing stopped.
  9475. * All parameters must be valid pointers (not NULL).
  9476. * Return <0 on error. */
  9477. static int
  9478. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9479. {
  9480. int i;
  9481. int num_headers = 0;
  9482. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9483. char *dp = *buf;
  9484. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9485. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9486. dp++;
  9487. }
  9488. if (dp == *buf) {
  9489. /* End of headers reached. */
  9490. break;
  9491. }
  9492. /* Drop all spaces after header name before : */
  9493. while (*dp == ' ') {
  9494. *dp = 0;
  9495. dp++;
  9496. }
  9497. if (*dp != ':') {
  9498. /* This is not a valid field. */
  9499. return -1;
  9500. }
  9501. /* End of header key (*dp == ':') */
  9502. /* Truncate here and set the key name */
  9503. *dp = 0;
  9504. hdr[i].name = *buf;
  9505. /* Skip all spaces */
  9506. do {
  9507. dp++;
  9508. } while ((*dp == ' ') || (*dp == '\t'));
  9509. /* The rest of the line is the value */
  9510. hdr[i].value = dp;
  9511. /* Find end of line */
  9512. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9513. dp++;
  9514. };
  9515. /* eliminate \r */
  9516. if (*dp == '\r') {
  9517. *dp = 0;
  9518. dp++;
  9519. if (*dp != '\n') {
  9520. /* This is not a valid line. */
  9521. return -1;
  9522. }
  9523. }
  9524. /* here *dp is either 0 or '\n' */
  9525. /* in any case, we have found a complete header */
  9526. num_headers = i + 1;
  9527. if (*dp) {
  9528. *dp = 0;
  9529. dp++;
  9530. *buf = dp;
  9531. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9532. /* We've had CRLF twice in a row
  9533. * This is the end of the headers */
  9534. break;
  9535. }
  9536. /* continue within the loop, find the next header */
  9537. } else {
  9538. *buf = dp;
  9539. break;
  9540. }
  9541. }
  9542. return num_headers;
  9543. }
  9544. struct mg_http_method_info {
  9545. const char *name;
  9546. int request_has_body;
  9547. int response_has_body;
  9548. int is_safe;
  9549. int is_idempotent;
  9550. int is_cacheable;
  9551. };
  9552. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9553. static const struct mg_http_method_info http_methods[] = {
  9554. /* HTTP (RFC 2616) */
  9555. {"GET", 0, 1, 1, 1, 1},
  9556. {"POST", 1, 1, 0, 0, 0},
  9557. {"PUT", 1, 0, 0, 1, 0},
  9558. {"DELETE", 0, 0, 0, 1, 0},
  9559. {"HEAD", 0, 0, 1, 1, 1},
  9560. {"OPTIONS", 0, 0, 1, 1, 0},
  9561. {"CONNECT", 1, 1, 0, 0, 0},
  9562. /* TRACE method (RFC 2616) is not supported for security reasons */
  9563. /* PATCH method (RFC 5789) */
  9564. {"PATCH", 1, 0, 0, 0, 0},
  9565. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9566. /* WEBDAV (RFC 2518) */
  9567. {"PROPFIND", 0, 1, 1, 1, 0},
  9568. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9569. * Some PROPFIND results MAY be cached, with care,
  9570. * as there is no cache validation mechanism for
  9571. * most properties. This method is both safe and
  9572. * idempotent (see Section 9.1 of [RFC2616]). */
  9573. {"MKCOL", 0, 0, 0, 1, 0},
  9574. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9575. * When MKCOL is invoked without a request body,
  9576. * the newly created collection SHOULD have no
  9577. * members. A MKCOL request message may contain
  9578. * a message body. The precise behavior of a MKCOL
  9579. * request when the body is present is undefined,
  9580. * ... ==> We do not support MKCOL with body data.
  9581. * This method is idempotent, but not safe (see
  9582. * Section 9.1 of [RFC2616]). Responses to this
  9583. * method MUST NOT be cached. */
  9584. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9585. {"LOCK", 1, 1, 0, 0, 0},
  9586. {"UNLOCK", 1, 0, 0, 0, 0},
  9587. {"PROPPATCH", 1, 1, 0, 0, 0},
  9588. {"COPY", 1, 0, 0, 0, 0},
  9589. {"MOVE", 1, 1, 0, 0, 0},
  9590. /* Unsupported WEBDAV Methods: */
  9591. /* + 11 methods from RFC 3253 */
  9592. /* ORDERPATCH (RFC 3648) */
  9593. /* ACL (RFC 3744) */
  9594. /* SEARCH (RFC 5323) */
  9595. /* + MicroSoft extensions
  9596. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9597. /* REPORT method (RFC 3253) */
  9598. {"REPORT", 1, 1, 1, 1, 1},
  9599. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9600. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9601. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9602. * to be useful for REST in case a "GET request with body" is
  9603. * required. */
  9604. {NULL, 0, 0, 0, 0, 0}
  9605. /* end of list */
  9606. };
  9607. /* All method names */
  9608. static char *all_methods = NULL; /* Built by mg_init_library */
  9609. static const struct mg_http_method_info *
  9610. get_http_method_info(const char *method)
  9611. {
  9612. /* Check if the method is known to the server. The list of all known
  9613. * HTTP methods can be found here at
  9614. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9615. */
  9616. const struct mg_http_method_info *m = http_methods;
  9617. while (m->name) {
  9618. if (!strcmp(m->name, method)) {
  9619. return m;
  9620. }
  9621. m++;
  9622. }
  9623. return NULL;
  9624. }
  9625. static int
  9626. is_valid_http_method(const char *method)
  9627. {
  9628. return (get_http_method_info(method) != NULL);
  9629. }
  9630. /* Parse HTTP request, fill in mg_request_info structure.
  9631. * This function modifies the buffer by NUL-terminating
  9632. * HTTP request components, header names and header values.
  9633. * Parameters:
  9634. * buf (in/out): pointer to the HTTP header to parse and split
  9635. * len (in): length of HTTP header buffer
  9636. * re (out): parsed header as mg_request_info
  9637. * buf and ri must be valid pointers (not NULL), len>0.
  9638. * Returns <0 on error. */
  9639. static int
  9640. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9641. {
  9642. int request_length;
  9643. int init_skip = 0;
  9644. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9645. * remote_port */
  9646. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9647. NULL;
  9648. ri->num_headers = 0;
  9649. /* RFC says that all initial whitespaces should be ignored */
  9650. /* This included all leading \r and \n (isspace) */
  9651. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9652. while ((len > 0) && isspace((unsigned char)*buf)) {
  9653. buf++;
  9654. len--;
  9655. init_skip++;
  9656. }
  9657. if (len == 0) {
  9658. /* Incomplete request */
  9659. return 0;
  9660. }
  9661. /* Control characters are not allowed, including zero */
  9662. if (iscntrl((unsigned char)*buf)) {
  9663. return -1;
  9664. }
  9665. /* Find end of HTTP header */
  9666. request_length = get_http_header_len(buf, len);
  9667. if (request_length <= 0) {
  9668. return request_length;
  9669. }
  9670. buf[request_length - 1] = '\0';
  9671. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9672. return -1;
  9673. }
  9674. /* The first word has to be the HTTP method */
  9675. ri->request_method = buf;
  9676. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9677. return -1;
  9678. }
  9679. /* The second word is the URI */
  9680. ri->request_uri = buf;
  9681. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9682. return -1;
  9683. }
  9684. /* Next would be the HTTP version */
  9685. ri->http_version = buf;
  9686. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9687. return -1;
  9688. }
  9689. /* Check for a valid HTTP version key */
  9690. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9691. /* Invalid request */
  9692. return -1;
  9693. }
  9694. ri->http_version += 5;
  9695. /* Check for a valid http method */
  9696. if (!is_valid_http_method(ri->request_method)) {
  9697. return -1;
  9698. }
  9699. /* Parse all HTTP headers */
  9700. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9701. if (ri->num_headers < 0) {
  9702. /* Error while parsing headers */
  9703. return -1;
  9704. }
  9705. return request_length + init_skip;
  9706. }
  9707. static int
  9708. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9709. {
  9710. int response_length;
  9711. int init_skip = 0;
  9712. char *tmp, *tmp2;
  9713. long l;
  9714. /* Initialize elements. */
  9715. ri->http_version = ri->status_text = NULL;
  9716. ri->num_headers = ri->status_code = 0;
  9717. /* RFC says that all initial whitespaces should be ignored */
  9718. /* This included all leading \r and \n (isspace) */
  9719. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9720. while ((len > 0) && isspace((unsigned char)*buf)) {
  9721. buf++;
  9722. len--;
  9723. init_skip++;
  9724. }
  9725. if (len == 0) {
  9726. /* Incomplete request */
  9727. return 0;
  9728. }
  9729. /* Control characters are not allowed, including zero */
  9730. if (iscntrl((unsigned char)*buf)) {
  9731. return -1;
  9732. }
  9733. /* Find end of HTTP header */
  9734. response_length = get_http_header_len(buf, len);
  9735. if (response_length <= 0) {
  9736. return response_length;
  9737. }
  9738. buf[response_length - 1] = '\0';
  9739. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9740. return -1;
  9741. }
  9742. /* The first word is the HTTP version */
  9743. /* Check for a valid HTTP version key */
  9744. if (strncmp(buf, "HTTP/", 5) != 0) {
  9745. /* Invalid request */
  9746. return -1;
  9747. }
  9748. buf += 5;
  9749. if (!isgraph((unsigned char)buf[0])) {
  9750. /* Invalid request */
  9751. return -1;
  9752. }
  9753. ri->http_version = buf;
  9754. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9755. return -1;
  9756. }
  9757. /* The second word is the status as a number */
  9758. tmp = buf;
  9759. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9760. return -1;
  9761. }
  9762. l = strtol(tmp, &tmp2, 10);
  9763. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9764. /* Everything else but a 3 digit code is invalid */
  9765. return -1;
  9766. }
  9767. ri->status_code = (int)l;
  9768. /* The rest of the line is the status text */
  9769. ri->status_text = buf;
  9770. /* Find end of status text */
  9771. /* isgraph or isspace = isprint */
  9772. while (isprint((unsigned char)*buf)) {
  9773. buf++;
  9774. }
  9775. if ((*buf != '\r') && (*buf != '\n')) {
  9776. return -1;
  9777. }
  9778. /* Terminate string and forward buf to next line */
  9779. do {
  9780. *buf = 0;
  9781. buf++;
  9782. } while (isspace((unsigned char)*buf));
  9783. /* Parse all HTTP headers */
  9784. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9785. if (ri->num_headers < 0) {
  9786. /* Error while parsing headers */
  9787. return -1;
  9788. }
  9789. return response_length + init_skip;
  9790. }
  9791. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9792. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9793. * buffer (which marks the end of HTTP request). Buffer buf may already
  9794. * have some data. The length of the data is stored in nread.
  9795. * Upon every read operation, increase nread by the number of bytes read. */
  9796. static int
  9797. read_message(FILE *fp,
  9798. struct mg_connection *conn,
  9799. char *buf,
  9800. int bufsiz,
  9801. int *nread)
  9802. {
  9803. int request_len, n = 0;
  9804. struct timespec last_action_time;
  9805. double request_timeout;
  9806. if (!conn) {
  9807. return 0;
  9808. }
  9809. memset(&last_action_time, 0, sizeof(last_action_time));
  9810. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9811. /* value of request_timeout is in seconds, config in milliseconds */
  9812. request_timeout =
  9813. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9814. } else {
  9815. request_timeout =
  9816. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9817. / 1000.0;
  9818. }
  9819. if (conn->handled_requests > 0) {
  9820. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9821. request_timeout =
  9822. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9823. / 1000.0;
  9824. }
  9825. }
  9826. request_len = get_http_header_len(buf, *nread);
  9827. while (request_len == 0) {
  9828. /* Full request not yet received */
  9829. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9830. /* Server is to be stopped. */
  9831. return -1;
  9832. }
  9833. if (*nread >= bufsiz) {
  9834. /* Request too long */
  9835. return -2;
  9836. }
  9837. n = pull_inner(
  9838. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9839. if (n == -2) {
  9840. /* Receive error */
  9841. return -1;
  9842. }
  9843. /* update clock after every read request */
  9844. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9845. if (n > 0) {
  9846. *nread += n;
  9847. request_len = get_http_header_len(buf, *nread);
  9848. }
  9849. if ((n <= 0) && (request_timeout >= 0)) {
  9850. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9851. > request_timeout) {
  9852. /* Timeout */
  9853. return -3;
  9854. }
  9855. }
  9856. }
  9857. return request_len;
  9858. }
  9859. #if !defined(NO_CGI) || !defined(NO_FILES)
  9860. static int
  9861. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9862. {
  9863. const char *expect;
  9864. char buf[MG_BUF_LEN];
  9865. int success = 0;
  9866. if (!conn) {
  9867. return 0;
  9868. }
  9869. expect = mg_get_header(conn, "Expect");
  9870. DEBUG_ASSERT(fp != NULL);
  9871. if (!fp) {
  9872. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9873. return 0;
  9874. }
  9875. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9876. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9877. */
  9878. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9879. } else {
  9880. if (expect != NULL) {
  9881. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9882. conn->status_code = 100;
  9883. } else {
  9884. conn->status_code = 200;
  9885. }
  9886. DEBUG_ASSERT(conn->consumed_content == 0);
  9887. if (conn->consumed_content != 0) {
  9888. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9889. return 0;
  9890. }
  9891. for (;;) {
  9892. int nread = mg_read(conn, buf, sizeof(buf));
  9893. if (nread <= 0) {
  9894. success = (nread == 0);
  9895. break;
  9896. }
  9897. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9898. break;
  9899. }
  9900. }
  9901. /* Each error code path in this function must send an error */
  9902. if (!success) {
  9903. /* NOTE: Maybe some data has already been sent. */
  9904. /* TODO (low): If some data has been sent, a correct error
  9905. * reply can no longer be sent, so just close the connection */
  9906. mg_send_http_error(conn, 500, "%s", "");
  9907. }
  9908. }
  9909. return success;
  9910. }
  9911. #endif
  9912. #if defined(USE_TIMERS)
  9913. #define TIMER_API static
  9914. #include "timer.inl"
  9915. #endif /* USE_TIMERS */
  9916. #if !defined(NO_CGI)
  9917. /* This structure helps to create an environment for the spawned CGI
  9918. * program.
  9919. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9920. * last element must be NULL.
  9921. * However, on Windows there is a requirement that all these
  9922. * VARIABLE=VALUE\0
  9923. * strings must reside in a contiguous buffer. The end of the buffer is
  9924. * marked by two '\0' characters.
  9925. * We satisfy both worlds: we create an envp array (which is vars), all
  9926. * entries are actually pointers inside buf. */
  9927. struct cgi_environment {
  9928. struct mg_connection *conn;
  9929. /* Data block */
  9930. char *buf; /* Environment buffer */
  9931. size_t buflen; /* Space available in buf */
  9932. size_t bufused; /* Space taken in buf */
  9933. /* Index block */
  9934. char **var; /* char **envp */
  9935. size_t varlen; /* Number of variables available in var */
  9936. size_t varused; /* Number of variables stored in var */
  9937. };
  9938. static void addenv(struct cgi_environment *env,
  9939. PRINTF_FORMAT_STRING(const char *fmt),
  9940. ...) PRINTF_ARGS(2, 3);
  9941. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9942. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9943. static void
  9944. addenv(struct cgi_environment *env, const char *fmt, ...)
  9945. {
  9946. size_t i, n, space;
  9947. int truncated = 0;
  9948. char *added;
  9949. va_list ap;
  9950. if ((env->varlen - env->varused) < 2) {
  9951. mg_cry_internal(env->conn,
  9952. "%s: Cannot register CGI variable [%s]",
  9953. __func__,
  9954. fmt);
  9955. return;
  9956. }
  9957. /* Calculate how much space is left in the buffer */
  9958. space = (env->buflen - env->bufused);
  9959. do {
  9960. /* Space for "\0\0" is always needed. */
  9961. if (space <= 2) {
  9962. /* Allocate new buffer */
  9963. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9964. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9965. if (!added) {
  9966. /* Out of memory */
  9967. mg_cry_internal(
  9968. env->conn,
  9969. "%s: Cannot allocate memory for CGI variable [%s]",
  9970. __func__,
  9971. fmt);
  9972. return;
  9973. }
  9974. /* Retarget pointers */
  9975. env->buf = added;
  9976. env->buflen = n;
  9977. for (i = 0, n = 0; i < env->varused; i++) {
  9978. env->var[i] = added + n;
  9979. n += strlen(added + n) + 1;
  9980. }
  9981. space = (env->buflen - env->bufused);
  9982. }
  9983. /* Make a pointer to the free space int the buffer */
  9984. added = env->buf + env->bufused;
  9985. /* Copy VARIABLE=VALUE\0 string into the free space */
  9986. va_start(ap, fmt);
  9987. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9988. va_end(ap);
  9989. /* Do not add truncated strings to the environment */
  9990. if (truncated) {
  9991. /* Reallocate the buffer */
  9992. space = 0;
  9993. }
  9994. } while (truncated);
  9995. /* Calculate number of bytes added to the environment */
  9996. n = strlen(added) + 1;
  9997. env->bufused += n;
  9998. /* Append a pointer to the added string into the envp array */
  9999. env->var[env->varused] = added;
  10000. env->varused++;
  10001. }
  10002. /* Return 0 on success, non-zero if an error occurs. */
  10003. static int
  10004. prepare_cgi_environment(struct mg_connection *conn,
  10005. const char *prog,
  10006. struct cgi_environment *env,
  10007. int cgi_config_idx)
  10008. {
  10009. const char *s;
  10010. struct vec var_vec;
  10011. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  10012. int i, truncated, uri_len;
  10013. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  10014. return -1;
  10015. }
  10016. env->conn = conn;
  10017. env->buflen = CGI_ENVIRONMENT_SIZE;
  10018. env->bufused = 0;
  10019. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  10020. if (env->buf == NULL) {
  10021. mg_cry_internal(conn,
  10022. "%s: Not enough memory for environmental buffer",
  10023. __func__);
  10024. return -1;
  10025. }
  10026. env->varlen = MAX_CGI_ENVIR_VARS;
  10027. env->varused = 0;
  10028. env->var =
  10029. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  10030. if (env->var == NULL) {
  10031. mg_cry_internal(conn,
  10032. "%s: Not enough memory for environmental variables",
  10033. __func__);
  10034. mg_free(env->buf);
  10035. return -1;
  10036. }
  10037. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10038. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10039. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10040. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10041. addenv(env,
  10042. "FALLBACK_DOCUMENT_ROOT=%s",
  10043. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10044. }
  10045. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10046. /* Prepare the environment block */
  10047. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10048. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10049. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10050. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10051. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10052. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10053. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10054. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10055. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10056. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10057. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10058. /* SCRIPT_NAME */
  10059. uri_len = (int)strlen(conn->request_info.local_uri);
  10060. if (conn->path_info == NULL) {
  10061. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10062. /* URI: /path_to_script/script.cgi */
  10063. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10064. } else {
  10065. /* URI: /path_to_script/ ... using index.cgi */
  10066. const char *index_file = strrchr(prog, '/');
  10067. if (index_file) {
  10068. addenv(env,
  10069. "SCRIPT_NAME=%s%s",
  10070. conn->request_info.local_uri,
  10071. index_file + 1);
  10072. }
  10073. }
  10074. } else {
  10075. /* URI: /path_to_script/script.cgi/path_info */
  10076. addenv(env,
  10077. "SCRIPT_NAME=%.*s",
  10078. uri_len - (int)strlen(conn->path_info),
  10079. conn->request_info.local_uri);
  10080. }
  10081. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10082. if (conn->path_info == NULL) {
  10083. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10084. } else {
  10085. addenv(env,
  10086. "PATH_TRANSLATED=%s%s",
  10087. conn->dom_ctx->config[DOCUMENT_ROOT],
  10088. conn->path_info);
  10089. }
  10090. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10091. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10092. addenv(env, "CONTENT_TYPE=%s", s);
  10093. }
  10094. if (conn->request_info.query_string != NULL) {
  10095. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10096. }
  10097. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10098. addenv(env, "CONTENT_LENGTH=%s", s);
  10099. }
  10100. if ((s = getenv("PATH")) != NULL) {
  10101. addenv(env, "PATH=%s", s);
  10102. }
  10103. if (conn->path_info != NULL) {
  10104. addenv(env, "PATH_INFO=%s", conn->path_info);
  10105. }
  10106. if (conn->status_code > 0) {
  10107. /* CGI error handler should show the status code */
  10108. addenv(env, "STATUS=%d", conn->status_code);
  10109. }
  10110. #if defined(_WIN32)
  10111. if ((s = getenv("COMSPEC")) != NULL) {
  10112. addenv(env, "COMSPEC=%s", s);
  10113. }
  10114. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10115. addenv(env, "SYSTEMROOT=%s", s);
  10116. }
  10117. if ((s = getenv("SystemDrive")) != NULL) {
  10118. addenv(env, "SystemDrive=%s", s);
  10119. }
  10120. if ((s = getenv("ProgramFiles")) != NULL) {
  10121. addenv(env, "ProgramFiles=%s", s);
  10122. }
  10123. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10124. addenv(env, "ProgramFiles(x86)=%s", s);
  10125. }
  10126. #else
  10127. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10128. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10129. }
  10130. #endif /* _WIN32 */
  10131. if ((s = getenv("PERLLIB")) != NULL) {
  10132. addenv(env, "PERLLIB=%s", s);
  10133. }
  10134. if (conn->request_info.remote_user != NULL) {
  10135. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10136. addenv(env, "%s", "AUTH_TYPE=Digest");
  10137. }
  10138. /* Add all headers as HTTP_* variables */
  10139. for (i = 0; i < conn->request_info.num_headers; i++) {
  10140. (void)mg_snprintf(conn,
  10141. &truncated,
  10142. http_var_name,
  10143. sizeof(http_var_name),
  10144. "HTTP_%s",
  10145. conn->request_info.http_headers[i].name);
  10146. if (truncated) {
  10147. mg_cry_internal(conn,
  10148. "%s: HTTP header variable too long [%s]",
  10149. __func__,
  10150. conn->request_info.http_headers[i].name);
  10151. continue;
  10152. }
  10153. /* Convert variable name into uppercase, and change - to _ */
  10154. for (p = http_var_name; *p != '\0'; p++) {
  10155. if (*p == '-') {
  10156. *p = '_';
  10157. }
  10158. *p = (char)toupper((unsigned char)*p);
  10159. }
  10160. addenv(env,
  10161. "%s=%s",
  10162. http_var_name,
  10163. conn->request_info.http_headers[i].value);
  10164. }
  10165. /* Add user-specified variables */
  10166. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10167. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10168. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10169. }
  10170. env->var[env->varused] = NULL;
  10171. env->buf[env->bufused] = '\0';
  10172. return 0;
  10173. }
  10174. /* Data for CGI process control: PID and number of references */
  10175. struct process_control_data {
  10176. pid_t pid;
  10177. ptrdiff_t references;
  10178. };
  10179. static int
  10180. abort_cgi_process(void *data)
  10181. {
  10182. /* Waitpid checks for child status and won't work for a pid that does
  10183. * not identify a child of the current process. Thus, if the pid is
  10184. * reused, we will not affect a different process. */
  10185. struct process_control_data *proc = (struct process_control_data *)data;
  10186. int status = 0;
  10187. ptrdiff_t refs;
  10188. pid_t ret_pid;
  10189. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10190. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10191. /* Stop child process */
  10192. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10193. kill(proc->pid, SIGABRT);
  10194. /* Wait until process is terminated (don't leave zombies) */
  10195. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10196. ;
  10197. } else {
  10198. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10199. }
  10200. /* Dec reference counter */
  10201. refs = mg_atomic_dec(&proc->references);
  10202. if (refs == 0) {
  10203. /* no more references - free data */
  10204. mg_free(data);
  10205. }
  10206. return 0;
  10207. }
  10208. /* Local (static) function assumes all arguments are valid. */
  10209. static void
  10210. handle_cgi_request(struct mg_connection *conn,
  10211. const char *prog,
  10212. int cgi_config_idx)
  10213. {
  10214. char *buf;
  10215. size_t buflen;
  10216. int headers_len, data_len, i, truncated;
  10217. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10218. const char *status, *status_text;
  10219. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10220. struct mg_request_info ri;
  10221. struct cgi_environment blk;
  10222. FILE *in = NULL, *out = NULL, *err = NULL;
  10223. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10224. pid_t pid = (pid_t)-1;
  10225. struct process_control_data *proc = NULL;
  10226. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10227. int no_buffering = 0;
  10228. #if defined(USE_TIMERS)
  10229. double cgi_timeout;
  10230. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10231. /* Get timeout in seconds */
  10232. cgi_timeout =
  10233. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10234. } else {
  10235. cgi_timeout =
  10236. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10237. }
  10238. #endif
  10239. if (cfg_buffering != NULL) {
  10240. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10241. no_buffering = 1;
  10242. }
  10243. }
  10244. buf = NULL;
  10245. buflen = conn->phys_ctx->max_request_size;
  10246. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10247. if (i != 0) {
  10248. blk.buf = NULL;
  10249. blk.var = NULL;
  10250. goto done;
  10251. }
  10252. /* CGI must be executed in its own directory. 'dir' must point to the
  10253. * directory containing executable program, 'p' must point to the
  10254. * executable program name relative to 'dir'. */
  10255. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10256. if (truncated) {
  10257. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10258. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10259. goto done;
  10260. }
  10261. if ((p = strrchr(dir, '/')) != NULL) {
  10262. *p++ = '\0';
  10263. } else {
  10264. dir[0] = '.';
  10265. dir[1] = '\0';
  10266. p = (char *)prog;
  10267. }
  10268. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10269. status = strerror(ERRNO);
  10270. mg_cry_internal(
  10271. conn,
  10272. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10273. prog,
  10274. status);
  10275. mg_send_http_error(conn,
  10276. 500,
  10277. "Error: Cannot create CGI pipe: %s",
  10278. status);
  10279. goto done;
  10280. }
  10281. proc = (struct process_control_data *)
  10282. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10283. if (proc == NULL) {
  10284. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10285. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10286. goto done;
  10287. }
  10288. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10289. pid = spawn_process(
  10290. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10291. if (pid == (pid_t)-1) {
  10292. status = strerror(ERRNO);
  10293. mg_cry_internal(
  10294. conn,
  10295. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10296. prog,
  10297. status);
  10298. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10299. mg_free(proc);
  10300. proc = NULL;
  10301. goto done;
  10302. }
  10303. /* Store data in shared process_control_data */
  10304. proc->pid = pid;
  10305. proc->references = 1;
  10306. #if defined(USE_TIMERS)
  10307. if (cgi_timeout > 0.0) {
  10308. proc->references = 2;
  10309. // Start a timer for CGI
  10310. timer_add(conn->phys_ctx,
  10311. cgi_timeout /* in seconds */,
  10312. 0.0,
  10313. 1,
  10314. abort_cgi_process,
  10315. (void *)proc,
  10316. NULL);
  10317. }
  10318. #endif
  10319. /* Parent closes only one side of the pipes.
  10320. * If we don't mark them as closed, close() attempt before
  10321. * return from this function throws an exception on Windows.
  10322. * Windows does not like when closed descriptor is closed again. */
  10323. (void)close(fdin[0]);
  10324. (void)close(fdout[1]);
  10325. (void)close(fderr[1]);
  10326. fdin[0] = fdout[1] = fderr[1] = -1;
  10327. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10328. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10329. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10330. status = strerror(ERRNO);
  10331. mg_cry_internal(conn,
  10332. "Error: CGI program \"%s\": Can not open fd: %s",
  10333. prog,
  10334. status);
  10335. mg_send_http_error(conn,
  10336. 500,
  10337. "Error: CGI can not open fd\nfdopen: %s",
  10338. status);
  10339. goto done;
  10340. }
  10341. setbuf(in, NULL);
  10342. setbuf(out, NULL);
  10343. setbuf(err, NULL);
  10344. fout.access.fp = out;
  10345. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10346. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10347. conn->content_len);
  10348. /* This is a POST/PUT request, or another request with body data. */
  10349. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10350. /* Error sending the body data */
  10351. mg_cry_internal(
  10352. conn,
  10353. "Error: CGI program \"%s\": Forward body data failed",
  10354. prog);
  10355. goto done;
  10356. }
  10357. }
  10358. /* Close so child gets an EOF. */
  10359. fclose(in);
  10360. in = NULL;
  10361. fdin[1] = -1;
  10362. /* Now read CGI reply into a buffer. We need to set correct
  10363. * status code, thus we need to see all HTTP headers first.
  10364. * Do not send anything back to client, until we buffer in all
  10365. * HTTP headers. */
  10366. data_len = 0;
  10367. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10368. if (buf == NULL) {
  10369. mg_send_http_error(conn,
  10370. 500,
  10371. "Error: Not enough memory for CGI buffer (%u bytes)",
  10372. (unsigned int)buflen);
  10373. mg_cry_internal(
  10374. conn,
  10375. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10376. "bytes)",
  10377. prog,
  10378. (unsigned int)buflen);
  10379. goto done;
  10380. }
  10381. DEBUG_TRACE("CGI: %s", "wait for response");
  10382. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10383. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10384. if (headers_len <= 0) {
  10385. /* Could not parse the CGI response. Check if some error message on
  10386. * stderr. */
  10387. i = pull_all(err, conn, buf, (int)buflen);
  10388. if (i > 0) {
  10389. /* CGI program explicitly sent an error */
  10390. /* Write the error message to the internal log */
  10391. mg_cry_internal(conn,
  10392. "Error: CGI program \"%s\" sent error "
  10393. "message: [%.*s]",
  10394. prog,
  10395. i,
  10396. buf);
  10397. /* Don't send the error message back to the client */
  10398. mg_send_http_error(conn,
  10399. 500,
  10400. "Error: CGI program \"%s\" failed.",
  10401. prog);
  10402. } else {
  10403. /* CGI program did not explicitly send an error, but a broken
  10404. * respon header */
  10405. mg_cry_internal(conn,
  10406. "Error: CGI program sent malformed or too big "
  10407. "(>%u bytes) HTTP headers: [%.*s]",
  10408. (unsigned)buflen,
  10409. data_len,
  10410. buf);
  10411. mg_send_http_error(conn,
  10412. 500,
  10413. "Error: CGI program sent malformed or too big "
  10414. "(>%u bytes) HTTP headers: [%.*s]",
  10415. (unsigned)buflen,
  10416. data_len,
  10417. buf);
  10418. }
  10419. /* in both cases, abort processing CGI */
  10420. goto done;
  10421. }
  10422. pbuf = buf;
  10423. buf[headers_len - 1] = '\0';
  10424. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10425. /* Make up and send the status line */
  10426. status_text = "OK";
  10427. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10428. != NULL) {
  10429. conn->status_code = atoi(status);
  10430. status_text = status;
  10431. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10432. status_text++;
  10433. }
  10434. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10435. != NULL) {
  10436. conn->status_code = 307;
  10437. } else {
  10438. conn->status_code = 200;
  10439. }
  10440. if (!should_keep_alive(conn)) {
  10441. conn->must_close = 1;
  10442. }
  10443. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10444. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10445. /* Send headers */
  10446. for (i = 0; i < ri.num_headers; i++) {
  10447. DEBUG_TRACE("CGI header: %s: %s",
  10448. ri.http_headers[i].name,
  10449. ri.http_headers[i].value);
  10450. mg_printf(conn,
  10451. "%s: %s\r\n",
  10452. ri.http_headers[i].name,
  10453. ri.http_headers[i].value);
  10454. }
  10455. mg_write(conn, "\r\n", 2);
  10456. /* Send chunk of data that may have been read after the headers */
  10457. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10458. /* Read the rest of CGI output and send to the client */
  10459. DEBUG_TRACE("CGI: %s", "forward all data");
  10460. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10461. DEBUG_TRACE("CGI: %s", "all data sent");
  10462. done:
  10463. mg_free(blk.var);
  10464. mg_free(blk.buf);
  10465. if (pid != (pid_t)-1) {
  10466. abort_cgi_process((void *)proc);
  10467. }
  10468. if (fdin[0] != -1) {
  10469. close(fdin[0]);
  10470. }
  10471. if (fdout[1] != -1) {
  10472. close(fdout[1]);
  10473. }
  10474. if (fderr[1] != -1) {
  10475. close(fderr[1]);
  10476. }
  10477. if (in != NULL) {
  10478. fclose(in);
  10479. } else if (fdin[1] != -1) {
  10480. close(fdin[1]);
  10481. }
  10482. if (out != NULL) {
  10483. fclose(out);
  10484. } else if (fdout[0] != -1) {
  10485. close(fdout[0]);
  10486. }
  10487. if (err != NULL) {
  10488. fclose(err);
  10489. } else if (fderr[0] != -1) {
  10490. close(fderr[0]);
  10491. }
  10492. mg_free(buf);
  10493. }
  10494. #endif /* !NO_CGI */
  10495. #if !defined(NO_FILES)
  10496. static void
  10497. dav_mkcol(struct mg_connection *conn, const char *path)
  10498. {
  10499. int rc, body_len;
  10500. struct de de;
  10501. if (conn == NULL) {
  10502. return;
  10503. }
  10504. /* TODO (mid): Check the mg_send_http_error situations in this function
  10505. */
  10506. memset(&de.file, 0, sizeof(de.file));
  10507. if (!mg_stat(conn, path, &de.file)) {
  10508. mg_cry_internal(conn,
  10509. "%s: mg_stat(%s) failed: %s",
  10510. __func__,
  10511. path,
  10512. strerror(ERRNO));
  10513. }
  10514. if (de.file.last_modified) {
  10515. /* TODO (mid): This check does not seem to make any sense ! */
  10516. /* TODO (mid): Add a webdav unit test first, before changing
  10517. * anything here. */
  10518. mg_send_http_error(
  10519. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10520. return;
  10521. }
  10522. body_len = conn->data_len - conn->request_len;
  10523. if (body_len > 0) {
  10524. mg_send_http_error(
  10525. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10526. return;
  10527. }
  10528. rc = mg_mkdir(conn, path, 0755);
  10529. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10530. if (rc == 0) {
  10531. /* Create 201 "Created" response */
  10532. mg_response_header_start(conn, 201);
  10533. send_static_cache_header(conn);
  10534. send_additional_header(conn);
  10535. mg_response_header_add(conn, "Content-Length", "0", -1);
  10536. /* Send all headers - there is no body */
  10537. mg_response_header_send(conn);
  10538. } else {
  10539. int http_status = 500;
  10540. switch (errno) {
  10541. case EEXIST:
  10542. http_status = 405;
  10543. break;
  10544. case EACCES:
  10545. http_status = 403;
  10546. break;
  10547. case ENOENT:
  10548. http_status = 409;
  10549. break;
  10550. }
  10551. mg_send_http_error(conn,
  10552. http_status,
  10553. "Error processing %s: %s",
  10554. path,
  10555. strerror(ERRNO));
  10556. }
  10557. }
  10558. /* Forward decrlaration */
  10559. static int get_uri_type(const char *uri);
  10560. static const char *
  10561. get_rel_url_at_current_server(const char *uri,
  10562. const struct mg_connection *conn);
  10563. static void
  10564. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10565. {
  10566. const char *overwrite_hdr;
  10567. const char *destination_hdr;
  10568. const char *root;
  10569. int rc, dest_uri_type;
  10570. int http_status = 400;
  10571. int do_overwrite = 0;
  10572. int destination_ok = 0;
  10573. char dest_path[UTF8_PATH_MAX];
  10574. struct mg_file_stat ignored;
  10575. if (conn == NULL) {
  10576. return;
  10577. }
  10578. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10579. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10580. destination_hdr = mg_get_header(conn, "Destination");
  10581. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10582. do_overwrite = 1;
  10583. }
  10584. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10585. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10586. return;
  10587. }
  10588. if (root != NULL) {
  10589. char *local_dest = NULL;
  10590. dest_uri_type = get_uri_type(destination_hdr);
  10591. if (dest_uri_type == 2) {
  10592. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10593. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10594. const char *h =
  10595. get_rel_url_at_current_server(destination_hdr, conn);
  10596. if (h) {
  10597. size_t len = strlen(h);
  10598. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10599. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10600. }
  10601. }
  10602. if (local_dest != NULL) {
  10603. remove_dot_segments(local_dest);
  10604. if (local_dest[0] == '/') {
  10605. int trunc_check = 0;
  10606. mg_snprintf(conn,
  10607. &trunc_check,
  10608. dest_path,
  10609. sizeof(dest_path),
  10610. "%s/%s",
  10611. root,
  10612. local_dest);
  10613. if (trunc_check == 0) {
  10614. destination_ok = 1;
  10615. }
  10616. }
  10617. mg_free(local_dest);
  10618. }
  10619. }
  10620. if (!destination_ok) {
  10621. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10622. return;
  10623. }
  10624. /* Check now if this file exists */
  10625. if (mg_stat(conn, dest_path, &ignored)) {
  10626. /* File exists */
  10627. if (do_overwrite) {
  10628. /* Overwrite allowed: delete the file first */
  10629. if (0 != remove(dest_path)) {
  10630. /* No overwrite: return error */
  10631. mg_send_http_error(conn,
  10632. 403,
  10633. "Cannot overwrite file: %s",
  10634. dest_path);
  10635. return;
  10636. }
  10637. } else {
  10638. /* No overwrite: return error */
  10639. mg_send_http_error(conn,
  10640. 412,
  10641. "Destination already exists: %s",
  10642. dest_path);
  10643. return;
  10644. }
  10645. }
  10646. /* Copy / Move / Rename operation. */
  10647. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10648. #if defined(_WIN32)
  10649. {
  10650. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10651. wchar_t wSource[UTF16_PATH_MAX];
  10652. wchar_t wDest[UTF16_PATH_MAX];
  10653. BOOL ok;
  10654. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10655. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10656. if (do_copy) {
  10657. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10658. } else {
  10659. ok = MoveFileExW(wSource,
  10660. wDest,
  10661. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10662. }
  10663. if (ok) {
  10664. rc = 0;
  10665. } else {
  10666. DWORD lastErr = GetLastError();
  10667. if (lastErr == ERROR_ALREADY_EXISTS) {
  10668. mg_send_http_error(conn,
  10669. 412,
  10670. "Destination already exists: %s",
  10671. dest_path);
  10672. return;
  10673. }
  10674. rc = -1;
  10675. http_status = 400;
  10676. }
  10677. }
  10678. #else
  10679. {
  10680. /* Linux uses already UTF-8, we don't need to convert file names. */
  10681. if (do_copy) {
  10682. /* TODO: COPY for Linux. */
  10683. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10684. return;
  10685. }
  10686. rc = rename(path, dest_path);
  10687. if (rc) {
  10688. switch (errno) {
  10689. case EEXIST:
  10690. http_status = 412;
  10691. break;
  10692. case EACCES:
  10693. http_status = 403;
  10694. break;
  10695. case ENOENT:
  10696. http_status = 409;
  10697. break;
  10698. }
  10699. }
  10700. }
  10701. #endif
  10702. if (rc == 0) {
  10703. /* Create 204 "No Content" response */
  10704. mg_response_header_start(conn, 204);
  10705. mg_response_header_add(conn, "Content-Length", "0", -1);
  10706. /* Send all headers - there is no body */
  10707. mg_response_header_send(conn);
  10708. } else {
  10709. mg_send_http_error(conn, http_status, "Operation failed");
  10710. }
  10711. }
  10712. static void
  10713. put_file(struct mg_connection *conn, const char *path)
  10714. {
  10715. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10716. const char *range;
  10717. int64_t r1, r2;
  10718. int rc;
  10719. if (conn == NULL) {
  10720. return;
  10721. }
  10722. DEBUG_TRACE("store %s", path);
  10723. if (mg_stat(conn, path, &file.stat)) {
  10724. /* File already exists */
  10725. conn->status_code = 200;
  10726. if (file.stat.is_directory) {
  10727. /* This is an already existing directory,
  10728. * so there is nothing to do for the server. */
  10729. rc = 0;
  10730. } else {
  10731. /* File exists and is not a directory. */
  10732. /* Can it be replaced? */
  10733. /* Check if the server may write this file */
  10734. if (access(path, W_OK) == 0) {
  10735. /* Access granted */
  10736. rc = 1;
  10737. } else {
  10738. mg_send_http_error(
  10739. conn,
  10740. 403,
  10741. "Error: Put not possible\nReplacing %s is not allowed",
  10742. path);
  10743. return;
  10744. }
  10745. }
  10746. } else {
  10747. /* File should be created */
  10748. conn->status_code = 201;
  10749. rc = put_dir(conn, path);
  10750. }
  10751. if (rc == 0) {
  10752. /* put_dir returns 0 if path is a directory */
  10753. /* Create response */
  10754. mg_response_header_start(conn, conn->status_code);
  10755. send_no_cache_header(conn);
  10756. send_additional_header(conn);
  10757. mg_response_header_add(conn, "Content-Length", "0", -1);
  10758. /* Send all headers - there is no body */
  10759. mg_response_header_send(conn);
  10760. /* Request to create a directory has been fulfilled successfully.
  10761. * No need to put a file. */
  10762. return;
  10763. }
  10764. if (rc == -1) {
  10765. /* put_dir returns -1 if the path is too long */
  10766. mg_send_http_error(conn,
  10767. 414,
  10768. "Error: Path too long\nput_dir(%s): %s",
  10769. path,
  10770. strerror(ERRNO));
  10771. return;
  10772. }
  10773. if (rc == -2) {
  10774. /* put_dir returns -2 if the directory can not be created */
  10775. mg_send_http_error(conn,
  10776. 500,
  10777. "Error: Can not create directory\nput_dir(%s): %s",
  10778. path,
  10779. strerror(ERRNO));
  10780. return;
  10781. }
  10782. /* A file should be created or overwritten. */
  10783. /* Currently CivetWeb does not need read+write access. */
  10784. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10785. || file.access.fp == NULL) {
  10786. (void)mg_fclose(&file.access);
  10787. mg_send_http_error(conn,
  10788. 500,
  10789. "Error: Can not create file\nfopen(%s): %s",
  10790. path,
  10791. strerror(ERRNO));
  10792. return;
  10793. }
  10794. fclose_on_exec(&file.access, conn);
  10795. range = mg_get_header(conn, "Content-Range");
  10796. r1 = r2 = 0;
  10797. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10798. conn->status_code = 206; /* Partial content */
  10799. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10800. mg_send_http_error(conn,
  10801. 500,
  10802. "Error: Internal error processing file %s",
  10803. path);
  10804. return;
  10805. }
  10806. }
  10807. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10808. /* forward_body_data failed.
  10809. * The error code has already been sent to the client,
  10810. * and conn->status_code is already set. */
  10811. (void)mg_fclose(&file.access);
  10812. return;
  10813. }
  10814. if (mg_fclose(&file.access) != 0) {
  10815. /* fclose failed. This might have different reasons, but a likely
  10816. * one is "no space on disk", http 507. */
  10817. conn->status_code = 507;
  10818. }
  10819. /* Create response (status_code has been set before) */
  10820. mg_response_header_start(conn, conn->status_code);
  10821. send_no_cache_header(conn);
  10822. send_additional_header(conn);
  10823. mg_response_header_add(conn, "Content-Length", "0", -1);
  10824. /* Send all headers - there is no body */
  10825. mg_response_header_send(conn);
  10826. }
  10827. static void
  10828. delete_file(struct mg_connection *conn, const char *path)
  10829. {
  10830. struct de de;
  10831. memset(&de.file, 0, sizeof(de.file));
  10832. if (!mg_stat(conn, path, &de.file)) {
  10833. /* mg_stat returns 0 if the file does not exist */
  10834. mg_send_http_error(conn,
  10835. 404,
  10836. "Error: Cannot delete file\nFile %s not found",
  10837. path);
  10838. return;
  10839. }
  10840. DEBUG_TRACE("delete %s", path);
  10841. if (de.file.is_directory) {
  10842. if (remove_directory(conn, path)) {
  10843. /* Delete is successful: Return 204 without content. */
  10844. mg_send_http_error(conn, 204, "%s", "");
  10845. } else {
  10846. /* Delete is not successful: Return 500 (Server error). */
  10847. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10848. }
  10849. return;
  10850. }
  10851. /* This is an existing file (not a directory).
  10852. * Check if write permission is granted. */
  10853. if (access(path, W_OK) != 0) {
  10854. /* File is read only */
  10855. mg_send_http_error(
  10856. conn,
  10857. 403,
  10858. "Error: Delete not possible\nDeleting %s is not allowed",
  10859. path);
  10860. return;
  10861. }
  10862. /* Try to delete it. */
  10863. if (mg_remove(conn, path) == 0) {
  10864. /* Delete was successful: Return 204 without content. */
  10865. mg_response_header_start(conn, 204);
  10866. send_no_cache_header(conn);
  10867. send_additional_header(conn);
  10868. mg_response_header_add(conn, "Content-Length", "0", -1);
  10869. mg_response_header_send(conn);
  10870. } else {
  10871. /* Delete not successful (file locked). */
  10872. mg_send_http_error(conn,
  10873. 423,
  10874. "Error: Cannot delete file\nremove(%s): %s",
  10875. path,
  10876. strerror(ERRNO));
  10877. }
  10878. }
  10879. #endif /* !NO_FILES */
  10880. #if !defined(NO_FILESYSTEMS)
  10881. static void
  10882. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10883. static void
  10884. do_ssi_include(struct mg_connection *conn,
  10885. const char *ssi,
  10886. char *tag,
  10887. int include_level)
  10888. {
  10889. char file_name[MG_BUF_LEN], path[512], *p;
  10890. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10891. size_t len;
  10892. int truncated = 0;
  10893. if (conn == NULL) {
  10894. return;
  10895. }
  10896. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10897. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10898. * always < MG_BUF_LEN. */
  10899. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10900. /* File name is relative to the webserver root */
  10901. file_name[511] = 0;
  10902. (void)mg_snprintf(conn,
  10903. &truncated,
  10904. path,
  10905. sizeof(path),
  10906. "%s/%s",
  10907. conn->dom_ctx->config[DOCUMENT_ROOT],
  10908. file_name);
  10909. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10910. /* File name is relative to the webserver working directory
  10911. * or it is absolute system path */
  10912. file_name[511] = 0;
  10913. (void)
  10914. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10915. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10916. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10917. /* File name is relative to the current document */
  10918. file_name[511] = 0;
  10919. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10920. if (!truncated) {
  10921. if ((p = strrchr(path, '/')) != NULL) {
  10922. p[1] = '\0';
  10923. }
  10924. len = strlen(path);
  10925. (void)mg_snprintf(conn,
  10926. &truncated,
  10927. path + len,
  10928. sizeof(path) - len,
  10929. "%s",
  10930. file_name);
  10931. }
  10932. } else {
  10933. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10934. return;
  10935. }
  10936. if (truncated) {
  10937. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10938. return;
  10939. }
  10940. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10941. mg_cry_internal(conn,
  10942. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10943. tag,
  10944. path,
  10945. strerror(ERRNO));
  10946. } else {
  10947. fclose_on_exec(&file.access, conn);
  10948. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10949. > 0) {
  10950. send_ssi_file(conn, path, &file, include_level + 1);
  10951. } else {
  10952. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10953. }
  10954. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10955. }
  10956. }
  10957. #if !defined(NO_POPEN)
  10958. static void
  10959. do_ssi_exec(struct mg_connection *conn, char *tag)
  10960. {
  10961. char cmd[1024] = "";
  10962. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10963. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10964. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10965. } else {
  10966. cmd[1023] = 0;
  10967. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10968. mg_cry_internal(conn,
  10969. "Cannot SSI #exec: [%s]: %s",
  10970. cmd,
  10971. strerror(ERRNO));
  10972. } else {
  10973. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10974. pclose(file.access.fp);
  10975. }
  10976. }
  10977. }
  10978. #endif /* !NO_POPEN */
  10979. static int
  10980. mg_fgetc(struct mg_file *filep)
  10981. {
  10982. if (filep == NULL) {
  10983. return EOF;
  10984. }
  10985. if (filep->access.fp != NULL) {
  10986. return fgetc(filep->access.fp);
  10987. } else {
  10988. return EOF;
  10989. }
  10990. }
  10991. static void
  10992. send_ssi_file(struct mg_connection *conn,
  10993. const char *path,
  10994. struct mg_file *filep,
  10995. int include_level)
  10996. {
  10997. char buf[MG_BUF_LEN];
  10998. int ch, len, in_tag, in_ssi_tag;
  10999. if (include_level > 10) {
  11000. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  11001. return;
  11002. }
  11003. in_tag = in_ssi_tag = len = 0;
  11004. /* Read file, byte by byte, and look for SSI include tags */
  11005. while ((ch = mg_fgetc(filep)) != EOF) {
  11006. if (in_tag) {
  11007. /* We are in a tag, either SSI tag or html tag */
  11008. if (ch == '>') {
  11009. /* Tag is closing */
  11010. buf[len++] = '>';
  11011. if (in_ssi_tag) {
  11012. /* Handle SSI tag */
  11013. buf[len] = 0;
  11014. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  11015. do_ssi_include(conn, path, buf + 12, include_level + 1);
  11016. #if !defined(NO_POPEN)
  11017. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  11018. do_ssi_exec(conn, buf + 9);
  11019. #endif /* !NO_POPEN */
  11020. } else {
  11021. mg_cry_internal(conn,
  11022. "%s: unknown SSI "
  11023. "command: \"%s\"",
  11024. path,
  11025. buf);
  11026. }
  11027. len = 0;
  11028. in_ssi_tag = in_tag = 0;
  11029. } else {
  11030. /* Not an SSI tag */
  11031. /* Flush buffer */
  11032. (void)mg_write(conn, buf, (size_t)len);
  11033. len = 0;
  11034. in_tag = 0;
  11035. }
  11036. } else {
  11037. /* Tag is still open */
  11038. buf[len++] = (char)(ch & 0xff);
  11039. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11040. /* All SSI tags start with <!--# */
  11041. in_ssi_tag = 1;
  11042. }
  11043. if ((len + 2) > (int)sizeof(buf)) {
  11044. /* Tag to long for buffer */
  11045. mg_cry_internal(conn, "%s: tag is too large", path);
  11046. return;
  11047. }
  11048. }
  11049. } else {
  11050. /* We are not in a tag yet. */
  11051. if (ch == '<') {
  11052. /* Tag is opening */
  11053. in_tag = 1;
  11054. if (len > 0) {
  11055. /* Flush current buffer.
  11056. * Buffer is filled with "len" bytes. */
  11057. (void)mg_write(conn, buf, (size_t)len);
  11058. }
  11059. /* Store the < */
  11060. len = 1;
  11061. buf[0] = '<';
  11062. } else {
  11063. /* No Tag */
  11064. /* Add data to buffer */
  11065. buf[len++] = (char)(ch & 0xff);
  11066. /* Flush if buffer is full */
  11067. if (len == (int)sizeof(buf)) {
  11068. mg_write(conn, buf, (size_t)len);
  11069. len = 0;
  11070. }
  11071. }
  11072. }
  11073. }
  11074. /* Send the rest of buffered data */
  11075. if (len > 0) {
  11076. mg_write(conn, buf, (size_t)len);
  11077. }
  11078. }
  11079. static void
  11080. handle_ssi_file_request(struct mg_connection *conn,
  11081. const char *path,
  11082. struct mg_file *filep)
  11083. {
  11084. char date[64];
  11085. time_t curtime = time(NULL);
  11086. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11087. return;
  11088. }
  11089. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11090. /* File exists (precondition for calling this function),
  11091. * but can not be opened by the server. */
  11092. mg_send_http_error(conn,
  11093. 500,
  11094. "Error: Cannot read file\nfopen(%s): %s",
  11095. path,
  11096. strerror(ERRNO));
  11097. } else {
  11098. /* Set "must_close" for HTTP/1.x, since we do not know the
  11099. * content length */
  11100. conn->must_close = 1;
  11101. gmt_time_string(date, sizeof(date), &curtime);
  11102. fclose_on_exec(&filep->access, conn);
  11103. /* 200 OK response */
  11104. mg_response_header_start(conn, 200);
  11105. send_no_cache_header(conn);
  11106. send_additional_header(conn);
  11107. send_cors_header(conn);
  11108. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11109. mg_response_header_send(conn);
  11110. /* Header sent, now send body */
  11111. send_ssi_file(conn, path, filep, 0);
  11112. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11113. }
  11114. }
  11115. #endif /* NO_FILESYSTEMS */
  11116. #if !defined(NO_FILES)
  11117. static void
  11118. send_options(struct mg_connection *conn)
  11119. {
  11120. if (!conn || !all_methods) {
  11121. return;
  11122. }
  11123. /* We do not set a "Cache-Control" header here, but leave the default.
  11124. * Since browsers do not send an OPTIONS request, we can not test the
  11125. * effect anyway. */
  11126. mg_response_header_start(conn, 200);
  11127. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11128. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11129. /* Use the same as before */
  11130. mg_response_header_add(conn, "Allow", all_methods, -1);
  11131. mg_response_header_add(conn, "DAV", "1", -1);
  11132. } else {
  11133. /* TODO: Check this later for HTTP/2 */
  11134. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11135. }
  11136. send_additional_header(conn);
  11137. mg_response_header_send(conn);
  11138. }
  11139. /* Writes PROPFIND properties for a collection element */
  11140. static int
  11141. print_props(struct mg_connection *conn,
  11142. const char *uri,
  11143. const char *name,
  11144. struct mg_file_stat *filep)
  11145. {
  11146. size_t i;
  11147. char mtime[64];
  11148. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11149. char *link_concat;
  11150. size_t link_concat_len;
  11151. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11152. return 0;
  11153. }
  11154. link_concat_len = strlen(uri) + strlen(name) + 1;
  11155. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11156. if (!link_concat) {
  11157. return 0;
  11158. }
  11159. strcpy(link_concat, uri);
  11160. strcat(link_concat, name);
  11161. /* Get full link used in request */
  11162. mg_construct_local_link(
  11163. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11164. /*
  11165. OutputDebugStringA("print_props:\n uri: ");
  11166. OutputDebugStringA(uri);
  11167. OutputDebugStringA("\n name: ");
  11168. OutputDebugStringA(name);
  11169. OutputDebugStringA("\n link: ");
  11170. OutputDebugStringA(link_buf);
  11171. OutputDebugStringA("\n");
  11172. */
  11173. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11174. mg_printf(conn,
  11175. "<d:response>"
  11176. "<d:href>%s</d:href>"
  11177. "<d:propstat>"
  11178. "<d:prop>"
  11179. "<d:resourcetype>%s</d:resourcetype>"
  11180. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11181. "<d:getlastmodified>%s</d:getlastmodified>"
  11182. "<d:lockdiscovery>",
  11183. link_buf,
  11184. filep->is_directory ? "<d:collection/>" : "",
  11185. filep->size,
  11186. mtime);
  11187. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11188. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11189. if (!strcmp(dav_lock[i].path, link_buf)) {
  11190. mg_printf(conn,
  11191. "<d:activelock>"
  11192. "<d:locktype><d:write/></d:locktype>"
  11193. "<d:lockscope><d:exclusive/></d:lockscope>"
  11194. "<d:depth>0</d:depth>"
  11195. "<d:owner>%s</d:owner>"
  11196. "<d:timeout>Second-%u</d:timeout>"
  11197. "<d:locktoken>"
  11198. "<d:href>%s</d:href>"
  11199. "</d:locktoken>"
  11200. "</d:activelock>\n",
  11201. dav_lock[i].user,
  11202. (unsigned)LOCK_DURATION_S,
  11203. dav_lock[i].token);
  11204. }
  11205. }
  11206. mg_printf(conn,
  11207. "</d:lockdiscovery>"
  11208. "</d:prop>"
  11209. "<d:status>HTTP/1.1 200 OK</d:status>"
  11210. "</d:propstat>"
  11211. "</d:response>\n");
  11212. mg_free(link_concat);
  11213. return 1;
  11214. }
  11215. static int
  11216. print_dav_dir_entry(struct de *de, void *data)
  11217. {
  11218. struct mg_connection *conn = (struct mg_connection *)data;
  11219. if (!de || !conn
  11220. || !print_props(
  11221. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11222. /* stop scan */
  11223. return 1;
  11224. }
  11225. return 0;
  11226. }
  11227. static void
  11228. handle_propfind(struct mg_connection *conn,
  11229. const char *path,
  11230. struct mg_file_stat *filep)
  11231. {
  11232. const char *depth = mg_get_header(conn, "Depth");
  11233. if (!conn || !path || !filep || !conn->dom_ctx) {
  11234. return;
  11235. }
  11236. /* return 207 "Multi-Status" */
  11237. conn->must_close = 1;
  11238. mg_response_header_start(conn, 207);
  11239. send_static_cache_header(conn);
  11240. send_additional_header(conn);
  11241. mg_response_header_add(conn,
  11242. "Content-Type",
  11243. "application/xml; charset=utf-8",
  11244. -1);
  11245. mg_response_header_send(conn);
  11246. /* Content */
  11247. mg_printf(conn,
  11248. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11249. "<d:multistatus xmlns:d='DAV:'>\n");
  11250. /* Print properties for the requested resource itself */
  11251. print_props(conn, conn->request_info.local_uri, "", filep);
  11252. /* If it is a directory, print directory entries too if Depth is not 0
  11253. */
  11254. if (filep->is_directory
  11255. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11256. "yes")
  11257. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11258. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11259. }
  11260. mg_printf(conn, "%s\n", "</d:multistatus>");
  11261. }
  11262. static void
  11263. dav_lock_file(struct mg_connection *conn, const char *path)
  11264. {
  11265. /* internal function - therefore conn is assumed to be valid */
  11266. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11267. uint64_t new_locktime;
  11268. int lock_index = -1;
  11269. int i;
  11270. uint64_t LOCK_DURATION_NS =
  11271. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11272. struct twebdav_lock *dav_lock = NULL;
  11273. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11274. || !conn->phys_ctx) {
  11275. return;
  11276. }
  11277. dav_lock = conn->phys_ctx->webdav_lock;
  11278. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11279. /* const char *refresh = mg_get_header(conn, "If"); */
  11280. /* Link refresh should have an "If" header:
  11281. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11282. * But it seems Windows Explorer does not send them.
  11283. */
  11284. mg_lock_context(conn->phys_ctx);
  11285. new_locktime = mg_get_current_time_ns();
  11286. /* Find a slot for a lock */
  11287. while (lock_index < 0) {
  11288. /* find existing lock */
  11289. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11290. if (!strcmp(dav_lock[i].path, link_buf)) {
  11291. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11292. /* locked by the same user */
  11293. dav_lock[i].locktime = new_locktime;
  11294. lock_index = i;
  11295. break;
  11296. } else {
  11297. /* already locked by someone else */
  11298. if (new_locktime
  11299. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11300. /* Lock expired */
  11301. dav_lock[i].path[0] = 0;
  11302. } else {
  11303. /* Lock still valid */
  11304. mg_unlock_context(conn->phys_ctx);
  11305. mg_send_http_error(conn, 423, "%s", "Already locked");
  11306. return;
  11307. }
  11308. }
  11309. }
  11310. }
  11311. /* create new lock token */
  11312. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11313. if (dav_lock[i].path[0] == 0) {
  11314. char s[32];
  11315. dav_lock[i].locktime = mg_get_current_time_ns();
  11316. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11317. mg_md5(dav_lock[i].token,
  11318. link_buf,
  11319. "\x01",
  11320. s,
  11321. "\x01",
  11322. conn->request_info.remote_user,
  11323. NULL);
  11324. mg_strlcpy(dav_lock[i].path,
  11325. link_buf,
  11326. sizeof(dav_lock[i].path));
  11327. mg_strlcpy(dav_lock[i].user,
  11328. conn->request_info.remote_user,
  11329. sizeof(dav_lock[i].user));
  11330. lock_index = i;
  11331. break;
  11332. }
  11333. }
  11334. if (lock_index < 0) {
  11335. /* too many locks. Find oldest lock */
  11336. uint64_t oldest_locktime = dav_lock[0].locktime;
  11337. lock_index = 0;
  11338. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11339. if (dav_lock[i].locktime < oldest_locktime) {
  11340. oldest_locktime = dav_lock[i].locktime;
  11341. lock_index = i;
  11342. }
  11343. }
  11344. /* invalidate oldest lock */
  11345. dav_lock[lock_index].path[0] = 0;
  11346. }
  11347. }
  11348. mg_unlock_context(conn->phys_ctx);
  11349. /* return 200 "OK" */
  11350. conn->must_close = 1;
  11351. mg_response_header_start(conn, 200);
  11352. send_static_cache_header(conn);
  11353. send_additional_header(conn);
  11354. mg_response_header_add(conn,
  11355. "Content-Type",
  11356. "application/xml; charset=utf-8",
  11357. -1);
  11358. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11359. mg_response_header_send(conn);
  11360. /* Content */
  11361. mg_printf(conn,
  11362. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11363. "<d:prop xmlns:d=\"DAV:\">\n"
  11364. " <d:lockdiscovery>\n"
  11365. " <d:activelock>\n"
  11366. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11367. " <d:locktype><d:write/></d:locktype>\n"
  11368. " <d:owner>\n"
  11369. " <d:href>%s</d:href>\n"
  11370. " </d:owner>\n"
  11371. " <d:timeout>Second-%u</d:timeout>\n"
  11372. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11373. " <d:lockroot>\n"
  11374. " <d:href>%s</d:href>\n"
  11375. " </d:lockroot>\n"
  11376. " </d:activelock>\n"
  11377. " </d:lockdiscovery>\n"
  11378. " </d:prop>\n",
  11379. dav_lock[lock_index].user,
  11380. (LOCK_DURATION_S),
  11381. dav_lock[lock_index].token,
  11382. dav_lock[lock_index].path);
  11383. }
  11384. static void
  11385. dav_unlock_file(struct mg_connection *conn, const char *path)
  11386. {
  11387. /* internal function - therefore conn is assumed to be valid */
  11388. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11389. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11390. int lock_index;
  11391. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11392. return;
  11393. }
  11394. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11395. mg_lock_context(conn->phys_ctx);
  11396. /* find existing lock */
  11397. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11398. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11399. /* Success: return 204 "No Content" */
  11400. mg_unlock_context(conn->phys_ctx);
  11401. conn->must_close = 1;
  11402. mg_response_header_start(conn, 204);
  11403. mg_response_header_send(conn);
  11404. return;
  11405. }
  11406. }
  11407. mg_unlock_context(conn->phys_ctx);
  11408. /* Error: Cannot unlock a resource that is not locked */
  11409. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11410. }
  11411. static void
  11412. dav_proppatch(struct mg_connection *conn, const char *path)
  11413. {
  11414. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11415. if (!conn || !path || !conn->dom_ctx) {
  11416. return;
  11417. }
  11418. /* return 207 "Multi-Status" */
  11419. conn->must_close = 1;
  11420. mg_response_header_start(conn, 207);
  11421. send_static_cache_header(conn);
  11422. send_additional_header(conn);
  11423. mg_response_header_add(conn,
  11424. "Content-Type",
  11425. "application/xml; charset=utf-8",
  11426. -1);
  11427. mg_response_header_send(conn);
  11428. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11429. /* Content */
  11430. mg_printf(conn,
  11431. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11432. "<d:multistatus xmlns:d='DAV:'>\n"
  11433. "<d:response>\n<d:href>%s</d:href>\n",
  11434. link_buf);
  11435. mg_printf(conn,
  11436. "<d:propstat><d:status>HTTP/1.1 403 "
  11437. "Forbidden</d:status></d:propstat>\n");
  11438. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11439. }
  11440. #endif
  11441. CIVETWEB_API void
  11442. mg_lock_connection(struct mg_connection *conn)
  11443. {
  11444. if (conn) {
  11445. (void)pthread_mutex_lock(&conn->mutex);
  11446. }
  11447. }
  11448. CIVETWEB_API void
  11449. mg_unlock_connection(struct mg_connection *conn)
  11450. {
  11451. if (conn) {
  11452. (void)pthread_mutex_unlock(&conn->mutex);
  11453. }
  11454. }
  11455. CIVETWEB_API void
  11456. mg_lock_context(struct mg_context *ctx)
  11457. {
  11458. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11459. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11460. }
  11461. }
  11462. CIVETWEB_API void
  11463. mg_unlock_context(struct mg_context *ctx)
  11464. {
  11465. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11466. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11467. }
  11468. }
  11469. #if defined(USE_LUA)
  11470. #include "mod_lua.inl"
  11471. #endif /* USE_LUA */
  11472. #if defined(USE_DUKTAPE)
  11473. #include "mod_duktape.inl"
  11474. #endif /* USE_DUKTAPE */
  11475. #if defined(USE_WEBSOCKET)
  11476. #if !defined(NO_SSL_DL)
  11477. #if !defined(OPENSSL_API_3_0)
  11478. #define SHA_API static
  11479. #include "sha1.inl"
  11480. #endif
  11481. #endif
  11482. static int
  11483. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11484. {
  11485. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11486. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11487. size_t dst_len = sizeof(b64_sha);
  11488. #if !defined(OPENSSL_API_3_0)
  11489. SHA_CTX sha_ctx;
  11490. #endif
  11491. int truncated;
  11492. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11493. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11494. if (truncated) {
  11495. conn->must_close = 1;
  11496. return 0;
  11497. }
  11498. DEBUG_TRACE("%s", "Send websocket handshake");
  11499. #if defined(OPENSSL_API_3_0)
  11500. EVP_Digest((unsigned char *)buf,
  11501. (uint32_t)strlen(buf),
  11502. (unsigned char *)sha,
  11503. NULL,
  11504. EVP_get_digestbyname("sha1"),
  11505. NULL);
  11506. #else
  11507. SHA1_Init(&sha_ctx);
  11508. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11509. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11510. #endif
  11511. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11512. mg_printf(conn,
  11513. "HTTP/1.1 101 Switching Protocols\r\n"
  11514. "Upgrade: websocket\r\n"
  11515. "Connection: Upgrade\r\n"
  11516. "Sec-WebSocket-Accept: %s\r\n",
  11517. b64_sha);
  11518. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11519. // Send negotiated compression extension parameters
  11520. websocket_deflate_response(conn);
  11521. #endif
  11522. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11523. mg_printf(conn,
  11524. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11525. conn->request_info.acceptedWebSocketSubprotocol);
  11526. } else {
  11527. mg_printf(conn, "%s", "\r\n");
  11528. }
  11529. return 1;
  11530. }
  11531. #if !defined(MG_MAX_UNANSWERED_PING)
  11532. /* Configuration of the maximum number of websocket PINGs that might
  11533. * stay unanswered before the connection is considered broken.
  11534. * Note: The name of this define may still change (until it is
  11535. * defined as a compile parameter in a documentation).
  11536. */
  11537. #define MG_MAX_UNANSWERED_PING (5)
  11538. #endif
  11539. static void
  11540. read_websocket(struct mg_connection *conn,
  11541. mg_websocket_data_handler ws_data_handler,
  11542. void *callback_data)
  11543. {
  11544. /* Pointer to the beginning of the portion of the incoming websocket
  11545. * message queue.
  11546. * The original websocket upgrade request is never removed, so the queue
  11547. * begins after it. */
  11548. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11549. int n, error, exit_by_callback;
  11550. int ret;
  11551. /* body_len is the length of the entire queue in bytes
  11552. * len is the length of the current message
  11553. * data_len is the length of the current message's data payload
  11554. * header_len is the length of the current message's header */
  11555. size_t i, len, mask_len = 0, header_len, body_len;
  11556. uint64_t data_len = 0;
  11557. /* "The masking key is a 32-bit value chosen at random by the client."
  11558. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11559. */
  11560. unsigned char mask[4];
  11561. /* data points to the place where the message is stored when passed to
  11562. * the websocket_data callback. This is either mem on the stack, or a
  11563. * dynamically allocated buffer if it is too large. */
  11564. unsigned char mem[4096];
  11565. unsigned char mop; /* mask flag and opcode */
  11566. /* Variables used for connection monitoring */
  11567. double timeout = -1.0;
  11568. int enable_ping_pong = 0;
  11569. int ping_count = 0;
  11570. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11571. enable_ping_pong =
  11572. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11573. "yes");
  11574. }
  11575. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11576. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11577. }
  11578. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11579. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11580. }
  11581. if (timeout <= 0.0) {
  11582. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11583. }
  11584. /* Enter data processing loop */
  11585. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11586. conn->request_info.remote_addr,
  11587. conn->request_info.remote_port);
  11588. conn->in_websocket_handling = 1;
  11589. mg_set_thread_name("wsock");
  11590. /* Loop continuously, reading messages from the socket, invoking the
  11591. * callback, and waiting repeatedly until an error occurs. */
  11592. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11593. && (!conn->must_close)) {
  11594. header_len = 0;
  11595. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11596. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11597. len = buf[1] & 127;
  11598. mask_len = (buf[1] & 128) ? 4 : 0;
  11599. if ((len < 126) && (body_len >= mask_len)) {
  11600. /* inline 7-bit length field */
  11601. data_len = len;
  11602. header_len = 2 + mask_len;
  11603. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11604. /* 16-bit length field */
  11605. header_len = 4 + mask_len;
  11606. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11607. } else if (body_len >= (10 + mask_len)) {
  11608. /* 64-bit length field */
  11609. uint32_t l1, l2;
  11610. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11611. memcpy(&l2, &buf[6], 4);
  11612. header_len = 10 + mask_len;
  11613. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11614. if (data_len > (uint64_t)0x7FFF0000ul) {
  11615. /* no can do */
  11616. mg_cry_internal(
  11617. conn,
  11618. "%s",
  11619. "websocket out of memory; closing connection");
  11620. break;
  11621. }
  11622. }
  11623. }
  11624. if ((header_len > 0) && (body_len >= header_len)) {
  11625. /* Allocate space to hold websocket payload */
  11626. unsigned char *data = mem;
  11627. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11628. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11629. conn->phys_ctx);
  11630. if (data == NULL) {
  11631. /* Allocation failed, exit the loop and then close the
  11632. * connection */
  11633. mg_cry_internal(
  11634. conn,
  11635. "%s",
  11636. "websocket out of memory; closing connection");
  11637. break;
  11638. }
  11639. }
  11640. /* Copy the mask before we shift the queue and destroy it */
  11641. if (mask_len > 0) {
  11642. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11643. } else {
  11644. memset(mask, 0, sizeof(mask));
  11645. }
  11646. /* Read frame payload from the first message in the queue into
  11647. * data and advance the queue by moving the memory in place. */
  11648. DEBUG_ASSERT(body_len >= header_len);
  11649. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11650. mop = buf[0]; /* current mask and opcode */
  11651. /* Overflow case */
  11652. len = body_len - header_len;
  11653. memcpy(data, buf + header_len, len);
  11654. error = 0;
  11655. while ((uint64_t)len < data_len) {
  11656. n = pull_inner(NULL,
  11657. conn,
  11658. (char *)(data + len),
  11659. (int)(data_len - len),
  11660. timeout);
  11661. if (n <= -2) {
  11662. error = 1;
  11663. break;
  11664. } else if (n > 0) {
  11665. len += (size_t)n;
  11666. } else {
  11667. /* Timeout: should retry */
  11668. /* TODO: retry condition */
  11669. }
  11670. }
  11671. if (error) {
  11672. mg_cry_internal(
  11673. conn,
  11674. "%s",
  11675. "Websocket pull failed; closing connection");
  11676. if (data != mem) {
  11677. mg_free(data);
  11678. }
  11679. break;
  11680. }
  11681. conn->data_len = conn->request_len;
  11682. } else {
  11683. mop = buf[0]; /* current mask and opcode, overwritten by
  11684. * memmove() */
  11685. /* Length of the message being read at the front of the
  11686. * queue. Cast to 31 bit is OK, since we limited
  11687. * data_len before. */
  11688. len = (size_t)data_len + header_len;
  11689. /* Copy the data payload into the data pointer for the
  11690. * callback. Cast to 31 bit is OK, since we
  11691. * limited data_len */
  11692. memcpy(data, buf + header_len, (size_t)data_len);
  11693. /* Move the queue forward len bytes */
  11694. memmove(buf, buf + len, body_len - len);
  11695. /* Mark the queue as advanced */
  11696. conn->data_len -= (int)len;
  11697. }
  11698. /* Apply mask if necessary */
  11699. if (mask_len > 0) {
  11700. for (i = 0; i < (size_t)data_len; i++) {
  11701. data[i] ^= mask[i & 3];
  11702. }
  11703. }
  11704. exit_by_callback = 0;
  11705. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11706. /* filter PONG messages */
  11707. DEBUG_TRACE("PONG from %s:%u",
  11708. conn->request_info.remote_addr,
  11709. conn->request_info.remote_port);
  11710. /* No unanwered PINGs left */
  11711. ping_count = 0;
  11712. } else if (enable_ping_pong
  11713. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11714. /* reply PING messages */
  11715. DEBUG_TRACE("Reply PING from %s:%u",
  11716. conn->request_info.remote_addr,
  11717. conn->request_info.remote_port);
  11718. ret = mg_websocket_write(conn,
  11719. MG_WEBSOCKET_OPCODE_PONG,
  11720. (char *)data,
  11721. (size_t)data_len);
  11722. if (ret <= 0) {
  11723. /* Error: send failed */
  11724. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11725. break;
  11726. }
  11727. } else {
  11728. /* Exit the loop if callback signals to exit (server side),
  11729. * or "connection close" opcode received (client side). */
  11730. if (ws_data_handler != NULL) {
  11731. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11732. if (mop & 0x40) {
  11733. /* Inflate the data received if bit RSV1 is set. */
  11734. if (!conn->websocket_deflate_initialized) {
  11735. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11736. exit_by_callback = 1;
  11737. }
  11738. if (!exit_by_callback) {
  11739. size_t inflate_buf_size_old = 0;
  11740. size_t inflate_buf_size =
  11741. data_len
  11742. * 4; // Initial guess of the inflated message
  11743. // size. We double the memory when needed.
  11744. Bytef *inflated = NULL;
  11745. Bytef *new_mem = NULL;
  11746. conn->websocket_inflate_state.avail_in =
  11747. (uInt)(data_len + 4);
  11748. conn->websocket_inflate_state.next_in = data;
  11749. // Add trailing 0x00 0x00 0xff 0xff bytes
  11750. data[data_len] = '\x00';
  11751. data[data_len + 1] = '\x00';
  11752. data[data_len + 2] = '\xff';
  11753. data[data_len + 3] = '\xff';
  11754. do {
  11755. if (inflate_buf_size_old == 0) {
  11756. new_mem =
  11757. (Bytef *)mg_calloc(inflate_buf_size,
  11758. sizeof(Bytef));
  11759. } else {
  11760. inflate_buf_size *= 2;
  11761. new_mem =
  11762. (Bytef *)mg_realloc(inflated,
  11763. inflate_buf_size);
  11764. }
  11765. if (new_mem == NULL) {
  11766. mg_cry_internal(
  11767. conn,
  11768. "Out of memory: Cannot allocate "
  11769. "inflate buffer of %lu bytes",
  11770. (unsigned long)inflate_buf_size);
  11771. exit_by_callback = 1;
  11772. break;
  11773. }
  11774. inflated = new_mem;
  11775. conn->websocket_inflate_state.avail_out =
  11776. (uInt)(inflate_buf_size
  11777. - inflate_buf_size_old);
  11778. conn->websocket_inflate_state.next_out =
  11779. inflated + inflate_buf_size_old;
  11780. ret = inflate(&conn->websocket_inflate_state,
  11781. Z_SYNC_FLUSH);
  11782. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11783. || ret == Z_MEM_ERROR) {
  11784. mg_cry_internal(
  11785. conn,
  11786. "ZLIB inflate error: %i %s",
  11787. ret,
  11788. (conn->websocket_inflate_state.msg
  11789. ? conn->websocket_inflate_state.msg
  11790. : "<no error message>"));
  11791. exit_by_callback = 1;
  11792. break;
  11793. }
  11794. inflate_buf_size_old = inflate_buf_size;
  11795. } while (conn->websocket_inflate_state.avail_out
  11796. == 0);
  11797. inflate_buf_size -=
  11798. conn->websocket_inflate_state.avail_out;
  11799. if (!ws_data_handler(conn,
  11800. mop,
  11801. (char *)inflated,
  11802. inflate_buf_size,
  11803. callback_data)) {
  11804. exit_by_callback = 1;
  11805. }
  11806. mg_free(inflated);
  11807. }
  11808. } else
  11809. #endif
  11810. if (!ws_data_handler(conn,
  11811. mop,
  11812. (char *)data,
  11813. (size_t)data_len,
  11814. callback_data)) {
  11815. exit_by_callback = 1;
  11816. }
  11817. }
  11818. }
  11819. /* It a buffer has been allocated, free it again */
  11820. if (data != mem) {
  11821. mg_free(data);
  11822. }
  11823. if (exit_by_callback) {
  11824. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11825. conn->request_info.remote_addr,
  11826. conn->request_info.remote_port);
  11827. break;
  11828. }
  11829. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11830. /* Opcode == 8, connection close */
  11831. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11832. conn->request_info.remote_addr,
  11833. conn->request_info.remote_port);
  11834. break;
  11835. }
  11836. /* Not breaking the loop, process next websocket frame. */
  11837. } else {
  11838. /* Read from the socket into the next available location in the
  11839. * message queue. */
  11840. n = pull_inner(NULL,
  11841. conn,
  11842. conn->buf + conn->data_len,
  11843. conn->buf_size - conn->data_len,
  11844. timeout);
  11845. if (n <= -2) {
  11846. /* Error, no bytes read */
  11847. DEBUG_TRACE("PULL from %s:%u failed",
  11848. conn->request_info.remote_addr,
  11849. conn->request_info.remote_port);
  11850. break;
  11851. }
  11852. if (n > 0) {
  11853. conn->data_len += n;
  11854. /* Reset open PING count */
  11855. ping_count = 0;
  11856. } else {
  11857. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11858. && (!conn->must_close)) {
  11859. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11860. /* Stop sending PING */
  11861. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11862. "- closing connection",
  11863. ping_count,
  11864. conn->request_info.remote_addr,
  11865. conn->request_info.remote_port);
  11866. break;
  11867. }
  11868. if (enable_ping_pong) {
  11869. /* Send Websocket PING message */
  11870. DEBUG_TRACE("PING to %s:%u",
  11871. conn->request_info.remote_addr,
  11872. conn->request_info.remote_port);
  11873. ret = mg_websocket_write(conn,
  11874. MG_WEBSOCKET_OPCODE_PING,
  11875. NULL,
  11876. 0);
  11877. if (ret <= 0) {
  11878. /* Error: send failed */
  11879. DEBUG_TRACE("Send PING failed (%i)", ret);
  11880. break;
  11881. }
  11882. ping_count++;
  11883. }
  11884. }
  11885. /* Timeout: should retry */
  11886. /* TODO: get timeout def */
  11887. }
  11888. }
  11889. }
  11890. /* Leave data processing loop */
  11891. mg_set_thread_name("worker");
  11892. conn->in_websocket_handling = 0;
  11893. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11894. conn->request_info.remote_addr,
  11895. conn->request_info.remote_port);
  11896. }
  11897. static int
  11898. mg_websocket_write_exec(struct mg_connection *conn,
  11899. int opcode,
  11900. const char *data,
  11901. size_t dataLen,
  11902. uint32_t masking_key)
  11903. {
  11904. unsigned char header[14];
  11905. size_t headerLen;
  11906. int retval;
  11907. #if defined(GCC_DIAGNOSTIC)
  11908. /* Disable spurious conversion warning for GCC */
  11909. #pragma GCC diagnostic push
  11910. #pragma GCC diagnostic ignored "-Wconversion"
  11911. #endif
  11912. /* Note that POSIX/Winsock's send() is threadsafe
  11913. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11914. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11915. * push(), although that is only a problem if the packet is large or
  11916. * outgoing buffer is full). */
  11917. /* TODO: Check if this lock should be moved to user land.
  11918. * Currently the server sets this lock for websockets, but
  11919. * not for any other connection. It must be set for every
  11920. * conn read/written by more than one thread, no matter if
  11921. * it is a websocket or regular connection. */
  11922. (void)mg_lock_connection(conn);
  11923. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11924. size_t deflated_size = 0;
  11925. Bytef *deflated = 0;
  11926. // Deflate websocket messages over 100kb
  11927. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11928. if (use_deflate) {
  11929. if (!conn->websocket_deflate_initialized) {
  11930. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11931. return 0;
  11932. }
  11933. // Deflating the message
  11934. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11935. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11936. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11937. deflated_size = (size_t)compressBound((uLong)dataLen);
  11938. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11939. if (deflated == NULL) {
  11940. mg_cry_internal(
  11941. conn,
  11942. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11943. (unsigned long)deflated_size);
  11944. mg_unlock_connection(conn);
  11945. return -1;
  11946. }
  11947. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11948. conn->websocket_deflate_state.next_out = deflated;
  11949. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11950. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11951. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11952. } else
  11953. #endif
  11954. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11955. #if defined(GCC_DIAGNOSTIC)
  11956. #pragma GCC diagnostic pop
  11957. #endif
  11958. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11959. if (dataLen < 126) {
  11960. /* inline 7-bit length field */
  11961. header[1] = (unsigned char)dataLen;
  11962. headerLen = 2;
  11963. } else if (dataLen <= 0xFFFF) {
  11964. /* 16-bit length field */
  11965. uint16_t len = htons((uint16_t)dataLen);
  11966. header[1] = 126;
  11967. memcpy(header + 2, &len, 2);
  11968. headerLen = 4;
  11969. } else {
  11970. /* 64-bit length field */
  11971. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11972. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11973. header[1] = 127;
  11974. memcpy(header + 2, &len1, 4);
  11975. memcpy(header + 6, &len2, 4);
  11976. headerLen = 10;
  11977. }
  11978. if (masking_key) {
  11979. /* add mask */
  11980. header[1] |= 0x80;
  11981. memcpy(header + headerLen, &masking_key, 4);
  11982. headerLen += 4;
  11983. }
  11984. retval = mg_write(conn, header, headerLen);
  11985. if (retval != (int)headerLen) {
  11986. /* Did not send complete header */
  11987. retval = -1;
  11988. } else {
  11989. if (dataLen > 0) {
  11990. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11991. if (use_deflate) {
  11992. retval = mg_write(conn, deflated, dataLen);
  11993. mg_free(deflated);
  11994. } else
  11995. #endif
  11996. retval = mg_write(conn, data, dataLen);
  11997. }
  11998. /* if dataLen == 0, the header length (2) is returned */
  11999. }
  12000. /* TODO: Remove this unlock as well, when lock is removed. */
  12001. mg_unlock_connection(conn);
  12002. return retval;
  12003. }
  12004. CIVETWEB_API int
  12005. mg_websocket_write(struct mg_connection *conn,
  12006. int opcode,
  12007. const char *data,
  12008. size_t dataLen)
  12009. {
  12010. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  12011. }
  12012. static void
  12013. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  12014. {
  12015. size_t i = 0;
  12016. i = 0;
  12017. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  12018. /* Convert in 32 bit words, if data is 4 byte aligned */
  12019. while (i < (in_len - 3)) {
  12020. *(uint32_t *)(void *)(out + i) =
  12021. *(uint32_t *)(void *)(in + i) ^ masking_key;
  12022. i += 4;
  12023. }
  12024. }
  12025. if (i != in_len) {
  12026. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  12027. while (i < in_len) {
  12028. *(uint8_t *)(void *)(out + i) =
  12029. *(uint8_t *)(void *)(in + i)
  12030. ^ *(((uint8_t *)&masking_key) + (i % 4));
  12031. i++;
  12032. }
  12033. }
  12034. }
  12035. CIVETWEB_API int
  12036. mg_websocket_client_write(struct mg_connection *conn,
  12037. int opcode,
  12038. const char *data,
  12039. size_t dataLen)
  12040. {
  12041. int retval = -1;
  12042. char *masked_data =
  12043. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12044. uint32_t masking_key = 0;
  12045. if (masked_data == NULL) {
  12046. /* Return -1 in an error case */
  12047. mg_cry_internal(conn,
  12048. "%s",
  12049. "Cannot allocate buffer for masked websocket response: "
  12050. "Out of memory");
  12051. return -1;
  12052. }
  12053. do {
  12054. /* Get a masking key - but not 0 */
  12055. masking_key = (uint32_t)get_random();
  12056. } while (masking_key == 0);
  12057. mask_data(data, dataLen, masking_key, masked_data);
  12058. retval = mg_websocket_write_exec(
  12059. conn, opcode, masked_data, dataLen, masking_key);
  12060. mg_free(masked_data);
  12061. return retval;
  12062. }
  12063. static void
  12064. handle_websocket_request(struct mg_connection *conn,
  12065. const char *path,
  12066. int is_callback_resource,
  12067. struct mg_websocket_subprotocols *subprotocols,
  12068. mg_websocket_connect_handler ws_connect_handler,
  12069. mg_websocket_ready_handler ws_ready_handler,
  12070. mg_websocket_data_handler ws_data_handler,
  12071. mg_websocket_close_handler ws_close_handler,
  12072. void *cbData)
  12073. {
  12074. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12075. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12076. ptrdiff_t lua_websock = 0;
  12077. #if !defined(USE_LUA)
  12078. (void)path;
  12079. #endif
  12080. /* Step 1: Check websocket protocol version. */
  12081. /* Step 1.1: Check Sec-WebSocket-Key. */
  12082. if (!websock_key) {
  12083. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12084. * requires a Sec-WebSocket-Key header.
  12085. */
  12086. /* It could be the hixie draft version
  12087. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12088. */
  12089. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12090. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12091. char key3[8];
  12092. if ((key1 != NULL) && (key2 != NULL)) {
  12093. /* This version uses 8 byte body data in a GET request */
  12094. conn->content_len = 8;
  12095. if (8 == mg_read(conn, key3, 8)) {
  12096. /* This is the hixie version */
  12097. mg_send_http_error(conn,
  12098. 426,
  12099. "%s",
  12100. "Protocol upgrade to RFC 6455 required");
  12101. return;
  12102. }
  12103. }
  12104. /* This is an unknown version */
  12105. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12106. return;
  12107. }
  12108. /* Step 1.2: Check websocket protocol version. */
  12109. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12110. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12111. /* Reject wrong versions */
  12112. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12113. return;
  12114. }
  12115. /* Step 1.3: Could check for "Host", but we do not really need this
  12116. * value for anything, so just ignore it. */
  12117. /* Step 2: If a callback is responsible, call it. */
  12118. if (is_callback_resource) {
  12119. /* Step 2.1 check and select subprotocol */
  12120. const char *protocols[64]; // max 64 headers
  12121. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12122. "Sec-WebSocket-Protocol",
  12123. protocols,
  12124. 64);
  12125. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12126. int headerNo, idx;
  12127. size_t len;
  12128. const char *sep, *curSubProtocol,
  12129. *acceptedWebSocketSubprotocol = NULL;
  12130. /* look for matching subprotocol */
  12131. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12132. /* There might be multiple headers ... */
  12133. const char *protocol = protocols[headerNo];
  12134. curSubProtocol = protocol;
  12135. /* ... and in every header there might be a , separated list */
  12136. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12137. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12138. curSubProtocol++;
  12139. sep = strchr(curSubProtocol, ',');
  12140. if (sep) {
  12141. len = (size_t)(sep - curSubProtocol);
  12142. } else {
  12143. len = strlen(curSubProtocol);
  12144. }
  12145. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12146. // COMPARE: curSubProtocol ==
  12147. // subprotocols->subprotocols[idx]
  12148. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12149. && (strncmp(curSubProtocol,
  12150. subprotocols->subprotocols[idx],
  12151. len)
  12152. == 0)) {
  12153. acceptedWebSocketSubprotocol =
  12154. subprotocols->subprotocols[idx];
  12155. break;
  12156. }
  12157. }
  12158. curSubProtocol += len;
  12159. }
  12160. }
  12161. conn->request_info.acceptedWebSocketSubprotocol =
  12162. acceptedWebSocketSubprotocol;
  12163. }
  12164. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12165. websocket_deflate_negotiate(conn);
  12166. #endif
  12167. if ((ws_connect_handler != NULL)
  12168. && (ws_connect_handler(conn, cbData) != 0)) {
  12169. /* C callback has returned non-zero, do not proceed with
  12170. * handshake.
  12171. */
  12172. /* Note that C callbacks are no longer called when Lua is
  12173. * responsible, so C can no longer filter callbacks for Lua. */
  12174. return;
  12175. }
  12176. }
  12177. #if defined(USE_LUA)
  12178. /* Step 3: No callback. Check if Lua is responsible. */
  12179. else {
  12180. /* Step 3.1: Check if Lua is responsible. */
  12181. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12182. lua_websock = match_prefix_strlen(
  12183. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12184. }
  12185. if (lua_websock > 0) {
  12186. /* Step 3.2: Lua is responsible: call it. */
  12187. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12188. if (!conn->lua_websocket_state) {
  12189. /* Lua rejected the new client */
  12190. return;
  12191. }
  12192. }
  12193. }
  12194. #endif
  12195. /* Step 4: Check if there is a responsible websocket handler. */
  12196. if (!is_callback_resource && !lua_websock) {
  12197. /* There is no callback, and Lua is not responsible either. */
  12198. /* Reply with a 404 Not Found. We are still at a standard
  12199. * HTTP request here, before the websocket handshake, so
  12200. * we can still send standard HTTP error replies. */
  12201. mg_send_http_error(conn, 404, "%s", "Not found");
  12202. return;
  12203. }
  12204. /* Step 5: The websocket connection has been accepted */
  12205. if (!send_websocket_handshake(conn, websock_key)) {
  12206. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12207. return;
  12208. }
  12209. /* Step 6: Call the ready handler */
  12210. if (is_callback_resource) {
  12211. if (ws_ready_handler != NULL) {
  12212. ws_ready_handler(conn, cbData);
  12213. }
  12214. #if defined(USE_LUA)
  12215. } else if (lua_websock) {
  12216. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12217. /* the ready handler returned false */
  12218. return;
  12219. }
  12220. #endif
  12221. }
  12222. /* Step 7: Enter the read loop */
  12223. if (is_callback_resource) {
  12224. read_websocket(conn, ws_data_handler, cbData);
  12225. #if defined(USE_LUA)
  12226. } else if (lua_websock) {
  12227. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12228. #endif
  12229. }
  12230. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12231. /* Step 8: Close the deflate & inflate buffers */
  12232. if (conn->websocket_deflate_initialized) {
  12233. deflateEnd(&conn->websocket_deflate_state);
  12234. inflateEnd(&conn->websocket_inflate_state);
  12235. }
  12236. #endif
  12237. /* Step 9: Call the close handler */
  12238. if (ws_close_handler) {
  12239. ws_close_handler(conn, cbData);
  12240. }
  12241. }
  12242. #endif /* !USE_WEBSOCKET */
  12243. /* Is upgrade request:
  12244. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12245. * 1 = upgrade to websocket
  12246. * 2 = upgrade to HTTP/2
  12247. * -1 = upgrade to unknown protocol
  12248. */
  12249. static int
  12250. should_switch_to_protocol(const struct mg_connection *conn)
  12251. {
  12252. const char *connection_headers[8];
  12253. const char *upgrade_to;
  12254. int connection_header_count, i, should_upgrade;
  12255. /* A websocket protocol has the following HTTP headers:
  12256. *
  12257. * Connection: Upgrade
  12258. * Upgrade: Websocket
  12259. *
  12260. * It seems some clients use multiple headers:
  12261. * see https://github.com/civetweb/civetweb/issues/1083
  12262. */
  12263. connection_header_count = get_req_headers(&conn->request_info,
  12264. "Connection",
  12265. connection_headers,
  12266. 8);
  12267. should_upgrade = 0;
  12268. for (i = 0; i < connection_header_count; i++) {
  12269. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12270. should_upgrade = 1;
  12271. }
  12272. }
  12273. if (!should_upgrade) {
  12274. return PROTOCOL_TYPE_HTTP1;
  12275. }
  12276. upgrade_to = mg_get_header(conn, "Upgrade");
  12277. if (upgrade_to == NULL) {
  12278. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12279. return -1;
  12280. }
  12281. /* Upgrade to ... */
  12282. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12283. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12284. * "Sec-WebSocket-Version" are also required.
  12285. * Don't check them here, since even an unsupported websocket protocol
  12286. * request still IS a websocket request (in contrast to a standard HTTP
  12287. * request). It will fail later in handle_websocket_request.
  12288. */
  12289. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12290. }
  12291. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12292. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12293. }
  12294. /* Upgrade to another protocol */
  12295. return -1;
  12296. }
  12297. static int
  12298. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12299. {
  12300. int n;
  12301. unsigned int a, b, c, d, slash;
  12302. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12303. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12304. // integer value, but function will not report conversion
  12305. // errors; consider using 'strtol' instead
  12306. slash = 32;
  12307. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12308. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12309. // an integer value, but function will not report conversion
  12310. // errors; consider using 'strtol' instead
  12311. n = 0;
  12312. }
  12313. }
  12314. if ((n > 0) && ((size_t)n == vec->len)) {
  12315. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12316. /* IPv4 format */
  12317. if (sa->sa.sa_family == AF_INET) {
  12318. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12319. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12320. | ((uint32_t)c << 8) | (uint32_t)d;
  12321. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12322. return (ip & mask) == net;
  12323. }
  12324. return 0;
  12325. }
  12326. }
  12327. #if defined(USE_IPV6)
  12328. else {
  12329. char ad[50];
  12330. const char *p;
  12331. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12332. slash = 128;
  12333. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12334. n = 0;
  12335. }
  12336. }
  12337. if ((n <= 0) && no_strict) {
  12338. /* no square brackets? */
  12339. p = strchr(vec->ptr, '/');
  12340. if (p && (p < (vec->ptr + vec->len))) {
  12341. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12342. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12343. n += (int)(p - vec->ptr);
  12344. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12345. } else {
  12346. n = 0;
  12347. }
  12348. } else if (vec->len < sizeof(ad)) {
  12349. n = (int)vec->len;
  12350. slash = 128;
  12351. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12352. }
  12353. }
  12354. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12355. p = ad;
  12356. c = 0;
  12357. /* zone indexes are unsupported, at least two colons are needed */
  12358. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12359. if (*(p++) == ':') {
  12360. c++;
  12361. }
  12362. }
  12363. if ((*p == '\0') && (c >= 2)) {
  12364. struct sockaddr_in6 sin6;
  12365. unsigned int i;
  12366. /* for strict validation, an actual IPv6 argument is needed */
  12367. if (sa->sa.sa_family != AF_INET6) {
  12368. return 0;
  12369. }
  12370. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12371. /* IPv6 format */
  12372. for (i = 0; i < 16; i++) {
  12373. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12374. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12375. uint8_t mask = 0;
  12376. if (8 * i + 8 < slash) {
  12377. mask = 0xFFu;
  12378. } else if (8 * i < slash) {
  12379. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12380. }
  12381. if ((ip & mask) != net) {
  12382. return 0;
  12383. }
  12384. }
  12385. return 1;
  12386. }
  12387. }
  12388. }
  12389. }
  12390. #else
  12391. (void)no_strict;
  12392. #endif
  12393. /* malformed */
  12394. return -1;
  12395. }
  12396. static int
  12397. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12398. {
  12399. int throttle = 0;
  12400. struct vec vec, val;
  12401. char mult;
  12402. double v;
  12403. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12404. mult = ',';
  12405. if ((val.ptr == NULL)
  12406. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12407. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12408. // to an integer value, but function will not report
  12409. // conversion errors; consider using 'strtol' instead
  12410. || (v < 0)
  12411. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12412. && (mult != ','))) {
  12413. continue;
  12414. }
  12415. v *= (lowercase(&mult) == 'k')
  12416. ? 1024
  12417. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12418. if (vec.len == 1 && vec.ptr[0] == '*') {
  12419. throttle = (int)v;
  12420. } else {
  12421. int matched = parse_match_net(&vec, rsa, 0);
  12422. if (matched >= 0) {
  12423. /* a valid IP subnet */
  12424. if (matched) {
  12425. throttle = (int)v;
  12426. }
  12427. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12428. throttle = (int)v;
  12429. }
  12430. }
  12431. }
  12432. return throttle;
  12433. }
  12434. /* The mg_upload function is superseded by mg_handle_form_request. */
  12435. #include "handle_form.inl"
  12436. static int
  12437. get_first_ssl_listener_index(const struct mg_context *ctx)
  12438. {
  12439. unsigned int i;
  12440. int idx = -1;
  12441. if (ctx) {
  12442. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12443. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12444. }
  12445. }
  12446. return idx;
  12447. }
  12448. /* Return host (without port) */
  12449. static void
  12450. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12451. {
  12452. const char *host_header =
  12453. get_header(ri->http_headers, ri->num_headers, "Host");
  12454. host->ptr = NULL;
  12455. host->len = 0;
  12456. if (host_header != NULL) {
  12457. const char *pos;
  12458. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12459. * is found. */
  12460. if (*host_header == '[') {
  12461. pos = strchr(host_header, ']');
  12462. if (!pos) {
  12463. /* Malformed hostname starts with '[', but no ']' found */
  12464. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12465. return;
  12466. }
  12467. /* terminate after ']' */
  12468. host->ptr = host_header;
  12469. host->len = (size_t)(pos + 1 - host_header);
  12470. } else {
  12471. /* Otherwise, a ':' separates hostname and port number */
  12472. pos = strchr(host_header, ':');
  12473. if (pos != NULL) {
  12474. host->len = (size_t)(pos - host_header);
  12475. } else {
  12476. host->len = strlen(host_header);
  12477. }
  12478. host->ptr = host_header;
  12479. }
  12480. }
  12481. }
  12482. static int
  12483. switch_domain_context(struct mg_connection *conn)
  12484. {
  12485. struct vec host;
  12486. get_host_from_request_info(&host, &conn->request_info);
  12487. if (host.ptr) {
  12488. if (conn->ssl) {
  12489. /* This is a HTTPS connection, maybe we have a hostname
  12490. * from SNI (set in ssl_servername_callback). */
  12491. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12492. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12493. /* We are not using the default domain */
  12494. if ((strlen(sslhost) != host.len)
  12495. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12496. /* Mismatch between SNI domain and HTTP domain */
  12497. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12498. sslhost,
  12499. (int)host.len,
  12500. host.ptr);
  12501. return 0;
  12502. }
  12503. }
  12504. } else {
  12505. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12506. while (dom) {
  12507. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12508. size_t domNameLen = strlen(domName);
  12509. if ((domNameLen == host.len)
  12510. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12511. /* Found matching domain */
  12512. DEBUG_TRACE("HTTP domain %s found",
  12513. dom->config[AUTHENTICATION_DOMAIN]);
  12514. /* TODO: Check if this is a HTTP or HTTPS domain */
  12515. conn->dom_ctx = dom;
  12516. break;
  12517. }
  12518. mg_lock_context(conn->phys_ctx);
  12519. dom = dom->next;
  12520. mg_unlock_context(conn->phys_ctx);
  12521. }
  12522. }
  12523. DEBUG_TRACE("HTTP%s Host: %.*s",
  12524. conn->ssl ? "S" : "",
  12525. (int)host.len,
  12526. host.ptr);
  12527. } else {
  12528. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12529. return 1;
  12530. }
  12531. return 1;
  12532. }
  12533. static void
  12534. redirect_to_https_port(struct mg_connection *conn, int port)
  12535. {
  12536. char target_url[MG_BUF_LEN];
  12537. int truncated = 0;
  12538. const char *expect_proto =
  12539. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12540. /* Use "308 Permanent Redirect" */
  12541. int redirect_code = 308;
  12542. /* In any case, close the current connection */
  12543. conn->must_close = 1;
  12544. /* Send host, port, uri and (if it exists) ?query_string */
  12545. if (mg_construct_local_link(
  12546. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12547. < 0) {
  12548. truncated = 1;
  12549. } else if (conn->request_info.query_string != NULL) {
  12550. size_t slen1 = strlen(target_url);
  12551. size_t slen2 = strlen(conn->request_info.query_string);
  12552. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12553. target_url[slen1] = '?';
  12554. memcpy(target_url + slen1 + 1,
  12555. conn->request_info.query_string,
  12556. slen2);
  12557. target_url[slen1 + slen2 + 1] = 0;
  12558. } else {
  12559. truncated = 1;
  12560. }
  12561. }
  12562. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12563. * is used as buffer size) */
  12564. if (truncated) {
  12565. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12566. return;
  12567. }
  12568. /* Use redirect helper function */
  12569. mg_send_http_redirect(conn, target_url, redirect_code);
  12570. }
  12571. static void
  12572. mg_set_handler_type(struct mg_context *phys_ctx,
  12573. struct mg_domain_context *dom_ctx,
  12574. const char *uri,
  12575. int handler_type,
  12576. int is_delete_request,
  12577. mg_request_handler handler,
  12578. struct mg_websocket_subprotocols *subprotocols,
  12579. mg_websocket_connect_handler connect_handler,
  12580. mg_websocket_ready_handler ready_handler,
  12581. mg_websocket_data_handler data_handler,
  12582. mg_websocket_close_handler close_handler,
  12583. mg_authorization_handler auth_handler,
  12584. void *cbdata)
  12585. {
  12586. struct mg_handler_info *tmp_rh, **lastref;
  12587. size_t urilen = strlen(uri);
  12588. if (handler_type == WEBSOCKET_HANDLER) {
  12589. DEBUG_ASSERT(handler == NULL);
  12590. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12591. || ready_handler != NULL || data_handler != NULL
  12592. || close_handler != NULL);
  12593. DEBUG_ASSERT(auth_handler == NULL);
  12594. if (handler != NULL) {
  12595. return;
  12596. }
  12597. if (!is_delete_request && (connect_handler == NULL)
  12598. && (ready_handler == NULL) && (data_handler == NULL)
  12599. && (close_handler == NULL)) {
  12600. return;
  12601. }
  12602. if (auth_handler != NULL) {
  12603. return;
  12604. }
  12605. } else if (handler_type == REQUEST_HANDLER) {
  12606. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12607. && data_handler == NULL && close_handler == NULL);
  12608. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12609. DEBUG_ASSERT(auth_handler == NULL);
  12610. if ((connect_handler != NULL) || (ready_handler != NULL)
  12611. || (data_handler != NULL) || (close_handler != NULL)) {
  12612. return;
  12613. }
  12614. if (!is_delete_request && (handler == NULL)) {
  12615. return;
  12616. }
  12617. if (auth_handler != NULL) {
  12618. return;
  12619. }
  12620. } else if (handler_type == AUTH_HANDLER) {
  12621. DEBUG_ASSERT(handler == NULL);
  12622. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12623. && data_handler == NULL && close_handler == NULL);
  12624. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12625. if (handler != NULL) {
  12626. return;
  12627. }
  12628. if ((connect_handler != NULL) || (ready_handler != NULL)
  12629. || (data_handler != NULL) || (close_handler != NULL)) {
  12630. return;
  12631. }
  12632. if (!is_delete_request && (auth_handler == NULL)) {
  12633. return;
  12634. }
  12635. } else {
  12636. /* Unknown handler type. */
  12637. return;
  12638. }
  12639. if (!phys_ctx || !dom_ctx) {
  12640. /* no context available */
  12641. return;
  12642. }
  12643. mg_lock_context(phys_ctx);
  12644. /* first try to find an existing handler */
  12645. do {
  12646. lastref = &(dom_ctx->handlers);
  12647. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12648. tmp_rh = tmp_rh->next) {
  12649. if (tmp_rh->handler_type == handler_type
  12650. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12651. if (!is_delete_request) {
  12652. /* update existing handler */
  12653. if (handler_type == REQUEST_HANDLER) {
  12654. /* Wait for end of use before updating */
  12655. if (tmp_rh->refcount) {
  12656. mg_unlock_context(phys_ctx);
  12657. mg_sleep(1);
  12658. mg_lock_context(phys_ctx);
  12659. /* tmp_rh might have been freed, search again. */
  12660. break;
  12661. }
  12662. /* Ok, the handler is no more use -> Update it */
  12663. tmp_rh->handler = handler;
  12664. } else if (handler_type == WEBSOCKET_HANDLER) {
  12665. tmp_rh->subprotocols = subprotocols;
  12666. tmp_rh->connect_handler = connect_handler;
  12667. tmp_rh->ready_handler = ready_handler;
  12668. tmp_rh->data_handler = data_handler;
  12669. tmp_rh->close_handler = close_handler;
  12670. } else { /* AUTH_HANDLER */
  12671. tmp_rh->auth_handler = auth_handler;
  12672. }
  12673. tmp_rh->cbdata = cbdata;
  12674. } else {
  12675. /* remove existing handler */
  12676. if (handler_type == REQUEST_HANDLER) {
  12677. /* Wait for end of use before removing */
  12678. if (tmp_rh->refcount) {
  12679. tmp_rh->removing = 1;
  12680. mg_unlock_context(phys_ctx);
  12681. mg_sleep(1);
  12682. mg_lock_context(phys_ctx);
  12683. /* tmp_rh might have been freed, search again. */
  12684. break;
  12685. }
  12686. /* Ok, the handler is no more used */
  12687. }
  12688. *lastref = tmp_rh->next;
  12689. mg_free(tmp_rh->uri);
  12690. mg_free(tmp_rh);
  12691. }
  12692. mg_unlock_context(phys_ctx);
  12693. return;
  12694. }
  12695. lastref = &(tmp_rh->next);
  12696. }
  12697. } while (tmp_rh != NULL);
  12698. if (is_delete_request) {
  12699. /* no handler to set, this was a remove request to a non-existing
  12700. * handler */
  12701. mg_unlock_context(phys_ctx);
  12702. return;
  12703. }
  12704. tmp_rh =
  12705. (struct mg_handler_info *)mg_calloc_ctx(1,
  12706. sizeof(struct mg_handler_info),
  12707. phys_ctx);
  12708. if (tmp_rh == NULL) {
  12709. mg_unlock_context(phys_ctx);
  12710. mg_cry_ctx_internal(phys_ctx,
  12711. "%s",
  12712. "Cannot create new request handler struct, OOM");
  12713. return;
  12714. }
  12715. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12716. if (!tmp_rh->uri) {
  12717. mg_unlock_context(phys_ctx);
  12718. mg_free(tmp_rh);
  12719. mg_cry_ctx_internal(phys_ctx,
  12720. "%s",
  12721. "Cannot create new request handler struct, OOM");
  12722. return;
  12723. }
  12724. tmp_rh->uri_len = urilen;
  12725. if (handler_type == REQUEST_HANDLER) {
  12726. tmp_rh->refcount = 0;
  12727. tmp_rh->removing = 0;
  12728. tmp_rh->handler = handler;
  12729. } else if (handler_type == WEBSOCKET_HANDLER) {
  12730. tmp_rh->subprotocols = subprotocols;
  12731. tmp_rh->connect_handler = connect_handler;
  12732. tmp_rh->ready_handler = ready_handler;
  12733. tmp_rh->data_handler = data_handler;
  12734. tmp_rh->close_handler = close_handler;
  12735. } else { /* AUTH_HANDLER */
  12736. tmp_rh->auth_handler = auth_handler;
  12737. }
  12738. tmp_rh->cbdata = cbdata;
  12739. tmp_rh->handler_type = handler_type;
  12740. tmp_rh->next = NULL;
  12741. *lastref = tmp_rh;
  12742. mg_unlock_context(phys_ctx);
  12743. }
  12744. CIVETWEB_API void
  12745. mg_set_request_handler(struct mg_context *ctx,
  12746. const char *uri,
  12747. mg_request_handler handler,
  12748. void *cbdata)
  12749. {
  12750. mg_set_handler_type(ctx,
  12751. &(ctx->dd),
  12752. uri,
  12753. REQUEST_HANDLER,
  12754. handler == NULL,
  12755. handler,
  12756. NULL,
  12757. NULL,
  12758. NULL,
  12759. NULL,
  12760. NULL,
  12761. NULL,
  12762. cbdata);
  12763. }
  12764. CIVETWEB_API void
  12765. mg_set_websocket_handler(struct mg_context *ctx,
  12766. const char *uri,
  12767. mg_websocket_connect_handler connect_handler,
  12768. mg_websocket_ready_handler ready_handler,
  12769. mg_websocket_data_handler data_handler,
  12770. mg_websocket_close_handler close_handler,
  12771. void *cbdata)
  12772. {
  12773. mg_set_websocket_handler_with_subprotocols(ctx,
  12774. uri,
  12775. NULL,
  12776. connect_handler,
  12777. ready_handler,
  12778. data_handler,
  12779. close_handler,
  12780. cbdata);
  12781. }
  12782. CIVETWEB_API void
  12783. mg_set_websocket_handler_with_subprotocols(
  12784. struct mg_context *ctx,
  12785. const char *uri,
  12786. struct mg_websocket_subprotocols *subprotocols,
  12787. mg_websocket_connect_handler connect_handler,
  12788. mg_websocket_ready_handler ready_handler,
  12789. mg_websocket_data_handler data_handler,
  12790. mg_websocket_close_handler close_handler,
  12791. void *cbdata)
  12792. {
  12793. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12794. && (data_handler == NULL)
  12795. && (close_handler == NULL);
  12796. mg_set_handler_type(ctx,
  12797. &(ctx->dd),
  12798. uri,
  12799. WEBSOCKET_HANDLER,
  12800. is_delete_request,
  12801. NULL,
  12802. subprotocols,
  12803. connect_handler,
  12804. ready_handler,
  12805. data_handler,
  12806. close_handler,
  12807. NULL,
  12808. cbdata);
  12809. }
  12810. CIVETWEB_API void
  12811. mg_set_auth_handler(struct mg_context *ctx,
  12812. const char *uri,
  12813. mg_authorization_handler handler,
  12814. void *cbdata)
  12815. {
  12816. mg_set_handler_type(ctx,
  12817. &(ctx->dd),
  12818. uri,
  12819. AUTH_HANDLER,
  12820. handler == NULL,
  12821. NULL,
  12822. NULL,
  12823. NULL,
  12824. NULL,
  12825. NULL,
  12826. NULL,
  12827. handler,
  12828. cbdata);
  12829. }
  12830. static int
  12831. get_request_handler(struct mg_connection *conn,
  12832. int handler_type,
  12833. mg_request_handler *handler,
  12834. struct mg_websocket_subprotocols **subprotocols,
  12835. mg_websocket_connect_handler *connect_handler,
  12836. mg_websocket_ready_handler *ready_handler,
  12837. mg_websocket_data_handler *data_handler,
  12838. mg_websocket_close_handler *close_handler,
  12839. mg_authorization_handler *auth_handler,
  12840. void **cbdata,
  12841. struct mg_handler_info **handler_info)
  12842. {
  12843. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12844. if (request_info) {
  12845. const char *uri = request_info->local_uri;
  12846. size_t urilen = strlen(uri);
  12847. struct mg_handler_info *tmp_rh;
  12848. int step, matched;
  12849. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12850. return 0;
  12851. }
  12852. mg_lock_context(conn->phys_ctx);
  12853. for (step = 0; step < 3; step++) {
  12854. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12855. tmp_rh = tmp_rh->next) {
  12856. if (tmp_rh->handler_type != handler_type) {
  12857. continue;
  12858. }
  12859. if (step == 0) {
  12860. /* first try for an exact match */
  12861. matched = (tmp_rh->uri_len == urilen)
  12862. && (strcmp(tmp_rh->uri, uri) == 0);
  12863. } else if (step == 1) {
  12864. /* next try for a partial match, we will accept
  12865. uri/something */
  12866. matched =
  12867. (tmp_rh->uri_len < urilen)
  12868. && (uri[tmp_rh->uri_len] == '/')
  12869. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12870. } else {
  12871. /* finally try for pattern match */
  12872. matched =
  12873. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12874. }
  12875. if (matched) {
  12876. if (handler_type == WEBSOCKET_HANDLER) {
  12877. *subprotocols = tmp_rh->subprotocols;
  12878. *connect_handler = tmp_rh->connect_handler;
  12879. *ready_handler = tmp_rh->ready_handler;
  12880. *data_handler = tmp_rh->data_handler;
  12881. *close_handler = tmp_rh->close_handler;
  12882. } else if (handler_type == REQUEST_HANDLER) {
  12883. if (tmp_rh->removing) {
  12884. /* Treat as none found */
  12885. step = 2;
  12886. break;
  12887. }
  12888. *handler = tmp_rh->handler;
  12889. /* Acquire handler and give it back */
  12890. tmp_rh->refcount++;
  12891. *handler_info = tmp_rh;
  12892. } else { /* AUTH_HANDLER */
  12893. *auth_handler = tmp_rh->auth_handler;
  12894. }
  12895. *cbdata = tmp_rh->cbdata;
  12896. mg_unlock_context(conn->phys_ctx);
  12897. return 1;
  12898. }
  12899. }
  12900. }
  12901. mg_unlock_context(conn->phys_ctx);
  12902. }
  12903. return 0; /* none found */
  12904. }
  12905. /* Check if the script file is in a path, allowed for script files.
  12906. * This can be used if uploading files is possible not only for the server
  12907. * admin, and the upload mechanism does not check the file extension.
  12908. */
  12909. static int
  12910. is_in_script_path(const struct mg_connection *conn, const char *path)
  12911. {
  12912. /* TODO (Feature): Add config value for allowed script path.
  12913. * Default: All allowed. */
  12914. (void)conn;
  12915. (void)path;
  12916. return 1;
  12917. }
  12918. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12919. static int
  12920. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12921. int bits,
  12922. char *data,
  12923. size_t len,
  12924. void *cbdata)
  12925. {
  12926. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12927. if (pcallbacks->websocket_data) {
  12928. return pcallbacks->websocket_data(conn, bits, data, len);
  12929. }
  12930. /* No handler set - assume "OK" */
  12931. return 1;
  12932. }
  12933. static void
  12934. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12935. void *cbdata)
  12936. {
  12937. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12938. if (pcallbacks->connection_close) {
  12939. pcallbacks->connection_close(conn);
  12940. }
  12941. }
  12942. #endif
  12943. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12944. */
  12945. static void
  12946. release_handler_ref(struct mg_connection *conn,
  12947. struct mg_handler_info *handler_info)
  12948. {
  12949. if (handler_info != NULL) {
  12950. /* Use context lock for ref counter */
  12951. mg_lock_context(conn->phys_ctx);
  12952. handler_info->refcount--;
  12953. mg_unlock_context(conn->phys_ctx);
  12954. }
  12955. }
  12956. /* This is the heart of the Civetweb's logic.
  12957. * This function is called when the request is read, parsed and validated,
  12958. * and Civetweb must decide what action to take: serve a file, or
  12959. * a directory, or call embedded function, etcetera. */
  12960. static void
  12961. handle_request(struct mg_connection *conn)
  12962. {
  12963. struct mg_request_info *ri = &conn->request_info;
  12964. char path[UTF8_PATH_MAX];
  12965. int uri_len, ssl_index;
  12966. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12967. is_put_or_delete_request = 0, is_callback_resource = 0,
  12968. is_template_text_file = 0, is_webdav_request = 0;
  12969. int i;
  12970. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12971. mg_request_handler callback_handler = NULL;
  12972. struct mg_handler_info *handler_info = NULL;
  12973. struct mg_websocket_subprotocols *subprotocols;
  12974. mg_websocket_connect_handler ws_connect_handler = NULL;
  12975. mg_websocket_ready_handler ws_ready_handler = NULL;
  12976. mg_websocket_data_handler ws_data_handler = NULL;
  12977. mg_websocket_close_handler ws_close_handler = NULL;
  12978. void *callback_data = NULL;
  12979. mg_authorization_handler auth_handler = NULL;
  12980. void *auth_callback_data = NULL;
  12981. int handler_type;
  12982. time_t curtime = time(NULL);
  12983. char date[64];
  12984. char *tmp;
  12985. path[0] = 0;
  12986. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12987. conn->request_state = 0;
  12988. /* 1. get the request url */
  12989. /* 1.1. split into url and query string */
  12990. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12991. != NULL) {
  12992. *((char *)conn->request_info.query_string++) = '\0';
  12993. }
  12994. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12995. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12996. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12997. if (ssl_index >= 0) {
  12998. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12999. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  13000. redirect_to_https_port(conn, port);
  13001. } else {
  13002. /* A http to https forward port has been specified,
  13003. * but no https port to forward to. */
  13004. mg_send_http_error(conn,
  13005. 503,
  13006. "%s",
  13007. "Error: SSL forward not configured properly");
  13008. mg_cry_internal(conn,
  13009. "%s",
  13010. "Can not redirect to SSL, no SSL port available");
  13011. }
  13012. return;
  13013. }
  13014. /* 1.3. decode url (if config says so) */
  13015. if (should_decode_url(conn)) {
  13016. url_decode_in_place((char *)ri->local_uri);
  13017. }
  13018. /* URL decode the query-string only if explicitly set in the configuration
  13019. */
  13020. if (conn->request_info.query_string) {
  13021. if (should_decode_query_string(conn)) {
  13022. url_decode_in_place((char *)conn->request_info.query_string);
  13023. }
  13024. }
  13025. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  13026. * possible. The fact that we cleaned the URI is stored in that the
  13027. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  13028. * ri->local_uri_raw still points to memory allocated in
  13029. * worker_thread_run(). ri->local_uri is private to the request so we
  13030. * don't have to use preallocated memory here. */
  13031. tmp = mg_strdup(ri->local_uri_raw);
  13032. if (!tmp) {
  13033. /* Out of memory. We cannot do anything reasonable here. */
  13034. return;
  13035. }
  13036. remove_dot_segments(tmp);
  13037. ri->local_uri = tmp;
  13038. #if !defined(NO_FILES) /* Only compute if later code can actually use it */
  13039. /* Cache URI length once; recompute only if the buffer changes later. */
  13040. uri_len = (int)strlen(ri->local_uri);
  13041. #endif
  13042. /* step 1. completed, the url is known now */
  13043. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13044. /* 2. if this ip has limited speed, set it for this connection */
  13045. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13046. &conn->client.rsa,
  13047. ri->local_uri);
  13048. /* 3. call a "handle everything" callback, if registered */
  13049. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13050. /* Note that since V1.7 the "begin_request" function is called
  13051. * before an authorization check. If an authorization check is
  13052. * required, use a request_handler instead. */
  13053. i = conn->phys_ctx->callbacks.begin_request(conn);
  13054. if (i > 0) {
  13055. /* callback already processed the request. Store the
  13056. return value as a status code for the access log. */
  13057. conn->status_code = i;
  13058. if (!conn->must_close) {
  13059. discard_unread_request_data(conn);
  13060. }
  13061. DEBUG_TRACE("%s", "begin_request handled request");
  13062. return;
  13063. } else if (i == 0) {
  13064. /* civetweb should process the request */
  13065. } else {
  13066. /* unspecified - may change with the next version */
  13067. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13068. return;
  13069. }
  13070. }
  13071. /* request not yet handled by a handler or redirect, so the request
  13072. * is processed here */
  13073. /* 4. Check for CORS preflight requests and handle them (if configured).
  13074. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13075. */
  13076. if (!strcmp(ri->request_method, "OPTIONS")) {
  13077. /* Send a response to CORS preflights only if
  13078. * access_control_allow_methods is not NULL and not an empty string.
  13079. * In this case, scripts can still handle CORS. */
  13080. const char *cors_meth_cfg =
  13081. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13082. const char *cors_orig_cfg =
  13083. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13084. const char *cors_origin =
  13085. get_header(ri->http_headers, ri->num_headers, "Origin");
  13086. const char *cors_acrm = get_header(ri->http_headers,
  13087. ri->num_headers,
  13088. "Access-Control-Request-Method");
  13089. const char *cors_repl_asterisk_with_orig_cfg =
  13090. conn->dom_ctx->config[REPLACE_ASTERISK_WITH_ORIGIN];
  13091. /* Todo: check if cors_origin is in cors_orig_cfg.
  13092. * Or, let the client check this. */
  13093. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13094. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13095. && (cors_origin != NULL) && (cors_acrm != NULL)
  13096. && (cors_repl_asterisk_with_orig_cfg != NULL)
  13097. && (*cors_repl_asterisk_with_orig_cfg != 0)) {
  13098. int cors_repl_asterisk_with_orig =
  13099. mg_strcasecmp(cors_repl_asterisk_with_orig_cfg, "yes");
  13100. /* This is a valid CORS preflight, and the server is configured
  13101. * to handle it automatically. */
  13102. const char *cors_acrh =
  13103. get_header(ri->http_headers,
  13104. ri->num_headers,
  13105. "Access-Control-Request-Headers");
  13106. const char *cors_cred_cfg =
  13107. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13108. const char *cors_exphdr_cfg =
  13109. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13110. gmt_time_string(date, sizeof(date), &curtime);
  13111. mg_printf(conn,
  13112. "HTTP/1.1 200 OK\r\n"
  13113. "Date: %s\r\n"
  13114. "Access-Control-Allow-Origin: %s\r\n"
  13115. "Access-Control-Allow-Methods: %s\r\n"
  13116. "Content-Length: 0\r\n"
  13117. "Connection: %s\r\n",
  13118. date,
  13119. (cors_repl_asterisk_with_orig == 0
  13120. && cors_orig_cfg[0] == '*')
  13121. ? cors_origin
  13122. : cors_orig_cfg,
  13123. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13124. suggest_connection_header(conn));
  13125. if (cors_cred_cfg && *cors_cred_cfg) {
  13126. mg_printf(conn,
  13127. "Access-Control-Allow-Credentials: %s\r\n",
  13128. cors_cred_cfg);
  13129. }
  13130. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13131. mg_printf(conn,
  13132. "Access-Control-Expose-Headers: %s\r\n",
  13133. cors_exphdr_cfg);
  13134. }
  13135. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13136. /* CORS request is asking for additional headers */
  13137. const char *cors_hdr_cfg =
  13138. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13139. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13140. /* Allow only if access_control_allow_headers is
  13141. * not NULL and not an empty string. If this
  13142. * configuration is set to *, allow everything.
  13143. * Otherwise this configuration must be a list
  13144. * of allowed HTTP header names. */
  13145. mg_printf(conn,
  13146. "Access-Control-Allow-Headers: %s\r\n",
  13147. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13148. : cors_hdr_cfg));
  13149. }
  13150. }
  13151. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13152. mg_printf(conn, "\r\n");
  13153. DEBUG_TRACE("%s", "OPTIONS done");
  13154. return;
  13155. }
  13156. }
  13157. /* 5. interpret the url to find out how the request must be handled
  13158. */
  13159. /* 5.1. first test, if the request targets the regular http(s)://
  13160. * protocol namespace or the websocket ws(s):// protocol namespace.
  13161. */
  13162. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13163. #if defined(USE_WEBSOCKET)
  13164. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13165. #else
  13166. handler_type = REQUEST_HANDLER;
  13167. #endif /* defined(USE_WEBSOCKET) */
  13168. if (is_websocket_request) {
  13169. HTTP1_only;
  13170. }
  13171. /* 5.2. check if the request will be handled by a callback */
  13172. if (get_request_handler(conn,
  13173. handler_type,
  13174. &callback_handler,
  13175. &subprotocols,
  13176. &ws_connect_handler,
  13177. &ws_ready_handler,
  13178. &ws_data_handler,
  13179. &ws_close_handler,
  13180. NULL,
  13181. &callback_data,
  13182. &handler_info)) {
  13183. /* 5.2.1. A callback will handle this request. All requests
  13184. * handled by a callback have to be considered as requests
  13185. * to a script resource. */
  13186. is_callback_resource = 1;
  13187. is_script_resource = 1;
  13188. is_put_or_delete_request = is_put_or_delete_method(conn);
  13189. /* Never handle a C callback according to File WebDav rules,
  13190. * even if it is a webdav method */
  13191. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13192. } else {
  13193. no_callback_resource:
  13194. /* 5.2.2. No callback is responsible for this request. The URI
  13195. * addresses a file based resource (static content or Lua/cgi
  13196. * scripts in the file system). */
  13197. is_callback_resource = 0;
  13198. interpret_uri(conn,
  13199. path,
  13200. sizeof(path),
  13201. &file.stat,
  13202. &is_found,
  13203. &is_script_resource,
  13204. &is_websocket_request,
  13205. &is_put_or_delete_request,
  13206. &is_webdav_request,
  13207. &is_template_text_file);
  13208. }
  13209. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13210. if (is_webdav_request) {
  13211. /* TODO: Do we need a config option? */
  13212. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13213. if (webdav_enable[0] != 'y') {
  13214. mg_send_http_error(conn,
  13215. 405,
  13216. "%s method not allowed",
  13217. conn->request_info.request_method);
  13218. DEBUG_TRACE("%s", "webdav rejected");
  13219. return;
  13220. }
  13221. }
  13222. /* 6. authorization check */
  13223. /* 6.1. a custom authorization handler is installed */
  13224. if (get_request_handler(conn,
  13225. AUTH_HANDLER,
  13226. NULL,
  13227. NULL,
  13228. NULL,
  13229. NULL,
  13230. NULL,
  13231. NULL,
  13232. &auth_handler,
  13233. &auth_callback_data,
  13234. NULL)) {
  13235. if (!auth_handler(conn, auth_callback_data)) {
  13236. /* Callback handler will not be used anymore. Release it */
  13237. release_handler_ref(conn, handler_info);
  13238. DEBUG_TRACE("%s", "auth handler rejected request");
  13239. return;
  13240. }
  13241. } else if (is_put_or_delete_request && !is_script_resource
  13242. && !is_callback_resource) {
  13243. HTTP1_only;
  13244. /* 6.2. this request is a PUT/DELETE to a real file */
  13245. /* 6.2.1. thus, the server must have real files */
  13246. #if defined(NO_FILES)
  13247. if (1) {
  13248. #else
  13249. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13250. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13251. #endif
  13252. /* This code path will not be called for request handlers */
  13253. DEBUG_ASSERT(handler_info == NULL);
  13254. /* This server does not have any real files, thus the
  13255. * PUT/DELETE methods are not valid. */
  13256. mg_send_http_error(conn,
  13257. 405,
  13258. "%s method not allowed",
  13259. conn->request_info.request_method);
  13260. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13261. return;
  13262. }
  13263. #if !defined(NO_FILES)
  13264. /* 6.2.2. Check if put authorization for static files is
  13265. * available.
  13266. */
  13267. if (!is_authorized_for_put(conn)) {
  13268. send_authorization_request(conn, NULL);
  13269. DEBUG_TRACE("%s", "file write needs authorization");
  13270. return;
  13271. }
  13272. #endif
  13273. } else {
  13274. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13275. * or it is a PUT or DELETE request to a resource that does not
  13276. * correspond to a file. Check authorization. */
  13277. if (!check_authorization(conn, path)) {
  13278. send_authorization_request(conn, NULL);
  13279. /* Callback handler will not be used anymore. Release it */
  13280. release_handler_ref(conn, handler_info);
  13281. DEBUG_TRACE("%s", "access authorization required");
  13282. return;
  13283. }
  13284. }
  13285. /* request is authorized or does not need authorization */
  13286. /* 7. check if there are request handlers for this uri */
  13287. if (is_callback_resource) {
  13288. HTTP1_only;
  13289. if (!is_websocket_request) {
  13290. i = callback_handler(conn, callback_data);
  13291. /* Callback handler will not be used anymore. Release it */
  13292. release_handler_ref(conn, handler_info);
  13293. if (i > 0) {
  13294. /* Do nothing, callback has served the request. Store
  13295. * then return value as status code for the log and discard
  13296. * all data from the client not used by the callback. */
  13297. conn->status_code = i;
  13298. if (!conn->must_close) {
  13299. discard_unread_request_data(conn);
  13300. }
  13301. } else {
  13302. /* The handler did NOT handle the request. */
  13303. /* Some proper reactions would be:
  13304. * a) close the connections without sending anything
  13305. * b) send a 404 not found
  13306. * c) try if there is a file matching the URI
  13307. * It would be possible to do a, b or c in the callback
  13308. * implementation, and return 1 - we cannot do anything
  13309. * here, that is not possible in the callback.
  13310. *
  13311. * TODO: What would be the best reaction here?
  13312. * (Note: The reaction may change, if there is a better
  13313. * idea.)
  13314. */
  13315. /* For the moment, use option c: We look for a proper file,
  13316. * but since a file request is not always a script resource,
  13317. * the authorization check might be different. */
  13318. callback_handler = NULL;
  13319. /* Here we are at a dead end:
  13320. * According to URI matching, a callback should be
  13321. * responsible for handling the request,
  13322. * we called it, but the callback declared itself
  13323. * not responsible.
  13324. * We use a goto here, to get out of this dead end,
  13325. * and continue with the default handling.
  13326. * A goto here is simpler and better to understand
  13327. * than some curious loop. */
  13328. goto no_callback_resource;
  13329. }
  13330. } else {
  13331. #if defined(USE_WEBSOCKET)
  13332. handle_websocket_request(conn,
  13333. path,
  13334. is_callback_resource,
  13335. subprotocols,
  13336. ws_connect_handler,
  13337. ws_ready_handler,
  13338. ws_data_handler,
  13339. ws_close_handler,
  13340. callback_data);
  13341. #endif
  13342. }
  13343. DEBUG_TRACE("%s", "websocket handling done");
  13344. return;
  13345. }
  13346. /* 8. handle websocket requests */
  13347. #if defined(USE_WEBSOCKET)
  13348. if (is_websocket_request) {
  13349. HTTP1_only;
  13350. if (is_script_resource) {
  13351. if (is_in_script_path(conn, path)) {
  13352. /* Websocket Lua script */
  13353. handle_websocket_request(conn,
  13354. path,
  13355. 0 /* Lua Script */,
  13356. NULL,
  13357. NULL,
  13358. NULL,
  13359. NULL,
  13360. NULL,
  13361. conn->phys_ctx->user_data);
  13362. } else {
  13363. /* Script was in an illegal path */
  13364. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13365. }
  13366. } else {
  13367. mg_send_http_error(conn, 404, "%s", "Not found");
  13368. }
  13369. DEBUG_TRACE("%s", "websocket script done");
  13370. return;
  13371. } else
  13372. #endif
  13373. #if defined(NO_FILES)
  13374. /* 9a. In case the server uses only callbacks, this uri is
  13375. * unknown.
  13376. * Then, all request handling ends here. */
  13377. mg_send_http_error(conn, 404, "%s", "Not Found");
  13378. #else
  13379. /* 9b. This request is either for a static file or resource handled
  13380. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13381. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13382. mg_send_http_error(conn, 404, "%s", "Not Found");
  13383. DEBUG_TRACE("%s", "no document root available");
  13384. return;
  13385. }
  13386. /* 10. Request is handled by a script */
  13387. if (is_script_resource) {
  13388. HTTP1_only;
  13389. handle_file_based_request(conn, path, &file);
  13390. DEBUG_TRACE("%s", "script handling done");
  13391. return;
  13392. }
  13393. /* Request was not handled by a callback or script. It will be
  13394. * handled by a server internal method. */
  13395. /* 11. Handle put/delete/mkcol requests */
  13396. if (is_put_or_delete_request) {
  13397. HTTP1_only;
  13398. /* 11.1. PUT method */
  13399. if (!strcmp(ri->request_method, "PUT")) {
  13400. put_file(conn, path);
  13401. DEBUG_TRACE("handling %s request to %s done",
  13402. ri->request_method,
  13403. path);
  13404. return;
  13405. }
  13406. /* 11.2. DELETE method */
  13407. if (!strcmp(ri->request_method, "DELETE")) {
  13408. delete_file(conn, path);
  13409. DEBUG_TRACE("handling %s request to %s done",
  13410. ri->request_method,
  13411. path);
  13412. return;
  13413. }
  13414. /* 11.3. MKCOL method */
  13415. if (!strcmp(ri->request_method, "MKCOL")) {
  13416. dav_mkcol(conn, path);
  13417. DEBUG_TRACE("handling %s request to %s done",
  13418. ri->request_method,
  13419. path);
  13420. return;
  13421. }
  13422. /* 11.4. MOVE method */
  13423. if (!strcmp(ri->request_method, "MOVE")) {
  13424. dav_move_file(conn, path, 0);
  13425. DEBUG_TRACE("handling %s request to %s done",
  13426. ri->request_method,
  13427. path);
  13428. return;
  13429. }
  13430. if (!strcmp(ri->request_method, "COPY")) {
  13431. dav_move_file(conn, path, 1);
  13432. DEBUG_TRACE("handling %s request to %s done",
  13433. ri->request_method,
  13434. path);
  13435. return;
  13436. }
  13437. /* 11.5. LOCK method */
  13438. if (!strcmp(ri->request_method, "LOCK")) {
  13439. dav_lock_file(conn, path);
  13440. DEBUG_TRACE("handling %s request to %s done",
  13441. ri->request_method,
  13442. path);
  13443. return;
  13444. }
  13445. /* 11.6. UNLOCK method */
  13446. if (!strcmp(ri->request_method, "UNLOCK")) {
  13447. dav_unlock_file(conn, path);
  13448. DEBUG_TRACE("handling %s request to %s done",
  13449. ri->request_method,
  13450. path);
  13451. return;
  13452. }
  13453. /* 11.7. PROPPATCH method */
  13454. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13455. dav_proppatch(conn, path);
  13456. DEBUG_TRACE("handling %s request to %s done",
  13457. ri->request_method,
  13458. path);
  13459. return;
  13460. }
  13461. /* 11.8. Other methods, e.g.: PATCH
  13462. * This method is not supported for static resources,
  13463. * only for scripts (Lua, CGI) and callbacks. */
  13464. mg_send_http_error(conn,
  13465. 405,
  13466. "%s method not allowed",
  13467. conn->request_info.request_method);
  13468. DEBUG_TRACE("method %s on %s is not supported",
  13469. ri->request_method,
  13470. path);
  13471. return;
  13472. }
  13473. /* 11. File does not exist, or it was configured that it should be
  13474. * hidden */
  13475. if (!is_found || (must_hide_file(conn, path))) {
  13476. mg_send_http_error(conn, 404, "%s", "Not found");
  13477. DEBUG_TRACE("handling %s request to %s: file not found",
  13478. ri->request_method,
  13479. path);
  13480. return;
  13481. }
  13482. /* 12. Directory uris should end with a slash */
  13483. if (file.stat.is_directory && (uri_len > 0)
  13484. && (ri->local_uri[uri_len - 1] != '/')) {
  13485. /* Path + server root */
  13486. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13487. char *new_path;
  13488. if (ri->query_string) {
  13489. buflen += strlen(ri->query_string);
  13490. }
  13491. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13492. if (!new_path) {
  13493. mg_send_http_error(conn, 500, "out or memory");
  13494. } else {
  13495. mg_get_request_link(conn, new_path, buflen - 1);
  13496. size_t len = strlen(new_path);
  13497. if (len + 1 < buflen) {
  13498. new_path[len] = '/';
  13499. new_path[len + 1] = '\0';
  13500. len++;
  13501. }
  13502. if (ri->query_string) {
  13503. if (len + 1 < buflen) {
  13504. new_path[len] = '?';
  13505. new_path[len + 1] = '\0';
  13506. len++;
  13507. }
  13508. /* Append with size of space left for query string + null
  13509. * terminator */
  13510. size_t max_append = buflen - len - 1;
  13511. strncat(new_path, ri->query_string, max_append);
  13512. }
  13513. mg_send_http_redirect(conn, new_path, 301);
  13514. mg_free(new_path);
  13515. }
  13516. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13517. ri->request_method,
  13518. path);
  13519. return;
  13520. }
  13521. /* 13. Handle other methods than GET/HEAD */
  13522. /* 13.1. Handle PROPFIND */
  13523. if (!strcmp(ri->request_method, "PROPFIND")) {
  13524. handle_propfind(conn, path, &file.stat);
  13525. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13526. return;
  13527. }
  13528. /* 13.2. Handle OPTIONS for files */
  13529. if (!strcmp(ri->request_method, "OPTIONS")) {
  13530. /* This standard handler is only used for real files.
  13531. * Scripts should support the OPTIONS method themselves, to allow a
  13532. * maximum flexibility.
  13533. * Lua and CGI scripts may fully support CORS this way (including
  13534. * preflights). */
  13535. send_options(conn);
  13536. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13537. return;
  13538. }
  13539. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13540. if ((0 != strcmp(ri->request_method, "GET"))
  13541. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13542. mg_send_http_error(conn,
  13543. 405,
  13544. "%s method not allowed",
  13545. conn->request_info.request_method);
  13546. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13547. return;
  13548. }
  13549. /* 14. directories */
  13550. if (file.stat.is_directory) {
  13551. /* Substitute files have already been handled above. */
  13552. /* Here we can either generate and send a directory listing,
  13553. * or send an "access denied" error. */
  13554. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13555. "yes")) {
  13556. handle_directory_request(conn, path);
  13557. } else {
  13558. mg_send_http_error(conn,
  13559. 403,
  13560. "%s",
  13561. "Error: Directory listing denied");
  13562. }
  13563. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13564. return;
  13565. }
  13566. /* 15. Files with search/replace patterns: LSP and SSI */
  13567. if (is_template_text_file) {
  13568. HTTP1_only;
  13569. handle_file_based_request(conn, path, &file);
  13570. DEBUG_TRACE("handling %s request to %s done (template)",
  13571. ri->request_method,
  13572. path);
  13573. return;
  13574. }
  13575. /* 16. Static file - maybe cached */
  13576. #if !defined(NO_CACHING)
  13577. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13578. /* Send 304 "Not Modified" - this must not send any body data */
  13579. handle_not_modified_static_file_request(conn, &file);
  13580. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13581. ri->request_method,
  13582. path);
  13583. return;
  13584. }
  13585. #endif /* !NO_CACHING */
  13586. /* 17. Static file - not cached */
  13587. handle_static_file_request(conn, path, &file, NULL, NULL);
  13588. DEBUG_TRACE("handling %s request to %s done (static)",
  13589. ri->request_method,
  13590. path);
  13591. #endif /* !defined(NO_FILES) */
  13592. }
  13593. #if !defined(NO_FILESYSTEMS)
  13594. static void
  13595. handle_file_based_request(struct mg_connection *conn,
  13596. const char *path,
  13597. struct mg_file *file)
  13598. {
  13599. #if !defined(NO_CGI)
  13600. int cgi_config_idx, inc, max;
  13601. #endif
  13602. if (!conn || !conn->dom_ctx) {
  13603. return;
  13604. }
  13605. #if defined(USE_LUA)
  13606. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13607. path)
  13608. > 0) {
  13609. if (is_in_script_path(conn, path)) {
  13610. /* Lua server page: an SSI like page containing mostly plain
  13611. * html code plus some tags with server generated contents. */
  13612. handle_lsp_request(conn, path, file, NULL);
  13613. } else {
  13614. /* Script was in an illegal path */
  13615. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13616. }
  13617. return;
  13618. }
  13619. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13620. > 0) {
  13621. if (is_in_script_path(conn, path)) {
  13622. /* Lua in-server module script: a CGI like script used to
  13623. * generate the entire reply. */
  13624. mg_exec_lua_script(conn, path, NULL);
  13625. } else {
  13626. /* Script was in an illegal path */
  13627. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13628. }
  13629. return;
  13630. }
  13631. #endif
  13632. #if defined(USE_DUKTAPE)
  13633. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13634. path)
  13635. > 0) {
  13636. if (is_in_script_path(conn, path)) {
  13637. /* Call duktape to generate the page */
  13638. mg_exec_duktape_script(conn, path);
  13639. } else {
  13640. /* Script was in an illegal path */
  13641. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13642. }
  13643. return;
  13644. }
  13645. #endif
  13646. #if !defined(NO_CGI)
  13647. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13648. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13649. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13650. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13651. if (match_prefix_strlen(
  13652. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13653. path)
  13654. > 0) {
  13655. if (is_in_script_path(conn, path)) {
  13656. /* CGI scripts may support all HTTP methods */
  13657. handle_cgi_request(conn, path, cgi_config_idx);
  13658. } else {
  13659. /* Script was in an illegal path */
  13660. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13661. }
  13662. return;
  13663. }
  13664. }
  13665. }
  13666. #endif /* !NO_CGI */
  13667. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13668. if (is_in_script_path(conn, path)) {
  13669. handle_ssi_file_request(conn, path, file);
  13670. } else {
  13671. /* Script was in an illegal path */
  13672. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13673. }
  13674. return;
  13675. }
  13676. #if !defined(NO_CACHING)
  13677. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13678. /* Send 304 "Not Modified" - this must not send any body data */
  13679. handle_not_modified_static_file_request(conn, file);
  13680. return;
  13681. }
  13682. #endif /* !NO_CACHING */
  13683. handle_static_file_request(conn, path, file, NULL, NULL);
  13684. }
  13685. #endif /* NO_FILESYSTEMS */
  13686. static void
  13687. close_all_listening_sockets(struct mg_context *ctx)
  13688. {
  13689. unsigned int i;
  13690. if (!ctx) {
  13691. return;
  13692. }
  13693. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13694. closesocket(ctx->listening_sockets[i].sock);
  13695. #if defined(USE_X_DOM_SOCKET)
  13696. /* For unix domain sockets, the socket name represents a file that has
  13697. * to be deleted. */
  13698. /* See
  13699. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13700. */
  13701. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13702. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13703. IGNORE_UNUSED_RESULT(
  13704. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13705. }
  13706. #endif
  13707. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13708. }
  13709. mg_free(ctx->listening_sockets);
  13710. ctx->listening_sockets = NULL;
  13711. mg_free(ctx->listening_socket_fds);
  13712. ctx->listening_socket_fds = NULL;
  13713. }
  13714. /* Valid listening port specification is: [ip_address:]port[s]
  13715. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13716. * Examples for IPv6: [::]:80, [::1]:80,
  13717. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13718. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13719. * In order to bind to both, IPv4 and IPv6, you can either add
  13720. * both ports using 8080,[::]:8080, or the short form +8080.
  13721. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13722. * one only accepting IPv4 the other only IPv6. +8080 creates
  13723. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13724. * environment, they might work differently, or might not work
  13725. * at all - it must be tested what options work best in the
  13726. * relevant network environment.
  13727. */
  13728. static int
  13729. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13730. {
  13731. unsigned int a, b, c, d;
  13732. unsigned port;
  13733. unsigned long portUL;
  13734. int len;
  13735. const char *cb;
  13736. char *endptr;
  13737. #if defined(USE_IPV6)
  13738. char buf[100] = {0};
  13739. #endif
  13740. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13741. * Also, all-zeroes in the socket address means binding to all addresses
  13742. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13743. memset(so, 0, sizeof(*so));
  13744. so->lsa.sin.sin_family = AF_INET;
  13745. *ip_version = 0;
  13746. /* Initialize len as invalid. */
  13747. port = 0;
  13748. len = 0;
  13749. /* Test for different ways to format this string */
  13750. if (sscanf(vec->ptr,
  13751. "%u.%u.%u.%u:%u%n",
  13752. &a,
  13753. &b,
  13754. &c,
  13755. &d,
  13756. &port,
  13757. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13758. // to an integer value, but function will not report
  13759. // conversion errors; consider using 'strtol' instead
  13760. == 5) {
  13761. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13762. so->lsa.sin.sin_addr.s_addr =
  13763. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13764. so->lsa.sin.sin_port = htons((uint16_t)port);
  13765. *ip_version = 4;
  13766. #if defined(USE_IPV6)
  13767. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13768. && ((size_t)len <= vec->len)
  13769. && mg_inet_pton(
  13770. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13771. /* IPv6 address, examples: see above */
  13772. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13773. */
  13774. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13775. *ip_version = 6;
  13776. #endif
  13777. } else if ((vec->ptr[0] == '+')
  13778. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13779. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13780. // string to an integer value, but function will not
  13781. // report conversion errors; consider using 'strtol'
  13782. // instead
  13783. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13784. /* Add 1 to len for the + character we skipped before */
  13785. len++;
  13786. #if defined(USE_IPV6)
  13787. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13788. so->lsa.sin6.sin6_family = AF_INET6;
  13789. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13790. *ip_version = 4 + 6;
  13791. #else
  13792. /* Bind to IPv4 only, since IPv6 is not built in. */
  13793. so->lsa.sin.sin_port = htons((uint16_t)port);
  13794. *ip_version = 4;
  13795. #endif
  13796. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13797. && (vec->ptr != endptr)) {
  13798. len = (int)(endptr - vec->ptr);
  13799. port = (uint16_t)portUL;
  13800. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13801. so->lsa.sin.sin_port = htons((uint16_t)port);
  13802. *ip_version = 4;
  13803. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13804. /* String could be a hostname. This check algorithm
  13805. * will only work for RFC 952 compliant hostnames,
  13806. * starting with a letter, containing only letters,
  13807. * digits and hyphen ('-'). Newer specs may allow
  13808. * more, but this is not guaranteed here, since it
  13809. * may interfere with rules for port option lists. */
  13810. /* According to RFC 1035, hostnames are restricted to 255 characters
  13811. * in total (63 between two dots). */
  13812. char hostname[256];
  13813. size_t hostnlen = (size_t)(cb - vec->ptr);
  13814. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13815. /* This would be invalid in any case */
  13816. *ip_version = 0;
  13817. return 0;
  13818. }
  13819. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13820. if (mg_inet_pton(
  13821. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13822. if (sscanf(cb + 1, "%u%n", &port, &len)
  13823. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13824. // string to an integer value, but function will not
  13825. // report conversion errors; consider using 'strtol'
  13826. // instead
  13827. *ip_version = 4;
  13828. so->lsa.sin.sin_port = htons((uint16_t)port);
  13829. len += (int)(hostnlen + 1);
  13830. } else {
  13831. len = 0;
  13832. }
  13833. #if defined(USE_IPV6)
  13834. } else if (mg_inet_pton(AF_INET6,
  13835. hostname,
  13836. &so->lsa.sin6,
  13837. sizeof(so->lsa.sin6),
  13838. 1)) {
  13839. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13840. *ip_version = 6;
  13841. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13842. len += (int)(hostnlen + 1);
  13843. } else {
  13844. len = 0;
  13845. }
  13846. #endif
  13847. } else {
  13848. len = 0;
  13849. }
  13850. #if defined(USE_X_DOM_SOCKET)
  13851. } else if (vec->ptr[0] == 'x') {
  13852. /* unix (linux) domain socket */
  13853. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13854. len = vec->len;
  13855. so->lsa.sun.sun_family = AF_UNIX;
  13856. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13857. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13858. port = 0;
  13859. *ip_version = 99;
  13860. } else {
  13861. /* String too long */
  13862. len = 0;
  13863. }
  13864. #endif
  13865. } else {
  13866. /* Parsing failure. */
  13867. len = 0;
  13868. }
  13869. /* sscanf and the option splitting code ensure the following condition
  13870. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13871. * 'r' */
  13872. if ((len > 0) && (is_valid_port(port))) {
  13873. int bad_suffix = 0;
  13874. size_t i;
  13875. /* Parse any suffix character(s) after the port number */
  13876. for (i = len; i < vec->len; i++) {
  13877. unsigned char *opt = NULL;
  13878. switch (vec->ptr[i]) {
  13879. case 'o':
  13880. opt = &so->is_optional;
  13881. break;
  13882. case 'r':
  13883. opt = &so->ssl_redir;
  13884. break;
  13885. case 's':
  13886. opt = &so->is_ssl;
  13887. break;
  13888. default: /* empty */
  13889. break;
  13890. }
  13891. if ((opt) && (*opt == 0))
  13892. *opt = 1;
  13893. else {
  13894. bad_suffix = 1;
  13895. break;
  13896. }
  13897. }
  13898. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13899. return 1;
  13900. }
  13901. }
  13902. /* Reset ip_version to 0 if there is an error */
  13903. *ip_version = 0;
  13904. return 0;
  13905. }
  13906. /* Is there any SSL port in use? */
  13907. static int
  13908. is_ssl_port_used(const char *ports)
  13909. {
  13910. if (ports) {
  13911. /* There are several different allowed syntax variants:
  13912. * - "80" for a single port using every network interface
  13913. * - "localhost:80" for a single port using only localhost
  13914. * - "80,localhost:8080" for two ports, one bound to localhost
  13915. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13916. * to IPv4 localhost, one to IPv6 localhost
  13917. * - "+80" use port 80 for IPv4 and IPv6
  13918. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13919. * for both: IPv4 and IPv4
  13920. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13921. * additionally port 8080 bound to localhost connections
  13922. *
  13923. * If we just look for 's' anywhere in the string, "localhost:80"
  13924. * will be detected as SSL (false positive).
  13925. * Looking for 's' after a digit may cause false positives in
  13926. * "my24service:8080".
  13927. * Looking from 's' backward if there are only ':' and numbers
  13928. * before will not work for "24service:8080" (non SSL, port 8080)
  13929. * or "24s" (SSL, port 24).
  13930. *
  13931. * Remark: Initially hostnames were not allowed to start with a
  13932. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13933. * Section 2.1).
  13934. *
  13935. * To get this correct, the entire string must be parsed as a whole,
  13936. * reading it as a list element for element and parsing with an
  13937. * algorithm equivalent to parse_port_string.
  13938. *
  13939. * In fact, we use local interface names here, not arbitrary
  13940. * hostnames, so in most cases the only name will be "localhost".
  13941. *
  13942. * So, for now, we use this simple algorithm, that may still return
  13943. * a false positive in bizarre cases.
  13944. */
  13945. int i;
  13946. int portslen = (int)strlen(ports);
  13947. char prevIsNumber = 0;
  13948. for (i = 0; i < portslen; i++) {
  13949. if (prevIsNumber) {
  13950. int suffixCharIdx = (ports[i] == 'o')
  13951. ? (i + 1)
  13952. : i; /* allow "os" and "or" suffixes */
  13953. if (ports[suffixCharIdx] == 's'
  13954. || ports[suffixCharIdx] == 'r') {
  13955. return 1;
  13956. }
  13957. }
  13958. if (ports[i] >= '0' && ports[i] <= '9') {
  13959. prevIsNumber = 1;
  13960. } else {
  13961. prevIsNumber = 0;
  13962. }
  13963. }
  13964. }
  13965. return 0;
  13966. }
  13967. static int
  13968. set_ports_option(struct mg_context *phys_ctx)
  13969. {
  13970. const char *list;
  13971. int on = 1;
  13972. #if defined(USE_IPV6)
  13973. int off = 0;
  13974. #endif
  13975. struct vec vec;
  13976. struct socket so, *ptr;
  13977. struct mg_pollfd *pfd;
  13978. union usa usa;
  13979. socklen_t len;
  13980. int ip_version;
  13981. int portsTotal = 0;
  13982. int portsOk = 0;
  13983. const char *opt_txt;
  13984. long opt_listen_backlog;
  13985. if (!phys_ctx) {
  13986. return 0;
  13987. }
  13988. memset(&so, 0, sizeof(so));
  13989. memset(&usa, 0, sizeof(usa));
  13990. len = sizeof(usa);
  13991. list = phys_ctx->dd.config[LISTENING_PORTS];
  13992. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13993. portsTotal++;
  13994. if (!parse_port_string(&vec, &so, &ip_version)) {
  13995. mg_cry_ctx_internal(
  13996. phys_ctx,
  13997. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13998. (int)vec.len,
  13999. vec.ptr,
  14000. portsTotal,
  14001. "[IP_ADDRESS:]PORT[s|r]");
  14002. continue;
  14003. }
  14004. #if !defined(NO_SSL)
  14005. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  14006. mg_cry_ctx_internal(phys_ctx,
  14007. "Cannot add SSL socket (entry %i)",
  14008. portsTotal);
  14009. continue;
  14010. }
  14011. #endif
  14012. /* Create socket. */
  14013. /* For a list of protocol numbers (e.g., TCP==6) see:
  14014. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  14015. */
  14016. if ((so.sock =
  14017. socket(so.lsa.sa.sa_family,
  14018. SOCK_STREAM,
  14019. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  14020. == INVALID_SOCKET) {
  14021. mg_cry_ctx_internal(phys_ctx,
  14022. "cannot create socket (entry %i)",
  14023. portsTotal);
  14024. if (so.is_optional) {
  14025. portsOk++; /* it's okay if we couldn't create a socket,
  14026. this port is optional anyway */
  14027. }
  14028. continue;
  14029. }
  14030. #if defined(_WIN32)
  14031. /* Windows SO_REUSEADDR lets many procs binds to a
  14032. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  14033. * if someone already has the socket -- DTL */
  14034. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  14035. * Windows might need a few seconds before
  14036. * the same port can be used again in the
  14037. * same process, so a short Sleep may be
  14038. * required between mg_stop and mg_start.
  14039. */
  14040. if (setsockopt(so.sock,
  14041. SOL_SOCKET,
  14042. SO_EXCLUSIVEADDRUSE,
  14043. (SOCK_OPT_TYPE)&on,
  14044. sizeof(on))
  14045. != 0) {
  14046. /* Set reuse option, but don't abort on errors. */
  14047. mg_cry_ctx_internal(
  14048. phys_ctx,
  14049. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  14050. portsTotal);
  14051. }
  14052. #else
  14053. if (setsockopt(so.sock,
  14054. SOL_SOCKET,
  14055. SO_REUSEADDR,
  14056. (SOCK_OPT_TYPE)&on,
  14057. sizeof(on))
  14058. != 0) {
  14059. /* Set reuse option, but don't abort on errors. */
  14060. mg_cry_ctx_internal(
  14061. phys_ctx,
  14062. "cannot set socket option SO_REUSEADDR (entry %i)",
  14063. portsTotal);
  14064. }
  14065. #endif
  14066. #if defined(USE_X_DOM_SOCKET)
  14067. if (ip_version == 99) {
  14068. /* Unix domain socket */
  14069. } else
  14070. #endif
  14071. if (ip_version > 4) {
  14072. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14073. #if defined(USE_IPV6)
  14074. if (ip_version > 6) {
  14075. if (so.lsa.sa.sa_family == AF_INET6
  14076. && setsockopt(so.sock,
  14077. IPPROTO_IPV6,
  14078. IPV6_V6ONLY,
  14079. (void *)&off,
  14080. sizeof(off))
  14081. != 0) {
  14082. /* Set IPv6 only option, but don't abort on errors. */
  14083. mg_cry_ctx_internal(phys_ctx,
  14084. "cannot set socket option "
  14085. "IPV6_V6ONLY=off (entry %i)",
  14086. portsTotal);
  14087. }
  14088. } else {
  14089. if (so.lsa.sa.sa_family == AF_INET6
  14090. && setsockopt(so.sock,
  14091. IPPROTO_IPV6,
  14092. IPV6_V6ONLY,
  14093. (void *)&on,
  14094. sizeof(on))
  14095. != 0) {
  14096. /* Set IPv6 only option, but don't abort on errors. */
  14097. mg_cry_ctx_internal(phys_ctx,
  14098. "cannot set socket option "
  14099. "IPV6_V6ONLY=on (entry %i)",
  14100. portsTotal);
  14101. }
  14102. }
  14103. #else
  14104. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14105. closesocket(so.sock);
  14106. if (so.is_optional) {
  14107. portsOk++; /* it's okay if we couldn't set the socket option,
  14108. this port is optional anyway */
  14109. }
  14110. so.sock = INVALID_SOCKET;
  14111. continue;
  14112. #endif
  14113. }
  14114. if (so.lsa.sa.sa_family == AF_INET) {
  14115. len = sizeof(so.lsa.sin);
  14116. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14117. mg_cry_ctx_internal(phys_ctx,
  14118. "cannot bind to %.*s: %d (%s)",
  14119. (int)vec.len,
  14120. vec.ptr,
  14121. (int)ERRNO,
  14122. strerror(errno));
  14123. closesocket(so.sock);
  14124. so.sock = INVALID_SOCKET;
  14125. if (so.is_optional) {
  14126. portsOk++; /* it's okay if we couldn't bind, this port is
  14127. optional anyway */
  14128. }
  14129. continue;
  14130. }
  14131. }
  14132. #if defined(USE_IPV6)
  14133. else if (so.lsa.sa.sa_family == AF_INET6) {
  14134. len = sizeof(so.lsa.sin6);
  14135. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14136. mg_cry_ctx_internal(phys_ctx,
  14137. "cannot bind to IPv6 %.*s: %d (%s)",
  14138. (int)vec.len,
  14139. vec.ptr,
  14140. (int)ERRNO,
  14141. strerror(errno));
  14142. closesocket(so.sock);
  14143. so.sock = INVALID_SOCKET;
  14144. if (so.is_optional) {
  14145. portsOk++; /* it's okay if we couldn't bind, this port is
  14146. optional anyway */
  14147. }
  14148. continue;
  14149. }
  14150. }
  14151. #endif
  14152. #if defined(USE_X_DOM_SOCKET)
  14153. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14154. len = sizeof(so.lsa.sun);
  14155. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14156. mg_cry_ctx_internal(phys_ctx,
  14157. "cannot bind to unix socket %s: %d (%s)",
  14158. so.lsa.sun.sun_path,
  14159. (int)ERRNO,
  14160. strerror(errno));
  14161. closesocket(so.sock);
  14162. so.sock = INVALID_SOCKET;
  14163. if (so.is_optional) {
  14164. portsOk++; /* it's okay if we couldn't bind, this port is
  14165. optional anyway */
  14166. }
  14167. continue;
  14168. }
  14169. }
  14170. #endif
  14171. else {
  14172. mg_cry_ctx_internal(
  14173. phys_ctx,
  14174. "cannot bind: address family not supported (entry %i)",
  14175. portsTotal);
  14176. closesocket(so.sock);
  14177. so.sock = INVALID_SOCKET;
  14178. continue;
  14179. }
  14180. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14181. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14182. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14183. mg_cry_ctx_internal(phys_ctx,
  14184. "%s value \"%s\" is invalid",
  14185. config_options[LISTEN_BACKLOG_SIZE].name,
  14186. opt_txt);
  14187. closesocket(so.sock);
  14188. so.sock = INVALID_SOCKET;
  14189. continue;
  14190. }
  14191. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14192. mg_cry_ctx_internal(phys_ctx,
  14193. "cannot listen to %.*s: %d (%s)",
  14194. (int)vec.len,
  14195. vec.ptr,
  14196. (int)ERRNO,
  14197. strerror(errno));
  14198. closesocket(so.sock);
  14199. so.sock = INVALID_SOCKET;
  14200. continue;
  14201. }
  14202. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14203. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14204. int err = (int)ERRNO;
  14205. mg_cry_ctx_internal(phys_ctx,
  14206. "call to getsockname failed %.*s: %d (%s)",
  14207. (int)vec.len,
  14208. vec.ptr,
  14209. err,
  14210. strerror(errno));
  14211. closesocket(so.sock);
  14212. so.sock = INVALID_SOCKET;
  14213. continue;
  14214. }
  14215. /* Update lsa port in case of random free ports */
  14216. #if defined(USE_IPV6)
  14217. if (so.lsa.sa.sa_family == AF_INET6) {
  14218. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14219. } else
  14220. #endif
  14221. {
  14222. so.lsa.sin.sin_port = usa.sin.sin_port;
  14223. }
  14224. if ((ptr = (struct socket *)
  14225. mg_realloc_ctx(phys_ctx->listening_sockets,
  14226. (phys_ctx->num_listening_sockets + 1)
  14227. * sizeof(phys_ctx->listening_sockets[0]),
  14228. phys_ctx))
  14229. == NULL) {
  14230. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14231. closesocket(so.sock);
  14232. so.sock = INVALID_SOCKET;
  14233. continue;
  14234. }
  14235. /* The +2 below includes the original +1 (for the socket we're about to
  14236. * add), plus another +1 for the thread_shutdown_notification_socket
  14237. * that we'll also want to poll() on so that mg_stop() can return
  14238. * quickly
  14239. */
  14240. if ((pfd = (struct mg_pollfd *)
  14241. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14242. (phys_ctx->num_listening_sockets + 2)
  14243. * sizeof(phys_ctx->listening_socket_fds[0]),
  14244. phys_ctx))
  14245. == NULL) {
  14246. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14247. closesocket(so.sock);
  14248. so.sock = INVALID_SOCKET;
  14249. mg_free(ptr);
  14250. continue;
  14251. }
  14252. set_close_on_exec(so.sock, NULL, phys_ctx);
  14253. phys_ctx->listening_sockets = ptr;
  14254. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14255. phys_ctx->listening_socket_fds = pfd;
  14256. phys_ctx->num_listening_sockets++;
  14257. portsOk++;
  14258. }
  14259. if (portsOk != portsTotal) {
  14260. close_all_listening_sockets(phys_ctx);
  14261. portsOk = 0;
  14262. }
  14263. return portsOk;
  14264. }
  14265. static const char *
  14266. header_val(const struct mg_connection *conn, const char *header)
  14267. {
  14268. const char *header_value;
  14269. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14270. return "-";
  14271. } else {
  14272. return header_value;
  14273. }
  14274. }
  14275. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14276. #include "external_log_access.inl"
  14277. #elif !defined(NO_FILESYSTEMS)
  14278. static void
  14279. log_access(const struct mg_connection *conn)
  14280. {
  14281. const struct mg_request_info *ri;
  14282. struct mg_file fi;
  14283. char date[64], src_addr[IP_ADDR_STR_LEN];
  14284. #if defined(REENTRANT_TIME)
  14285. struct tm _tm;
  14286. struct tm *tm = &_tm;
  14287. #else
  14288. struct tm *tm;
  14289. #endif
  14290. const char *referer;
  14291. const char *user_agent;
  14292. char log_buf[4096];
  14293. if (!conn || !conn->dom_ctx) {
  14294. return;
  14295. }
  14296. /* Set log message to "empty" */
  14297. log_buf[0] = 0;
  14298. #if defined(USE_LUA)
  14299. if (conn->phys_ctx->lua_bg_log_available) {
  14300. int ret;
  14301. struct mg_context *ctx = conn->phys_ctx;
  14302. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14303. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14304. /* call "log()" in Lua */
  14305. lua_getglobal(lstate, "log");
  14306. prepare_lua_request_info_inner(conn, lstate);
  14307. push_lua_response_log_data(conn, lstate);
  14308. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14309. if (ret == 0) {
  14310. int t = lua_type(lstate, -1);
  14311. if (t == LUA_TBOOLEAN) {
  14312. if (lua_toboolean(lstate, -1) == 0) {
  14313. /* log() returned false: do not log */
  14314. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14315. return;
  14316. }
  14317. /* log returned true: continue logging */
  14318. } else if (t == LUA_TSTRING) {
  14319. size_t len;
  14320. const char *txt = lua_tolstring(lstate, -1, &len);
  14321. if ((len == 0) || (*txt == 0)) {
  14322. /* log() returned empty string: do not log */
  14323. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14324. return;
  14325. }
  14326. /* Copy test from Lua into log_buf */
  14327. if (len >= sizeof(log_buf)) {
  14328. len = sizeof(log_buf) - 1;
  14329. }
  14330. memcpy(log_buf, txt, len);
  14331. log_buf[len] = 0;
  14332. }
  14333. } else {
  14334. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14335. }
  14336. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14337. }
  14338. #endif
  14339. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14340. if (mg_fopen(conn,
  14341. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14342. MG_FOPEN_MODE_APPEND,
  14343. &fi)
  14344. == 0) {
  14345. fi.access.fp = NULL;
  14346. }
  14347. } else {
  14348. fi.access.fp = NULL;
  14349. }
  14350. /* Log is written to a file and/or a callback. If both are not set,
  14351. * executing the rest of the function is pointless. */
  14352. if ((fi.access.fp == NULL)
  14353. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14354. return;
  14355. }
  14356. /* If we did not get a log message from Lua, create it here. */
  14357. if (!log_buf[0]) {
  14358. #if defined(REENTRANT_TIME)
  14359. localtime_r(&conn->conn_birth_time, tm);
  14360. #else
  14361. tm = localtime(&conn->conn_birth_time);
  14362. #endif
  14363. if (tm != NULL) {
  14364. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14365. } else {
  14366. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14367. }
  14368. ri = &conn->request_info;
  14369. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14370. referer = header_val(conn, "Referer");
  14371. user_agent = header_val(conn, "User-Agent");
  14372. mg_snprintf(conn,
  14373. NULL, /* Ignore truncation in access log */
  14374. log_buf,
  14375. sizeof(log_buf),
  14376. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14377. " %s %s",
  14378. src_addr,
  14379. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14380. date,
  14381. ri->request_method ? ri->request_method : "-",
  14382. ri->request_uri ? ri->request_uri : "-",
  14383. ri->query_string ? "?" : "",
  14384. ri->query_string ? ri->query_string : "",
  14385. ri->http_version,
  14386. conn->status_code,
  14387. conn->num_bytes_sent,
  14388. referer,
  14389. user_agent);
  14390. }
  14391. /* Here we have a log message in log_buf. Call the callback */
  14392. if (conn->phys_ctx->callbacks.log_access) {
  14393. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14394. /* do not log if callback returns non-zero */
  14395. if (fi.access.fp) {
  14396. mg_fclose(&fi.access);
  14397. }
  14398. return;
  14399. }
  14400. }
  14401. /* Store in file */
  14402. if (fi.access.fp) {
  14403. int ok = 1;
  14404. flockfile(fi.access.fp);
  14405. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14406. ok = 0;
  14407. }
  14408. if (fflush(fi.access.fp) != 0) {
  14409. ok = 0;
  14410. }
  14411. funlockfile(fi.access.fp);
  14412. if (mg_fclose(&fi.access) != 0) {
  14413. ok = 0;
  14414. }
  14415. if (!ok) {
  14416. mg_cry_internal(conn,
  14417. "Error writing log file %s",
  14418. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14419. }
  14420. }
  14421. }
  14422. #else
  14423. #error "Either enable filesystems or provide a custom log_access implementation"
  14424. #endif /* Externally provided function */
  14425. /* Verify given socket address against the ACL.
  14426. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14427. */
  14428. static int
  14429. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14430. {
  14431. int allowed, flag, matched;
  14432. struct vec vec;
  14433. if (phys_ctx) {
  14434. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14435. /* If any ACL is set, deny by default */
  14436. allowed = (list == NULL) ? '+' : '-';
  14437. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14438. flag = vec.ptr[0];
  14439. matched = -1;
  14440. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14441. vec.ptr++;
  14442. vec.len--;
  14443. matched = parse_match_net(&vec, sa, 1);
  14444. }
  14445. if (matched < 0) {
  14446. mg_cry_ctx_internal(phys_ctx,
  14447. "%s: subnet must be [+|-]IP-addr[/x]",
  14448. __func__);
  14449. return -1;
  14450. }
  14451. if (matched) {
  14452. allowed = flag;
  14453. }
  14454. }
  14455. return allowed == '+';
  14456. }
  14457. return -1;
  14458. }
  14459. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14460. static int
  14461. set_uid_option(struct mg_context *phys_ctx)
  14462. {
  14463. int success = 0;
  14464. if (phys_ctx) {
  14465. /* We are currently running as curr_uid. */
  14466. const uid_t curr_uid = getuid();
  14467. /* If set, we want to run as run_as_user. */
  14468. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14469. const struct passwd *to_pw = NULL;
  14470. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14471. /* run_as_user does not exist on the system. We can't proceed
  14472. * further. */
  14473. mg_cry_ctx_internal(phys_ctx,
  14474. "%s: unknown user [%s]",
  14475. __func__,
  14476. run_as_user);
  14477. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14478. /* There was either no request to change user, or we're already
  14479. * running as run_as_user. Nothing else to do.
  14480. */
  14481. success = 1;
  14482. } else {
  14483. /* Valid change request. */
  14484. if (setgid(to_pw->pw_gid) == -1) {
  14485. mg_cry_ctx_internal(phys_ctx,
  14486. "%s: setgid(%s): %s",
  14487. __func__,
  14488. run_as_user,
  14489. strerror(errno));
  14490. } else if (setgroups(0, NULL) == -1) {
  14491. mg_cry_ctx_internal(phys_ctx,
  14492. "%s: setgroups(): %s",
  14493. __func__,
  14494. strerror(errno));
  14495. } else if (setuid(to_pw->pw_uid) == -1) {
  14496. mg_cry_ctx_internal(phys_ctx,
  14497. "%s: setuid(%s): %s",
  14498. __func__,
  14499. run_as_user,
  14500. strerror(errno));
  14501. } else {
  14502. success = 1;
  14503. }
  14504. }
  14505. }
  14506. return success;
  14507. }
  14508. #endif /* !_WIN32 */
  14509. static void
  14510. tls_dtor(void *key)
  14511. {
  14512. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14513. /* key == pthread_getspecific(sTlsKey); */
  14514. if (tls) {
  14515. if (tls->is_master == 2) {
  14516. tls->is_master = -3; /* Mark memory as dead */
  14517. mg_free(tls);
  14518. }
  14519. }
  14520. pthread_setspecific(sTlsKey, NULL);
  14521. }
  14522. #if defined(USE_MBEDTLS)
  14523. /* Check if SSL is required.
  14524. * If so, set up ctx->ssl_ctx pointer. */
  14525. static int
  14526. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14527. {
  14528. if (!phys_ctx) {
  14529. return 0;
  14530. }
  14531. if (!dom_ctx) {
  14532. dom_ctx = &(phys_ctx->dd);
  14533. }
  14534. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14535. /* No SSL port is set. No need to setup SSL. */
  14536. return 1;
  14537. }
  14538. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14539. if (dom_ctx->ssl_ctx == NULL) {
  14540. fprintf(stderr, "ssl_ctx malloc failed\n");
  14541. return 0;
  14542. }
  14543. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE],
  14544. dom_ctx->config[SSL_CIPHER_LIST])
  14545. == 0
  14546. ? 1
  14547. : 0;
  14548. }
  14549. #elif defined(USE_GNUTLS)
  14550. /* Check if SSL is required.
  14551. * If so, set up ctx->ssl_ctx pointer. */
  14552. static int
  14553. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14554. {
  14555. if (!phys_ctx) {
  14556. return 0;
  14557. }
  14558. if (!dom_ctx) {
  14559. dom_ctx = &(phys_ctx->dd);
  14560. }
  14561. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14562. /* No SSL port is set. No need to setup SSL. */
  14563. return 1;
  14564. }
  14565. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14566. if (dom_ctx->ssl_ctx == NULL) {
  14567. fprintf(stderr, "ssl_ctx malloc failed\n");
  14568. return 0;
  14569. }
  14570. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14571. == 0
  14572. ? 1
  14573. : 0;
  14574. }
  14575. #elif !defined(NO_SSL)
  14576. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14577. struct mg_domain_context *dom_ctx,
  14578. const char *pem,
  14579. const char *chain);
  14580. static const char *ssl_error(void);
  14581. static int
  14582. refresh_trust(struct mg_connection *conn)
  14583. {
  14584. struct stat cert_buf;
  14585. int64_t t = 0;
  14586. const char *pem;
  14587. const char *chain;
  14588. int should_verify_peer;
  14589. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14590. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14591. * refresh_trust still can not work. */
  14592. return 0;
  14593. }
  14594. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14595. if (chain == NULL) {
  14596. /* pem is not NULL here */
  14597. chain = pem;
  14598. }
  14599. if (*chain == 0) {
  14600. chain = NULL;
  14601. }
  14602. if (stat(pem, &cert_buf) != -1) {
  14603. t = (int64_t)cert_buf.st_mtime;
  14604. }
  14605. mg_lock_context(conn->phys_ctx);
  14606. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14607. conn->dom_ctx->ssl_cert_last_mtime = t;
  14608. should_verify_peer = 0;
  14609. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14610. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14611. == 0) {
  14612. should_verify_peer = 1;
  14613. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14614. "optional")
  14615. == 0) {
  14616. should_verify_peer = 1;
  14617. }
  14618. }
  14619. if (should_verify_peer) {
  14620. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14621. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14622. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14623. ca_file,
  14624. ca_path)
  14625. != 1) {
  14626. mg_unlock_context(conn->phys_ctx);
  14627. mg_cry_ctx_internal(
  14628. conn->phys_ctx,
  14629. "SSL_CTX_load_verify_locations error: %s "
  14630. "ssl_verify_peer requires setting "
  14631. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14632. "present in "
  14633. "the .conf file?",
  14634. ssl_error());
  14635. return 0;
  14636. }
  14637. }
  14638. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14639. mg_unlock_context(conn->phys_ctx);
  14640. return 0;
  14641. }
  14642. }
  14643. mg_unlock_context(conn->phys_ctx);
  14644. return 1;
  14645. }
  14646. #if defined(OPENSSL_API_1_1)
  14647. #else
  14648. static pthread_mutex_t *ssl_mutexes;
  14649. #endif /* OPENSSL_API_1_1 */
  14650. static int
  14651. sslize(struct mg_connection *conn,
  14652. int (*func)(SSL *),
  14653. const struct mg_client_options *client_options)
  14654. {
  14655. int ret, err;
  14656. int short_trust;
  14657. unsigned timeout = 1024;
  14658. unsigned i;
  14659. if (!conn) {
  14660. return 0;
  14661. }
  14662. short_trust =
  14663. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14664. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14665. if (short_trust) {
  14666. int trust_ret = refresh_trust(conn);
  14667. if (!trust_ret) {
  14668. return trust_ret;
  14669. }
  14670. }
  14671. mg_lock_context(conn->phys_ctx);
  14672. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14673. mg_unlock_context(conn->phys_ctx);
  14674. if (conn->ssl == NULL) {
  14675. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14676. OPENSSL_REMOVE_THREAD_STATE();
  14677. return 0;
  14678. }
  14679. SSL_set_app_data(conn->ssl, (char *)conn);
  14680. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14681. if (ret != 1) {
  14682. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14683. SSL_free(conn->ssl);
  14684. conn->ssl = NULL;
  14685. OPENSSL_REMOVE_THREAD_STATE();
  14686. return 0;
  14687. }
  14688. if (client_options) {
  14689. if (client_options->host_name) {
  14690. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14691. }
  14692. }
  14693. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14694. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14695. /* NOTE: The loop below acts as a back-off, so we can end
  14696. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14697. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14698. if (to >= 0) {
  14699. timeout = (unsigned)to;
  14700. }
  14701. }
  14702. /* SSL functions may fail and require to be called again:
  14703. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14704. * Here "func" could be SSL_connect or SSL_accept. */
  14705. for (i = 0; i <= timeout; i += 50) {
  14706. ERR_clear_error();
  14707. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14708. ret = func(conn->ssl);
  14709. if (ret != 1) {
  14710. err = SSL_get_error(conn->ssl, ret);
  14711. if ((err == SSL_ERROR_WANT_CONNECT)
  14712. || (err == SSL_ERROR_WANT_ACCEPT)
  14713. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14714. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14715. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14716. /* Don't wait if the server is going to be stopped. */
  14717. break;
  14718. }
  14719. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14720. /* Simply retry the function call. */
  14721. mg_sleep(50);
  14722. } else {
  14723. /* Need to retry the function call "later".
  14724. * See https://linux.die.net/man/3/ssl_get_error
  14725. * This is typical for non-blocking sockets. */
  14726. struct mg_pollfd pfd[2];
  14727. int pollres;
  14728. unsigned int num_sock = 1;
  14729. pfd[0].fd = conn->client.sock;
  14730. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14731. || (err == SSL_ERROR_WANT_WRITE))
  14732. ? POLLOUT
  14733. : POLLIN;
  14734. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14735. pfd[num_sock].fd =
  14736. conn->phys_ctx->thread_shutdown_notification_socket;
  14737. pfd[num_sock].events = POLLIN;
  14738. num_sock++;
  14739. }
  14740. pollres = mg_poll(pfd,
  14741. num_sock,
  14742. 50,
  14743. &(conn->phys_ctx->stop_flag));
  14744. if (pollres < 0) {
  14745. /* Break if error occurred (-1)
  14746. * or server shutdown (-2) */
  14747. break;
  14748. }
  14749. }
  14750. } else if (err == SSL_ERROR_SYSCALL) {
  14751. /* This is an IO error. Look at errno. */
  14752. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14753. break;
  14754. } else {
  14755. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14756. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14757. break;
  14758. }
  14759. } else {
  14760. /* success */
  14761. break;
  14762. }
  14763. }
  14764. ERR_clear_error();
  14765. if (ret != 1) {
  14766. SSL_free(conn->ssl);
  14767. conn->ssl = NULL;
  14768. OPENSSL_REMOVE_THREAD_STATE();
  14769. return 0;
  14770. }
  14771. return 1;
  14772. }
  14773. /* Return OpenSSL error message (from CRYPTO lib) */
  14774. static const char *
  14775. ssl_error(void)
  14776. {
  14777. unsigned long err;
  14778. err = ERR_get_error();
  14779. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14780. }
  14781. static int
  14782. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14783. {
  14784. int i;
  14785. const char hexdigit[] = "0123456789abcdef";
  14786. if ((memlen <= 0) || (buflen <= 0)) {
  14787. return 0;
  14788. }
  14789. if (buflen < (3 * memlen)) {
  14790. return 0;
  14791. }
  14792. for (i = 0; i < memlen; i++) {
  14793. if (i > 0) {
  14794. buf[3 * i - 1] = ' ';
  14795. }
  14796. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14797. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14798. }
  14799. buf[3 * memlen - 1] = 0;
  14800. return 1;
  14801. }
  14802. static int
  14803. ssl_get_client_cert_info(const struct mg_connection *conn,
  14804. struct mg_client_cert *client_cert)
  14805. {
  14806. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14807. if (cert) {
  14808. char str_buf[1024];
  14809. unsigned char buf[256];
  14810. char *str_serial = NULL;
  14811. unsigned int ulen;
  14812. int ilen;
  14813. unsigned char *tmp_buf;
  14814. unsigned char *tmp_p;
  14815. /* Handle to algorithm used for fingerprint */
  14816. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14817. /* Get Subject and issuer */
  14818. X509_NAME *subj = X509_get_subject_name(cert);
  14819. X509_NAME *iss = X509_get_issuer_name(cert);
  14820. /* Get serial number */
  14821. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14822. /* Translate serial number to a hex string */
  14823. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14824. if (serial_bn) {
  14825. str_serial = BN_bn2hex(serial_bn);
  14826. BN_free(serial_bn);
  14827. }
  14828. client_cert->serial =
  14829. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14830. /* Translate subject and issuer to a string */
  14831. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14832. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14833. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14834. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14835. /* Calculate SHA1 fingerprint and store as a hex string */
  14836. ulen = 0;
  14837. /* ASN1_digest is deprecated. Do the calculation manually,
  14838. * using EVP_Digest. */
  14839. ilen = i2d_X509(cert, NULL);
  14840. tmp_buf = (ilen > 0)
  14841. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14842. conn->phys_ctx)
  14843. : NULL;
  14844. if (tmp_buf) {
  14845. tmp_p = tmp_buf;
  14846. (void)i2d_X509(cert, &tmp_p);
  14847. if (!EVP_Digest(
  14848. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14849. ulen = 0;
  14850. }
  14851. mg_free(tmp_buf);
  14852. }
  14853. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14854. *str_buf = 0;
  14855. }
  14856. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14857. client_cert->peer_cert = (void *)cert;
  14858. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14859. * see https://linux.die.net/man/3/bn_bn2hex */
  14860. OPENSSL_free(str_serial);
  14861. return 1;
  14862. }
  14863. return 0;
  14864. }
  14865. #if defined(OPENSSL_API_1_1)
  14866. #else
  14867. static void
  14868. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14869. {
  14870. (void)line;
  14871. (void)file;
  14872. if (mode & 1) {
  14873. /* 1 is CRYPTO_LOCK */
  14874. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14875. } else {
  14876. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14877. }
  14878. }
  14879. #endif /* OPENSSL_API_1_1 */
  14880. #if !defined(NO_SSL_DL)
  14881. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14882. static void *
  14883. load_tls_dll(char *ebuf,
  14884. size_t ebuf_len,
  14885. const char *dll_name,
  14886. struct ssl_func *sw,
  14887. int *feature_missing)
  14888. {
  14889. union {
  14890. void *p;
  14891. void (*fp)(void);
  14892. } u;
  14893. void *dll_handle;
  14894. struct ssl_func *fp;
  14895. int ok;
  14896. int truncated = 0;
  14897. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14898. mg_snprintf(NULL,
  14899. NULL, /* No truncation check for ebuf */
  14900. ebuf,
  14901. ebuf_len,
  14902. "%s: cannot load %s",
  14903. __func__,
  14904. dll_name);
  14905. return NULL;
  14906. }
  14907. ok = 1;
  14908. for (fp = sw; fp->name != NULL; fp++) {
  14909. #if defined(_WIN32)
  14910. /* GetProcAddress() returns pointer to function */
  14911. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14912. #else
  14913. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14914. * pointers to function pointers. We need to use a union to make a
  14915. * cast. */
  14916. u.p = dlsym(dll_handle, fp->name);
  14917. #endif /* _WIN32 */
  14918. /* Set pointer (might be NULL) */
  14919. fp->ptr = u.fp;
  14920. if (u.fp == NULL) {
  14921. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14922. if (feature_missing) {
  14923. feature_missing[fp->required]++;
  14924. }
  14925. if (fp->required == TLS_Mandatory) {
  14926. /* Mandatory function is missing */
  14927. if (ok) {
  14928. /* This is the first missing function.
  14929. * Create a new error message. */
  14930. mg_snprintf(NULL,
  14931. &truncated,
  14932. ebuf,
  14933. ebuf_len,
  14934. "%s: %s: cannot find %s",
  14935. __func__,
  14936. dll_name,
  14937. fp->name);
  14938. ok = 0;
  14939. } else {
  14940. /* This is yet anothermissing function.
  14941. * Append existing error message. */
  14942. size_t cur_len = strlen(ebuf);
  14943. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14944. mg_snprintf(NULL,
  14945. &truncated,
  14946. ebuf + cur_len,
  14947. ebuf_len - cur_len - 3,
  14948. ", %s",
  14949. fp->name);
  14950. if (truncated) {
  14951. /* If truncated, add "..." */
  14952. strcat(ebuf, "...");
  14953. }
  14954. }
  14955. }
  14956. }
  14957. }
  14958. }
  14959. if (!ok) {
  14960. (void)dlclose(dll_handle);
  14961. return NULL;
  14962. }
  14963. return dll_handle;
  14964. }
  14965. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14966. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14967. #endif /* NO_SSL_DL */
  14968. #if defined(SSL_ALREADY_INITIALIZED)
  14969. static volatile ptrdiff_t cryptolib_users =
  14970. 1; /* Reference counter for crypto library. */
  14971. #else
  14972. static volatile ptrdiff_t cryptolib_users =
  14973. 0; /* Reference counter for crypto library. */
  14974. #endif
  14975. static int
  14976. initialize_openssl(char *ebuf, size_t ebuf_len)
  14977. {
  14978. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14979. int i, num_locks;
  14980. size_t size;
  14981. #endif
  14982. if (ebuf_len > 0) {
  14983. ebuf[0] = 0;
  14984. }
  14985. #if !defined(NO_SSL_DL)
  14986. if (!cryptolib_dll_handle) {
  14987. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14988. cryptolib_dll_handle = load_tls_dll(
  14989. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14990. if (!cryptolib_dll_handle) {
  14991. mg_snprintf(NULL,
  14992. NULL, /* No truncation check for ebuf */
  14993. ebuf,
  14994. ebuf_len,
  14995. "%s: error loading library %s",
  14996. __func__,
  14997. CRYPTO_LIB);
  14998. DEBUG_TRACE("%s", ebuf);
  14999. return 0;
  15000. }
  15001. }
  15002. #endif /* NO_SSL_DL */
  15003. if (mg_atomic_inc(&cryptolib_users) > 1) {
  15004. return 1;
  15005. }
  15006. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  15007. /* Initialize locking callbacks, needed for thread safety.
  15008. * http://www.openssl.org/support/faq.html#PROG1
  15009. */
  15010. num_locks = CRYPTO_num_locks();
  15011. if (num_locks < 0) {
  15012. num_locks = 0;
  15013. }
  15014. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  15015. /* allocate mutex array, if required */
  15016. if (num_locks == 0) {
  15017. /* No mutex array required */
  15018. ssl_mutexes = NULL;
  15019. } else {
  15020. /* Mutex array required - allocate it */
  15021. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  15022. /* Check OOM */
  15023. if (ssl_mutexes == NULL) {
  15024. mg_snprintf(NULL,
  15025. NULL, /* No truncation check for ebuf */
  15026. ebuf,
  15027. ebuf_len,
  15028. "%s: cannot allocate mutexes: %s",
  15029. __func__,
  15030. ssl_error());
  15031. DEBUG_TRACE("%s", ebuf);
  15032. return 0;
  15033. }
  15034. /* initialize mutex array */
  15035. for (i = 0; i < num_locks; i++) {
  15036. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  15037. mg_snprintf(NULL,
  15038. NULL, /* No truncation check for ebuf */
  15039. ebuf,
  15040. ebuf_len,
  15041. "%s: error initializing mutex %i of %i",
  15042. __func__,
  15043. i,
  15044. num_locks);
  15045. DEBUG_TRACE("%s", ebuf);
  15046. mg_free(ssl_mutexes);
  15047. return 0;
  15048. }
  15049. }
  15050. }
  15051. CRYPTO_set_locking_callback(&ssl_locking_callback);
  15052. CRYPTO_set_id_callback(&mg_current_thread_id);
  15053. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15054. #if !defined(NO_SSL_DL)
  15055. if (!ssllib_dll_handle) {
  15056. ssllib_dll_handle =
  15057. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  15058. if (!ssllib_dll_handle) {
  15059. #if !defined(OPENSSL_API_1_1)
  15060. mg_free(ssl_mutexes);
  15061. #endif
  15062. DEBUG_TRACE("%s", ebuf);
  15063. return 0;
  15064. }
  15065. }
  15066. #endif /* NO_SSL_DL */
  15067. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15068. && !defined(NO_SSL_DL)
  15069. /* Initialize SSL library */
  15070. OPENSSL_init_ssl(0, NULL);
  15071. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15072. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15073. NULL);
  15074. #else
  15075. /* Initialize SSL library */
  15076. SSL_library_init();
  15077. SSL_load_error_strings();
  15078. #endif
  15079. return 1;
  15080. }
  15081. static int
  15082. ssl_use_pem_file(struct mg_context *phys_ctx,
  15083. struct mg_domain_context *dom_ctx,
  15084. const char *pem,
  15085. const char *chain)
  15086. {
  15087. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15088. mg_cry_ctx_internal(phys_ctx,
  15089. "%s: cannot open certificate file %s: %s",
  15090. __func__,
  15091. pem,
  15092. ssl_error());
  15093. return 0;
  15094. }
  15095. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15096. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15097. mg_cry_ctx_internal(phys_ctx,
  15098. "%s: cannot open private key file %s: %s",
  15099. __func__,
  15100. pem,
  15101. ssl_error());
  15102. return 0;
  15103. }
  15104. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15105. mg_cry_ctx_internal(phys_ctx,
  15106. "%s: certificate and private key do not match: %s",
  15107. __func__,
  15108. pem);
  15109. return 0;
  15110. }
  15111. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15112. * chain files that contain private keys and certificates in
  15113. * SSL_CTX_use_certificate_chain_file.
  15114. * The CivetWeb-Server used pem-Files that contained both information.
  15115. * In order to make wolfSSL work, it is split in two files.
  15116. * One file that contains key and certificate used by the server and
  15117. * an optional chain file for the ssl stack.
  15118. */
  15119. if (chain) {
  15120. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15121. mg_cry_ctx_internal(phys_ctx,
  15122. "%s: cannot use certificate chain file %s: %s",
  15123. __func__,
  15124. chain,
  15125. ssl_error());
  15126. return 0;
  15127. }
  15128. }
  15129. return 1;
  15130. }
  15131. #if defined(OPENSSL_API_1_1)
  15132. static unsigned long
  15133. ssl_get_protocol(int version_id)
  15134. {
  15135. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15136. if (version_id > 0)
  15137. ret |= SSL_OP_NO_SSLv2;
  15138. if (version_id > 1)
  15139. ret |= SSL_OP_NO_SSLv3;
  15140. if (version_id > 2)
  15141. ret |= SSL_OP_NO_TLSv1;
  15142. if (version_id > 3)
  15143. ret |= SSL_OP_NO_TLSv1_1;
  15144. if (version_id > 4)
  15145. ret |= SSL_OP_NO_TLSv1_2;
  15146. #if defined(SSL_OP_NO_TLSv1_3)
  15147. if (version_id > 5)
  15148. ret |= SSL_OP_NO_TLSv1_3;
  15149. #endif
  15150. return ret;
  15151. }
  15152. #else
  15153. static long
  15154. ssl_get_protocol(int version_id)
  15155. {
  15156. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15157. if (version_id > 0)
  15158. ret |= SSL_OP_NO_SSLv2;
  15159. if (version_id > 1)
  15160. ret |= SSL_OP_NO_SSLv3;
  15161. if (version_id > 2)
  15162. ret |= SSL_OP_NO_TLSv1;
  15163. if (version_id > 3)
  15164. ret |= SSL_OP_NO_TLSv1_1;
  15165. if (version_id > 4)
  15166. ret |= SSL_OP_NO_TLSv1_2;
  15167. #if defined(SSL_OP_NO_TLSv1_3)
  15168. if (version_id > 5)
  15169. ret |= SSL_OP_NO_TLSv1_3;
  15170. #endif
  15171. return (long)ret;
  15172. }
  15173. #endif /* OPENSSL_API_1_1 */
  15174. /* SSL callback documentation:
  15175. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15176. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15177. * https://linux.die.net/man/3/ssl_set_info_callback */
  15178. /* Note: There is no "const" for the first argument in the documentation
  15179. * examples, however some (maybe most, but not all) headers of OpenSSL
  15180. * versions / OpenSSL compatibility layers have it. Having a different
  15181. * definition will cause a warning in C and an error in C++. Use "const SSL
  15182. * *", while automatic conversion from "SSL *" works for all compilers,
  15183. * but not other way around */
  15184. static void
  15185. ssl_info_callback(const SSL *ssl, int what, int ret)
  15186. {
  15187. (void)ret;
  15188. if (what & SSL_CB_HANDSHAKE_START) {
  15189. SSL_get_app_data(ssl);
  15190. }
  15191. if (what & SSL_CB_HANDSHAKE_DONE) {
  15192. /* TODO: check for openSSL 1.1 */
  15193. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15194. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15195. }
  15196. }
  15197. static int
  15198. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15199. {
  15200. #if defined(GCC_DIAGNOSTIC)
  15201. #pragma GCC diagnostic push
  15202. #pragma GCC diagnostic ignored "-Wcast-align"
  15203. #endif /* defined(GCC_DIAGNOSTIC) */
  15204. /* We used an aligned pointer in SSL_set_app_data */
  15205. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15206. #if defined(GCC_DIAGNOSTIC)
  15207. #pragma GCC diagnostic pop
  15208. #endif /* defined(GCC_DIAGNOSTIC) */
  15209. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15210. (void)ad;
  15211. (void)arg;
  15212. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15213. DEBUG_ASSERT(0);
  15214. return SSL_TLSEXT_ERR_NOACK;
  15215. }
  15216. conn->dom_ctx = &(conn->phys_ctx->dd);
  15217. /* Old clients (Win XP) will not support SNI. Then, there
  15218. * is no server name available in the request - we can
  15219. * only work with the default certificate.
  15220. * Multiple HTTPS hosts on one IP+port are only possible
  15221. * with a certificate containing all alternative names.
  15222. */
  15223. if ((servername == NULL) || (*servername == 0)) {
  15224. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15225. mg_lock_context(conn->phys_ctx);
  15226. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15227. mg_unlock_context(conn->phys_ctx);
  15228. return SSL_TLSEXT_ERR_NOACK;
  15229. }
  15230. DEBUG_TRACE("TLS connection to host %s", servername);
  15231. while (conn->dom_ctx) {
  15232. if (!mg_strcasecmp(servername,
  15233. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15234. /* Found matching domain */
  15235. DEBUG_TRACE("TLS domain %s found",
  15236. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15237. break;
  15238. }
  15239. mg_lock_context(conn->phys_ctx);
  15240. conn->dom_ctx = conn->dom_ctx->next;
  15241. mg_unlock_context(conn->phys_ctx);
  15242. }
  15243. if (conn->dom_ctx == NULL) {
  15244. /* Default domain */
  15245. DEBUG_TRACE("TLS default domain %s used",
  15246. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15247. conn->dom_ctx = &(conn->phys_ctx->dd);
  15248. }
  15249. mg_lock_context(conn->phys_ctx);
  15250. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15251. mg_unlock_context(conn->phys_ctx);
  15252. return SSL_TLSEXT_ERR_OK;
  15253. }
  15254. #if defined(USE_ALPN)
  15255. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15256. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15257. alpn_proto_list + 3 + 8,
  15258. NULL};
  15259. #if defined(USE_HTTP2)
  15260. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15261. alpn_proto_list + 3,
  15262. alpn_proto_list + 3 + 8,
  15263. NULL};
  15264. #endif
  15265. static int
  15266. alpn_select_cb(SSL *ssl,
  15267. const unsigned char **out,
  15268. unsigned char *outlen,
  15269. const unsigned char *in,
  15270. unsigned int inlen,
  15271. void *arg)
  15272. {
  15273. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15274. unsigned int i, j, enable_http2 = 0;
  15275. const char **alpn_proto_order = alpn_proto_order_http1;
  15276. struct mg_workerTLS *tls =
  15277. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15278. (void)ssl;
  15279. if (tls == NULL) {
  15280. /* Need to store protocol in Thread Local Storage */
  15281. /* If there is no Thread Local Storage, don't use ALPN */
  15282. return SSL_TLSEXT_ERR_NOACK;
  15283. }
  15284. #if defined(USE_HTTP2)
  15285. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15286. if (enable_http2) {
  15287. alpn_proto_order = alpn_proto_order_http2;
  15288. }
  15289. #endif
  15290. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15291. /* check all accepted protocols in this order */
  15292. const char *alpn_proto = alpn_proto_order[j];
  15293. /* search input for matching protocol */
  15294. for (i = 0; i < inlen; i++) {
  15295. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15296. *out = in + i + 1;
  15297. *outlen = in[i];
  15298. tls->alpn_proto = alpn_proto;
  15299. return SSL_TLSEXT_ERR_OK;
  15300. }
  15301. }
  15302. }
  15303. /* Nothing found */
  15304. return SSL_TLSEXT_ERR_NOACK;
  15305. }
  15306. static int
  15307. next_protos_advertised_cb(SSL *ssl,
  15308. const unsigned char **data,
  15309. unsigned int *len,
  15310. void *arg)
  15311. {
  15312. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15313. *data = (const unsigned char *)alpn_proto_list;
  15314. *len = (unsigned int)strlen((const char *)data);
  15315. (void)ssl;
  15316. (void)dom_ctx;
  15317. return SSL_TLSEXT_ERR_OK;
  15318. }
  15319. static int
  15320. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15321. {
  15322. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15323. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15324. (const unsigned char *)alpn_proto_list,
  15325. alpn_len);
  15326. if (ret != 0) {
  15327. mg_cry_ctx_internal(phys_ctx,
  15328. "SSL_CTX_set_alpn_protos error: %s",
  15329. ssl_error());
  15330. }
  15331. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15332. alpn_select_cb,
  15333. (void *)dom_ctx);
  15334. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15335. next_protos_advertised_cb,
  15336. (void *)dom_ctx);
  15337. return ret;
  15338. }
  15339. #endif
  15340. /* Setup SSL CTX as required by CivetWeb */
  15341. static int
  15342. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15343. struct mg_domain_context *dom_ctx,
  15344. const char *pem,
  15345. const char *chain)
  15346. {
  15347. int callback_ret;
  15348. int should_verify_peer;
  15349. int peer_certificate_optional;
  15350. const char *ca_path;
  15351. const char *ca_file;
  15352. int use_default_verify_paths;
  15353. int verify_depth;
  15354. struct timespec now_mt;
  15355. md5_byte_t ssl_context_id[16];
  15356. md5_state_t md5state;
  15357. int protocol_ver;
  15358. int ssl_cache_timeout;
  15359. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15360. && !defined(NO_SSL_DL)
  15361. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15362. mg_cry_ctx_internal(phys_ctx,
  15363. "SSL_CTX_new (server) error: %s",
  15364. ssl_error());
  15365. return 0;
  15366. }
  15367. #else
  15368. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15369. mg_cry_ctx_internal(phys_ctx,
  15370. "SSL_CTX_new (server) error: %s",
  15371. ssl_error());
  15372. return 0;
  15373. }
  15374. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15375. #if defined(SSL_OP_NO_TLSv1_3)
  15376. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15377. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15378. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15379. | SSL_OP_NO_TLSv1_3);
  15380. #else
  15381. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15382. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15383. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15384. #endif
  15385. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15386. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15387. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15388. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15389. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15390. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15391. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15392. #if defined(SSL_OP_NO_RENEGOTIATION)
  15393. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15394. #endif
  15395. #if !defined(NO_SSL_DL)
  15396. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15397. #endif /* NO_SSL_DL */
  15398. /* In SSL documentation examples callback defined without const
  15399. * specifier 'void (*)(SSL *, int, int)' See:
  15400. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15401. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15402. * But in the source code const SSL is used:
  15403. * 'void (*)(const SSL *, int, int)' See:
  15404. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15405. * Problem about wrong documentation described, but not resolved:
  15406. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15407. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15408. * But when compiled with modern C++ compiler, correct const should be
  15409. * provided
  15410. */
  15411. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15412. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15413. ssl_servername_callback);
  15414. /* If a callback has been specified, call it. */
  15415. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15416. ? 0
  15417. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15418. phys_ctx->user_data));
  15419. /* If callback returns 0, civetweb sets up the SSL certificate.
  15420. * If it returns 1, civetweb assumes the callback already did this.
  15421. * If it returns -1, initializing ssl fails. */
  15422. if (callback_ret < 0) {
  15423. mg_cry_ctx_internal(phys_ctx,
  15424. "SSL callback returned error: %i",
  15425. callback_ret);
  15426. return 0;
  15427. }
  15428. if (callback_ret > 0) {
  15429. /* Callback did everything. */
  15430. return 1;
  15431. }
  15432. /* If a domain callback has been specified, call it. */
  15433. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15434. ? 0
  15435. : (phys_ctx->callbacks.init_ssl_domain(
  15436. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15437. dom_ctx->ssl_ctx,
  15438. phys_ctx->user_data));
  15439. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15440. * If it returns 1, civetweb assumes the callback already did this.
  15441. * If it returns -1, initializing ssl fails. */
  15442. if (callback_ret < 0) {
  15443. mg_cry_ctx_internal(phys_ctx,
  15444. "Domain SSL callback returned error: %i",
  15445. callback_ret);
  15446. return 0;
  15447. }
  15448. if (callback_ret > 0) {
  15449. /* Domain callback did everything. */
  15450. return 1;
  15451. }
  15452. /* Use some combination of start time, domain and port as a SSL
  15453. * context ID. This should be unique on the current machine. */
  15454. md5_init(&md5state);
  15455. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15456. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15457. md5_append(&md5state,
  15458. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15459. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15460. md5_append(&md5state,
  15461. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15462. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15463. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15464. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15465. md5_finish(&md5state, ssl_context_id);
  15466. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15467. (unsigned char *)ssl_context_id,
  15468. sizeof(ssl_context_id));
  15469. if (pem != NULL) {
  15470. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15471. return 0;
  15472. }
  15473. }
  15474. /* Should we support client certificates? */
  15475. /* Default is "no". */
  15476. should_verify_peer = 0;
  15477. peer_certificate_optional = 0;
  15478. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15479. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15480. /* Yes, they are mandatory */
  15481. should_verify_peer = 1;
  15482. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15483. "optional")
  15484. == 0) {
  15485. /* Yes, they are optional */
  15486. should_verify_peer = 1;
  15487. peer_certificate_optional = 1;
  15488. }
  15489. }
  15490. use_default_verify_paths =
  15491. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15492. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15493. == 0);
  15494. if (should_verify_peer) {
  15495. ca_path = dom_ctx->config[SSL_CA_PATH];
  15496. ca_file = dom_ctx->config[SSL_CA_FILE];
  15497. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15498. != 1) {
  15499. mg_cry_ctx_internal(phys_ctx,
  15500. "SSL_CTX_load_verify_locations error: %s "
  15501. "ssl_verify_peer requires setting "
  15502. "either ssl_ca_path or ssl_ca_file. "
  15503. "Is any of them present in the "
  15504. ".conf file?",
  15505. ssl_error());
  15506. return 0;
  15507. }
  15508. if (peer_certificate_optional) {
  15509. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15510. } else {
  15511. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15512. SSL_VERIFY_PEER
  15513. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15514. NULL);
  15515. }
  15516. if (use_default_verify_paths
  15517. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15518. mg_cry_ctx_internal(phys_ctx,
  15519. "SSL_CTX_set_default_verify_paths error: %s",
  15520. ssl_error());
  15521. return 0;
  15522. }
  15523. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15524. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15525. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15526. }
  15527. }
  15528. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15529. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15530. dom_ctx->config[SSL_CIPHER_LIST])
  15531. != 1) {
  15532. mg_cry_ctx_internal(phys_ctx,
  15533. "SSL_CTX_set_cipher_list error: %s",
  15534. ssl_error());
  15535. }
  15536. }
  15537. /* SSL session caching */
  15538. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15539. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15540. : 0);
  15541. if (ssl_cache_timeout > 0) {
  15542. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15543. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15544. * default */
  15545. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15546. }
  15547. #if defined(USE_ALPN)
  15548. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15549. #if !defined(NO_SSL_DL)
  15550. if (!tls_feature_missing[TLS_ALPN])
  15551. #endif
  15552. {
  15553. init_alpn(phys_ctx, dom_ctx);
  15554. }
  15555. #endif
  15556. return 1;
  15557. }
  15558. /* Check if SSL is required.
  15559. * If so, dynamically load SSL library
  15560. * and set up ctx->ssl_ctx pointer. */
  15561. static int
  15562. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15563. {
  15564. void *ssl_ctx = 0;
  15565. int callback_ret;
  15566. const char *pem;
  15567. const char *chain;
  15568. char ebuf[128];
  15569. if (!phys_ctx) {
  15570. return 0;
  15571. }
  15572. if (!dom_ctx) {
  15573. dom_ctx = &(phys_ctx->dd);
  15574. }
  15575. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15576. /* No SSL port is set. No need to setup SSL. */
  15577. return 1;
  15578. }
  15579. /* Check for external SSL_CTX */
  15580. callback_ret =
  15581. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15582. ? 0
  15583. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15584. phys_ctx->user_data));
  15585. if (callback_ret < 0) {
  15586. /* Callback exists and returns <0: Initializing failed. */
  15587. mg_cry_ctx_internal(phys_ctx,
  15588. "external_ssl_ctx callback returned error: %i",
  15589. callback_ret);
  15590. return 0;
  15591. } else if (callback_ret > 0) {
  15592. /* Callback exists and returns >0: Initializing complete,
  15593. * civetweb should not modify the SSL context. */
  15594. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15595. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15596. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15597. return 0;
  15598. }
  15599. return 1;
  15600. }
  15601. /* If the callback does not exist or return 0, civetweb must initialize
  15602. * the SSL context. Handle "domain" callback next. */
  15603. /* Check for external domain SSL_CTX callback. */
  15604. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15605. ? 0
  15606. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15607. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15608. &ssl_ctx,
  15609. phys_ctx->user_data));
  15610. if (callback_ret < 0) {
  15611. /* Callback < 0: Error. Abort init. */
  15612. mg_cry_ctx_internal(
  15613. phys_ctx,
  15614. "external_ssl_ctx_domain callback returned error: %i",
  15615. callback_ret);
  15616. return 0;
  15617. } else if (callback_ret > 0) {
  15618. /* Callback > 0: Consider init done. */
  15619. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15620. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15621. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15622. return 0;
  15623. }
  15624. return 1;
  15625. }
  15626. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15627. * 0, CivetWeb should continue initializing SSL */
  15628. /* If PEM file is not specified and the init_ssl callbacks
  15629. * are not specified, setup will fail. */
  15630. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15631. && (phys_ctx->callbacks.init_ssl == NULL)
  15632. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15633. /* No certificate and no init_ssl callbacks:
  15634. * Essential data to set up TLS is missing.
  15635. */
  15636. mg_cry_ctx_internal(phys_ctx,
  15637. "Initializing SSL failed: -%s is not set",
  15638. config_options[SSL_CERTIFICATE].name);
  15639. return 0;
  15640. }
  15641. /* If a certificate chain is configured, use it. */
  15642. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15643. if (chain == NULL) {
  15644. /* Default: certificate chain in PEM file */
  15645. chain = pem;
  15646. }
  15647. if ((chain != NULL) && (*chain == 0)) {
  15648. /* If the chain is an empty string, don't use it. */
  15649. chain = NULL;
  15650. }
  15651. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15652. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15653. return 0;
  15654. }
  15655. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15656. }
  15657. static void
  15658. uninitialize_openssl(void)
  15659. {
  15660. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15661. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15662. /* Shutdown according to
  15663. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15664. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15665. */
  15666. CONF_modules_unload(1);
  15667. #else
  15668. int i;
  15669. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15670. /* Shutdown according to
  15671. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15672. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15673. */
  15674. CRYPTO_set_locking_callback(NULL);
  15675. CRYPTO_set_id_callback(NULL);
  15676. ENGINE_cleanup();
  15677. CONF_modules_unload(1);
  15678. ERR_free_strings();
  15679. EVP_cleanup();
  15680. CRYPTO_cleanup_all_ex_data();
  15681. OPENSSL_REMOVE_THREAD_STATE();
  15682. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15683. pthread_mutex_destroy(&ssl_mutexes[i]);
  15684. }
  15685. mg_free(ssl_mutexes);
  15686. ssl_mutexes = NULL;
  15687. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15688. }
  15689. }
  15690. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15691. #if !defined(NO_FILESYSTEMS)
  15692. static int
  15693. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15694. {
  15695. if (phys_ctx) {
  15696. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15697. const char *path;
  15698. struct mg_connection fc;
  15699. if (!dom_ctx) {
  15700. dom_ctx = &(phys_ctx->dd);
  15701. }
  15702. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15703. if ((path != NULL)
  15704. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15705. mg_cry_ctx_internal(phys_ctx,
  15706. "Cannot open %s: %s",
  15707. path,
  15708. strerror(ERRNO));
  15709. return 0;
  15710. }
  15711. return 1;
  15712. }
  15713. return 0;
  15714. }
  15715. #endif /* NO_FILESYSTEMS */
  15716. static int
  15717. set_acl_option(struct mg_context *phys_ctx)
  15718. {
  15719. union usa sa;
  15720. memset(&sa, 0, sizeof(sa));
  15721. #if defined(USE_IPV6)
  15722. sa.sin6.sin6_family = AF_INET6;
  15723. #else
  15724. sa.sin.sin_family = AF_INET;
  15725. #endif
  15726. return check_acl(phys_ctx, &sa) != -1;
  15727. }
  15728. static void
  15729. reset_per_request_attributes(struct mg_connection *conn)
  15730. {
  15731. if (!conn) {
  15732. return;
  15733. }
  15734. conn->num_bytes_sent = conn->consumed_content = 0;
  15735. conn->path_info = NULL;
  15736. conn->status_code = -1;
  15737. conn->content_len = -1;
  15738. conn->is_chunked = 0;
  15739. conn->must_close = 0;
  15740. conn->request_len = 0;
  15741. conn->request_state = 0;
  15742. conn->throttle = 0;
  15743. conn->accept_gzip = 0;
  15744. conn->response_info.content_length = conn->request_info.content_length = -1;
  15745. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15746. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15747. conn->response_info.status_text = NULL;
  15748. conn->response_info.status_code = 0;
  15749. conn->request_info.remote_user = NULL;
  15750. conn->request_info.request_method = NULL;
  15751. conn->request_info.request_uri = NULL;
  15752. /* Free cleaned local URI (if any) */
  15753. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15754. mg_free((void *)conn->request_info.local_uri);
  15755. conn->request_info.local_uri = NULL;
  15756. }
  15757. conn->request_info.local_uri = NULL;
  15758. #if defined(USE_SERVER_STATS)
  15759. conn->processing_time = 0;
  15760. #endif
  15761. }
  15762. static int
  15763. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15764. {
  15765. if ((so->lsa.sa.sa_family == AF_INET)
  15766. || (so->lsa.sa.sa_family == AF_INET6)) {
  15767. /* Only for TCP sockets */
  15768. if (setsockopt(so->sock,
  15769. IPPROTO_TCP,
  15770. TCP_NODELAY,
  15771. (SOCK_OPT_TYPE)&nodelay_on,
  15772. sizeof(nodelay_on))
  15773. != 0) {
  15774. /* Error */
  15775. return 1;
  15776. }
  15777. }
  15778. /* OK */
  15779. return 0;
  15780. }
  15781. #if !defined(__ZEPHYR__)
  15782. static void
  15783. close_socket_gracefully(struct mg_connection *conn)
  15784. {
  15785. #if defined(_WIN32)
  15786. char buf[MG_BUF_LEN];
  15787. int n;
  15788. #endif
  15789. struct linger linger;
  15790. int error_code = 0;
  15791. int linger_timeout = -2;
  15792. socklen_t opt_len = sizeof(error_code);
  15793. if (!conn) {
  15794. return;
  15795. }
  15796. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15797. * "Note that enabling a nonzero timeout on a nonblocking socket
  15798. * is not recommended.", so set it to blocking now */
  15799. set_blocking_mode(conn->client.sock);
  15800. /* Send FIN to the client */
  15801. shutdown(conn->client.sock, SHUTDOWN_WR);
  15802. #if defined(_WIN32)
  15803. /* Read and discard pending incoming data. If we do not do that and
  15804. * close
  15805. * the socket, the data in the send buffer may be discarded. This
  15806. * behaviour is seen on Windows, when client keeps sending data
  15807. * when server decides to close the connection; then when client
  15808. * does recv() it gets no data back. */
  15809. do {
  15810. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15811. } while (n > 0);
  15812. #endif
  15813. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15814. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15815. }
  15816. /* Set linger option according to configuration */
  15817. if (linger_timeout >= 0) {
  15818. /* Set linger option to avoid socket hanging out after close. This
  15819. * prevent ephemeral port exhaust problem under high QPS. */
  15820. linger.l_onoff = 1;
  15821. #if defined(_MSC_VER)
  15822. #pragma warning(push)
  15823. #pragma warning(disable : 4244)
  15824. #endif
  15825. #if defined(GCC_DIAGNOSTIC)
  15826. #pragma GCC diagnostic push
  15827. #pragma GCC diagnostic ignored "-Wconversion"
  15828. #endif
  15829. /* Data type of linger structure elements may differ,
  15830. * so we don't know what cast we need here.
  15831. * Disable type conversion warnings. */
  15832. linger.l_linger = (linger_timeout + 999) / 1000;
  15833. #if defined(GCC_DIAGNOSTIC)
  15834. #pragma GCC diagnostic pop
  15835. #endif
  15836. #if defined(_MSC_VER)
  15837. #pragma warning(pop)
  15838. #endif
  15839. } else {
  15840. linger.l_onoff = 0;
  15841. linger.l_linger = 0;
  15842. }
  15843. if (linger_timeout < -1) {
  15844. /* Default: don't configure any linger */
  15845. } else if (getsockopt(conn->client.sock,
  15846. SOL_SOCKET,
  15847. SO_ERROR,
  15848. #if defined(_WIN32) /* WinSock uses different data type here */
  15849. (char *)&error_code,
  15850. #else
  15851. &error_code,
  15852. #endif
  15853. &opt_len)
  15854. != 0) {
  15855. /* Cannot determine if socket is already closed. This should
  15856. * not occur and never did in a test. Log an error message
  15857. * and continue. */
  15858. mg_cry_internal(conn,
  15859. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15860. __func__,
  15861. strerror(ERRNO));
  15862. #if defined(_WIN32)
  15863. } else if (error_code == WSAECONNRESET) {
  15864. #else
  15865. } else if (error_code == ECONNRESET) {
  15866. #endif
  15867. /* Socket already closed by client/peer, close socket without linger
  15868. */
  15869. } else {
  15870. /* Set linger timeout */
  15871. if (setsockopt(conn->client.sock,
  15872. SOL_SOCKET,
  15873. SO_LINGER,
  15874. (char *)&linger,
  15875. sizeof(linger))
  15876. != 0) {
  15877. mg_cry_internal(
  15878. conn,
  15879. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15880. __func__,
  15881. linger.l_onoff,
  15882. linger.l_linger,
  15883. strerror(ERRNO));
  15884. }
  15885. }
  15886. /* Now we know that our FIN is ACK-ed, safe to close */
  15887. closesocket(conn->client.sock);
  15888. conn->client.sock = INVALID_SOCKET;
  15889. }
  15890. #endif
  15891. static void
  15892. close_connection(struct mg_connection *conn)
  15893. {
  15894. #if defined(USE_SERVER_STATS)
  15895. conn->conn_state = 6; /* to close */
  15896. #endif
  15897. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15898. if (conn->lua_websocket_state) {
  15899. lua_websocket_close(conn, conn->lua_websocket_state);
  15900. conn->lua_websocket_state = NULL;
  15901. }
  15902. #endif
  15903. mg_lock_connection(conn);
  15904. /* Set close flag, so keep-alive loops will stop */
  15905. conn->must_close = 1;
  15906. /* call the connection_close callback if assigned */
  15907. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15908. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15909. conn->phys_ctx->callbacks.connection_close(conn);
  15910. }
  15911. }
  15912. /* Reset user data, after close callback is called.
  15913. * Do not reuse it. If the user needs a destructor,
  15914. * it must be done in the connection_close callback. */
  15915. mg_set_user_connection_data(conn, NULL);
  15916. #if defined(USE_SERVER_STATS)
  15917. conn->conn_state = 7; /* closing */
  15918. #endif
  15919. #if defined(USE_MBEDTLS)
  15920. if (conn->ssl != NULL) {
  15921. mbed_ssl_close(conn->ssl);
  15922. conn->ssl = NULL;
  15923. }
  15924. #elif defined(USE_GNUTLS)
  15925. if (conn->ssl != NULL) {
  15926. gtls_ssl_close(conn->ssl);
  15927. conn->ssl = NULL;
  15928. }
  15929. #elif !defined(NO_SSL)
  15930. if (conn->ssl != NULL) {
  15931. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15932. */
  15933. SSL_shutdown(conn->ssl);
  15934. SSL_free(conn->ssl);
  15935. OPENSSL_REMOVE_THREAD_STATE();
  15936. conn->ssl = NULL;
  15937. }
  15938. #endif
  15939. if (conn->client.sock != INVALID_SOCKET) {
  15940. #if defined(__ZEPHYR__)
  15941. closesocket(conn->client.sock);
  15942. #else
  15943. close_socket_gracefully(conn);
  15944. #endif
  15945. conn->client.sock = INVALID_SOCKET;
  15946. }
  15947. /* call the connection_closed callback if assigned */
  15948. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15949. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15950. conn->phys_ctx->callbacks.connection_closed(conn);
  15951. }
  15952. }
  15953. mg_unlock_connection(conn);
  15954. #if defined(USE_SERVER_STATS)
  15955. conn->conn_state = 8; /* closed */
  15956. #endif
  15957. }
  15958. CIVETWEB_API void
  15959. mg_close_connection(struct mg_connection *conn)
  15960. {
  15961. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15962. return;
  15963. }
  15964. #if defined(USE_WEBSOCKET)
  15965. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15966. if (conn->in_websocket_handling) {
  15967. /* Set close flag, so the server thread can exit. */
  15968. conn->must_close = 1;
  15969. return;
  15970. }
  15971. }
  15972. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15973. unsigned int i;
  15974. /* client context: loops must end */
  15975. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15976. conn->must_close = 1;
  15977. /* We need to get the client thread out of the select/recv call
  15978. * here. */
  15979. /* Since we use a sleep quantum of some seconds to check for recv
  15980. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15981. /* join worker thread */
  15982. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15983. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15984. }
  15985. }
  15986. #endif /* defined(USE_WEBSOCKET) */
  15987. close_connection(conn);
  15988. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  15989. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15990. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15991. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15992. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15993. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15994. }
  15995. #endif
  15996. #if defined(USE_WEBSOCKET)
  15997. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15998. mg_free(conn->phys_ctx->worker_threadids);
  15999. (void)pthread_mutex_destroy(&conn->mutex);
  16000. mg_free(conn);
  16001. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  16002. (void)pthread_mutex_destroy(&conn->mutex);
  16003. mg_free(conn);
  16004. }
  16005. #else
  16006. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  16007. (void)pthread_mutex_destroy(&conn->mutex);
  16008. mg_free(conn);
  16009. }
  16010. #endif /* defined(USE_WEBSOCKET) */
  16011. }
  16012. static struct mg_connection *
  16013. mg_connect_client_impl(const struct mg_client_options *client_options,
  16014. int use_ssl,
  16015. struct mg_init_data *init,
  16016. struct mg_error_data *error)
  16017. {
  16018. struct mg_connection *conn = NULL;
  16019. SOCKET sock;
  16020. union usa sa;
  16021. struct sockaddr *psa;
  16022. socklen_t len;
  16023. unsigned max_req_size =
  16024. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  16025. /* Size of structures, aligned to 8 bytes */
  16026. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  16027. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  16028. size_t alloc_size = conn_size + ctx_size + max_req_size;
  16029. (void)init; /* TODO: Implement required options */
  16030. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  16031. if (error != NULL) {
  16032. error->code = MG_ERROR_DATA_CODE_OK;
  16033. error->code_sub = 0;
  16034. if (error->text_buffer_size > 0) {
  16035. error->text[0] = 0;
  16036. }
  16037. }
  16038. if (conn == NULL) {
  16039. if (error != NULL) {
  16040. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  16041. error->code_sub = (unsigned)alloc_size;
  16042. mg_snprintf(NULL,
  16043. NULL, /* No truncation check for ebuf */
  16044. error->text,
  16045. error->text_buffer_size,
  16046. "calloc(): %s",
  16047. strerror(ERRNO));
  16048. }
  16049. return NULL;
  16050. }
  16051. #if defined(GCC_DIAGNOSTIC)
  16052. #pragma GCC diagnostic push
  16053. #pragma GCC diagnostic ignored "-Wcast-align"
  16054. #endif /* defined(GCC_DIAGNOSTIC) */
  16055. /* conn_size is aligned to 8 bytes */
  16056. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  16057. #if defined(GCC_DIAGNOSTIC)
  16058. #pragma GCC diagnostic pop
  16059. #endif /* defined(GCC_DIAGNOSTIC) */
  16060. conn->buf = (((char *)conn) + conn_size + ctx_size);
  16061. conn->buf_size = (int)max_req_size;
  16062. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  16063. conn->dom_ctx = &(conn->phys_ctx->dd);
  16064. if (!connect_socket(conn->phys_ctx,
  16065. client_options->host,
  16066. client_options->port,
  16067. use_ssl,
  16068. error,
  16069. &sock,
  16070. &sa)) {
  16071. /* "error" will be set by connect_socket. */
  16072. /* free all memory and return NULL; */
  16073. mg_free(conn);
  16074. return NULL;
  16075. }
  16076. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16077. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16078. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16079. && !defined(NO_SSL_DL)
  16080. if (use_ssl
  16081. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16082. == NULL) {
  16083. if (error != NULL) {
  16084. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16085. mg_snprintf(NULL,
  16086. NULL, /* No truncation check for ebuf */
  16087. error->text,
  16088. error->text_buffer_size,
  16089. "SSL_CTX_new error: %s",
  16090. ssl_error());
  16091. }
  16092. closesocket(sock);
  16093. mg_free(conn);
  16094. return NULL;
  16095. }
  16096. #else
  16097. if (use_ssl
  16098. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16099. == NULL) {
  16100. if (error != NULL) {
  16101. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16102. mg_snprintf(NULL,
  16103. NULL, /* No truncation check for ebuf */
  16104. error->text,
  16105. error->text_buffer_size,
  16106. "SSL_CTX_new error: %s",
  16107. ssl_error());
  16108. }
  16109. closesocket(sock);
  16110. mg_free(conn);
  16111. return NULL;
  16112. }
  16113. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16114. #endif /* NO_SSL */
  16115. #if defined(USE_IPV6)
  16116. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16117. : sizeof(conn->client.rsa.sin6);
  16118. psa = (sa.sa.sa_family == AF_INET)
  16119. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16120. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16121. #else
  16122. len = sizeof(conn->client.rsa.sin);
  16123. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16124. #endif
  16125. conn->client.sock = sock;
  16126. conn->client.lsa = sa;
  16127. if (getsockname(sock, psa, &len) != 0) {
  16128. mg_cry_internal(conn,
  16129. "%s: getsockname() failed: %s",
  16130. __func__,
  16131. strerror(ERRNO));
  16132. }
  16133. conn->client.is_ssl = use_ssl ? 1 : 0;
  16134. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16135. if (error != NULL) {
  16136. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16137. error->code_sub = (unsigned)ERRNO;
  16138. mg_snprintf(NULL,
  16139. NULL, /* No truncation check for ebuf */
  16140. error->text,
  16141. error->text_buffer_size,
  16142. "Can not create mutex");
  16143. }
  16144. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16145. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16146. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16147. #endif
  16148. closesocket(sock);
  16149. mg_free(conn);
  16150. return NULL;
  16151. }
  16152. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16153. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16154. if (use_ssl) {
  16155. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16156. * SSL_CTX_set_verify call is needed to switch off server
  16157. * certificate checking, which is off by default in OpenSSL and
  16158. * on in yaSSL. */
  16159. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16160. * SSL_VERIFY_PEER, verify_ssl_server); */
  16161. if (client_options->client_cert) {
  16162. if (!ssl_use_pem_file(conn->phys_ctx,
  16163. conn->dom_ctx,
  16164. client_options->client_cert,
  16165. NULL)) {
  16166. if (error != NULL) {
  16167. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16168. mg_snprintf(NULL,
  16169. NULL, /* No truncation check for ebuf */
  16170. error->text,
  16171. error->text_buffer_size,
  16172. "Can not use SSL client certificate");
  16173. }
  16174. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16175. closesocket(sock);
  16176. mg_free(conn);
  16177. return NULL;
  16178. }
  16179. }
  16180. if (client_options->server_cert) {
  16181. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16182. client_options->server_cert,
  16183. NULL)
  16184. != 1) {
  16185. if (error != NULL) {
  16186. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16187. mg_snprintf(NULL,
  16188. NULL, /* No truncation check for ebuf */
  16189. error->text,
  16190. error->text_buffer_size,
  16191. "SSL_CTX_load_verify_locations error: %s",
  16192. ssl_error());
  16193. }
  16194. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16195. closesocket(sock);
  16196. mg_free(conn);
  16197. return NULL;
  16198. }
  16199. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16200. } else {
  16201. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16202. }
  16203. if (!sslize(conn, SSL_connect, client_options)) {
  16204. if (error != NULL) {
  16205. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16206. mg_snprintf(NULL,
  16207. NULL, /* No truncation check for ebuf */
  16208. error->text,
  16209. error->text_buffer_size,
  16210. "SSL connection error");
  16211. }
  16212. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16213. closesocket(sock);
  16214. mg_free(conn);
  16215. return NULL;
  16216. }
  16217. }
  16218. #endif
  16219. return conn;
  16220. }
  16221. CIVETWEB_API struct mg_connection *
  16222. mg_connect_client_secure(const struct mg_client_options *client_options,
  16223. char *error_buffer,
  16224. size_t error_buffer_size)
  16225. {
  16226. struct mg_init_data init;
  16227. struct mg_error_data error;
  16228. memset(&init, 0, sizeof(init));
  16229. memset(&error, 0, sizeof(error));
  16230. error.text_buffer_size = error_buffer_size;
  16231. error.text = error_buffer;
  16232. return mg_connect_client_impl(client_options, 1, &init, &error);
  16233. }
  16234. CIVETWEB_API struct mg_connection *
  16235. mg_connect_client(const char *host,
  16236. int port,
  16237. int use_ssl,
  16238. char *error_buffer,
  16239. size_t error_buffer_size)
  16240. {
  16241. struct mg_client_options opts;
  16242. struct mg_init_data init;
  16243. struct mg_error_data error;
  16244. memset(&init, 0, sizeof(init));
  16245. memset(&error, 0, sizeof(error));
  16246. error.text_buffer_size = error_buffer_size;
  16247. error.text = error_buffer;
  16248. memset(&opts, 0, sizeof(opts));
  16249. opts.host = host;
  16250. opts.port = port;
  16251. if (use_ssl) {
  16252. opts.host_name = host;
  16253. }
  16254. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16255. }
  16256. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16257. CIVETWEB_API struct mg_connection *
  16258. mg_connect_client2(const char *host,
  16259. const char *protocol,
  16260. int port,
  16261. const char *path,
  16262. struct mg_init_data *init,
  16263. struct mg_error_data *error)
  16264. {
  16265. (void)path;
  16266. int is_ssl, is_ws;
  16267. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16268. if (error != NULL) {
  16269. error->code = MG_ERROR_DATA_CODE_OK;
  16270. error->code_sub = 0;
  16271. if (error->text_buffer_size > 0) {
  16272. *error->text = 0;
  16273. }
  16274. }
  16275. if ((host == NULL) || (protocol == NULL)) {
  16276. if (error != NULL) {
  16277. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16278. mg_snprintf(NULL,
  16279. NULL, /* No truncation check for error buffers */
  16280. error->text,
  16281. error->text_buffer_size,
  16282. "%s",
  16283. "Invalid parameters");
  16284. }
  16285. return NULL;
  16286. }
  16287. /* check all known protocols */
  16288. if (!mg_strcasecmp(protocol, "http")) {
  16289. is_ssl = 0;
  16290. is_ws = 0;
  16291. } else if (!mg_strcasecmp(protocol, "https")) {
  16292. is_ssl = 1;
  16293. is_ws = 0;
  16294. #if defined(USE_WEBSOCKET)
  16295. } else if (!mg_strcasecmp(protocol, "ws")) {
  16296. is_ssl = 0;
  16297. is_ws = 1;
  16298. } else if (!mg_strcasecmp(protocol, "wss")) {
  16299. is_ssl = 1;
  16300. is_ws = 1;
  16301. #endif
  16302. } else {
  16303. if (error != NULL) {
  16304. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16305. mg_snprintf(NULL,
  16306. NULL, /* No truncation check for error buffers */
  16307. error->text,
  16308. error->text_buffer_size,
  16309. "Protocol %s not supported",
  16310. protocol);
  16311. }
  16312. return NULL;
  16313. }
  16314. /* TODO: The current implementation here just calls the old
  16315. * implementations, without using any new options. This is just a first
  16316. * step to test the new interfaces. */
  16317. #if defined(USE_WEBSOCKET)
  16318. if (is_ws) {
  16319. /* TODO: implement all options */
  16320. return mg_connect_websocket_client(
  16321. host,
  16322. port,
  16323. is_ssl,
  16324. ((error != NULL) ? error->text : NULL),
  16325. ((error != NULL) ? error->text_buffer_size : 0),
  16326. (path ? path : ""),
  16327. NULL /* TODO: origin */,
  16328. experimental_websocket_client_data_wrapper,
  16329. experimental_websocket_client_close_wrapper,
  16330. (void *)init->callbacks);
  16331. }
  16332. #else
  16333. (void)is_ws;
  16334. #endif
  16335. /* TODO: all additional options */
  16336. struct mg_client_options opts;
  16337. memset(&opts, 0, sizeof(opts));
  16338. opts.host = host;
  16339. opts.port = port;
  16340. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16341. }
  16342. #endif
  16343. static const struct {
  16344. const char *proto;
  16345. size_t proto_len;
  16346. unsigned default_port;
  16347. } abs_uri_protocols[] = {{"http://", 7, 80},
  16348. {"https://", 8, 443},
  16349. {"ws://", 5, 80},
  16350. {"wss://", 6, 443},
  16351. {NULL, 0, 0}};
  16352. /* Check if the uri is valid.
  16353. * return 0 for invalid uri,
  16354. * return 1 for *,
  16355. * return 2 for relative uri,
  16356. * return 3 for absolute uri without port,
  16357. * return 4 for absolute uri with port */
  16358. static int
  16359. get_uri_type(const char *uri)
  16360. {
  16361. int i;
  16362. const char *hostend, *portbegin;
  16363. char *portend;
  16364. unsigned long port;
  16365. /* According to the HTTP standard
  16366. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16367. * URI can be an asterisk (*) or should start with slash (relative uri),
  16368. * or it should start with the protocol (absolute uri). */
  16369. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16370. /* asterisk */
  16371. return 1;
  16372. }
  16373. /* Valid URIs according to RFC 3986
  16374. * (https://www.ietf.org/rfc/rfc3986.txt)
  16375. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16376. * and unreserved characters A-Z a-z 0-9 and -._~
  16377. * and % encoded symbols.
  16378. */
  16379. for (i = 0; uri[i] != 0; i++) {
  16380. /* Check for CRLF injection attempts */
  16381. if (uri[i] == '%') {
  16382. if (uri[i + 1] == '0' && (uri[i + 2] == 'd' || uri[i + 2] == 'D')) {
  16383. /* Found %0d (CR) */
  16384. DEBUG_TRACE("CRLF injection attempt detected: %s\r\n", uri);
  16385. return 0;
  16386. }
  16387. if (uri[i + 1] == '0' && (uri[i + 2] == 'a' || uri[i + 2] == 'A')) {
  16388. /* Found %0a (LF) */
  16389. DEBUG_TRACE("CRLF injection attempt detected: %s\r\n", uri);
  16390. return 0;
  16391. }
  16392. }
  16393. if ((unsigned char)uri[i] < 33) {
  16394. /* control characters and spaces are invalid */
  16395. return 0;
  16396. }
  16397. /* Allow everything else here (See #894) */
  16398. }
  16399. /* A relative uri starts with a / character */
  16400. if (uri[0] == '/') {
  16401. /* relative uri */
  16402. return 2;
  16403. }
  16404. /* It could be an absolute uri: */
  16405. /* This function only checks if the uri is valid, not if it is
  16406. * addressing the current server. So civetweb can also be used
  16407. * as a proxy server. */
  16408. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16409. if (mg_strncasecmp(uri,
  16410. abs_uri_protocols[i].proto,
  16411. abs_uri_protocols[i].proto_len)
  16412. == 0) {
  16413. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16414. if (!hostend) {
  16415. return 0;
  16416. }
  16417. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16418. if (!portbegin) {
  16419. return 3;
  16420. }
  16421. port = strtoul(portbegin + 1, &portend, 10);
  16422. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16423. return 0;
  16424. }
  16425. return 4;
  16426. }
  16427. }
  16428. return 0;
  16429. }
  16430. /* Return NULL or the relative uri at the current server */
  16431. static const char *
  16432. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16433. {
  16434. const char *server_domain;
  16435. size_t server_domain_len;
  16436. size_t request_domain_len = 0;
  16437. unsigned long port = 0;
  16438. int i, auth_domain_check_enabled;
  16439. const char *hostbegin = NULL;
  16440. const char *hostend = NULL;
  16441. const char *portbegin;
  16442. char *portend;
  16443. auth_domain_check_enabled =
  16444. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16445. /* DNS is case insensitive, so use case insensitive string compare here
  16446. */
  16447. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16448. if (mg_strncasecmp(uri,
  16449. abs_uri_protocols[i].proto,
  16450. abs_uri_protocols[i].proto_len)
  16451. == 0) {
  16452. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16453. hostend = strchr(hostbegin, '/');
  16454. if (!hostend) {
  16455. return 0;
  16456. }
  16457. portbegin = strchr(hostbegin, ':');
  16458. if ((!portbegin) || (portbegin > hostend)) {
  16459. port = abs_uri_protocols[i].default_port;
  16460. request_domain_len = (size_t)(hostend - hostbegin);
  16461. } else {
  16462. port = strtoul(portbegin + 1, &portend, 10);
  16463. if ((portend != hostend) || (port <= 0)
  16464. || !is_valid_port(port)) {
  16465. return 0;
  16466. }
  16467. request_domain_len = (size_t)(portbegin - hostbegin);
  16468. }
  16469. /* protocol found, port set */
  16470. break;
  16471. }
  16472. }
  16473. if (!port) {
  16474. /* port remains 0 if the protocol is not found */
  16475. return 0;
  16476. }
  16477. /* Check if the request is directed to a different server. */
  16478. /* First check if the port is the same. */
  16479. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16480. /* Request is directed to a different port */
  16481. return 0;
  16482. }
  16483. /* Finally check if the server corresponds to the authentication
  16484. * domain of the server (the server domain).
  16485. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16486. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16487. * but do not allow substrings (like
  16488. * http://notmydomain.com/path/file.ext
  16489. * or http://mydomain.com.fake/path/file.ext).
  16490. */
  16491. if (auth_domain_check_enabled) {
  16492. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16493. server_domain_len = strlen(server_domain);
  16494. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16495. return 0;
  16496. }
  16497. if ((request_domain_len == server_domain_len)
  16498. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16499. /* Request is directed to this server - full name match. */
  16500. } else {
  16501. if (request_domain_len < (server_domain_len + 2)) {
  16502. /* Request is directed to another server: The server name
  16503. * is longer than the request name.
  16504. * Drop this case here to avoid overflows in the
  16505. * following checks. */
  16506. return 0;
  16507. }
  16508. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16509. /* Request is directed to another server: It could be a
  16510. * substring
  16511. * like notmyserver.com */
  16512. return 0;
  16513. }
  16514. if (0
  16515. != memcmp(server_domain,
  16516. hostbegin + request_domain_len - server_domain_len,
  16517. server_domain_len)) {
  16518. /* Request is directed to another server:
  16519. * The server name is different. */
  16520. return 0;
  16521. }
  16522. }
  16523. }
  16524. return hostend;
  16525. }
  16526. static int
  16527. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16528. {
  16529. if (ebuf_len > 0) {
  16530. ebuf[0] = '\0';
  16531. }
  16532. *err = 0;
  16533. reset_per_request_attributes(conn);
  16534. if (!conn) {
  16535. mg_snprintf(conn,
  16536. NULL, /* No truncation check for ebuf */
  16537. ebuf,
  16538. ebuf_len,
  16539. "%s",
  16540. "Internal error");
  16541. *err = 500;
  16542. return 0;
  16543. }
  16544. /* Set the time the request was received. This value should be used for
  16545. * timeouts. */
  16546. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16547. conn->request_len =
  16548. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16549. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16550. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16551. mg_snprintf(conn,
  16552. NULL, /* No truncation check for ebuf */
  16553. ebuf,
  16554. ebuf_len,
  16555. "%s",
  16556. "Invalid message size");
  16557. *err = 500;
  16558. return 0;
  16559. }
  16560. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16561. mg_snprintf(conn,
  16562. NULL, /* No truncation check for ebuf */
  16563. ebuf,
  16564. ebuf_len,
  16565. "%s",
  16566. "Message too large");
  16567. *err = 413;
  16568. return 0;
  16569. }
  16570. if (conn->request_len <= 0) {
  16571. if (conn->data_len > 0) {
  16572. mg_snprintf(conn,
  16573. NULL, /* No truncation check for ebuf */
  16574. ebuf,
  16575. ebuf_len,
  16576. "%s",
  16577. conn->request_len == -3 ? "Request timeout"
  16578. : "Malformed message");
  16579. *err = 400;
  16580. } else {
  16581. /* Server did not recv anything -> just close the connection */
  16582. conn->must_close = 1;
  16583. mg_snprintf(conn,
  16584. NULL, /* No truncation check for ebuf */
  16585. ebuf,
  16586. ebuf_len,
  16587. "%s",
  16588. "No data received");
  16589. *err = 0;
  16590. }
  16591. return 0;
  16592. }
  16593. return 1;
  16594. }
  16595. static int
  16596. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16597. {
  16598. const char *cl;
  16599. conn->connection_type =
  16600. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16601. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16602. return 0;
  16603. }
  16604. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16605. <= 0) {
  16606. mg_snprintf(conn,
  16607. NULL, /* No truncation check for ebuf */
  16608. ebuf,
  16609. ebuf_len,
  16610. "%s",
  16611. "Bad request");
  16612. *err = 400;
  16613. return 0;
  16614. }
  16615. /* Message is a valid request */
  16616. if (!switch_domain_context(conn)) {
  16617. mg_snprintf(conn,
  16618. NULL, /* No truncation check for ebuf */
  16619. ebuf,
  16620. ebuf_len,
  16621. "%s",
  16622. "Bad request: Host mismatch");
  16623. *err = 400;
  16624. return 0;
  16625. }
  16626. #if USE_ZLIB
  16627. if (((cl = get_header(conn->request_info.http_headers,
  16628. conn->request_info.num_headers,
  16629. "Accept-Encoding"))
  16630. != NULL)
  16631. && strstr(cl, "gzip")) {
  16632. conn->accept_gzip = 1;
  16633. }
  16634. #endif
  16635. if (((cl = get_header(conn->request_info.http_headers,
  16636. conn->request_info.num_headers,
  16637. "Transfer-Encoding"))
  16638. != NULL)
  16639. && mg_strcasecmp(cl, "identity")) {
  16640. if (mg_strcasecmp(cl, "chunked")) {
  16641. mg_snprintf(conn,
  16642. NULL, /* No truncation check for ebuf */
  16643. ebuf,
  16644. ebuf_len,
  16645. "%s",
  16646. "Bad request");
  16647. *err = 400;
  16648. return 0;
  16649. }
  16650. conn->is_chunked = 1;
  16651. conn->content_len = 0; /* not yet read */
  16652. } else if ((cl = get_header(conn->request_info.http_headers,
  16653. conn->request_info.num_headers,
  16654. "Content-Length"))
  16655. != NULL) {
  16656. /* Request has content length set */
  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 request info. */
  16670. conn->request_info.content_length = conn->content_len;
  16671. } else {
  16672. /* There is no exception, see RFC7230. */
  16673. conn->content_len = 0;
  16674. }
  16675. return 1;
  16676. }
  16677. /* conn is assumed to be valid in this internal function */
  16678. static int
  16679. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16680. {
  16681. const char *cl;
  16682. conn->connection_type =
  16683. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16684. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16685. return 0;
  16686. }
  16687. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16688. <= 0) {
  16689. mg_snprintf(conn,
  16690. NULL, /* No truncation check for ebuf */
  16691. ebuf,
  16692. ebuf_len,
  16693. "%s",
  16694. "Bad response");
  16695. *err = 400;
  16696. return 0;
  16697. }
  16698. /* Message is a valid response */
  16699. if (((cl = get_header(conn->response_info.http_headers,
  16700. conn->response_info.num_headers,
  16701. "Transfer-Encoding"))
  16702. != NULL)
  16703. && mg_strcasecmp(cl, "identity")) {
  16704. if (mg_strcasecmp(cl, "chunked")) {
  16705. mg_snprintf(conn,
  16706. NULL, /* No truncation check for ebuf */
  16707. ebuf,
  16708. ebuf_len,
  16709. "%s",
  16710. "Bad request");
  16711. *err = 400;
  16712. return 0;
  16713. }
  16714. conn->is_chunked = 1;
  16715. conn->content_len = 0; /* not yet read */
  16716. } else if ((cl = get_header(conn->response_info.http_headers,
  16717. conn->response_info.num_headers,
  16718. "Content-Length"))
  16719. != NULL) {
  16720. char *endptr = NULL;
  16721. conn->content_len = strtoll(cl, &endptr, 10);
  16722. if ((endptr == cl) || (conn->content_len < 0)) {
  16723. mg_snprintf(conn,
  16724. NULL, /* No truncation check for ebuf */
  16725. ebuf,
  16726. ebuf_len,
  16727. "%s",
  16728. "Bad request");
  16729. *err = 411;
  16730. return 0;
  16731. }
  16732. /* Publish the content length back to the response info. */
  16733. conn->response_info.content_length = conn->content_len;
  16734. /* TODO: check if it is still used in response_info */
  16735. conn->request_info.content_length = conn->content_len;
  16736. /* TODO: we should also consider HEAD method */
  16737. if (conn->response_info.status_code == 304) {
  16738. conn->content_len = 0;
  16739. }
  16740. } else {
  16741. /* TODO: we should also consider HEAD method */
  16742. if (((conn->response_info.status_code >= 100)
  16743. && (conn->response_info.status_code <= 199))
  16744. || (conn->response_info.status_code == 204)
  16745. || (conn->response_info.status_code == 304)) {
  16746. conn->content_len = 0;
  16747. } else {
  16748. conn->content_len = -1; /* unknown content length */
  16749. }
  16750. }
  16751. return 1;
  16752. }
  16753. CIVETWEB_API int
  16754. mg_get_response(struct mg_connection *conn,
  16755. char *ebuf,
  16756. size_t ebuf_len,
  16757. int timeout)
  16758. {
  16759. int err, ret;
  16760. char txt[32]; /* will not overflow */
  16761. char *save_timeout;
  16762. char *new_timeout;
  16763. if (ebuf_len > 0) {
  16764. ebuf[0] = '\0';
  16765. }
  16766. if (!conn) {
  16767. mg_snprintf(conn,
  16768. NULL, /* No truncation check for ebuf */
  16769. ebuf,
  16770. ebuf_len,
  16771. "%s",
  16772. "Parameter error");
  16773. return -1;
  16774. }
  16775. /* Reset the previous responses */
  16776. conn->data_len = 0;
  16777. /* Implementation of API function for HTTP clients */
  16778. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16779. if (timeout >= 0) {
  16780. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16781. new_timeout = txt;
  16782. } else {
  16783. new_timeout = NULL;
  16784. }
  16785. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16786. ret = get_response(conn, ebuf, ebuf_len, &err);
  16787. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16788. /* TODO: here, the URI is the http response code */
  16789. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16790. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16791. /* TODO (mid): Define proper return values - maybe return length?
  16792. * For the first test use <0 for error and >0 for OK */
  16793. return (ret == 0) ? -1 : +1;
  16794. }
  16795. CIVETWEB_API struct mg_connection *
  16796. mg_download(const char *host,
  16797. int port,
  16798. int use_ssl,
  16799. char *ebuf,
  16800. size_t ebuf_len,
  16801. const char *fmt,
  16802. ...)
  16803. {
  16804. struct mg_connection *conn;
  16805. va_list ap;
  16806. int i;
  16807. int reqerr;
  16808. if (ebuf_len > 0) {
  16809. ebuf[0] = '\0';
  16810. }
  16811. va_start(ap, fmt);
  16812. /* open a connection */
  16813. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16814. if (conn != NULL) {
  16815. i = mg_vprintf(conn, fmt, ap);
  16816. if (i <= 0) {
  16817. mg_snprintf(conn,
  16818. NULL, /* No truncation check for ebuf */
  16819. ebuf,
  16820. ebuf_len,
  16821. "%s",
  16822. "Error sending request");
  16823. } else {
  16824. /* make sure the buffer is clear */
  16825. conn->data_len = 0;
  16826. get_response(conn, ebuf, ebuf_len, &reqerr);
  16827. /* TODO: here, the URI is the http response code */
  16828. conn->request_info.local_uri = conn->request_info.request_uri;
  16829. }
  16830. }
  16831. /* if an error occurred, close the connection */
  16832. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16833. mg_close_connection(conn);
  16834. conn = NULL;
  16835. }
  16836. va_end(ap);
  16837. return conn;
  16838. }
  16839. struct websocket_client_thread_data {
  16840. struct mg_connection *conn;
  16841. mg_websocket_data_handler data_handler;
  16842. mg_websocket_close_handler close_handler;
  16843. void *callback_data;
  16844. };
  16845. #if defined(USE_WEBSOCKET)
  16846. #if defined(_WIN32)
  16847. static unsigned __stdcall websocket_client_thread(void *data)
  16848. #else
  16849. static void *
  16850. websocket_client_thread(void *data)
  16851. #endif
  16852. {
  16853. struct websocket_client_thread_data *cdata =
  16854. (struct websocket_client_thread_data *)data;
  16855. void *user_thread_ptr = NULL;
  16856. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16857. struct sigaction sa;
  16858. /* Ignore SIGPIPE */
  16859. memset(&sa, 0, sizeof(sa));
  16860. sa.sa_handler = SIG_IGN;
  16861. sigaction(SIGPIPE, &sa, NULL);
  16862. #endif
  16863. mg_set_thread_name("ws-clnt");
  16864. if (cdata->conn->phys_ctx) {
  16865. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16866. /* 3 indicates a websocket client thread */
  16867. /* TODO: check if conn->phys_ctx can be set */
  16868. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16869. cdata->conn->phys_ctx, 3);
  16870. }
  16871. }
  16872. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16873. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16874. if (cdata->close_handler != NULL) {
  16875. cdata->close_handler(cdata->conn, cdata->callback_data);
  16876. }
  16877. /* The websocket_client context has only this thread. If it runs out,
  16878. set the stop_flag to 2 (= "stopped"). */
  16879. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16880. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16881. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16882. 3,
  16883. user_thread_ptr);
  16884. }
  16885. mg_free((void *)cdata);
  16886. #if defined(_WIN32)
  16887. return 0;
  16888. #else
  16889. return NULL;
  16890. #endif
  16891. }
  16892. #endif
  16893. #if defined(USE_WEBSOCKET)
  16894. static void
  16895. generate_websocket_magic(char *magic25)
  16896. {
  16897. uint64_t rnd;
  16898. unsigned char buffer[2 * sizeof(rnd)];
  16899. rnd = get_random();
  16900. memcpy(buffer, &rnd, sizeof(rnd));
  16901. rnd = get_random();
  16902. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16903. size_t dst_len = 24 + 1;
  16904. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16905. }
  16906. #endif
  16907. static struct mg_connection *
  16908. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16909. int use_ssl,
  16910. char *error_buffer,
  16911. size_t error_buffer_size,
  16912. const char *path,
  16913. const char *origin,
  16914. const char *extensions,
  16915. mg_websocket_data_handler data_func,
  16916. mg_websocket_close_handler close_func,
  16917. void *user_data)
  16918. {
  16919. struct mg_connection *conn = NULL;
  16920. #if defined(USE_WEBSOCKET)
  16921. struct websocket_client_thread_data *thread_data;
  16922. char magic[32];
  16923. generate_websocket_magic(magic);
  16924. const char *host = client_options->host;
  16925. int i;
  16926. struct mg_init_data init;
  16927. struct mg_error_data error;
  16928. memset(&init, 0, sizeof(init));
  16929. memset(&error, 0, sizeof(error));
  16930. error.text_buffer_size = error_buffer_size;
  16931. error.text = error_buffer;
  16932. #if defined(__clang__)
  16933. #pragma clang diagnostic push
  16934. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16935. #endif
  16936. /* Establish the client connection and request upgrade */
  16937. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16938. /* Connection object will be null if something goes wrong */
  16939. if (conn == NULL) {
  16940. /* error_buffer should be already filled ... */
  16941. if (!error_buffer[0]) {
  16942. /* ... if not add an error message */
  16943. mg_snprintf(conn,
  16944. NULL, /* No truncation check for ebuf */
  16945. error_buffer,
  16946. error_buffer_size,
  16947. "Unexpected error");
  16948. }
  16949. return NULL;
  16950. }
  16951. if (origin != NULL) {
  16952. if (extensions != NULL) {
  16953. i = mg_printf(conn,
  16954. "GET %s HTTP/1.1\r\n"
  16955. "Host: %s\r\n"
  16956. "Upgrade: websocket\r\n"
  16957. "Connection: Upgrade\r\n"
  16958. "Sec-WebSocket-Key: %s\r\n"
  16959. "Sec-WebSocket-Version: 13\r\n"
  16960. "Sec-WebSocket-Extensions: %s\r\n"
  16961. "Origin: %s\r\n"
  16962. "\r\n",
  16963. path,
  16964. host,
  16965. magic,
  16966. extensions,
  16967. origin);
  16968. } else {
  16969. i = mg_printf(conn,
  16970. "GET %s HTTP/1.1\r\n"
  16971. "Host: %s\r\n"
  16972. "Upgrade: websocket\r\n"
  16973. "Connection: Upgrade\r\n"
  16974. "Sec-WebSocket-Key: %s\r\n"
  16975. "Sec-WebSocket-Version: 13\r\n"
  16976. "Origin: %s\r\n"
  16977. "\r\n",
  16978. path,
  16979. host,
  16980. magic,
  16981. origin);
  16982. }
  16983. } else {
  16984. if (extensions != NULL) {
  16985. i = mg_printf(conn,
  16986. "GET %s HTTP/1.1\r\n"
  16987. "Host: %s\r\n"
  16988. "Upgrade: websocket\r\n"
  16989. "Connection: Upgrade\r\n"
  16990. "Sec-WebSocket-Key: %s\r\n"
  16991. "Sec-WebSocket-Version: 13\r\n"
  16992. "Sec-WebSocket-Extensions: %s\r\n"
  16993. "\r\n",
  16994. path,
  16995. host,
  16996. magic,
  16997. extensions);
  16998. } else {
  16999. i = mg_printf(conn,
  17000. "GET %s HTTP/1.1\r\n"
  17001. "Host: %s\r\n"
  17002. "Upgrade: websocket\r\n"
  17003. "Connection: Upgrade\r\n"
  17004. "Sec-WebSocket-Key: %s\r\n"
  17005. "Sec-WebSocket-Version: 13\r\n"
  17006. "\r\n",
  17007. path,
  17008. host,
  17009. magic);
  17010. }
  17011. }
  17012. if (i <= 0) {
  17013. mg_snprintf(conn,
  17014. NULL, /* No truncation check for ebuf */
  17015. error_buffer,
  17016. error_buffer_size,
  17017. "%s",
  17018. "Error sending request");
  17019. mg_close_connection(conn);
  17020. return NULL;
  17021. }
  17022. conn->data_len = 0;
  17023. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  17024. mg_close_connection(conn);
  17025. return NULL;
  17026. }
  17027. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  17028. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  17029. #if defined(__clang__)
  17030. #pragma clang diagnostic pop
  17031. #endif
  17032. if (conn->response_info.status_code != 101) {
  17033. /* We sent an "upgrade" request. For a correct websocket
  17034. * protocol handshake, we expect a "101 Continue" response.
  17035. * Otherwise it is a protocol violation. Maybe the HTTP
  17036. * Server does not know websockets. */
  17037. if (!*error_buffer) {
  17038. /* set an error, if not yet set */
  17039. mg_snprintf(conn,
  17040. NULL, /* No truncation check for ebuf */
  17041. error_buffer,
  17042. error_buffer_size,
  17043. "Unexpected server reply");
  17044. }
  17045. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  17046. mg_close_connection(conn);
  17047. return NULL;
  17048. }
  17049. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  17050. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  17051. if (!thread_data) {
  17052. DEBUG_TRACE("%s\r\n", "Out of memory");
  17053. mg_close_connection(conn);
  17054. return NULL;
  17055. }
  17056. thread_data->conn = conn;
  17057. thread_data->data_handler = data_func;
  17058. thread_data->close_handler = close_func;
  17059. thread_data->callback_data = user_data;
  17060. conn->phys_ctx->worker_threadids =
  17061. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  17062. if (!conn->phys_ctx->worker_threadids) {
  17063. DEBUG_TRACE("%s\r\n", "Out of memory");
  17064. mg_free(thread_data);
  17065. mg_close_connection(conn);
  17066. return NULL;
  17067. }
  17068. /* Now upgrade to ws/wss client context */
  17069. conn->phys_ctx->user_data = user_data;
  17070. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  17071. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  17072. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  17073. /* Start a thread to read the websocket client connection
  17074. * This thread will automatically stop when mg_disconnect is
  17075. * called on the client connection */
  17076. if (mg_start_thread_with_id(websocket_client_thread,
  17077. thread_data,
  17078. conn->phys_ctx->worker_threadids)
  17079. != 0) {
  17080. conn->phys_ctx->spawned_worker_threads = 0;
  17081. mg_free(thread_data);
  17082. mg_close_connection(conn);
  17083. conn = NULL;
  17084. DEBUG_TRACE("%s",
  17085. "Websocket client connect thread could not be started\r\n");
  17086. }
  17087. #else
  17088. /* Appease "unused parameter" warnings */
  17089. (void)client_options;
  17090. (void)use_ssl;
  17091. (void)error_buffer;
  17092. (void)error_buffer_size;
  17093. (void)path;
  17094. (void)origin;
  17095. (void)extensions;
  17096. (void)user_data;
  17097. (void)data_func;
  17098. (void)close_func;
  17099. #endif
  17100. return conn;
  17101. }
  17102. CIVETWEB_API struct mg_connection *
  17103. mg_connect_websocket_client(const char *host,
  17104. int port,
  17105. int use_ssl,
  17106. char *error_buffer,
  17107. size_t error_buffer_size,
  17108. const char *path,
  17109. const char *origin,
  17110. mg_websocket_data_handler data_func,
  17111. mg_websocket_close_handler close_func,
  17112. void *user_data)
  17113. {
  17114. struct mg_client_options client_options;
  17115. memset(&client_options, 0, sizeof(client_options));
  17116. client_options.host = host;
  17117. client_options.port = port;
  17118. if (use_ssl) {
  17119. client_options.host_name = host;
  17120. }
  17121. return mg_connect_websocket_client_impl(&client_options,
  17122. use_ssl,
  17123. error_buffer,
  17124. error_buffer_size,
  17125. path,
  17126. origin,
  17127. NULL,
  17128. data_func,
  17129. close_func,
  17130. user_data);
  17131. }
  17132. CIVETWEB_API struct mg_connection *
  17133. mg_connect_websocket_client_secure(
  17134. const struct mg_client_options *client_options,
  17135. char *error_buffer,
  17136. size_t error_buffer_size,
  17137. const char *path,
  17138. const char *origin,
  17139. mg_websocket_data_handler data_func,
  17140. mg_websocket_close_handler close_func,
  17141. void *user_data)
  17142. {
  17143. if (!client_options) {
  17144. return NULL;
  17145. }
  17146. return mg_connect_websocket_client_impl(client_options,
  17147. 1,
  17148. error_buffer,
  17149. error_buffer_size,
  17150. path,
  17151. origin,
  17152. NULL,
  17153. data_func,
  17154. close_func,
  17155. user_data);
  17156. }
  17157. CIVETWEB_API struct mg_connection *
  17158. mg_connect_websocket_client_extensions(const char *host,
  17159. int port,
  17160. int use_ssl,
  17161. char *error_buffer,
  17162. size_t error_buffer_size,
  17163. const char *path,
  17164. const char *origin,
  17165. const char *extensions,
  17166. mg_websocket_data_handler data_func,
  17167. mg_websocket_close_handler close_func,
  17168. void *user_data)
  17169. {
  17170. struct mg_client_options client_options;
  17171. memset(&client_options, 0, sizeof(client_options));
  17172. client_options.host = host;
  17173. client_options.port = port;
  17174. return mg_connect_websocket_client_impl(&client_options,
  17175. use_ssl,
  17176. error_buffer,
  17177. error_buffer_size,
  17178. path,
  17179. origin,
  17180. extensions,
  17181. data_func,
  17182. close_func,
  17183. user_data);
  17184. }
  17185. CIVETWEB_API struct mg_connection *
  17186. mg_connect_websocket_client_secure_extensions(
  17187. const struct mg_client_options *client_options,
  17188. char *error_buffer,
  17189. size_t error_buffer_size,
  17190. const char *path,
  17191. const char *origin,
  17192. const char *extensions,
  17193. mg_websocket_data_handler data_func,
  17194. mg_websocket_close_handler close_func,
  17195. void *user_data)
  17196. {
  17197. if (!client_options) {
  17198. return NULL;
  17199. }
  17200. return mg_connect_websocket_client_impl(client_options,
  17201. 1,
  17202. error_buffer,
  17203. error_buffer_size,
  17204. path,
  17205. origin,
  17206. extensions,
  17207. data_func,
  17208. close_func,
  17209. user_data);
  17210. }
  17211. /* Prepare connection data structure */
  17212. static void
  17213. init_connection(struct mg_connection *conn)
  17214. {
  17215. /* Is keep alive allowed by the server */
  17216. int keep_alive_enabled =
  17217. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17218. if (!keep_alive_enabled) {
  17219. conn->must_close = 1;
  17220. }
  17221. /* Important: on new connection, reset the receiving buffer. Credit
  17222. * goes to crule42. */
  17223. conn->data_len = 0;
  17224. conn->handled_requests = 0;
  17225. conn->connection_type = CONNECTION_TYPE_INVALID;
  17226. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17227. mg_set_user_connection_data(conn, NULL);
  17228. #if defined(USE_SERVER_STATS)
  17229. conn->conn_state = 2; /* init */
  17230. #endif
  17231. /* call the init_connection callback if assigned */
  17232. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17233. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17234. void *conn_data = NULL;
  17235. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17236. mg_set_user_connection_data(conn, conn_data);
  17237. }
  17238. }
  17239. }
  17240. /* Process a connection - may handle multiple requests
  17241. * using the same connection.
  17242. * Must be called with a valid connection (conn and
  17243. * conn->phys_ctx must be valid).
  17244. */
  17245. static void
  17246. process_new_connection(struct mg_connection *conn)
  17247. {
  17248. struct mg_request_info *ri = &conn->request_info;
  17249. int keep_alive, discard_len;
  17250. char ebuf[100];
  17251. const char *hostend;
  17252. int reqerr, uri_type;
  17253. #if defined(USE_SERVER_STATS)
  17254. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17255. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17256. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17257. #endif
  17258. DEBUG_TRACE("Start processing connection from %s",
  17259. conn->request_info.remote_addr);
  17260. /* Loop over multiple requests sent using the same connection
  17261. * (while "keep alive"). */
  17262. do {
  17263. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17264. conn->handled_requests + 1);
  17265. #if defined(USE_SERVER_STATS)
  17266. conn->conn_state = 3; /* ready */
  17267. #endif
  17268. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17269. /* The request sent by the client could not be understood by
  17270. * the server, or it was incomplete or a timeout. Send an
  17271. * error message and close the connection. */
  17272. if (reqerr > 0) {
  17273. DEBUG_ASSERT(ebuf[0] != '\0');
  17274. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17275. }
  17276. } else if (strcmp(ri->http_version, "1.0")
  17277. && strcmp(ri->http_version, "1.1")) {
  17278. /* HTTP/2 is not allowed here */
  17279. mg_snprintf(conn,
  17280. NULL, /* No truncation check for ebuf */
  17281. ebuf,
  17282. sizeof(ebuf),
  17283. "Bad HTTP version: [%s]",
  17284. ri->http_version);
  17285. mg_send_http_error(conn, 505, "%s", ebuf);
  17286. }
  17287. if (ebuf[0] == '\0') {
  17288. uri_type = get_uri_type(conn->request_info.request_uri);
  17289. switch (uri_type) {
  17290. case 1:
  17291. /* Asterisk */
  17292. conn->request_info.local_uri_raw = 0;
  17293. /* TODO: Deal with '*'. */
  17294. break;
  17295. case 2:
  17296. /* relative uri */
  17297. conn->request_info.local_uri_raw =
  17298. conn->request_info.request_uri;
  17299. break;
  17300. case 3:
  17301. case 4:
  17302. /* absolute uri (with/without port) */
  17303. hostend = get_rel_url_at_current_server(
  17304. conn->request_info.request_uri, conn);
  17305. if (hostend) {
  17306. conn->request_info.local_uri_raw = hostend;
  17307. } else {
  17308. conn->request_info.local_uri_raw = NULL;
  17309. }
  17310. break;
  17311. default:
  17312. mg_snprintf(conn,
  17313. NULL, /* No truncation check for ebuf */
  17314. ebuf,
  17315. sizeof(ebuf),
  17316. "Invalid URI");
  17317. mg_send_http_error(conn, 400, "%s", ebuf);
  17318. conn->request_info.local_uri_raw = NULL;
  17319. break;
  17320. }
  17321. conn->request_info.local_uri =
  17322. (char *)conn->request_info.local_uri_raw;
  17323. }
  17324. if (ebuf[0] != '\0') {
  17325. conn->protocol_type = -1;
  17326. } else {
  17327. /* HTTP/1 allows protocol upgrade */
  17328. conn->protocol_type = should_switch_to_protocol(conn);
  17329. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17330. /* This will occur, if a HTTP/1.1 request should be upgraded
  17331. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17332. * Since most (all?) major browsers only support HTTP/2 using
  17333. * ALPN, this is hard to test and very low priority.
  17334. * Deactivate it (at least for now).
  17335. */
  17336. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17337. }
  17338. }
  17339. DEBUG_TRACE("http: %s, error: %s",
  17340. (ri->http_version ? ri->http_version : "none"),
  17341. (ebuf[0] ? ebuf : "none"));
  17342. if (ebuf[0] == '\0') {
  17343. if (conn->request_info.local_uri) {
  17344. /* handle request to local server */
  17345. handle_request_stat_log(conn);
  17346. } else {
  17347. /* TODO: handle non-local request (PROXY) */
  17348. conn->must_close = 1;
  17349. }
  17350. } else {
  17351. conn->must_close = 1;
  17352. }
  17353. /* Response complete. Free header buffer */
  17354. free_buffered_response_header_list(conn);
  17355. if (ri->remote_user != NULL) {
  17356. mg_free((void *)ri->remote_user);
  17357. /* Important! When having connections with and without auth
  17358. * would cause double free and then crash */
  17359. ri->remote_user = NULL;
  17360. }
  17361. /* NOTE(lsm): order is important here. should_keep_alive() call
  17362. * is using parsed request, which will be invalid after
  17363. * memmove's below.
  17364. * Therefore, memorize should_keep_alive() result now for later
  17365. * use in loop exit condition. */
  17366. /* Enable it only if this request is completely discardable. */
  17367. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17368. && should_keep_alive(conn) && (conn->content_len >= 0)
  17369. && (conn->request_len > 0)
  17370. && ((conn->is_chunked == 4)
  17371. || (!conn->is_chunked
  17372. && ((conn->consumed_content == conn->content_len)
  17373. || ((conn->request_len + conn->content_len)
  17374. <= conn->data_len))))
  17375. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17376. if (keep_alive) {
  17377. /* Discard all buffered data for this request */
  17378. discard_len =
  17379. ((conn->request_len + conn->content_len) < conn->data_len)
  17380. ? (int)(conn->request_len + conn->content_len)
  17381. : conn->data_len;
  17382. conn->data_len -= discard_len;
  17383. if (conn->data_len > 0) {
  17384. DEBUG_TRACE("discard_len = %d", discard_len);
  17385. memmove(conn->buf,
  17386. conn->buf + discard_len,
  17387. (size_t)conn->data_len);
  17388. }
  17389. }
  17390. DEBUG_ASSERT(conn->data_len >= 0);
  17391. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17392. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17393. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17394. (long int)conn->data_len,
  17395. (long int)conn->buf_size);
  17396. break;
  17397. }
  17398. conn->handled_requests++;
  17399. } while (keep_alive);
  17400. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17401. conn->request_info.remote_addr,
  17402. difftime(time(NULL), conn->conn_birth_time));
  17403. close_connection(conn);
  17404. #if defined(USE_SERVER_STATS)
  17405. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17406. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17407. #endif
  17408. }
  17409. static int
  17410. mg_start_worker_thread(struct mg_context *ctx,
  17411. int only_if_no_idle_threads); /* forward declaration */
  17412. #if defined(ALTERNATIVE_QUEUE)
  17413. static void
  17414. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17415. {
  17416. unsigned int i;
  17417. (void)mg_start_worker_thread(
  17418. ctx, 1); /* will start a worker-thread only if there aren't currently
  17419. any idle worker-threads */
  17420. while (!ctx->stop_flag) {
  17421. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17422. /* find a free worker slot and signal it */
  17423. if (ctx->client_socks[i].in_use == 2) {
  17424. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17425. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17426. ctx->client_socks[i] = *sp;
  17427. ctx->client_socks[i].in_use = 1;
  17428. /* socket has been moved to the consumer */
  17429. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17430. (void)event_signal(ctx->client_wait_events[i]);
  17431. return;
  17432. }
  17433. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17434. }
  17435. }
  17436. /* queue is full */
  17437. mg_sleep(1);
  17438. }
  17439. /* must consume */
  17440. set_blocking_mode(sp->sock);
  17441. closesocket(sp->sock);
  17442. }
  17443. static int
  17444. consume_socket(struct mg_context *ctx,
  17445. struct socket *sp,
  17446. int thread_index,
  17447. int counter_was_preincremented)
  17448. {
  17449. DEBUG_TRACE("%s", "going idle");
  17450. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17451. if (counter_was_preincremented
  17452. == 0) { /* first call only: the master-thread pre-incremented this
  17453. before he spawned us */
  17454. ctx->idle_worker_thread_count++;
  17455. }
  17456. ctx->client_socks[thread_index].in_use = 2;
  17457. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17458. event_wait(ctx->client_wait_events[thread_index]);
  17459. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17460. *sp = ctx->client_socks[thread_index];
  17461. if (ctx->stop_flag) {
  17462. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17463. if (sp->in_use == 1) {
  17464. /* must consume */
  17465. set_blocking_mode(sp->sock);
  17466. closesocket(sp->sock);
  17467. }
  17468. return 0;
  17469. }
  17470. ctx->idle_worker_thread_count--;
  17471. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17472. if (sp->in_use == 1) {
  17473. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17474. return 1;
  17475. }
  17476. /* must not reach here */
  17477. DEBUG_ASSERT(0);
  17478. return 0;
  17479. }
  17480. #else /* ALTERNATIVE_QUEUE */
  17481. /* Worker threads take accepted socket from the queue */
  17482. static int
  17483. consume_socket(struct mg_context *ctx,
  17484. struct socket *sp,
  17485. int thread_index,
  17486. int counter_was_preincremented)
  17487. {
  17488. (void)thread_index;
  17489. DEBUG_TRACE("%s", "going idle");
  17490. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17491. if (counter_was_preincremented
  17492. == 0) { /* first call only: the master-thread pre-incremented this
  17493. before he spawned us */
  17494. ctx->idle_worker_thread_count++;
  17495. }
  17496. /* If the queue is empty, wait. We're idle at this point. */
  17497. while ((ctx->sq_head == ctx->sq_tail)
  17498. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17499. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17500. }
  17501. /* If we're stopping, sq_head may be equal to sq_tail. */
  17502. if (ctx->sq_head > ctx->sq_tail) {
  17503. /* Copy socket from the queue and increment tail */
  17504. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17505. ctx->sq_tail++;
  17506. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17507. /* Wrap pointers if needed */
  17508. while (ctx->sq_tail > ctx->sq_size) {
  17509. ctx->sq_tail -= ctx->sq_size;
  17510. ctx->sq_head -= ctx->sq_size;
  17511. }
  17512. }
  17513. (void)pthread_cond_signal(&ctx->sq_empty);
  17514. ctx->idle_worker_thread_count--;
  17515. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17516. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17517. }
  17518. /* Master thread adds accepted socket to a queue */
  17519. static void
  17520. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17521. {
  17522. int queue_filled;
  17523. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17524. queue_filled = ctx->sq_head - ctx->sq_tail;
  17525. /* If the queue is full, wait */
  17526. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17527. && (queue_filled >= ctx->sq_size)) {
  17528. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17529. #if defined(USE_SERVER_STATS)
  17530. if (queue_filled > ctx->sq_max_fill) {
  17531. ctx->sq_max_fill = queue_filled;
  17532. }
  17533. #endif
  17534. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17535. ctx->sq_blocked = 0; /* Not blocked now */
  17536. queue_filled = ctx->sq_head - ctx->sq_tail;
  17537. }
  17538. if (queue_filled < ctx->sq_size) {
  17539. /* Copy socket to the queue and increment head */
  17540. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17541. ctx->sq_head++;
  17542. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17543. }
  17544. queue_filled = ctx->sq_head - ctx->sq_tail;
  17545. #if defined(USE_SERVER_STATS)
  17546. if (queue_filled > ctx->sq_max_fill) {
  17547. ctx->sq_max_fill = queue_filled;
  17548. }
  17549. #endif
  17550. (void)pthread_cond_signal(&ctx->sq_full);
  17551. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17552. (void)mg_start_worker_thread(
  17553. ctx, 1); /* will start a worker-thread only if there aren't currently
  17554. any idle worker-threads */
  17555. }
  17556. #endif /* ALTERNATIVE_QUEUE */
  17557. static void
  17558. worker_thread_run(struct mg_connection *conn)
  17559. {
  17560. struct mg_context *ctx = conn->phys_ctx;
  17561. int thread_index;
  17562. struct mg_workerTLS tls;
  17563. int first_call_to_consume_socket = 1;
  17564. mg_set_thread_name("worker");
  17565. tls.is_master = 0;
  17566. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17567. #if defined(_WIN32)
  17568. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17569. #endif
  17570. /* Initialize thread local storage before calling any callback */
  17571. pthread_setspecific(sTlsKey, &tls);
  17572. /* Check if there is a user callback */
  17573. if (ctx->callbacks.init_thread) {
  17574. /* call init_thread for a worker thread (type 1), and store the
  17575. * return value */
  17576. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17577. } else {
  17578. /* No callback: set user pointer to NULL */
  17579. tls.user_ptr = NULL;
  17580. }
  17581. /* Connection structure has been pre-allocated */
  17582. thread_index = (int)(conn - ctx->worker_connections);
  17583. if ((thread_index < 0)
  17584. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17585. mg_cry_ctx_internal(ctx,
  17586. "Internal error: Invalid worker index %i",
  17587. thread_index);
  17588. return;
  17589. }
  17590. /* Request buffers are not pre-allocated. They are private to the
  17591. * request and do not contain any state information that might be
  17592. * of interest to anyone observing a server status. */
  17593. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17594. if (conn->buf == NULL) {
  17595. mg_cry_ctx_internal(
  17596. ctx,
  17597. "Out of memory: Cannot allocate buffer for worker %i",
  17598. thread_index);
  17599. return;
  17600. }
  17601. conn->buf_size = (int)ctx->max_request_size;
  17602. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17603. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17604. conn->request_info.user_data = ctx->user_data;
  17605. /* Allocate a mutex for this connection to allow communication both
  17606. * within the request handler and from elsewhere in the application
  17607. */
  17608. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17609. mg_free(conn->buf);
  17610. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17611. return;
  17612. }
  17613. #if defined(USE_SERVER_STATS)
  17614. conn->conn_state = 1; /* not consumed */
  17615. #endif
  17616. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17617. * signal sq_empty condvar to wake up the master waiting in
  17618. * produce_socket() */
  17619. while (consume_socket(
  17620. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17621. first_call_to_consume_socket = 0;
  17622. /* New connections must start with new protocol negotiation */
  17623. tls.alpn_proto = NULL;
  17624. #if defined(USE_SERVER_STATS)
  17625. conn->conn_close_time = 0;
  17626. #endif
  17627. conn->conn_birth_time = time(NULL);
  17628. /* Fill in IP, port info early so even if SSL setup below fails,
  17629. * error handler would have the corresponding info.
  17630. * Thanks to Johannes Winkelmann for the patch.
  17631. */
  17632. conn->request_info.remote_port =
  17633. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17634. conn->request_info.server_port =
  17635. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17636. sockaddr_to_string(conn->request_info.remote_addr,
  17637. sizeof(conn->request_info.remote_addr),
  17638. &conn->client.rsa);
  17639. DEBUG_TRACE("Incoming %sconnection from %s",
  17640. (conn->client.is_ssl ? "SSL " : ""),
  17641. conn->request_info.remote_addr);
  17642. conn->request_info.is_ssl = conn->client.is_ssl;
  17643. if (conn->client.is_ssl) {
  17644. #if defined(USE_MBEDTLS)
  17645. /* HTTPS connection */
  17646. if (mbed_ssl_accept(&(conn->ssl),
  17647. conn->dom_ctx->ssl_ctx,
  17648. (int *)&(conn->client.sock),
  17649. conn->phys_ctx)
  17650. == 0) {
  17651. /* conn->dom_ctx is set in get_request */
  17652. /* process HTTPS connection */
  17653. init_connection(conn);
  17654. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17655. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17656. process_new_connection(conn);
  17657. } else {
  17658. /* make sure the connection is cleaned up on SSL failure */
  17659. close_connection(conn);
  17660. }
  17661. #elif defined(USE_GNUTLS)
  17662. /* HTTPS connection */
  17663. if (gtls_ssl_accept(&(conn->ssl),
  17664. conn->dom_ctx->ssl_ctx,
  17665. conn->client.sock,
  17666. conn->phys_ctx)
  17667. == 0) {
  17668. /* conn->dom_ctx is set in get_request */
  17669. /* process HTTPS connection */
  17670. init_connection(conn);
  17671. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17672. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17673. process_new_connection(conn);
  17674. } else {
  17675. /* make sure the connection is cleaned up on SSL failure */
  17676. close_connection(conn);
  17677. }
  17678. #elif !defined(NO_SSL)
  17679. /* HTTPS connection */
  17680. if (sslize(conn, SSL_accept, NULL)) {
  17681. /* conn->dom_ctx is set in get_request */
  17682. /* Get SSL client certificate information (if set) */
  17683. struct mg_client_cert client_cert;
  17684. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17685. conn->request_info.client_cert = &client_cert;
  17686. }
  17687. /* process HTTPS connection */
  17688. #if defined(USE_HTTP2)
  17689. if ((tls.alpn_proto != NULL)
  17690. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17691. /* process HTTPS/2 connection */
  17692. init_connection(conn);
  17693. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17694. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17695. conn->content_len =
  17696. -1; /* content length is not predefined */
  17697. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17698. process_new_http2_connection(conn);
  17699. } else
  17700. #endif
  17701. {
  17702. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17703. init_connection(conn);
  17704. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17705. /* Start with HTTP, WS will be an "upgrade" request later */
  17706. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17707. process_new_connection(conn);
  17708. }
  17709. /* Free client certificate info */
  17710. if (conn->request_info.client_cert) {
  17711. mg_free((void *)(conn->request_info.client_cert->subject));
  17712. mg_free((void *)(conn->request_info.client_cert->issuer));
  17713. mg_free((void *)(conn->request_info.client_cert->serial));
  17714. mg_free((void *)(conn->request_info.client_cert->finger));
  17715. /* Free certificate memory */
  17716. X509_free(
  17717. (X509 *)conn->request_info.client_cert->peer_cert);
  17718. conn->request_info.client_cert->peer_cert = 0;
  17719. conn->request_info.client_cert->subject = 0;
  17720. conn->request_info.client_cert->issuer = 0;
  17721. conn->request_info.client_cert->serial = 0;
  17722. conn->request_info.client_cert->finger = 0;
  17723. conn->request_info.client_cert = 0;
  17724. }
  17725. } else {
  17726. /* make sure the connection is cleaned up on SSL failure */
  17727. close_connection(conn);
  17728. }
  17729. #endif
  17730. } else {
  17731. /* process HTTP connection */
  17732. init_connection(conn);
  17733. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17734. /* Start with HTTP, WS will be an "upgrade" request later */
  17735. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17736. process_new_connection(conn);
  17737. }
  17738. DEBUG_TRACE("%s", "Connection closed");
  17739. #if defined(USE_SERVER_STATS)
  17740. conn->conn_close_time = time(NULL);
  17741. #endif
  17742. }
  17743. /* Call exit thread user callback */
  17744. if (ctx->callbacks.exit_thread) {
  17745. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17746. }
  17747. /* delete thread local storage objects */
  17748. pthread_setspecific(sTlsKey, NULL);
  17749. #if defined(_WIN32)
  17750. CloseHandle(tls.pthread_cond_helper_mutex);
  17751. #endif
  17752. pthread_mutex_destroy(&conn->mutex);
  17753. /* Free the request buffer. */
  17754. conn->buf_size = 0;
  17755. mg_free(conn->buf);
  17756. conn->buf = NULL;
  17757. /* Free cleaned URI (if any) */
  17758. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17759. mg_free((void *)conn->request_info.local_uri);
  17760. conn->request_info.local_uri = NULL;
  17761. }
  17762. #if defined(USE_SERVER_STATS)
  17763. conn->conn_state = 9; /* done */
  17764. #endif
  17765. DEBUG_TRACE("%s", "exiting");
  17766. }
  17767. /* Threads have different return types on Windows and Unix. */
  17768. #if defined(_WIN32)
  17769. static unsigned __stdcall worker_thread(void *thread_func_param)
  17770. {
  17771. worker_thread_run((struct mg_connection *)thread_func_param);
  17772. return 0;
  17773. }
  17774. #else
  17775. static void *
  17776. worker_thread(void *thread_func_param)
  17777. {
  17778. #if !defined(__ZEPHYR__)
  17779. struct sigaction sa;
  17780. /* Ignore SIGPIPE */
  17781. memset(&sa, 0, sizeof(sa));
  17782. sa.sa_handler = SIG_IGN;
  17783. sigaction(SIGPIPE, &sa, NULL);
  17784. #endif
  17785. worker_thread_run((struct mg_connection *)thread_func_param);
  17786. return NULL;
  17787. }
  17788. #endif /* _WIN32 */
  17789. /* This is an internal function, thus all arguments are expected to be
  17790. * valid - a NULL check is not required. */
  17791. static void
  17792. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17793. {
  17794. struct socket so;
  17795. char src_addr[IP_ADDR_STR_LEN];
  17796. socklen_t len = sizeof(so.rsa);
  17797. #if !defined(__ZEPHYR__)
  17798. int on = 1;
  17799. #endif
  17800. memset(&so, 0, sizeof(so));
  17801. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17802. == INVALID_SOCKET) {
  17803. } else if (check_acl(ctx, &so.rsa) != 1) {
  17804. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17805. mg_cry_ctx_internal(ctx,
  17806. "%s: %s is not allowed to connect",
  17807. __func__,
  17808. src_addr);
  17809. closesocket(so.sock);
  17810. } else {
  17811. /* Put so socket structure into the queue */
  17812. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17813. set_close_on_exec(so.sock, NULL, ctx);
  17814. so.is_ssl = listener->is_ssl;
  17815. so.ssl_redir = listener->ssl_redir;
  17816. so.is_optional = listener->is_optional;
  17817. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17818. mg_cry_ctx_internal(ctx,
  17819. "%s: getsockname() failed: %s",
  17820. __func__,
  17821. strerror(ERRNO));
  17822. }
  17823. #if !defined(__ZEPHYR__)
  17824. if ((so.lsa.sa.sa_family == AF_INET)
  17825. || (so.lsa.sa.sa_family == AF_INET6)) {
  17826. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17827. * This is needed because if HTTP-level keep-alive
  17828. * is enabled, and client resets the connection, server won't get
  17829. * TCP FIN or RST and will keep the connection open forever. With
  17830. * TCP keep-alive, next keep-alive handshake will figure out that
  17831. * the client is down and will close the server end.
  17832. * Thanks to Igor Klopov who suggested the patch. */
  17833. if (setsockopt(so.sock,
  17834. SOL_SOCKET,
  17835. SO_KEEPALIVE,
  17836. (SOCK_OPT_TYPE)&on,
  17837. sizeof(on))
  17838. != 0) {
  17839. mg_cry_ctx_internal(
  17840. ctx,
  17841. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17842. __func__,
  17843. strerror(ERRNO));
  17844. }
  17845. }
  17846. #endif
  17847. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17848. * to effectively fill up the underlying IP packet payload and
  17849. * reduce the overhead of sending lots of small buffers. However
  17850. * this hurts the server's throughput (ie. operations per second)
  17851. * when HTTP 1.1 persistent connections are used and the responses
  17852. * are relatively small (eg. less than 1400 bytes).
  17853. */
  17854. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17855. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17856. if (set_tcp_nodelay(&so, 1) != 0) {
  17857. mg_cry_ctx_internal(
  17858. ctx,
  17859. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17860. __func__,
  17861. strerror(ERRNO));
  17862. }
  17863. }
  17864. /* The "non blocking" property should already be
  17865. * inherited from the parent socket. Set it for
  17866. * non-compliant socket implementations. */
  17867. set_non_blocking_mode(so.sock);
  17868. so.in_use = 0;
  17869. produce_socket(ctx, &so);
  17870. }
  17871. }
  17872. static void
  17873. master_thread_run(struct mg_context *ctx)
  17874. {
  17875. struct mg_workerTLS tls;
  17876. struct mg_pollfd *pfd;
  17877. unsigned int i;
  17878. unsigned int workerthreadcount;
  17879. if (!ctx || !ctx->listening_socket_fds) {
  17880. return;
  17881. }
  17882. mg_set_thread_name("master");
  17883. /* Increase priority of the master thread */
  17884. #if defined(_WIN32)
  17885. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17886. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17887. int min_prio = sched_get_priority_min(SCHED_RR);
  17888. int max_prio = sched_get_priority_max(SCHED_RR);
  17889. if ((min_prio >= 0) && (max_prio >= 0)
  17890. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17891. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17892. struct sched_param sched_param = {0};
  17893. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17894. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17895. }
  17896. #endif
  17897. /* Initialize thread local storage */
  17898. #if defined(_WIN32)
  17899. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17900. #endif
  17901. tls.is_master = 1;
  17902. pthread_setspecific(sTlsKey, &tls);
  17903. if (ctx->callbacks.init_thread) {
  17904. /* Callback for the master thread (type 0) */
  17905. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17906. } else {
  17907. tls.user_ptr = NULL;
  17908. }
  17909. /* Lua background script "start" event */
  17910. #if defined(USE_LUA)
  17911. if (ctx->lua_background_state) {
  17912. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17913. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17914. /* call "start()" in Lua */
  17915. lua_getglobal(lstate, "start");
  17916. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17917. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17918. if (ret != 0) {
  17919. struct mg_connection fc;
  17920. lua_cry(fake_connection(&fc, ctx),
  17921. ret,
  17922. lstate,
  17923. "lua_background_script",
  17924. "start");
  17925. }
  17926. } else {
  17927. lua_pop(lstate, 1);
  17928. }
  17929. /* determine if there is a "log()" function in Lua background script */
  17930. lua_getglobal(lstate, "log");
  17931. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17932. ctx->lua_bg_log_available = 1;
  17933. }
  17934. lua_pop(lstate, 1);
  17935. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17936. }
  17937. #endif
  17938. /* Server starts *now* */
  17939. ctx->start_time = time(NULL);
  17940. /* Server accept loop */
  17941. pfd = ctx->listening_socket_fds;
  17942. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17943. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17944. pfd[i].fd = ctx->listening_sockets[i].sock;
  17945. pfd[i].events = POLLIN;
  17946. }
  17947. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17948. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17949. * of listening_socket_fds[] just to hold this
  17950. */
  17951. pfd[ctx->num_listening_sockets].fd =
  17952. ctx->thread_shutdown_notification_socket;
  17953. pfd[ctx->num_listening_sockets].events = POLLIN;
  17954. if (mg_poll(pfd,
  17955. ctx->num_listening_sockets
  17956. + 1, // +1 for the thread_shutdown_notification_socket
  17957. SOCKET_TIMEOUT_QUANTUM,
  17958. &(ctx->stop_flag))
  17959. > 0) {
  17960. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17961. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17962. * successful poll, and POLLIN is defined as
  17963. * (POLLRDNORM | POLLRDBAND)
  17964. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17965. * pfd[i].revents == POLLIN. */
  17966. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17967. && (pfd[i].revents & POLLIN)) {
  17968. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17969. }
  17970. }
  17971. }
  17972. }
  17973. /* Here stop_flag is 1 - Initiate shutdown. */
  17974. DEBUG_TRACE("%s", "stopping workers");
  17975. /* Stop signal received: somebody called mg_stop. Quit. */
  17976. close_all_listening_sockets(ctx);
  17977. /* Wakeup workers that are waiting for connections to handle. */
  17978. #if defined(ALTERNATIVE_QUEUE)
  17979. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17980. event_signal(ctx->client_wait_events[i]);
  17981. }
  17982. #else
  17983. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17984. pthread_cond_broadcast(&ctx->sq_full);
  17985. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17986. #endif
  17987. /* Join all worker threads to avoid leaking threads. */
  17988. workerthreadcount = ctx->spawned_worker_threads;
  17989. for (i = 0; i < workerthreadcount; i++) {
  17990. if (ctx->worker_threadids[i] != 0) {
  17991. mg_join_thread(ctx->worker_threadids[i]);
  17992. }
  17993. }
  17994. #if defined(USE_LUA)
  17995. /* Free Lua state of lua background task */
  17996. if (ctx->lua_background_state) {
  17997. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17998. ctx->lua_bg_log_available = 0;
  17999. /* call "stop()" in Lua */
  18000. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18001. lua_getglobal(lstate, "stop");
  18002. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  18003. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  18004. if (ret != 0) {
  18005. struct mg_connection fc;
  18006. lua_cry(fake_connection(&fc, ctx),
  18007. ret,
  18008. lstate,
  18009. "lua_background_script",
  18010. "stop");
  18011. }
  18012. }
  18013. DEBUG_TRACE("Close Lua background state %p", lstate);
  18014. lua_close(lstate);
  18015. ctx->lua_background_state = 0;
  18016. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18017. }
  18018. #endif
  18019. DEBUG_TRACE("%s", "exiting");
  18020. /* call exit thread callback */
  18021. if (ctx->callbacks.exit_thread) {
  18022. /* Callback for the master thread (type 0) */
  18023. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  18024. }
  18025. #if defined(_WIN32)
  18026. CloseHandle(tls.pthread_cond_helper_mutex);
  18027. #endif
  18028. pthread_setspecific(sTlsKey, NULL);
  18029. /* Signal mg_stop() that we're done.
  18030. * WARNING: This must be the very last thing this
  18031. * thread does, as ctx becomes invalid after this line. */
  18032. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  18033. }
  18034. /* Threads have different return types on Windows and Unix. */
  18035. #if defined(_WIN32)
  18036. static unsigned __stdcall master_thread(void *thread_func_param)
  18037. {
  18038. master_thread_run((struct mg_context *)thread_func_param);
  18039. return 0;
  18040. }
  18041. #else
  18042. static void *
  18043. master_thread(void *thread_func_param)
  18044. {
  18045. #if !defined(__ZEPHYR__)
  18046. struct sigaction sa;
  18047. /* Ignore SIGPIPE */
  18048. memset(&sa, 0, sizeof(sa));
  18049. sa.sa_handler = SIG_IGN;
  18050. sigaction(SIGPIPE, &sa, NULL);
  18051. #endif
  18052. master_thread_run((struct mg_context *)thread_func_param);
  18053. return NULL;
  18054. }
  18055. #endif /* _WIN32 */
  18056. static void
  18057. free_context(struct mg_context *ctx)
  18058. {
  18059. int i;
  18060. struct mg_handler_info *tmp_rh;
  18061. if (ctx == NULL) {
  18062. return;
  18063. }
  18064. /* Call user callback */
  18065. if (ctx->callbacks.exit_context) {
  18066. ctx->callbacks.exit_context(ctx);
  18067. }
  18068. /* All threads exited, no sync is needed. Destroy thread mutex and
  18069. * condvars
  18070. */
  18071. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  18072. #if defined(ALTERNATIVE_QUEUE)
  18073. mg_free(ctx->client_socks);
  18074. if (ctx->client_wait_events != NULL) {
  18075. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  18076. event_destroy(ctx->client_wait_events[i]);
  18077. }
  18078. mg_free(ctx->client_wait_events);
  18079. }
  18080. #else
  18081. (void)pthread_cond_destroy(&ctx->sq_empty);
  18082. (void)pthread_cond_destroy(&ctx->sq_full);
  18083. mg_free(ctx->squeue);
  18084. #endif
  18085. /* Destroy other context global data structures mutex */
  18086. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18087. #if defined(USE_LUA)
  18088. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18089. #endif
  18090. /* Deallocate shutdown-triggering socket-pair */
  18091. if (ctx->user_shutdown_notification_socket >= 0) {
  18092. closesocket(ctx->user_shutdown_notification_socket);
  18093. }
  18094. if (ctx->thread_shutdown_notification_socket >= 0) {
  18095. closesocket(ctx->thread_shutdown_notification_socket);
  18096. }
  18097. /* Deallocate config parameters */
  18098. for (i = 0; i < NUM_OPTIONS; i++) {
  18099. if (ctx->dd.config[i] != NULL) {
  18100. #if defined(_MSC_VER)
  18101. #pragma warning(suppress : 6001)
  18102. #endif
  18103. mg_free(ctx->dd.config[i]);
  18104. }
  18105. }
  18106. /* Deallocate request handlers */
  18107. while (ctx->dd.handlers) {
  18108. tmp_rh = ctx->dd.handlers;
  18109. ctx->dd.handlers = tmp_rh->next;
  18110. mg_free(tmp_rh->uri);
  18111. mg_free(tmp_rh);
  18112. }
  18113. #if defined(USE_MBEDTLS)
  18114. if (ctx->dd.ssl_ctx != NULL) {
  18115. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18116. mg_free(ctx->dd.ssl_ctx);
  18117. ctx->dd.ssl_ctx = NULL;
  18118. }
  18119. #elif defined(USE_GNUTLS)
  18120. if (ctx->dd.ssl_ctx != NULL) {
  18121. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18122. mg_free(ctx->dd.ssl_ctx);
  18123. ctx->dd.ssl_ctx = NULL;
  18124. }
  18125. #elif !defined(NO_SSL)
  18126. /* Deallocate SSL context */
  18127. if (ctx->dd.ssl_ctx != NULL) {
  18128. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18129. int callback_ret =
  18130. (ctx->callbacks.external_ssl_ctx == NULL)
  18131. ? 0
  18132. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18133. if (callback_ret == 0) {
  18134. SSL_CTX_free(ctx->dd.ssl_ctx);
  18135. }
  18136. /* else: ignore error and omit SSL_CTX_free in case
  18137. * callback_ret is 1 */
  18138. }
  18139. #endif /* !NO_SSL */
  18140. /* Deallocate worker thread ID array */
  18141. mg_free(ctx->worker_threadids);
  18142. /* Deallocate worker thread ID array */
  18143. mg_free(ctx->worker_connections);
  18144. /* deallocate system name string */
  18145. mg_free(ctx->systemName);
  18146. /* Deallocate context itself */
  18147. mg_free(ctx);
  18148. }
  18149. CIVETWEB_API void
  18150. mg_stop(struct mg_context *ctx)
  18151. {
  18152. pthread_t mt;
  18153. if (!ctx) {
  18154. return;
  18155. }
  18156. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18157. * two threads is not allowed. */
  18158. mt = ctx->masterthreadid;
  18159. if (mt == 0) {
  18160. return;
  18161. }
  18162. ctx->masterthreadid = 0;
  18163. /* Set stop flag, so all threads know they have to exit. */
  18164. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18165. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18166. * immediately */
  18167. closesocket(ctx->user_shutdown_notification_socket);
  18168. ctx->user_shutdown_notification_socket =
  18169. -1; /* to avoid calling closesocket() again in free_context() */
  18170. /* Join timer thread */
  18171. #if defined(USE_TIMERS)
  18172. timers_exit(ctx);
  18173. #endif
  18174. /* Wait until everything has stopped. */
  18175. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18176. (void)mg_sleep(10);
  18177. }
  18178. /* Wait to stop master thread */
  18179. mg_join_thread(mt);
  18180. /* Close remaining Lua states */
  18181. #if defined(USE_LUA)
  18182. lua_ctx_exit(ctx);
  18183. #endif
  18184. /* Free memory */
  18185. free_context(ctx);
  18186. }
  18187. static void
  18188. get_system_name(char **sysName)
  18189. {
  18190. #if defined(_WIN32)
  18191. char name[128];
  18192. DWORD dwVersion = 0;
  18193. DWORD dwMajorVersion = 0;
  18194. DWORD dwMinorVersion = 0;
  18195. DWORD dwBuild = 0;
  18196. BOOL wowRet, isWoW = FALSE;
  18197. #if defined(_MSC_VER)
  18198. #pragma warning(push)
  18199. /* GetVersion was declared deprecated */
  18200. #pragma warning(disable : 4996)
  18201. #endif
  18202. dwVersion = GetVersion();
  18203. #if defined(_MSC_VER)
  18204. #pragma warning(pop)
  18205. #endif
  18206. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18207. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18208. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18209. (void)dwBuild;
  18210. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18211. sprintf(name,
  18212. "Windows %u.%u%s",
  18213. (unsigned)dwMajorVersion,
  18214. (unsigned)dwMinorVersion,
  18215. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18216. *sysName = mg_strdup(name);
  18217. #elif defined(__rtems__)
  18218. *sysName = mg_strdup("RTEMS");
  18219. #elif defined(__ZEPHYR__)
  18220. *sysName = mg_strdup("Zephyr OS");
  18221. #else
  18222. struct utsname name;
  18223. memset(&name, 0, sizeof(name));
  18224. uname(&name);
  18225. *sysName = mg_strdup(name.sysname);
  18226. #endif
  18227. }
  18228. static void
  18229. legacy_init(const char **options)
  18230. {
  18231. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18232. if (options) {
  18233. const char **run_options = options;
  18234. const char *optname = config_options[LISTENING_PORTS].name;
  18235. /* Try to find the "listening_ports" option */
  18236. while (*run_options) {
  18237. if (!strcmp(*run_options, optname)) {
  18238. ports_option = run_options[1];
  18239. }
  18240. run_options += 2;
  18241. }
  18242. }
  18243. if (is_ssl_port_used(ports_option)) {
  18244. /* Initialize with SSL support */
  18245. mg_init_library(MG_FEATURES_TLS);
  18246. } else {
  18247. /* Initialize without SSL support */
  18248. mg_init_library(MG_FEATURES_DEFAULT);
  18249. }
  18250. }
  18251. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18252. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18253. #define HAVE_SOCKETPAIR 1
  18254. #endif
  18255. static int
  18256. mg_socketpair(int *sockA, int *sockB)
  18257. {
  18258. int temp[2] = {-1, -1};
  18259. int asock = -1;
  18260. /** Default to unallocated */
  18261. *sockA = -1;
  18262. *sockB = -1;
  18263. #if defined(HAVE_SOCKETPAIR)
  18264. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18265. if (ret == 0) {
  18266. *sockA = temp[0];
  18267. *sockB = temp[1];
  18268. set_close_on_exec(*sockA, NULL, NULL);
  18269. set_close_on_exec(*sockB, NULL, NULL);
  18270. }
  18271. (void)asock; /* not used */
  18272. return ret;
  18273. #else
  18274. /** No socketpair() call is available, so we'll have to roll our own
  18275. * implementation */
  18276. asock = socket(PF_INET, SOCK_STREAM, 0);
  18277. if (asock >= 0) {
  18278. struct sockaddr_in addr;
  18279. struct sockaddr *pa = (struct sockaddr *)&addr;
  18280. socklen_t addrLen = sizeof(addr);
  18281. memset(&addr, 0, sizeof(addr));
  18282. addr.sin_family = AF_INET;
  18283. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18284. addr.sin_port = 0;
  18285. if ((bind(asock, pa, sizeof(addr)) == 0)
  18286. && (getsockname(asock, pa, &addrLen) == 0)
  18287. && (listen(asock, 1) == 0)) {
  18288. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18289. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18290. temp[1] = accept(asock, pa, &addrLen);
  18291. if (temp[1] >= 0) {
  18292. closesocket(asock);
  18293. *sockA = temp[0];
  18294. *sockB = temp[1];
  18295. set_close_on_exec(*sockA, NULL, NULL);
  18296. set_close_on_exec(*sockB, NULL, NULL);
  18297. return 0; /* success! */
  18298. }
  18299. }
  18300. }
  18301. }
  18302. /* Cleanup */
  18303. if (asock >= 0)
  18304. closesocket(asock);
  18305. if (temp[0] >= 0)
  18306. closesocket(temp[0]);
  18307. if (temp[1] >= 0)
  18308. closesocket(temp[1]);
  18309. return -1; /* fail! */
  18310. #endif
  18311. }
  18312. static int
  18313. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18314. {
  18315. const unsigned int i = ctx->spawned_worker_threads;
  18316. if (i >= ctx->cfg_max_worker_threads) {
  18317. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18318. threads, ever! */
  18319. }
  18320. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18321. #if defined(ALTERNATIVE_QUEUE)
  18322. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18323. #else
  18324. if ((only_if_no_idle_threads)
  18325. && (ctx->idle_worker_thread_count
  18326. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18327. #endif
  18328. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18329. return -2; /* There are idle threads available, so no need to spawn a
  18330. new worker thread now */
  18331. }
  18332. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18333. condition while the thread is starting
  18334. up */
  18335. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18336. ctx->worker_connections[i].phys_ctx = ctx;
  18337. int ret = mg_start_thread_with_id(worker_thread,
  18338. &ctx->worker_connections[i],
  18339. &ctx->worker_threadids[i]);
  18340. if (ret == 0) {
  18341. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18342. the table */
  18343. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18344. } else {
  18345. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18346. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18347. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18348. }
  18349. return ret;
  18350. }
  18351. CIVETWEB_API struct mg_context *
  18352. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18353. {
  18354. struct mg_context *ctx;
  18355. const char *name, *value, *default_value;
  18356. int idx, ok, prespawnthreadcount, workerthreadcount;
  18357. unsigned int i;
  18358. int itmp;
  18359. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18360. const char **options =
  18361. ((init != NULL) ? (init->configuration_options) : (NULL));
  18362. struct mg_workerTLS tls;
  18363. if (error != NULL) {
  18364. error->code = MG_ERROR_DATA_CODE_OK;
  18365. error->code_sub = 0;
  18366. if (error->text_buffer_size > 0) {
  18367. *error->text = 0;
  18368. }
  18369. }
  18370. if (mg_init_library_called == 0) {
  18371. /* Legacy INIT, if mg_start is called without mg_init_library.
  18372. * Note: This will cause a memory leak when unloading the library.
  18373. */
  18374. legacy_init(options);
  18375. }
  18376. if (mg_init_library_called == 0) {
  18377. if (error != NULL) {
  18378. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18379. mg_snprintf(NULL,
  18380. NULL, /* No truncation check for error buffers */
  18381. error->text,
  18382. error->text_buffer_size,
  18383. "%s",
  18384. "Library uninitialized");
  18385. }
  18386. return NULL;
  18387. }
  18388. /* Allocate context and initialize reasonable general case defaults. */
  18389. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18390. if (ctx == NULL) {
  18391. if (error != NULL) {
  18392. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18393. error->code_sub = (unsigned)sizeof(*ctx);
  18394. mg_snprintf(NULL,
  18395. NULL, /* No truncation check for error buffers */
  18396. error->text,
  18397. error->text_buffer_size,
  18398. "%s",
  18399. "Out of memory");
  18400. }
  18401. return NULL;
  18402. }
  18403. /* Random number generator will initialize at the first call */
  18404. ctx->dd.auth_nonce_mask =
  18405. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18406. /* Save started thread index to reuse in other external API calls
  18407. * For the sake of thread synchronization all non-civetweb threads
  18408. * can be considered as single external thread */
  18409. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18410. tls.is_master = -1; /* Thread calling mg_start */
  18411. tls.thread_idx = ctx->starter_thread_idx;
  18412. #if defined(_WIN32)
  18413. tls.pthread_cond_helper_mutex = NULL;
  18414. #endif
  18415. pthread_setspecific(sTlsKey, &tls);
  18416. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18417. #if !defined(ALTERNATIVE_QUEUE)
  18418. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18419. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18420. ctx->sq_blocked = 0;
  18421. #endif
  18422. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18423. #if defined(USE_LUA)
  18424. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18425. #endif
  18426. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18427. * will cause poll() to return immediately in the master-thread, so that
  18428. * mg_stop() can also return immediately.
  18429. */
  18430. ok &= (0
  18431. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18432. &ctx->thread_shutdown_notification_socket));
  18433. if (!ok) {
  18434. unsigned error_id = (unsigned)ERRNO;
  18435. const char *err_msg =
  18436. "Cannot initialize thread synchronization objects";
  18437. /* Fatal error - abort start. However, this situation should never
  18438. * occur in practice. */
  18439. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18440. if (error != NULL) {
  18441. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18442. error->code_sub = error_id;
  18443. mg_snprintf(NULL,
  18444. NULL, /* No truncation check for error buffers */
  18445. error->text,
  18446. error->text_buffer_size,
  18447. "%s",
  18448. err_msg);
  18449. }
  18450. mg_free(ctx);
  18451. pthread_setspecific(sTlsKey, NULL);
  18452. return NULL;
  18453. }
  18454. if ((init != NULL) && (init->callbacks != NULL)) {
  18455. /* Set all callbacks except exit_context. */
  18456. ctx->callbacks = *init->callbacks;
  18457. exit_callback = init->callbacks->exit_context;
  18458. /* The exit callback is activated once the context is successfully
  18459. * created. It should not be called, if an incomplete context object
  18460. * is deleted during a failed initialization. */
  18461. ctx->callbacks.exit_context = 0;
  18462. }
  18463. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18464. ctx->dd.handlers = NULL;
  18465. ctx->dd.next = NULL;
  18466. #if defined(USE_LUA)
  18467. lua_ctx_init(ctx);
  18468. #endif
  18469. /* Store options */
  18470. while (options && (name = *options++) != NULL) {
  18471. idx = get_option_index(name);
  18472. if (idx == -1) {
  18473. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18474. if (error != NULL) {
  18475. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18476. error->code_sub = (unsigned)-1;
  18477. mg_snprintf(NULL,
  18478. NULL, /* No truncation check for error buffers */
  18479. error->text,
  18480. error->text_buffer_size,
  18481. "Invalid configuration option: %s",
  18482. name);
  18483. }
  18484. free_context(ctx);
  18485. pthread_setspecific(sTlsKey, NULL);
  18486. return NULL;
  18487. } else if ((value = *options++) == NULL) {
  18488. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18489. if (error != NULL) {
  18490. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18491. error->code_sub = (unsigned)idx;
  18492. mg_snprintf(NULL,
  18493. NULL, /* No truncation check for error buffers */
  18494. error->text,
  18495. error->text_buffer_size,
  18496. "Invalid configuration option value: %s",
  18497. name);
  18498. }
  18499. free_context(ctx);
  18500. pthread_setspecific(sTlsKey, NULL);
  18501. return NULL;
  18502. }
  18503. if (ctx->dd.config[idx] != NULL) {
  18504. /* A duplicate configuration option is not an error - the last
  18505. * option value will be used. */
  18506. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18507. mg_free(ctx->dd.config[idx]);
  18508. }
  18509. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18510. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18511. }
  18512. /* Set default value if needed */
  18513. for (i = 0; config_options[i].name != NULL; i++) {
  18514. default_value = config_options[i].default_value;
  18515. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18516. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18517. }
  18518. }
  18519. /* Request size option */
  18520. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18521. if (itmp < 1024) {
  18522. mg_cry_ctx_internal(ctx,
  18523. "%s too small",
  18524. config_options[MAX_REQUEST_SIZE].name);
  18525. if (error != NULL) {
  18526. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18527. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18528. mg_snprintf(NULL,
  18529. NULL, /* No truncation check for error buffers */
  18530. error->text,
  18531. error->text_buffer_size,
  18532. "Invalid configuration option value: %s",
  18533. config_options[MAX_REQUEST_SIZE].name);
  18534. }
  18535. free_context(ctx);
  18536. pthread_setspecific(sTlsKey, NULL);
  18537. return NULL;
  18538. }
  18539. ctx->max_request_size = (unsigned)itmp;
  18540. /* Queue length */
  18541. #if !defined(ALTERNATIVE_QUEUE)
  18542. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18543. if (itmp < 1) {
  18544. mg_cry_ctx_internal(ctx,
  18545. "%s too small",
  18546. config_options[CONNECTION_QUEUE_SIZE].name);
  18547. if (error != NULL) {
  18548. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18549. error->code_sub = CONNECTION_QUEUE_SIZE;
  18550. mg_snprintf(NULL,
  18551. NULL, /* No truncation check for error buffers */
  18552. error->text,
  18553. error->text_buffer_size,
  18554. "Invalid configuration option value: %s",
  18555. config_options[CONNECTION_QUEUE_SIZE].name);
  18556. }
  18557. free_context(ctx);
  18558. pthread_setspecific(sTlsKey, NULL);
  18559. return NULL;
  18560. }
  18561. ctx->squeue =
  18562. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18563. if (ctx->squeue == NULL) {
  18564. mg_cry_ctx_internal(ctx,
  18565. "Out of memory: Cannot allocate %s",
  18566. config_options[CONNECTION_QUEUE_SIZE].name);
  18567. if (error != NULL) {
  18568. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18569. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18570. mg_snprintf(NULL,
  18571. NULL, /* No truncation check for error buffers */
  18572. error->text,
  18573. error->text_buffer_size,
  18574. "Out of memory: Cannot allocate %s",
  18575. config_options[CONNECTION_QUEUE_SIZE].name);
  18576. }
  18577. free_context(ctx);
  18578. pthread_setspecific(sTlsKey, NULL);
  18579. return NULL;
  18580. }
  18581. ctx->sq_size = itmp;
  18582. #endif
  18583. /* Worker thread count option */
  18584. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18585. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18586. if ((prespawnthreadcount < 0)
  18587. || (prespawnthreadcount > workerthreadcount)) {
  18588. prespawnthreadcount =
  18589. workerthreadcount; /* can't prespawn more than all of them! */
  18590. }
  18591. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18592. if (workerthreadcount <= 0) {
  18593. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18594. } else {
  18595. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18596. }
  18597. if (error != NULL) {
  18598. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18599. error->code_sub = NUM_THREADS;
  18600. mg_snprintf(NULL,
  18601. NULL, /* No truncation check for error buffers */
  18602. error->text,
  18603. error->text_buffer_size,
  18604. "Invalid configuration option value: %s",
  18605. config_options[NUM_THREADS].name);
  18606. }
  18607. free_context(ctx);
  18608. pthread_setspecific(sTlsKey, NULL);
  18609. return NULL;
  18610. }
  18611. /* Document root */
  18612. #if defined(NO_FILES)
  18613. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18614. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18615. if (error != NULL) {
  18616. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18617. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18618. mg_snprintf(NULL,
  18619. NULL, /* No truncation check for error buffers */
  18620. error->text,
  18621. error->text_buffer_size,
  18622. "Invalid configuration option value: %s",
  18623. config_options[DOCUMENT_ROOT].name);
  18624. }
  18625. free_context(ctx);
  18626. pthread_setspecific(sTlsKey, NULL);
  18627. return NULL;
  18628. }
  18629. #endif
  18630. get_system_name(&ctx->systemName);
  18631. #if defined(USE_LUA)
  18632. /* If a Lua background script has been configured, start it. */
  18633. ctx->lua_bg_log_available = 0;
  18634. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18635. char ebuf[256];
  18636. struct vec opt_vec;
  18637. struct vec eq_vec;
  18638. const char *sparams;
  18639. memset(ebuf, 0, sizeof(ebuf));
  18640. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18641. /* Create a Lua state, load all standard libraries and the mg table */
  18642. lua_State *state = mg_lua_context_script_prepare(
  18643. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18644. if (!state) {
  18645. mg_cry_ctx_internal(ctx,
  18646. "lua_background_script load error: %s",
  18647. ebuf);
  18648. if (error != NULL) {
  18649. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18650. mg_snprintf(NULL,
  18651. NULL, /* No truncation check for error buffers */
  18652. error->text,
  18653. error->text_buffer_size,
  18654. "Error in script %s: %s",
  18655. config_options[LUA_BACKGROUND_SCRIPT].name,
  18656. ebuf);
  18657. }
  18658. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18659. free_context(ctx);
  18660. pthread_setspecific(sTlsKey, NULL);
  18661. return NULL;
  18662. }
  18663. /* Add a table with parameters into mg.params */
  18664. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18665. if (sparams && sparams[0]) {
  18666. lua_getglobal(state, "mg");
  18667. lua_pushstring(state, "params");
  18668. lua_newtable(state);
  18669. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18670. != NULL) {
  18671. reg_llstring(
  18672. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18673. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18674. break;
  18675. }
  18676. lua_rawset(state, -3);
  18677. lua_pop(state, 1);
  18678. }
  18679. /* Call script */
  18680. state = mg_lua_context_script_run(state,
  18681. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18682. ctx,
  18683. ebuf,
  18684. sizeof(ebuf));
  18685. if (!state) {
  18686. mg_cry_ctx_internal(ctx,
  18687. "lua_background_script start error: %s",
  18688. ebuf);
  18689. if (error != NULL) {
  18690. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18691. mg_snprintf(NULL,
  18692. NULL, /* No truncation check for error buffers */
  18693. error->text,
  18694. error->text_buffer_size,
  18695. "Error in script %s: %s",
  18696. config_options[DOCUMENT_ROOT].name,
  18697. ebuf);
  18698. }
  18699. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18700. free_context(ctx);
  18701. pthread_setspecific(sTlsKey, NULL);
  18702. return NULL;
  18703. }
  18704. /* state remains valid */
  18705. ctx->lua_background_state = (void *)state;
  18706. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18707. } else {
  18708. ctx->lua_background_state = 0;
  18709. }
  18710. #endif
  18711. /* Step by step initialization of ctx - depending on build options */
  18712. #if !defined(NO_FILESYSTEMS)
  18713. if (!set_gpass_option(ctx, NULL)) {
  18714. const char *err_msg = "Invalid global password file";
  18715. /* Fatal error - abort start. */
  18716. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18717. if (error != NULL) {
  18718. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18719. mg_snprintf(NULL,
  18720. NULL, /* No truncation check for error buffers */
  18721. error->text,
  18722. error->text_buffer_size,
  18723. "%s",
  18724. err_msg);
  18725. }
  18726. free_context(ctx);
  18727. pthread_setspecific(sTlsKey, NULL);
  18728. return NULL;
  18729. }
  18730. #endif
  18731. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18732. if (!mg_sslctx_init(ctx, NULL)) {
  18733. const char *err_msg = "Error initializing SSL context";
  18734. /* Fatal error - abort start. */
  18735. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18736. if (error != NULL) {
  18737. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18738. mg_snprintf(NULL,
  18739. NULL, /* No truncation check for error buffers */
  18740. error->text,
  18741. error->text_buffer_size,
  18742. "%s",
  18743. err_msg);
  18744. }
  18745. free_context(ctx);
  18746. pthread_setspecific(sTlsKey, NULL);
  18747. return NULL;
  18748. }
  18749. #elif !defined(NO_SSL)
  18750. if (!init_ssl_ctx(ctx, NULL)) {
  18751. const char *err_msg = "Error initializing SSL context";
  18752. /* Fatal error - abort start. */
  18753. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18754. if (error != NULL) {
  18755. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18756. mg_snprintf(NULL,
  18757. NULL, /* No truncation check for error buffers */
  18758. error->text,
  18759. error->text_buffer_size,
  18760. "%s",
  18761. err_msg);
  18762. }
  18763. free_context(ctx);
  18764. pthread_setspecific(sTlsKey, NULL);
  18765. return NULL;
  18766. }
  18767. #endif
  18768. if (!set_ports_option(ctx)) {
  18769. const char *err_msg = "Failed to setup server ports";
  18770. /* Fatal error - abort start. */
  18771. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18772. if (error != NULL) {
  18773. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18774. mg_snprintf(NULL,
  18775. NULL, /* No truncation check for error buffers */
  18776. error->text,
  18777. error->text_buffer_size,
  18778. "%s",
  18779. err_msg);
  18780. }
  18781. free_context(ctx);
  18782. pthread_setspecific(sTlsKey, NULL);
  18783. return NULL;
  18784. }
  18785. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18786. if (!set_uid_option(ctx)) {
  18787. const char *err_msg = "Failed to run as configured user";
  18788. /* Fatal error - abort start. */
  18789. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18790. if (error != NULL) {
  18791. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18792. mg_snprintf(NULL,
  18793. NULL, /* No truncation check for error buffers */
  18794. error->text,
  18795. error->text_buffer_size,
  18796. "%s",
  18797. err_msg);
  18798. }
  18799. free_context(ctx);
  18800. pthread_setspecific(sTlsKey, NULL);
  18801. return NULL;
  18802. }
  18803. #endif
  18804. if (!set_acl_option(ctx)) {
  18805. const char *err_msg = "Failed to setup access control list";
  18806. /* Fatal error - abort start. */
  18807. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18808. if (error != NULL) {
  18809. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18810. mg_snprintf(NULL,
  18811. NULL, /* No truncation check for error buffers */
  18812. error->text,
  18813. error->text_buffer_size,
  18814. "%s",
  18815. err_msg);
  18816. }
  18817. free_context(ctx);
  18818. pthread_setspecific(sTlsKey, NULL);
  18819. return NULL;
  18820. }
  18821. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18822. ctx->worker_threadids =
  18823. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18824. sizeof(pthread_t),
  18825. ctx);
  18826. if (ctx->worker_threadids == NULL) {
  18827. const char *err_msg = "Not enough memory for worker thread ID array";
  18828. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18829. if (error != NULL) {
  18830. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18831. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18832. * (unsigned)sizeof(pthread_t);
  18833. mg_snprintf(NULL,
  18834. NULL, /* No truncation check for error buffers */
  18835. error->text,
  18836. error->text_buffer_size,
  18837. "%s",
  18838. err_msg);
  18839. }
  18840. free_context(ctx);
  18841. pthread_setspecific(sTlsKey, NULL);
  18842. return NULL;
  18843. }
  18844. ctx->worker_connections =
  18845. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18846. sizeof(struct mg_connection),
  18847. ctx);
  18848. if (ctx->worker_connections == NULL) {
  18849. const char *err_msg =
  18850. "Not enough memory for worker thread connection array";
  18851. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18852. if (error != NULL) {
  18853. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18854. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18855. * (unsigned)sizeof(struct mg_connection);
  18856. mg_snprintf(NULL,
  18857. NULL, /* No truncation check for error buffers */
  18858. error->text,
  18859. error->text_buffer_size,
  18860. "%s",
  18861. err_msg);
  18862. }
  18863. free_context(ctx);
  18864. pthread_setspecific(sTlsKey, NULL);
  18865. return NULL;
  18866. }
  18867. #if defined(ALTERNATIVE_QUEUE)
  18868. ctx->client_wait_events =
  18869. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18870. sizeof(ctx->client_wait_events[0]),
  18871. ctx);
  18872. if (ctx->client_wait_events == NULL) {
  18873. const char *err_msg = "Not enough memory for worker event array";
  18874. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18875. mg_free(ctx->worker_threadids);
  18876. if (error != NULL) {
  18877. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18878. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18879. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18880. mg_snprintf(NULL,
  18881. NULL, /* No truncation check for error buffers */
  18882. error->text,
  18883. error->text_buffer_size,
  18884. "%s",
  18885. err_msg);
  18886. }
  18887. free_context(ctx);
  18888. pthread_setspecific(sTlsKey, NULL);
  18889. return NULL;
  18890. }
  18891. ctx->client_socks =
  18892. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18893. sizeof(ctx->client_socks[0]),
  18894. ctx);
  18895. if (ctx->client_socks == NULL) {
  18896. const char *err_msg = "Not enough memory for worker socket array";
  18897. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18898. mg_free(ctx->client_wait_events);
  18899. mg_free(ctx->worker_threadids);
  18900. if (error != NULL) {
  18901. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18902. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18903. * (unsigned)sizeof(ctx->client_socks[0]);
  18904. mg_snprintf(NULL,
  18905. NULL, /* No truncation check for error buffers */
  18906. error->text,
  18907. error->text_buffer_size,
  18908. "%s",
  18909. err_msg);
  18910. }
  18911. free_context(ctx);
  18912. pthread_setspecific(sTlsKey, NULL);
  18913. return NULL;
  18914. }
  18915. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18916. ctx->client_wait_events[i] = event_create();
  18917. if (ctx->client_wait_events[i] == 0) {
  18918. const char *err_msg = "Error creating worker event %i";
  18919. mg_cry_ctx_internal(ctx, err_msg, i);
  18920. while (i > 0) {
  18921. i--;
  18922. event_destroy(ctx->client_wait_events[i]);
  18923. }
  18924. mg_free(ctx->client_socks);
  18925. mg_free(ctx->client_wait_events);
  18926. mg_free(ctx->worker_threadids);
  18927. if (error != NULL) {
  18928. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18929. error->code_sub = (unsigned)ERRNO;
  18930. mg_snprintf(NULL,
  18931. NULL, /* No truncation check for error buffers */
  18932. error->text,
  18933. error->text_buffer_size,
  18934. err_msg,
  18935. i);
  18936. }
  18937. free_context(ctx);
  18938. pthread_setspecific(sTlsKey, NULL);
  18939. return NULL;
  18940. }
  18941. }
  18942. #endif
  18943. #if defined(USE_TIMERS)
  18944. if (timers_init(ctx) != 0) {
  18945. const char *err_msg = "Error creating timers";
  18946. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18947. if (error != NULL) {
  18948. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18949. error->code_sub = (unsigned)ERRNO;
  18950. mg_snprintf(NULL,
  18951. NULL, /* No truncation check for error buffers */
  18952. error->text,
  18953. error->text_buffer_size,
  18954. "%s",
  18955. err_msg);
  18956. }
  18957. free_context(ctx);
  18958. pthread_setspecific(sTlsKey, NULL);
  18959. return NULL;
  18960. }
  18961. #endif
  18962. /* Context has been created - init user libraries */
  18963. if (ctx->callbacks.init_context) {
  18964. ctx->callbacks.init_context(ctx);
  18965. }
  18966. /* From now, the context is successfully created.
  18967. * When it is destroyed, the exit callback should be called. */
  18968. ctx->callbacks.exit_context = exit_callback;
  18969. ctx->context_type = CONTEXT_SERVER; /* server context */
  18970. /* Start worker threads */
  18971. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18972. /* worker_thread sets up the other fields */
  18973. if (mg_start_worker_thread(ctx, 0) != 0) {
  18974. long error_no = (long)ERRNO;
  18975. /* thread was not created */
  18976. if (ctx->spawned_worker_threads > 0) {
  18977. /* If the second, third, ... thread cannot be created, set a
  18978. * warning, but keep running. */
  18979. mg_cry_ctx_internal(ctx,
  18980. "Cannot start worker thread %i: error %ld",
  18981. ctx->spawned_worker_threads + 1,
  18982. error_no);
  18983. /* If the server initialization should stop here, all
  18984. * threads that have already been created must be stopped
  18985. * first, before any free_context(ctx) call.
  18986. */
  18987. } else {
  18988. /* If the first worker thread cannot be created, stop
  18989. * initialization and free the entire server context. */
  18990. mg_cry_ctx_internal(ctx,
  18991. "Cannot create threads: error %ld",
  18992. error_no);
  18993. if (error != NULL) {
  18994. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18995. error->code_sub = (unsigned)error_no;
  18996. mg_snprintf(
  18997. NULL,
  18998. NULL, /* No truncation check for error buffers */
  18999. error->text,
  19000. error->text_buffer_size,
  19001. "Cannot create first worker thread: error %ld",
  19002. error_no);
  19003. }
  19004. free_context(ctx);
  19005. pthread_setspecific(sTlsKey, NULL);
  19006. return NULL;
  19007. }
  19008. break;
  19009. }
  19010. }
  19011. /* Start master (listening) thread */
  19012. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  19013. pthread_setspecific(sTlsKey, NULL);
  19014. return ctx;
  19015. }
  19016. CIVETWEB_API struct mg_context *
  19017. mg_start(const struct mg_callbacks *callbacks,
  19018. void *user_data,
  19019. const char **options)
  19020. {
  19021. struct mg_init_data init = {0};
  19022. init.callbacks = callbacks;
  19023. init.user_data = user_data;
  19024. init.configuration_options = options;
  19025. return mg_start2(&init, NULL);
  19026. }
  19027. /* Add an additional domain to an already running web server. */
  19028. CIVETWEB_API int
  19029. mg_start_domain2(struct mg_context *ctx,
  19030. const char **options,
  19031. struct mg_error_data *error)
  19032. {
  19033. const char *name;
  19034. const char *value;
  19035. const char *default_value;
  19036. struct mg_domain_context *new_dom;
  19037. struct mg_domain_context *dom;
  19038. int idx, i;
  19039. if (error != NULL) {
  19040. error->code = MG_ERROR_DATA_CODE_OK;
  19041. error->code_sub = 0;
  19042. if (error->text_buffer_size > 0) {
  19043. *error->text = 0;
  19044. }
  19045. }
  19046. if ((ctx == NULL) || (options == NULL)) {
  19047. if (error != NULL) {
  19048. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  19049. mg_snprintf(NULL,
  19050. NULL, /* No truncation check for error buffers */
  19051. error->text,
  19052. error->text_buffer_size,
  19053. "%s",
  19054. "Invalid parameters");
  19055. }
  19056. return -1;
  19057. }
  19058. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  19059. if (error != NULL) {
  19060. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  19061. mg_snprintf(NULL,
  19062. NULL, /* No truncation check for error buffers */
  19063. error->text,
  19064. error->text_buffer_size,
  19065. "%s",
  19066. "Server already stopped");
  19067. }
  19068. return -7;
  19069. }
  19070. new_dom = (struct mg_domain_context *)
  19071. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  19072. if (!new_dom) {
  19073. /* Out of memory */
  19074. if (error != NULL) {
  19075. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  19076. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  19077. mg_snprintf(NULL,
  19078. NULL, /* No truncation check for error buffers */
  19079. error->text,
  19080. error->text_buffer_size,
  19081. "%s",
  19082. "Out or memory");
  19083. }
  19084. return -6;
  19085. }
  19086. /* Store options - TODO: unite duplicate code */
  19087. while (options && (name = *options++) != NULL) {
  19088. idx = get_option_index(name);
  19089. if (idx == -1) {
  19090. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19091. if (error != NULL) {
  19092. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19093. error->code_sub = (unsigned)-1;
  19094. mg_snprintf(NULL,
  19095. NULL, /* No truncation check for error buffers */
  19096. error->text,
  19097. error->text_buffer_size,
  19098. "Invalid option: %s",
  19099. name);
  19100. }
  19101. mg_free(new_dom);
  19102. return -2;
  19103. } else if ((value = *options++) == NULL) {
  19104. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19105. if (error != NULL) {
  19106. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19107. error->code_sub = (unsigned)idx;
  19108. mg_snprintf(NULL,
  19109. NULL, /* No truncation check for error buffers */
  19110. error->text,
  19111. error->text_buffer_size,
  19112. "Invalid option value: %s",
  19113. name);
  19114. }
  19115. mg_free(new_dom);
  19116. return -2;
  19117. }
  19118. if (new_dom->config[idx] != NULL) {
  19119. /* Duplicate option: Later values overwrite earlier ones. */
  19120. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19121. mg_free(new_dom->config[idx]);
  19122. }
  19123. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19124. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19125. }
  19126. /* Authentication domain is mandatory */
  19127. /* TODO: Maybe use a new option hostname? */
  19128. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19129. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19130. if (error != NULL) {
  19131. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19132. error->code_sub = AUTHENTICATION_DOMAIN;
  19133. mg_snprintf(NULL,
  19134. NULL, /* No truncation check for error buffers */
  19135. error->text,
  19136. error->text_buffer_size,
  19137. "Mandatory option %s missing",
  19138. config_options[AUTHENTICATION_DOMAIN].name);
  19139. }
  19140. mg_free(new_dom);
  19141. return -4;
  19142. }
  19143. /* Set default value if needed. Take the config value from
  19144. * ctx as a default value. */
  19145. for (i = 0; config_options[i].name != NULL; i++) {
  19146. default_value = ctx->dd.config[i];
  19147. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19148. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19149. }
  19150. }
  19151. new_dom->handlers = ctx->dd.handlers;
  19152. new_dom->next = NULL;
  19153. new_dom->nonce_count = 0;
  19154. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19155. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19156. new_dom->shared_lua_websockets = NULL;
  19157. #endif
  19158. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19159. if (!init_ssl_ctx(ctx, new_dom)) {
  19160. /* Init SSL failed */
  19161. if (error != NULL) {
  19162. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19163. mg_snprintf(NULL,
  19164. NULL, /* No truncation check for error buffers */
  19165. error->text,
  19166. error->text_buffer_size,
  19167. "%s",
  19168. "Initializing SSL context failed");
  19169. }
  19170. mg_free(new_dom);
  19171. return -3;
  19172. }
  19173. #endif
  19174. /* Add element to linked list. */
  19175. mg_lock_context(ctx);
  19176. idx = 0;
  19177. dom = &(ctx->dd);
  19178. for (;;) {
  19179. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19180. dom->config[AUTHENTICATION_DOMAIN])) {
  19181. /* Domain collision */
  19182. mg_cry_ctx_internal(ctx,
  19183. "domain %s already in use",
  19184. new_dom->config[AUTHENTICATION_DOMAIN]);
  19185. if (error != NULL) {
  19186. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19187. mg_snprintf(NULL,
  19188. NULL, /* No truncation check for error buffers */
  19189. error->text,
  19190. error->text_buffer_size,
  19191. "Domain %s specified by %s is already in use",
  19192. new_dom->config[AUTHENTICATION_DOMAIN],
  19193. config_options[AUTHENTICATION_DOMAIN].name);
  19194. }
  19195. mg_free(new_dom);
  19196. mg_unlock_context(ctx);
  19197. return -5;
  19198. }
  19199. /* Count number of domains */
  19200. idx++;
  19201. if (dom->next == NULL) {
  19202. dom->next = new_dom;
  19203. break;
  19204. }
  19205. dom = dom->next;
  19206. }
  19207. mg_unlock_context(ctx);
  19208. /* Return domain number */
  19209. return idx;
  19210. }
  19211. CIVETWEB_API int
  19212. mg_start_domain(struct mg_context *ctx, const char **options)
  19213. {
  19214. return mg_start_domain2(ctx, options, NULL);
  19215. }
  19216. /* Feature check API function */
  19217. CIVETWEB_API unsigned
  19218. mg_check_feature(unsigned feature)
  19219. {
  19220. static const unsigned feature_set = 0
  19221. /* Set bits for available features according to API documentation.
  19222. * This bit mask is created at compile time, according to the active
  19223. * preprocessor defines. It is a single const value at runtime. */
  19224. #if !defined(NO_FILES)
  19225. | MG_FEATURES_FILES
  19226. #endif
  19227. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19228. | MG_FEATURES_SSL
  19229. #endif
  19230. #if !defined(NO_CGI)
  19231. | MG_FEATURES_CGI
  19232. #endif
  19233. #if defined(USE_IPV6)
  19234. | MG_FEATURES_IPV6
  19235. #endif
  19236. #if defined(USE_WEBSOCKET)
  19237. | MG_FEATURES_WEBSOCKET
  19238. #endif
  19239. #if defined(USE_LUA)
  19240. | MG_FEATURES_LUA
  19241. #endif
  19242. #if defined(USE_DUKTAPE)
  19243. | MG_FEATURES_SSJS
  19244. #endif
  19245. #if !defined(NO_CACHING)
  19246. | MG_FEATURES_CACHE
  19247. #endif
  19248. #if defined(USE_SERVER_STATS)
  19249. | MG_FEATURES_STATS
  19250. #endif
  19251. #if defined(USE_ZLIB)
  19252. | MG_FEATURES_COMPRESSION
  19253. #endif
  19254. #if defined(USE_HTTP2)
  19255. | MG_FEATURES_HTTP2
  19256. #endif
  19257. #if defined(USE_X_DOM_SOCKET)
  19258. | MG_FEATURES_X_DOMAIN_SOCKET
  19259. #endif
  19260. /* Set some extra bits not defined in the API documentation.
  19261. * These bits may change without further notice. */
  19262. #if defined(MG_LEGACY_INTERFACE)
  19263. | 0x80000000u
  19264. #endif
  19265. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19266. | 0x40000000u
  19267. #endif
  19268. #if !defined(NO_RESPONSE_BUFFERING)
  19269. | 0x20000000u
  19270. #endif
  19271. #if defined(MEMORY_DEBUGGING)
  19272. | 0x10000000u
  19273. #endif
  19274. ;
  19275. return (feature & feature_set);
  19276. }
  19277. static size_t
  19278. mg_str_append(char **dst, char *end, const char *src)
  19279. {
  19280. size_t len = strlen(src);
  19281. if (*dst != end) {
  19282. /* Append src if enough space, or close dst. */
  19283. if ((size_t)(end - *dst) > len) {
  19284. strcpy(*dst, src);
  19285. *dst += len;
  19286. } else {
  19287. *dst = end;
  19288. }
  19289. }
  19290. return len;
  19291. }
  19292. /* Get system information. It can be printed or stored by the caller.
  19293. * Return the size of available information. */
  19294. CIVETWEB_API int
  19295. mg_get_system_info(char *buffer, int buflen)
  19296. {
  19297. char *end, *append_eoobj = NULL, block[256];
  19298. size_t system_info_length = 0;
  19299. #if defined(_WIN32)
  19300. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19301. #else
  19302. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19303. #endif
  19304. if ((buffer == NULL) || (buflen < 1)) {
  19305. buflen = 0;
  19306. end = buffer;
  19307. } else {
  19308. *buffer = 0;
  19309. end = buffer + buflen;
  19310. }
  19311. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19312. /* has enough space to append eoobj */
  19313. append_eoobj = buffer;
  19314. if (end) {
  19315. end -= sizeof(eoobj) - 1;
  19316. }
  19317. }
  19318. system_info_length += mg_str_append(&buffer, end, "{");
  19319. /* Server version */
  19320. {
  19321. const char *version = mg_version();
  19322. mg_snprintf(NULL,
  19323. NULL,
  19324. block,
  19325. sizeof(block),
  19326. "%s\"version\" : \"%s\"",
  19327. eol,
  19328. version);
  19329. system_info_length += mg_str_append(&buffer, end, block);
  19330. }
  19331. /* System info */
  19332. {
  19333. #if defined(_WIN32)
  19334. DWORD dwVersion = 0;
  19335. DWORD dwMajorVersion = 0;
  19336. DWORD dwMinorVersion = 0;
  19337. SYSTEM_INFO si;
  19338. GetSystemInfo(&si);
  19339. #if defined(_MSC_VER)
  19340. #pragma warning(push)
  19341. /* GetVersion was declared deprecated */
  19342. #pragma warning(disable : 4996)
  19343. #endif
  19344. dwVersion = GetVersion();
  19345. #if defined(_MSC_VER)
  19346. #pragma warning(pop)
  19347. #endif
  19348. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19349. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19350. mg_snprintf(NULL,
  19351. NULL,
  19352. block,
  19353. sizeof(block),
  19354. ",%s\"os\" : \"Windows %u.%u\"",
  19355. eol,
  19356. (unsigned)dwMajorVersion,
  19357. (unsigned)dwMinorVersion);
  19358. system_info_length += mg_str_append(&buffer, end, block);
  19359. mg_snprintf(NULL,
  19360. NULL,
  19361. block,
  19362. sizeof(block),
  19363. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19364. eol,
  19365. (unsigned)si.wProcessorArchitecture,
  19366. (unsigned)si.dwNumberOfProcessors,
  19367. (unsigned)si.dwActiveProcessorMask);
  19368. system_info_length += mg_str_append(&buffer, end, block);
  19369. #elif defined(__rtems__)
  19370. mg_snprintf(NULL,
  19371. NULL,
  19372. block,
  19373. sizeof(block),
  19374. ",%s\"os\" : \"%s %s\"",
  19375. eol,
  19376. "RTEMS",
  19377. rtems_version());
  19378. system_info_length += mg_str_append(&buffer, end, block);
  19379. #elif defined(__ZEPHYR__)
  19380. mg_snprintf(NULL,
  19381. NULL,
  19382. block,
  19383. sizeof(block),
  19384. ",%s\"os\" : \"%s\"",
  19385. eol,
  19386. "Zephyr OS",
  19387. ZEPHYR_VERSION);
  19388. system_info_length += mg_str_append(&buffer, end, block);
  19389. #else
  19390. struct utsname name;
  19391. memset(&name, 0, sizeof(name));
  19392. uname(&name);
  19393. mg_snprintf(NULL,
  19394. NULL,
  19395. block,
  19396. sizeof(block),
  19397. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19398. eol,
  19399. name.sysname,
  19400. name.version,
  19401. name.release,
  19402. name.machine);
  19403. system_info_length += mg_str_append(&buffer, end, block);
  19404. #endif
  19405. }
  19406. /* Features */
  19407. {
  19408. mg_snprintf(NULL,
  19409. NULL,
  19410. block,
  19411. sizeof(block),
  19412. ",%s\"features\" : %lu"
  19413. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19414. eol,
  19415. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19416. eol,
  19417. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19418. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19419. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19420. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19421. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19422. : "",
  19423. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19424. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19425. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19426. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19427. system_info_length += mg_str_append(&buffer, end, block);
  19428. #if defined(USE_LUA)
  19429. mg_snprintf(NULL,
  19430. NULL,
  19431. block,
  19432. sizeof(block),
  19433. ",%s\"lua_version\" : \"%u (%s)\"",
  19434. eol,
  19435. (unsigned)LUA_VERSION_NUM,
  19436. LUA_RELEASE);
  19437. system_info_length += mg_str_append(&buffer, end, block);
  19438. #endif
  19439. #if defined(USE_DUKTAPE)
  19440. mg_snprintf(NULL,
  19441. NULL,
  19442. block,
  19443. sizeof(block),
  19444. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19445. eol,
  19446. (unsigned)DUK_VERSION / 10000,
  19447. ((unsigned)DUK_VERSION / 100) % 100,
  19448. (unsigned)DUK_VERSION % 100);
  19449. system_info_length += mg_str_append(&buffer, end, block);
  19450. #endif
  19451. }
  19452. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19453. {
  19454. #if defined(BUILD_DATE)
  19455. const char *bd = BUILD_DATE;
  19456. #else
  19457. #if defined(GCC_DIAGNOSTIC)
  19458. #if GCC_VERSION >= 40900
  19459. #pragma GCC diagnostic push
  19460. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19461. * does not work in some versions. If "BUILD_DATE" is defined to some
  19462. * string, it is used instead of __DATE__. */
  19463. #pragma GCC diagnostic ignored "-Wdate-time"
  19464. #endif
  19465. #endif
  19466. const char *bd = __DATE__;
  19467. #if defined(GCC_DIAGNOSTIC)
  19468. #if GCC_VERSION >= 40900
  19469. #pragma GCC diagnostic pop
  19470. #endif
  19471. #endif
  19472. #endif
  19473. mg_snprintf(
  19474. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19475. system_info_length += mg_str_append(&buffer, end, block);
  19476. }
  19477. /* Compiler information */
  19478. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19479. {
  19480. #if defined(_MSC_VER)
  19481. mg_snprintf(NULL,
  19482. NULL,
  19483. block,
  19484. sizeof(block),
  19485. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19486. eol,
  19487. (unsigned)_MSC_VER,
  19488. (unsigned)_MSC_FULL_VER);
  19489. system_info_length += mg_str_append(&buffer, end, block);
  19490. #elif defined(__MINGW64__)
  19491. mg_snprintf(NULL,
  19492. NULL,
  19493. block,
  19494. sizeof(block),
  19495. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19496. eol,
  19497. (unsigned)__MINGW64_VERSION_MAJOR,
  19498. (unsigned)__MINGW64_VERSION_MINOR);
  19499. system_info_length += mg_str_append(&buffer, end, block);
  19500. mg_snprintf(NULL,
  19501. NULL,
  19502. block,
  19503. sizeof(block),
  19504. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19505. eol,
  19506. (unsigned)__MINGW32_MAJOR_VERSION,
  19507. (unsigned)__MINGW32_MINOR_VERSION);
  19508. system_info_length += mg_str_append(&buffer, end, block);
  19509. #elif defined(__MINGW32__)
  19510. mg_snprintf(NULL,
  19511. NULL,
  19512. block,
  19513. sizeof(block),
  19514. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19515. eol,
  19516. (unsigned)__MINGW32_MAJOR_VERSION,
  19517. (unsigned)__MINGW32_MINOR_VERSION);
  19518. system_info_length += mg_str_append(&buffer, end, block);
  19519. #elif defined(__clang__)
  19520. mg_snprintf(NULL,
  19521. NULL,
  19522. block,
  19523. sizeof(block),
  19524. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19525. eol,
  19526. __clang_major__,
  19527. __clang_minor__,
  19528. __clang_patchlevel__,
  19529. __clang_version__);
  19530. system_info_length += mg_str_append(&buffer, end, block);
  19531. #elif defined(__GNUC__)
  19532. mg_snprintf(NULL,
  19533. NULL,
  19534. block,
  19535. sizeof(block),
  19536. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19537. eol,
  19538. (unsigned)__GNUC__,
  19539. (unsigned)__GNUC_MINOR__,
  19540. (unsigned)__GNUC_PATCHLEVEL__);
  19541. system_info_length += mg_str_append(&buffer, end, block);
  19542. #elif defined(__INTEL_COMPILER)
  19543. mg_snprintf(NULL,
  19544. NULL,
  19545. block,
  19546. sizeof(block),
  19547. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19548. eol,
  19549. (unsigned)__INTEL_COMPILER);
  19550. system_info_length += mg_str_append(&buffer, end, block);
  19551. #elif defined(__BORLANDC__)
  19552. mg_snprintf(NULL,
  19553. NULL,
  19554. block,
  19555. sizeof(block),
  19556. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19557. eol,
  19558. (unsigned)__BORLANDC__);
  19559. system_info_length += mg_str_append(&buffer, end, block);
  19560. #elif defined(__SUNPRO_C)
  19561. mg_snprintf(NULL,
  19562. NULL,
  19563. block,
  19564. sizeof(block),
  19565. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19566. eol,
  19567. (unsigned)__SUNPRO_C);
  19568. system_info_length += mg_str_append(&buffer, end, block);
  19569. #else
  19570. mg_snprintf(NULL,
  19571. NULL,
  19572. block,
  19573. sizeof(block),
  19574. ",%s\"compiler\" : \"other\"",
  19575. eol);
  19576. system_info_length += mg_str_append(&buffer, end, block);
  19577. #endif
  19578. }
  19579. /* Determine 32/64 bit data mode.
  19580. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19581. {
  19582. mg_snprintf(NULL,
  19583. NULL,
  19584. block,
  19585. sizeof(block),
  19586. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19587. "char:%u/%u, "
  19588. "ptr:%u, size:%u, time:%u\"",
  19589. eol,
  19590. (unsigned)sizeof(short),
  19591. (unsigned)sizeof(int),
  19592. (unsigned)sizeof(long),
  19593. (unsigned)sizeof(long long),
  19594. (unsigned)sizeof(float),
  19595. (unsigned)sizeof(double),
  19596. (unsigned)sizeof(long double),
  19597. (unsigned)sizeof(char),
  19598. (unsigned)sizeof(wchar_t),
  19599. (unsigned)sizeof(void *),
  19600. (unsigned)sizeof(size_t),
  19601. (unsigned)sizeof(time_t));
  19602. system_info_length += mg_str_append(&buffer, end, block);
  19603. }
  19604. /* Terminate string */
  19605. if (append_eoobj) {
  19606. strcat(append_eoobj, eoobj);
  19607. }
  19608. system_info_length += sizeof(eoobj) - 1;
  19609. return (int)system_info_length;
  19610. }
  19611. /* Get context information. It can be printed or stored by the caller.
  19612. * Return the size of available information. */
  19613. CIVETWEB_API int
  19614. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19615. {
  19616. #if defined(USE_SERVER_STATS)
  19617. char *end, *append_eoobj = NULL, block[256];
  19618. size_t context_info_length = 0;
  19619. #if defined(_WIN32)
  19620. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19621. #else
  19622. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19623. #endif
  19624. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19625. if ((buffer == NULL) || (buflen < 1)) {
  19626. buflen = 0;
  19627. end = buffer;
  19628. } else {
  19629. *buffer = 0;
  19630. end = buffer + buflen;
  19631. }
  19632. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19633. /* has enough space to append eoobj */
  19634. append_eoobj = buffer;
  19635. end -= sizeof(eoobj) - 1;
  19636. }
  19637. context_info_length += mg_str_append(&buffer, end, "{");
  19638. if (ms) { /* <-- should be always true */
  19639. /* Memory information */
  19640. int blockCount = (int)ms->blockCount;
  19641. int64_t totalMemUsed = ms->totalMemUsed;
  19642. int64_t maxMemUsed = ms->maxMemUsed;
  19643. if (totalMemUsed > maxMemUsed) {
  19644. maxMemUsed = totalMemUsed;
  19645. }
  19646. mg_snprintf(NULL,
  19647. NULL,
  19648. block,
  19649. sizeof(block),
  19650. "%s\"memory\" : {%s"
  19651. "\"blocks\" : %i,%s"
  19652. "\"used\" : %" INT64_FMT ",%s"
  19653. "\"maxUsed\" : %" INT64_FMT "%s"
  19654. "}",
  19655. eol,
  19656. eol,
  19657. blockCount,
  19658. eol,
  19659. totalMemUsed,
  19660. eol,
  19661. maxMemUsed,
  19662. eol);
  19663. context_info_length += mg_str_append(&buffer, end, block);
  19664. }
  19665. if (ctx) {
  19666. /* Declare all variables at begin of the block, to comply
  19667. * with old C standards. */
  19668. char start_time_str[64] = {0};
  19669. char now_str[64] = {0};
  19670. time_t start_time = ctx->start_time;
  19671. time_t now = time(NULL);
  19672. int64_t total_data_read, total_data_written;
  19673. int active_connections = (int)ctx->active_connections;
  19674. int max_active_connections = (int)ctx->max_active_connections;
  19675. int total_connections = (int)ctx->total_connections;
  19676. if (active_connections > max_active_connections) {
  19677. max_active_connections = active_connections;
  19678. }
  19679. if (active_connections > total_connections) {
  19680. total_connections = active_connections;
  19681. }
  19682. /* Connections information */
  19683. mg_snprintf(NULL,
  19684. NULL,
  19685. block,
  19686. sizeof(block),
  19687. ",%s\"connections\" : {%s"
  19688. "\"active\" : %i,%s"
  19689. "\"maxActive\" : %i,%s"
  19690. "\"total\" : %i%s"
  19691. "}",
  19692. eol,
  19693. eol,
  19694. active_connections,
  19695. eol,
  19696. max_active_connections,
  19697. eol,
  19698. total_connections,
  19699. eol);
  19700. context_info_length += mg_str_append(&buffer, end, block);
  19701. /* Queue information */
  19702. #if !defined(ALTERNATIVE_QUEUE)
  19703. mg_snprintf(NULL,
  19704. NULL,
  19705. block,
  19706. sizeof(block),
  19707. ",%s\"queue\" : {%s"
  19708. "\"length\" : %i,%s"
  19709. "\"filled\" : %i,%s"
  19710. "\"maxFilled\" : %i,%s"
  19711. "\"full\" : %s%s"
  19712. "}",
  19713. eol,
  19714. eol,
  19715. ctx->sq_size,
  19716. eol,
  19717. ctx->sq_head - ctx->sq_tail,
  19718. eol,
  19719. ctx->sq_max_fill,
  19720. eol,
  19721. (ctx->sq_blocked ? "true" : "false"),
  19722. eol);
  19723. context_info_length += mg_str_append(&buffer, end, block);
  19724. #endif
  19725. /* Requests information */
  19726. mg_snprintf(NULL,
  19727. NULL,
  19728. block,
  19729. sizeof(block),
  19730. ",%s\"requests\" : {%s"
  19731. "\"total\" : %lu%s"
  19732. "}",
  19733. eol,
  19734. eol,
  19735. (unsigned long)ctx->total_requests,
  19736. eol);
  19737. context_info_length += mg_str_append(&buffer, end, block);
  19738. /* Data information */
  19739. total_data_read =
  19740. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19741. total_data_written =
  19742. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19743. mg_snprintf(NULL,
  19744. NULL,
  19745. block,
  19746. sizeof(block),
  19747. ",%s\"data\" : {%s"
  19748. "\"read\" : %" INT64_FMT ",%s"
  19749. "\"written\" : %" INT64_FMT "%s"
  19750. "}",
  19751. eol,
  19752. eol,
  19753. total_data_read,
  19754. eol,
  19755. total_data_written,
  19756. eol);
  19757. context_info_length += mg_str_append(&buffer, end, block);
  19758. /* Execution time information */
  19759. gmt_time_string(start_time_str,
  19760. sizeof(start_time_str) - 1,
  19761. &start_time);
  19762. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19763. mg_snprintf(NULL,
  19764. NULL,
  19765. block,
  19766. sizeof(block),
  19767. ",%s\"time\" : {%s"
  19768. "\"uptime\" : %.0f,%s"
  19769. "\"start\" : \"%s\",%s"
  19770. "\"now\" : \"%s\"%s"
  19771. "}",
  19772. eol,
  19773. eol,
  19774. difftime(now, start_time),
  19775. eol,
  19776. start_time_str,
  19777. eol,
  19778. now_str,
  19779. eol);
  19780. context_info_length += mg_str_append(&buffer, end, block);
  19781. }
  19782. /* Terminate string */
  19783. if (append_eoobj) {
  19784. strcat(append_eoobj, eoobj);
  19785. }
  19786. context_info_length += sizeof(eoobj) - 1;
  19787. return (int)context_info_length;
  19788. #else
  19789. (void)ctx;
  19790. if ((buffer != NULL) && (buflen > 0)) {
  19791. *buffer = 0;
  19792. }
  19793. return 0;
  19794. #endif
  19795. }
  19796. CIVETWEB_API void
  19797. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19798. {
  19799. /* https://github.com/civetweb/civetweb/issues/727 */
  19800. if (conn != NULL) {
  19801. conn->must_close = 1;
  19802. }
  19803. }
  19804. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19805. /* Get connection information. It can be printed or stored by the caller.
  19806. * Return the size of available information. */
  19807. CIVETWEB_API int
  19808. mg_get_connection_info(const struct mg_context *ctx,
  19809. int idx,
  19810. char *buffer,
  19811. int buflen)
  19812. {
  19813. const struct mg_connection *conn;
  19814. const struct mg_request_info *ri;
  19815. char *end, *append_eoobj = NULL, block[256];
  19816. size_t connection_info_length = 0;
  19817. int state = 0;
  19818. const char *state_str = "unknown";
  19819. #if defined(_WIN32)
  19820. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19821. #else
  19822. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19823. #endif
  19824. if ((buffer == NULL) || (buflen < 1)) {
  19825. buflen = 0;
  19826. end = buffer;
  19827. } else {
  19828. *buffer = 0;
  19829. end = buffer + buflen;
  19830. }
  19831. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19832. /* has enough space to append eoobj */
  19833. append_eoobj = buffer;
  19834. end -= sizeof(eoobj) - 1;
  19835. }
  19836. if ((ctx == NULL) || (idx < 0)) {
  19837. /* Parameter error */
  19838. return 0;
  19839. }
  19840. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19841. /* Out of range */
  19842. return 0;
  19843. }
  19844. /* Take connection [idx]. This connection is not locked in
  19845. * any way, so some other thread might use it. */
  19846. conn = (ctx->worker_connections) + idx;
  19847. /* Initialize output string */
  19848. connection_info_length += mg_str_append(&buffer, end, "{");
  19849. /* Init variables */
  19850. ri = &(conn->request_info);
  19851. #if defined(USE_SERVER_STATS)
  19852. state = conn->conn_state;
  19853. /* State as string */
  19854. switch (state) {
  19855. case 0:
  19856. state_str = "undefined";
  19857. break;
  19858. case 1:
  19859. state_str = "not used";
  19860. break;
  19861. case 2:
  19862. state_str = "init";
  19863. break;
  19864. case 3:
  19865. state_str = "ready";
  19866. break;
  19867. case 4:
  19868. state_str = "processing";
  19869. break;
  19870. case 5:
  19871. state_str = "processed";
  19872. break;
  19873. case 6:
  19874. state_str = "to close";
  19875. break;
  19876. case 7:
  19877. state_str = "closing";
  19878. break;
  19879. case 8:
  19880. state_str = "closed";
  19881. break;
  19882. case 9:
  19883. state_str = "done";
  19884. break;
  19885. }
  19886. #endif
  19887. /* Connection info */
  19888. if ((state >= 3) && (state < 9)) {
  19889. mg_snprintf(NULL,
  19890. NULL,
  19891. block,
  19892. sizeof(block),
  19893. "%s\"connection\" : {%s"
  19894. "\"remote\" : {%s"
  19895. "\"protocol\" : \"%s\",%s"
  19896. "\"addr\" : \"%s\",%s"
  19897. "\"port\" : %u%s"
  19898. "},%s"
  19899. "\"handled_requests\" : %u%s"
  19900. "}",
  19901. eol,
  19902. eol,
  19903. eol,
  19904. get_proto_name(conn),
  19905. eol,
  19906. ri->remote_addr,
  19907. eol,
  19908. ri->remote_port,
  19909. eol,
  19910. eol,
  19911. conn->handled_requests,
  19912. eol);
  19913. connection_info_length += mg_str_append(&buffer, end, block);
  19914. }
  19915. /* Request info */
  19916. if ((state >= 4) && (state < 6)) {
  19917. mg_snprintf(NULL,
  19918. NULL,
  19919. block,
  19920. sizeof(block),
  19921. "%s%s\"request_info\" : {%s"
  19922. "\"method\" : \"%s\",%s"
  19923. "\"uri\" : \"%s\",%s"
  19924. "\"query\" : %s%s%s%s"
  19925. "}",
  19926. (connection_info_length > 1 ? "," : ""),
  19927. eol,
  19928. eol,
  19929. ri->request_method,
  19930. eol,
  19931. ri->request_uri,
  19932. eol,
  19933. ri->query_string ? "\"" : "",
  19934. ri->query_string ? ri->query_string : "null",
  19935. ri->query_string ? "\"" : "",
  19936. eol);
  19937. connection_info_length += mg_str_append(&buffer, end, block);
  19938. }
  19939. /* Execution time information */
  19940. if ((state >= 2) && (state < 9)) {
  19941. char start_time_str[64] = {0};
  19942. char close_time_str[64] = {0};
  19943. time_t start_time = conn->conn_birth_time;
  19944. time_t close_time = 0;
  19945. double time_diff;
  19946. gmt_time_string(start_time_str,
  19947. sizeof(start_time_str) - 1,
  19948. &start_time);
  19949. #if defined(USE_SERVER_STATS)
  19950. close_time = conn->conn_close_time;
  19951. #endif
  19952. if (close_time != 0) {
  19953. time_diff = difftime(close_time, start_time);
  19954. gmt_time_string(close_time_str,
  19955. sizeof(close_time_str) - 1,
  19956. &close_time);
  19957. } else {
  19958. time_t now = time(NULL);
  19959. time_diff = difftime(now, start_time);
  19960. close_time_str[0] = 0; /* or use "now" ? */
  19961. }
  19962. mg_snprintf(NULL,
  19963. NULL,
  19964. block,
  19965. sizeof(block),
  19966. "%s%s\"time\" : {%s"
  19967. "\"uptime\" : %.0f,%s"
  19968. "\"start\" : \"%s\",%s"
  19969. "\"closed\" : \"%s\"%s"
  19970. "}",
  19971. (connection_info_length > 1 ? "," : ""),
  19972. eol,
  19973. eol,
  19974. time_diff,
  19975. eol,
  19976. start_time_str,
  19977. eol,
  19978. close_time_str,
  19979. eol);
  19980. connection_info_length += mg_str_append(&buffer, end, block);
  19981. }
  19982. /* Remote user name */
  19983. if ((ri->remote_user) && (state < 9)) {
  19984. mg_snprintf(NULL,
  19985. NULL,
  19986. block,
  19987. sizeof(block),
  19988. "%s%s\"user\" : {%s"
  19989. "\"name\" : \"%s\",%s"
  19990. "}",
  19991. (connection_info_length > 1 ? "," : ""),
  19992. eol,
  19993. eol,
  19994. ri->remote_user,
  19995. eol);
  19996. connection_info_length += mg_str_append(&buffer, end, block);
  19997. }
  19998. /* Data block */
  19999. if (state >= 3) {
  20000. mg_snprintf(NULL,
  20001. NULL,
  20002. block,
  20003. sizeof(block),
  20004. "%s%s\"data\" : {%s"
  20005. "\"read\" : %" INT64_FMT ",%s"
  20006. "\"written\" : %" INT64_FMT "%s"
  20007. "}",
  20008. (connection_info_length > 1 ? "," : ""),
  20009. eol,
  20010. eol,
  20011. conn->consumed_content,
  20012. eol,
  20013. conn->num_bytes_sent,
  20014. eol);
  20015. connection_info_length += mg_str_append(&buffer, end, block);
  20016. }
  20017. /* State */
  20018. mg_snprintf(NULL,
  20019. NULL,
  20020. block,
  20021. sizeof(block),
  20022. "%s%s\"state\" : \"%s\"",
  20023. (connection_info_length > 1 ? "," : ""),
  20024. eol,
  20025. state_str);
  20026. connection_info_length += mg_str_append(&buffer, end, block);
  20027. /* Terminate string */
  20028. if (append_eoobj) {
  20029. strcat(append_eoobj, eoobj);
  20030. }
  20031. connection_info_length += sizeof(eoobj) - 1;
  20032. return (int)connection_info_length;
  20033. }
  20034. #if 0
  20035. /* Get handler information. Not fully implemented. Is it required? */
  20036. CIVETWEB_API int
  20037. mg_get_handler_info(struct mg_context *ctx,
  20038. char *buffer,
  20039. int buflen)
  20040. {
  20041. int handler_info_len = 0;
  20042. struct mg_handler_info *tmp_rh;
  20043. mg_lock_context(ctx);
  20044. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  20045. if (buflen > handler_info_len + tmp_rh->uri_len) {
  20046. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  20047. }
  20048. handler_info_len += tmp_rh->uri_len;
  20049. switch (tmp_rh->handler_type) {
  20050. case REQUEST_HANDLER:
  20051. (void)tmp_rh->handler;
  20052. break;
  20053. case WEBSOCKET_HANDLER:
  20054. (void)tmp_rh->connect_handler;
  20055. (void)tmp_rh->ready_handler;
  20056. (void)tmp_rh->data_handler;
  20057. (void)tmp_rh->close_handler;
  20058. break;
  20059. case AUTH_HANDLER:
  20060. (void)tmp_rh->auth_handler;
  20061. break;
  20062. }
  20063. (void)cbdata;
  20064. }
  20065. mg_unlock_context(ctx);
  20066. return handler_info_len;
  20067. }
  20068. #endif
  20069. #endif
  20070. /* Initialize this library. This function does not need to be thread safe.
  20071. */
  20072. CIVETWEB_API unsigned
  20073. mg_init_library(unsigned features)
  20074. {
  20075. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  20076. unsigned features_inited = features_to_init;
  20077. if (mg_init_library_called <= 0) {
  20078. /* Not initialized yet */
  20079. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  20080. return 0;
  20081. }
  20082. }
  20083. mg_global_lock();
  20084. if (mg_init_library_called <= 0) {
  20085. int i;
  20086. size_t len;
  20087. #if defined(_WIN32)
  20088. int file_mutex_init = 1;
  20089. int wsa = 1;
  20090. #else
  20091. int mutexattr_init = 1;
  20092. #endif
  20093. int failed = 1;
  20094. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20095. if (key_create == 0) {
  20096. #if defined(_WIN32)
  20097. file_mutex_init =
  20098. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20099. if (file_mutex_init == 0) {
  20100. /* Start WinSock */
  20101. WSADATA data;
  20102. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20103. }
  20104. #else
  20105. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20106. if (mutexattr_init == 0) {
  20107. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20108. PTHREAD_MUTEX_RECURSIVE);
  20109. }
  20110. #endif
  20111. }
  20112. if (failed) {
  20113. #if defined(_WIN32)
  20114. if (wsa == 0) {
  20115. (void)WSACleanup();
  20116. }
  20117. if (file_mutex_init == 0) {
  20118. (void)pthread_mutex_destroy(&global_log_file_lock);
  20119. }
  20120. #else
  20121. if (mutexattr_init == 0) {
  20122. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20123. }
  20124. #endif
  20125. if (key_create == 0) {
  20126. (void)pthread_key_delete(sTlsKey);
  20127. }
  20128. mg_global_unlock();
  20129. (void)pthread_mutex_destroy(&global_lock_mutex);
  20130. return 0;
  20131. }
  20132. len = 1;
  20133. for (i = 0; http_methods[i].name != NULL; i++) {
  20134. size_t sl = strlen(http_methods[i].name);
  20135. len += sl;
  20136. if (i > 0) {
  20137. len += 2;
  20138. }
  20139. }
  20140. all_methods = (char *)mg_malloc(len);
  20141. if (!all_methods) {
  20142. /* Must never happen */
  20143. mg_global_unlock();
  20144. (void)pthread_mutex_destroy(&global_lock_mutex);
  20145. return 0;
  20146. }
  20147. all_methods[0] = 0;
  20148. for (i = 0; http_methods[i].name != NULL; i++) {
  20149. if (i > 0) {
  20150. strcat(all_methods, ", ");
  20151. strcat(all_methods, http_methods[i].name);
  20152. } else {
  20153. strcpy(all_methods, http_methods[i].name);
  20154. }
  20155. }
  20156. }
  20157. #if defined(USE_LUA)
  20158. lua_init_optional_libraries();
  20159. #endif
  20160. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20161. || defined(OPENSSL_API_3_0)) \
  20162. && !defined(NO_SSL)
  20163. if (features_to_init & MG_FEATURES_SSL) {
  20164. if (!mg_openssl_initialized) {
  20165. char ebuf[128];
  20166. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20167. mg_openssl_initialized = 1;
  20168. } else {
  20169. (void)ebuf;
  20170. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20171. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20172. }
  20173. } else {
  20174. /* ssl already initialized */
  20175. }
  20176. }
  20177. #endif
  20178. if (mg_init_library_called <= 0) {
  20179. mg_init_library_called = 1;
  20180. } else {
  20181. mg_init_library_called++;
  20182. }
  20183. mg_global_unlock();
  20184. return features_inited;
  20185. }
  20186. /* Un-initialize this library. */
  20187. CIVETWEB_API unsigned
  20188. mg_exit_library(void)
  20189. {
  20190. if (mg_init_library_called <= 0) {
  20191. return 0;
  20192. }
  20193. mg_global_lock();
  20194. mg_init_library_called--;
  20195. if (mg_init_library_called == 0) {
  20196. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20197. if (mg_openssl_initialized) {
  20198. uninitialize_openssl();
  20199. mg_openssl_initialized = 0;
  20200. }
  20201. #endif
  20202. #if defined(_WIN32)
  20203. (void)WSACleanup();
  20204. (void)pthread_mutex_destroy(&global_log_file_lock);
  20205. #else
  20206. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20207. #endif
  20208. (void)pthread_key_delete(sTlsKey);
  20209. #if defined(USE_LUA)
  20210. lua_exit_optional_libraries();
  20211. #endif
  20212. mg_free(all_methods);
  20213. all_methods = NULL;
  20214. mg_global_unlock();
  20215. (void)pthread_mutex_destroy(&global_lock_mutex);
  20216. return 1;
  20217. }
  20218. mg_global_unlock();
  20219. return 1;
  20220. }
  20221. /* End of civetweb.c */