civetweb.c 621 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261
  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_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__rtems__)
  170. #include <rtems/version.h>
  171. #endif
  172. #if defined(__ZEPHYR__)
  173. #include <ctype.h>
  174. #include <fcntl.h>
  175. #include <netdb.h>
  176. #include <poll.h>
  177. #include <pthread.h>
  178. #include <stdio.h>
  179. #include <stdlib.h>
  180. #include <string.h>
  181. #include <sys/socket.h>
  182. #include <time.h>
  183. #include <zephyr/kernel.h>
  184. /* Max worker threads is the max of pthreads minus the main application thread
  185. * and minus the main civetweb thread, thus -2
  186. */
  187. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  188. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  189. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  190. #else
  191. #define ZEPHYR_STACK_SIZE (1024 * 16)
  192. #endif
  193. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  194. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  195. MAX_WORKER_THREADS,
  196. ZEPHYR_STACK_SIZE);
  197. static int zephyr_worker_stack_index;
  198. #endif
  199. #if !defined(CIVETWEB_HEADER_INCLUDED)
  200. /* Include the header file here, so the CivetWeb interface is defined for the
  201. * entire implementation, including the following forward definitions. */
  202. #include "civetweb.h"
  203. #endif
  204. #if !defined(DEBUG_TRACE)
  205. #if defined(DEBUG)
  206. static void DEBUG_TRACE_FUNC(const char *func,
  207. unsigned line,
  208. PRINTF_FORMAT_STRING(const char *fmt),
  209. ...) PRINTF_ARGS(3, 4);
  210. #define DEBUG_TRACE(fmt, ...) \
  211. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  212. #define NEED_DEBUG_TRACE_FUNC
  213. #if !defined(DEBUG_TRACE_STREAM)
  214. #define DEBUG_TRACE_STREAM 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 && cors_repl_asterisk_with_orig_cfg && *cors_repl_asterisk_with_orig_cfg) {
  3555. int cors_repl_asterisk_with_orig = mg_strcasecmp(cors_repl_asterisk_with_orig_cfg, "yes");
  3556. /* Cross-origin resource sharing (CORS), see
  3557. * http://www.html5rocks.com/en/tutorials/cors/,
  3558. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3559. * CORS preflight is not supported for files. */
  3560. if (cors_repl_asterisk_with_orig == 0 && cors_orig_cfg[0] == '*') {
  3561. mg_response_header_add(conn,
  3562. "Access-Control-Allow-Origin",
  3563. origin_hdr,
  3564. -1);
  3565. } else {
  3566. mg_response_header_add(conn,
  3567. "Access-Control-Allow-Origin",
  3568. cors_orig_cfg,
  3569. -1);
  3570. }
  3571. }
  3572. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3573. /* Cross-origin resource sharing (CORS), see
  3574. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3575. */
  3576. mg_response_header_add(conn,
  3577. "Access-Control-Allow-Credentials",
  3578. cors_cred_cfg,
  3579. -1);
  3580. }
  3581. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3582. mg_response_header_add(conn,
  3583. "Access-Control-Allow-Headers",
  3584. cors_hdr_cfg,
  3585. -1);
  3586. }
  3587. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3588. mg_response_header_add(conn,
  3589. "Access-Control-Expose-Headers",
  3590. cors_exphdr_cfg,
  3591. -1);
  3592. }
  3593. if (cors_meth_cfg && *cors_meth_cfg) {
  3594. mg_response_header_add(conn,
  3595. "Access-Control-Allow-Methods",
  3596. cors_meth_cfg,
  3597. -1);
  3598. }
  3599. }
  3600. #if !defined(NO_FILESYSTEMS)
  3601. static void handle_file_based_request(struct mg_connection *conn,
  3602. const char *path,
  3603. struct mg_file *filep);
  3604. #endif /* NO_FILESYSTEMS */
  3605. CIVETWEB_API const char *
  3606. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3607. {
  3608. /* See IANA HTTP status code assignment:
  3609. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3610. */
  3611. switch (response_code) {
  3612. /* RFC2616 Section 10.1 - Informational 1xx */
  3613. case 100:
  3614. return "Continue"; /* RFC2616 Section 10.1.1 */
  3615. case 101:
  3616. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3617. case 102:
  3618. return "Processing"; /* RFC2518 Section 10.1 */
  3619. /* RFC2616 Section 10.2 - Successful 2xx */
  3620. case 200:
  3621. return "OK"; /* RFC2616 Section 10.2.1 */
  3622. case 201:
  3623. return "Created"; /* RFC2616 Section 10.2.2 */
  3624. case 202:
  3625. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3626. case 203:
  3627. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3628. case 204:
  3629. return "No Content"; /* RFC2616 Section 10.2.5 */
  3630. case 205:
  3631. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3632. case 206:
  3633. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3634. case 207:
  3635. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3636. */
  3637. case 208:
  3638. return "Already Reported"; /* RFC5842 Section 7.1 */
  3639. case 226:
  3640. return "IM used"; /* RFC3229 Section 10.4.1 */
  3641. /* RFC2616 Section 10.3 - Redirection 3xx */
  3642. case 300:
  3643. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3644. case 301:
  3645. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3646. case 302:
  3647. return "Found"; /* RFC2616 Section 10.3.3 */
  3648. case 303:
  3649. return "See Other"; /* RFC2616 Section 10.3.4 */
  3650. case 304:
  3651. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3652. case 305:
  3653. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3654. case 307:
  3655. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3656. case 308:
  3657. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3658. /* RFC2616 Section 10.4 - Client Error 4xx */
  3659. case 400:
  3660. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3661. case 401:
  3662. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3663. case 402:
  3664. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3665. case 403:
  3666. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3667. case 404:
  3668. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3669. case 405:
  3670. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3671. case 406:
  3672. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3673. case 407:
  3674. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3675. case 408:
  3676. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3677. case 409:
  3678. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3679. case 410:
  3680. return "Gone"; /* RFC2616 Section 10.4.11 */
  3681. case 411:
  3682. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3683. case 412:
  3684. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3685. case 413:
  3686. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3687. case 414:
  3688. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3689. case 415:
  3690. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3691. case 416:
  3692. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3693. */
  3694. case 417:
  3695. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3696. case 421:
  3697. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3698. case 422:
  3699. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3700. * Section 11.2 */
  3701. case 423:
  3702. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3703. case 424:
  3704. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3705. * Section 11.4 */
  3706. case 426:
  3707. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3708. case 428:
  3709. return "Precondition Required"; /* RFC 6585, Section 3 */
  3710. case 429:
  3711. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3712. case 431:
  3713. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3714. case 451:
  3715. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3716. * Section 3 */
  3717. /* RFC2616 Section 10.5 - Server Error 5xx */
  3718. case 500:
  3719. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3720. case 501:
  3721. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3722. case 502:
  3723. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3724. case 503:
  3725. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3726. case 504:
  3727. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3728. case 505:
  3729. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3730. case 506:
  3731. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3732. case 507:
  3733. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3734. * Section 11.5 */
  3735. case 508:
  3736. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3737. case 510:
  3738. return "Not Extended"; /* RFC 2774, Section 7 */
  3739. case 511:
  3740. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3741. /* Other status codes, not shown in the IANA HTTP status code
  3742. * assignment.
  3743. * E.g., "de facto" standards due to common use, ... */
  3744. case 418:
  3745. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3746. case 419:
  3747. return "Authentication Timeout"; /* common use */
  3748. case 420:
  3749. return "Enhance Your Calm"; /* common use */
  3750. case 440:
  3751. return "Login Timeout"; /* common use */
  3752. case 509:
  3753. return "Bandwidth Limit Exceeded"; /* common use */
  3754. default:
  3755. /* This error code is unknown. This should not happen. */
  3756. if (conn) {
  3757. mg_cry_internal(conn,
  3758. "Unknown HTTP response code: %u",
  3759. response_code);
  3760. }
  3761. /* Return at least a category according to RFC 2616 Section 10. */
  3762. if (response_code >= 100 && response_code < 200) {
  3763. /* Unknown informational status code */
  3764. return "Information";
  3765. }
  3766. if (response_code >= 200 && response_code < 300) {
  3767. /* Unknown success code */
  3768. return "Success";
  3769. }
  3770. if (response_code >= 300 && response_code < 400) {
  3771. /* Unknown redirection code */
  3772. return "Redirection";
  3773. }
  3774. if (response_code >= 400 && response_code < 500) {
  3775. /* Unknown request error code */
  3776. return "Client Error";
  3777. }
  3778. if (response_code >= 500 && response_code < 600) {
  3779. /* Unknown server error code */
  3780. return "Server Error";
  3781. }
  3782. /* Response code not even within reasonable range */
  3783. return "";
  3784. }
  3785. }
  3786. static int
  3787. mg_send_http_error_impl(struct mg_connection *conn,
  3788. int status,
  3789. const char *fmt,
  3790. va_list args)
  3791. {
  3792. char errmsg_buf[MG_BUF_LEN];
  3793. va_list ap;
  3794. int has_body;
  3795. #if !defined(NO_FILESYSTEMS)
  3796. char path_buf[UTF8_PATH_MAX];
  3797. int len, i, page_handler_found, scope, truncated;
  3798. const char *error_handler = NULL;
  3799. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3800. const char *error_page_file_ext, *tstr;
  3801. #endif /* NO_FILESYSTEMS */
  3802. int handled_by_callback = 0;
  3803. if ((conn == NULL) || (fmt == NULL)) {
  3804. return -2;
  3805. }
  3806. /* Set status (for log) */
  3807. conn->status_code = status;
  3808. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3809. has_body = ((status > 199) && (status != 204) && (status != 304));
  3810. /* Prepare message in buf, if required */
  3811. if (has_body
  3812. || (!conn->in_error_handler
  3813. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3814. /* Store error message in errmsg_buf */
  3815. va_copy(ap, args);
  3816. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3817. va_end(ap);
  3818. /* In a debug build, print all html errors */
  3819. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3820. }
  3821. /* If there is a http_error callback, call it.
  3822. * But don't do it recursively, if callback calls mg_send_http_error again.
  3823. */
  3824. if (!conn->in_error_handler
  3825. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3826. /* Mark in_error_handler to avoid recursion and call user callback. */
  3827. conn->in_error_handler = 1;
  3828. handled_by_callback =
  3829. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3830. == 0);
  3831. conn->in_error_handler = 0;
  3832. }
  3833. if (!handled_by_callback) {
  3834. /* Check for recursion */
  3835. if (conn->in_error_handler) {
  3836. DEBUG_TRACE(
  3837. "Recursion when handling error %u - fall back to default",
  3838. status);
  3839. #if !defined(NO_FILESYSTEMS)
  3840. } else {
  3841. /* Send user defined error pages, if defined */
  3842. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3843. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3844. page_handler_found = 0;
  3845. if (error_handler != NULL) {
  3846. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3847. switch (scope) {
  3848. case 1: /* Handler for specific error, e.g. 404 error */
  3849. mg_snprintf(conn,
  3850. &truncated,
  3851. path_buf,
  3852. sizeof(path_buf) - 32,
  3853. "%serror%03u.",
  3854. error_handler,
  3855. status);
  3856. break;
  3857. case 2: /* Handler for error group, e.g., 5xx error
  3858. * handler
  3859. * for all server errors (500-599) */
  3860. mg_snprintf(conn,
  3861. &truncated,
  3862. path_buf,
  3863. sizeof(path_buf) - 32,
  3864. "%serror%01uxx.",
  3865. error_handler,
  3866. status / 100);
  3867. break;
  3868. default: /* Handler for all errors */
  3869. mg_snprintf(conn,
  3870. &truncated,
  3871. path_buf,
  3872. sizeof(path_buf) - 32,
  3873. "%serror.",
  3874. error_handler);
  3875. break;
  3876. }
  3877. /* String truncation in buf may only occur if
  3878. * error_handler is too long. This string is
  3879. * from the config, not from a client. */
  3880. (void)truncated;
  3881. /* The following code is redundant, but it should avoid
  3882. * false positives in static source code analyzers and
  3883. * vulnerability scanners.
  3884. */
  3885. path_buf[sizeof(path_buf) - 32] = 0;
  3886. len = (int)strlen(path_buf);
  3887. if (len > (int)sizeof(path_buf) - 32) {
  3888. len = (int)sizeof(path_buf) - 32;
  3889. }
  3890. /* Start with the file extension from the configuration. */
  3891. tstr = strchr(error_page_file_ext, '.');
  3892. while (tstr) {
  3893. for (i = 1;
  3894. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3895. i++) {
  3896. /* buffer overrun is not possible here, since
  3897. * (i < 32) && (len < sizeof(path_buf) - 32)
  3898. * ==> (i + len) < sizeof(path_buf) */
  3899. path_buf[len + i - 1] = tstr[i];
  3900. }
  3901. /* buffer overrun is not possible here, since
  3902. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3903. * ==> (i + len) <= sizeof(path_buf) */
  3904. path_buf[len + i - 1] = 0;
  3905. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3906. DEBUG_TRACE("Check error page %s - found",
  3907. path_buf);
  3908. page_handler_found = 1;
  3909. break;
  3910. }
  3911. DEBUG_TRACE("Check error page %s - not found",
  3912. path_buf);
  3913. /* Continue with the next file extension from the
  3914. * configuration (if there is a next one). */
  3915. tstr = strchr(tstr + i, '.');
  3916. }
  3917. }
  3918. }
  3919. if (page_handler_found) {
  3920. conn->in_error_handler = 1;
  3921. handle_file_based_request(conn, path_buf, &error_page_file);
  3922. conn->in_error_handler = 0;
  3923. return 0;
  3924. }
  3925. #endif /* NO_FILESYSTEMS */
  3926. }
  3927. /* No custom error page. Send default error page. */
  3928. conn->must_close = 1;
  3929. mg_response_header_start(conn, status);
  3930. send_no_cache_header(conn);
  3931. send_additional_header(conn);
  3932. send_cors_header(conn);
  3933. if (has_body) {
  3934. mg_response_header_add(conn,
  3935. "Content-Type",
  3936. "text/plain; charset=utf-8",
  3937. -1);
  3938. }
  3939. mg_response_header_send(conn);
  3940. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3941. if (has_body) {
  3942. /* For other errors, send a generic error message. */
  3943. const char *status_text = mg_get_response_code_text(conn, status);
  3944. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3945. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3946. } else {
  3947. /* No body allowed. Close the connection. */
  3948. DEBUG_TRACE("Error %i", status);
  3949. }
  3950. }
  3951. return 0;
  3952. }
  3953. CIVETWEB_API int
  3954. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3955. {
  3956. va_list ap;
  3957. int ret;
  3958. va_start(ap, fmt);
  3959. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3960. va_end(ap);
  3961. return ret;
  3962. }
  3963. CIVETWEB_API int
  3964. mg_send_http_ok(struct mg_connection *conn,
  3965. const char *mime_type,
  3966. long long content_length)
  3967. {
  3968. if ((mime_type == NULL) || (*mime_type == 0)) {
  3969. /* No content type defined: default to text/html */
  3970. mime_type = "text/html";
  3971. }
  3972. mg_response_header_start(conn, 200);
  3973. send_no_cache_header(conn);
  3974. send_additional_header(conn);
  3975. send_cors_header(conn);
  3976. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3977. if (content_length < 0) {
  3978. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3979. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3980. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3981. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3982. }
  3983. } else {
  3984. char len[32];
  3985. int trunc = 0;
  3986. mg_snprintf(conn,
  3987. &trunc,
  3988. len,
  3989. sizeof(len),
  3990. "%" UINT64_FMT,
  3991. (uint64_t)content_length);
  3992. if (!trunc) {
  3993. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3994. * !trunc is always true */
  3995. mg_response_header_add(conn, "Content-Length", len, -1);
  3996. }
  3997. }
  3998. mg_response_header_send(conn);
  3999. return 0;
  4000. }
  4001. CIVETWEB_API int
  4002. mg_send_http_redirect(struct mg_connection *conn,
  4003. const char *target_url,
  4004. int redirect_code)
  4005. {
  4006. /* Send a 30x redirect response.
  4007. *
  4008. * Redirect types (status codes):
  4009. *
  4010. * Status | Perm/Temp | Method | Version
  4011. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4012. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4013. * 303 | temporary | always use GET | HTTP/1.1
  4014. * 307 | temporary | always keep method | HTTP/1.1
  4015. * 308 | permanent | always keep method | HTTP/1.1
  4016. */
  4017. #if defined(MG_SEND_REDIRECT_BODY)
  4018. char redirect_body[MG_BUF_LEN];
  4019. size_t content_len = 0;
  4020. char content_len_text[32];
  4021. #endif
  4022. /* In case redirect_code=0, use 307. */
  4023. if (redirect_code == 0) {
  4024. redirect_code = 307;
  4025. }
  4026. /* In case redirect_code is none of the above, return error. */
  4027. if ((redirect_code != 301) && (redirect_code != 302)
  4028. && (redirect_code != 303) && (redirect_code != 307)
  4029. && (redirect_code != 308)) {
  4030. /* Parameter error */
  4031. return -2;
  4032. }
  4033. /* If target_url is not defined, redirect to "/". */
  4034. if ((target_url == NULL) || (*target_url == 0)) {
  4035. target_url = "/";
  4036. }
  4037. #if defined(MG_SEND_REDIRECT_BODY)
  4038. /* TODO: condition name? */
  4039. /* Prepare a response body with a hyperlink.
  4040. *
  4041. * According to RFC2616 (and RFC1945 before):
  4042. * Unless the request method was HEAD, the entity of the
  4043. * response SHOULD contain a short hypertext note with a hyperlink to
  4044. * the new URI(s).
  4045. *
  4046. * However, this response body is not useful in M2M communication.
  4047. * Probably the original reason in the RFC was, clients not supporting
  4048. * a 30x HTTP redirect could still show the HTML page and let the user
  4049. * press the link. Since current browsers support 30x HTTP, the additional
  4050. * HTML body does not seem to make sense anymore.
  4051. *
  4052. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4053. * but it only notes:
  4054. * The server's response payload usually contains a short
  4055. * hypertext note with a hyperlink to the new URI(s).
  4056. *
  4057. * Deactivated by default. If you need the 30x body, set the define.
  4058. */
  4059. mg_snprintf(
  4060. conn,
  4061. NULL /* ignore truncation */,
  4062. redirect_body,
  4063. sizeof(redirect_body),
  4064. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4065. redirect_text,
  4066. target_url,
  4067. target_url);
  4068. content_len = strlen(reply);
  4069. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4070. #endif
  4071. /* Send all required headers */
  4072. mg_response_header_start(conn, redirect_code);
  4073. mg_response_header_add(conn, "Location", target_url, -1);
  4074. if ((redirect_code == 301) || (redirect_code == 308)) {
  4075. /* Permanent redirect */
  4076. send_static_cache_header(conn);
  4077. } else {
  4078. /* Temporary redirect */
  4079. send_no_cache_header(conn);
  4080. }
  4081. send_additional_header(conn);
  4082. send_cors_header(conn);
  4083. #if defined(MG_SEND_REDIRECT_BODY)
  4084. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4085. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4086. #else
  4087. mg_response_header_add(conn, "Content-Length", "0", 1);
  4088. #endif
  4089. mg_response_header_send(conn);
  4090. #if defined(MG_SEND_REDIRECT_BODY)
  4091. /* Send response body */
  4092. /* ... unless it is a HEAD request */
  4093. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4094. ret = mg_write(conn, redirect_body, content_len);
  4095. }
  4096. #endif
  4097. return 1;
  4098. }
  4099. #if defined(_WIN32)
  4100. /* Create substitutes for POSIX functions in Win32. */
  4101. #if defined(GCC_DIAGNOSTIC)
  4102. /* Show no warning in case system functions are not used. */
  4103. #pragma GCC diagnostic push
  4104. #pragma GCC diagnostic ignored "-Wunused-function"
  4105. #endif
  4106. static int
  4107. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4108. {
  4109. (void)unused;
  4110. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4111. InitializeCriticalSection(&mutex->sec);
  4112. return 0;
  4113. }
  4114. static int
  4115. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4116. {
  4117. DeleteCriticalSection(&mutex->sec);
  4118. return 0;
  4119. }
  4120. static int
  4121. pthread_mutex_lock(pthread_mutex_t *mutex)
  4122. {
  4123. EnterCriticalSection(&mutex->sec);
  4124. return 0;
  4125. }
  4126. static int
  4127. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4128. {
  4129. LeaveCriticalSection(&mutex->sec);
  4130. return 0;
  4131. }
  4132. FUNCTION_MAY_BE_UNUSED
  4133. static int
  4134. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4135. {
  4136. (void)unused;
  4137. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4138. cv->waiting_thread = NULL;
  4139. return 0;
  4140. }
  4141. FUNCTION_MAY_BE_UNUSED
  4142. static int
  4143. pthread_cond_timedwait(pthread_cond_t *cv,
  4144. pthread_mutex_t *mutex,
  4145. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4146. {
  4147. struct mg_workerTLS **ptls,
  4148. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4149. int ok;
  4150. uint64_t nsnow, nswaitabs;
  4151. int64_t nswaitrel;
  4152. DWORD mswaitrel;
  4153. pthread_mutex_lock(&cv->threadIdSec);
  4154. /* Add this thread to cv's waiting list */
  4155. ptls = &cv->waiting_thread;
  4156. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4157. ;
  4158. tls->next_waiting_thread = NULL;
  4159. *ptls = tls;
  4160. pthread_mutex_unlock(&cv->threadIdSec);
  4161. if (abstime) {
  4162. nsnow = mg_get_current_time_ns();
  4163. nswaitabs =
  4164. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4165. nswaitrel = nswaitabs - nsnow;
  4166. if (nswaitrel < 0) {
  4167. nswaitrel = 0;
  4168. }
  4169. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4170. } else {
  4171. mswaitrel = (DWORD)INFINITE;
  4172. }
  4173. pthread_mutex_unlock(mutex);
  4174. ok = (WAIT_OBJECT_0
  4175. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4176. if (!ok) {
  4177. ok = 1;
  4178. pthread_mutex_lock(&cv->threadIdSec);
  4179. ptls = &cv->waiting_thread;
  4180. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4181. if (*ptls == tls) {
  4182. *ptls = tls->next_waiting_thread;
  4183. ok = 0;
  4184. break;
  4185. }
  4186. }
  4187. pthread_mutex_unlock(&cv->threadIdSec);
  4188. if (ok) {
  4189. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4190. (DWORD)INFINITE);
  4191. }
  4192. }
  4193. /* This thread has been removed from cv's waiting list */
  4194. pthread_mutex_lock(mutex);
  4195. return ok ? 0 : -1;
  4196. }
  4197. FUNCTION_MAY_BE_UNUSED
  4198. static int
  4199. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4200. {
  4201. return pthread_cond_timedwait(cv, mutex, NULL);
  4202. }
  4203. FUNCTION_MAY_BE_UNUSED
  4204. static int
  4205. pthread_cond_signal(pthread_cond_t *cv)
  4206. {
  4207. HANDLE wkup = NULL;
  4208. BOOL ok = FALSE;
  4209. pthread_mutex_lock(&cv->threadIdSec);
  4210. if (cv->waiting_thread) {
  4211. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4212. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4213. ok = SetEvent(wkup);
  4214. DEBUG_ASSERT(ok);
  4215. }
  4216. pthread_mutex_unlock(&cv->threadIdSec);
  4217. return ok ? 0 : 1;
  4218. }
  4219. FUNCTION_MAY_BE_UNUSED
  4220. static int
  4221. pthread_cond_broadcast(pthread_cond_t *cv)
  4222. {
  4223. pthread_mutex_lock(&cv->threadIdSec);
  4224. while (cv->waiting_thread) {
  4225. pthread_cond_signal(cv);
  4226. }
  4227. pthread_mutex_unlock(&cv->threadIdSec);
  4228. return 0;
  4229. }
  4230. FUNCTION_MAY_BE_UNUSED
  4231. static int
  4232. pthread_cond_destroy(pthread_cond_t *cv)
  4233. {
  4234. pthread_mutex_lock(&cv->threadIdSec);
  4235. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4236. pthread_mutex_unlock(&cv->threadIdSec);
  4237. pthread_mutex_destroy(&cv->threadIdSec);
  4238. return 0;
  4239. }
  4240. #if defined(ALTERNATIVE_QUEUE)
  4241. FUNCTION_MAY_BE_UNUSED
  4242. static void *
  4243. event_create(void)
  4244. {
  4245. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4246. }
  4247. FUNCTION_MAY_BE_UNUSED
  4248. static int
  4249. event_wait(void *eventhdl)
  4250. {
  4251. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4252. return (res == WAIT_OBJECT_0);
  4253. }
  4254. FUNCTION_MAY_BE_UNUSED
  4255. static int
  4256. event_signal(void *eventhdl)
  4257. {
  4258. return (int)SetEvent((HANDLE)eventhdl);
  4259. }
  4260. FUNCTION_MAY_BE_UNUSED
  4261. static void
  4262. event_destroy(void *eventhdl)
  4263. {
  4264. CloseHandle((HANDLE)eventhdl);
  4265. }
  4266. #endif
  4267. #if defined(GCC_DIAGNOSTIC)
  4268. /* Enable unused function warning again */
  4269. #pragma GCC diagnostic pop
  4270. #endif
  4271. /* For Windows, change all slashes to backslashes in path names. */
  4272. static void
  4273. change_slashes_to_backslashes(char *path)
  4274. {
  4275. int i;
  4276. for (i = 0; path[i] != '\0'; i++) {
  4277. if (path[i] == '/') {
  4278. path[i] = '\\';
  4279. }
  4280. /* remove double backslash (check i > 0 to preserve UNC paths,
  4281. * like \\server\file.txt) */
  4282. if ((i > 0) && (path[i] == '\\')) {
  4283. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4284. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4285. }
  4286. }
  4287. }
  4288. }
  4289. static int
  4290. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4291. {
  4292. int diff;
  4293. do {
  4294. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4295. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4296. s1++;
  4297. s2++;
  4298. } while ((diff == 0) && (s1[-1] != L'\0'));
  4299. return diff;
  4300. }
  4301. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4302. * wbuf and wbuf_len is a target buffer and its length. */
  4303. static void
  4304. path_to_unicode(const struct mg_connection *conn,
  4305. const char *path,
  4306. wchar_t *wbuf,
  4307. size_t wbuf_len)
  4308. {
  4309. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4310. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4311. DWORD long_len, err;
  4312. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4313. mg_strlcpy(buf, path, sizeof(buf));
  4314. change_slashes_to_backslashes(buf);
  4315. /* Convert to Unicode and back. If doubly-converted string does not
  4316. * match the original, something is fishy, reject. */
  4317. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4318. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4319. WideCharToMultiByte(
  4320. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4321. if (strcmp(buf, buf2) != 0) {
  4322. wbuf[0] = L'\0';
  4323. }
  4324. /* Windows file systems are not case sensitive, but you can still use
  4325. * uppercase and lowercase letters (on all modern file systems).
  4326. * The server can check if the URI uses the same upper/lowercase
  4327. * letters an the file system, effectively making Windows servers
  4328. * case sensitive (like Linux servers are). It is still not possible
  4329. * to use two files with the same name in different cases on Windows
  4330. * (like /a and /A) - this would be possible in Linux.
  4331. * As a default, Windows is not case sensitive, but the case sensitive
  4332. * file name check can be activated by an additional configuration. */
  4333. if (conn) {
  4334. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4335. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4336. "yes")) {
  4337. /* Use case sensitive compare function */
  4338. fcompare = wcscmp;
  4339. }
  4340. }
  4341. (void)conn; /* conn is currently unused */
  4342. /* Only accept a full file path, not a Windows short (8.3) path. */
  4343. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4344. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4345. if (long_len == 0) {
  4346. err = GetLastError();
  4347. if (err == ERROR_FILE_NOT_FOUND) {
  4348. /* File does not exist. This is not always a problem here. */
  4349. return;
  4350. }
  4351. }
  4352. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4353. /* Short name is used. */
  4354. wbuf[0] = L'\0';
  4355. }
  4356. }
  4357. #if !defined(NO_FILESYSTEMS)
  4358. /* Get file information, return 1 if file exists, 0 if not */
  4359. static int
  4360. mg_stat(const struct mg_connection *conn,
  4361. const char *path,
  4362. struct mg_file_stat *filep)
  4363. {
  4364. wchar_t wbuf[UTF16_PATH_MAX];
  4365. WIN32_FILE_ATTRIBUTE_DATA info;
  4366. time_t creation_time;
  4367. size_t len;
  4368. if (!filep) {
  4369. return 0;
  4370. }
  4371. memset(filep, 0, sizeof(*filep));
  4372. if (mg_path_suspicious(conn, path)) {
  4373. return 0;
  4374. }
  4375. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4376. /* Windows happily opens files with some garbage at the end of file name.
  4377. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4378. * "a.cgi", despite one would expect an error back. */
  4379. len = strlen(path);
  4380. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4381. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4382. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4383. filep->last_modified =
  4384. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4385. info.ftLastWriteTime.dwHighDateTime);
  4386. /* On Windows, the file creation time can be higher than the
  4387. * modification time, e.g. when a file is copied.
  4388. * Since the Last-Modified timestamp is used for caching
  4389. * it should be based on the most recent timestamp. */
  4390. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4391. info.ftCreationTime.dwHighDateTime);
  4392. if (creation_time > filep->last_modified) {
  4393. filep->last_modified = creation_time;
  4394. }
  4395. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4396. return 1;
  4397. }
  4398. return 0;
  4399. }
  4400. #endif
  4401. static int
  4402. mg_remove(const struct mg_connection *conn, const char *path)
  4403. {
  4404. wchar_t wbuf[UTF16_PATH_MAX];
  4405. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4406. return DeleteFileW(wbuf) ? 0 : -1;
  4407. }
  4408. static int
  4409. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4410. {
  4411. wchar_t wbuf[UTF16_PATH_MAX];
  4412. (void)mode;
  4413. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4414. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4415. }
  4416. /* Create substitutes for POSIX functions in Win32. */
  4417. #if defined(GCC_DIAGNOSTIC)
  4418. /* Show no warning in case system functions are not used. */
  4419. #pragma GCC diagnostic push
  4420. #pragma GCC diagnostic ignored "-Wunused-function"
  4421. #endif
  4422. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4423. FUNCTION_MAY_BE_UNUSED
  4424. static DIR *
  4425. mg_opendir(const struct mg_connection *conn, const char *name)
  4426. {
  4427. DIR *dir = NULL;
  4428. wchar_t wpath[UTF16_PATH_MAX];
  4429. DWORD attrs;
  4430. if (name == NULL) {
  4431. SetLastError(ERROR_BAD_ARGUMENTS);
  4432. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4433. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4434. } else {
  4435. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4436. attrs = GetFileAttributesW(wpath);
  4437. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4438. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4439. (void)wcscat(wpath, L"\\*");
  4440. dir->handle = FindFirstFileW(wpath, &dir->info);
  4441. dir->result.d_name[0] = '\0';
  4442. } else {
  4443. mg_free(dir);
  4444. dir = NULL;
  4445. }
  4446. }
  4447. return dir;
  4448. }
  4449. FUNCTION_MAY_BE_UNUSED
  4450. static int
  4451. mg_closedir(DIR *dir)
  4452. {
  4453. int result = 0;
  4454. if (dir != NULL) {
  4455. if (dir->handle != INVALID_HANDLE_VALUE)
  4456. result = FindClose(dir->handle) ? 0 : -1;
  4457. mg_free(dir);
  4458. } else {
  4459. result = -1;
  4460. SetLastError(ERROR_BAD_ARGUMENTS);
  4461. }
  4462. return result;
  4463. }
  4464. FUNCTION_MAY_BE_UNUSED
  4465. static struct dirent *
  4466. mg_readdir(DIR *dir)
  4467. {
  4468. struct dirent *result = 0;
  4469. if (dir) {
  4470. if (dir->handle != INVALID_HANDLE_VALUE) {
  4471. result = &dir->result;
  4472. (void)WideCharToMultiByte(CP_UTF8,
  4473. 0,
  4474. dir->info.cFileName,
  4475. -1,
  4476. result->d_name,
  4477. sizeof(result->d_name),
  4478. NULL,
  4479. NULL);
  4480. if (!FindNextFileW(dir->handle, &dir->info)) {
  4481. (void)FindClose(dir->handle);
  4482. dir->handle = INVALID_HANDLE_VALUE;
  4483. }
  4484. } else {
  4485. SetLastError(ERROR_FILE_NOT_FOUND);
  4486. }
  4487. } else {
  4488. SetLastError(ERROR_BAD_ARGUMENTS);
  4489. }
  4490. return result;
  4491. }
  4492. #if !defined(HAVE_POLL)
  4493. #undef POLLIN
  4494. #undef POLLPRI
  4495. #undef POLLOUT
  4496. #undef POLLERR
  4497. #define POLLIN (1) /* Data ready - read will not block. */
  4498. #define POLLPRI (2) /* Priority data ready. */
  4499. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4500. #define POLLERR (8) /* Error event */
  4501. FUNCTION_MAY_BE_UNUSED
  4502. static int
  4503. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4504. {
  4505. struct timeval tv;
  4506. fd_set rset;
  4507. fd_set wset;
  4508. fd_set eset;
  4509. unsigned int i;
  4510. int result;
  4511. SOCKET maxfd = 0;
  4512. memset(&tv, 0, sizeof(tv));
  4513. tv.tv_sec = milliseconds / 1000;
  4514. tv.tv_usec = (milliseconds % 1000) * 1000;
  4515. FD_ZERO(&rset);
  4516. FD_ZERO(&wset);
  4517. FD_ZERO(&eset);
  4518. for (i = 0; i < n; i++) {
  4519. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4520. if (pfd[i].events & POLLIN) {
  4521. FD_SET(pfd[i].fd, &rset);
  4522. }
  4523. if (pfd[i].events & POLLOUT) {
  4524. FD_SET(pfd[i].fd, &wset);
  4525. }
  4526. /* Check for errors for any FD in the set */
  4527. FD_SET(pfd[i].fd, &eset);
  4528. }
  4529. pfd[i].revents = 0;
  4530. if (pfd[i].fd > maxfd) {
  4531. maxfd = pfd[i].fd;
  4532. }
  4533. }
  4534. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4535. for (i = 0; i < n; i++) {
  4536. if (FD_ISSET(pfd[i].fd, &rset)) {
  4537. pfd[i].revents |= POLLIN;
  4538. }
  4539. if (FD_ISSET(pfd[i].fd, &wset)) {
  4540. pfd[i].revents |= POLLOUT;
  4541. }
  4542. if (FD_ISSET(pfd[i].fd, &eset)) {
  4543. pfd[i].revents |= POLLERR;
  4544. }
  4545. }
  4546. }
  4547. /* We should subtract the time used in select from remaining
  4548. * "milliseconds", in particular if called from mg_poll with a
  4549. * timeout quantum.
  4550. * Unfortunately, the remaining time is not stored in "tv" in all
  4551. * implementations, so the result in "tv" must be considered undefined.
  4552. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4553. return result;
  4554. }
  4555. #endif /* HAVE_POLL */
  4556. #if defined(GCC_DIAGNOSTIC)
  4557. /* Enable unused function warning again */
  4558. #pragma GCC diagnostic pop
  4559. #endif
  4560. static void
  4561. set_close_on_exec(SOCKET sock,
  4562. const struct mg_connection *conn /* may be null */,
  4563. struct mg_context *ctx /* may be null */)
  4564. {
  4565. (void)conn; /* Unused. */
  4566. (void)ctx;
  4567. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4568. }
  4569. CIVETWEB_API int
  4570. mg_start_thread(mg_thread_func_t f, void *p)
  4571. {
  4572. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4573. /* Compile-time option to control stack size, e.g.
  4574. * -DUSE_STACK_SIZE=16384
  4575. */
  4576. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4577. == ((uintptr_t)(-1L)))
  4578. ? -1
  4579. : 0);
  4580. #else
  4581. return (
  4582. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4583. ? -1
  4584. : 0);
  4585. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4586. }
  4587. /* Start a thread storing the thread context. */
  4588. static int
  4589. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4590. void *p,
  4591. pthread_t *threadidptr)
  4592. {
  4593. uintptr_t uip;
  4594. HANDLE threadhandle;
  4595. int result = -1;
  4596. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4597. threadhandle = (HANDLE)uip;
  4598. if ((uip != 0) && (threadidptr != NULL)) {
  4599. *threadidptr = threadhandle;
  4600. result = 0;
  4601. }
  4602. return result;
  4603. }
  4604. /* Wait for a thread to finish. */
  4605. static int
  4606. mg_join_thread(pthread_t threadid)
  4607. {
  4608. int result;
  4609. DWORD dwevent;
  4610. result = -1;
  4611. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4612. if (dwevent == WAIT_FAILED) {
  4613. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4614. } else {
  4615. if (dwevent == WAIT_OBJECT_0) {
  4616. CloseHandle(threadid);
  4617. result = 0;
  4618. }
  4619. }
  4620. return result;
  4621. }
  4622. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4623. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4624. /* Create substitutes for POSIX functions in Win32. */
  4625. #if defined(GCC_DIAGNOSTIC)
  4626. /* Show no warning in case system functions are not used. */
  4627. #pragma GCC diagnostic push
  4628. #pragma GCC diagnostic ignored "-Wunused-function"
  4629. #endif
  4630. FUNCTION_MAY_BE_UNUSED
  4631. static HANDLE
  4632. dlopen(const char *dll_name, int flags)
  4633. {
  4634. wchar_t wbuf[UTF16_PATH_MAX];
  4635. (void)flags;
  4636. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4637. return LoadLibraryW(wbuf);
  4638. }
  4639. FUNCTION_MAY_BE_UNUSED
  4640. static int
  4641. dlclose(void *handle)
  4642. {
  4643. int result;
  4644. if (FreeLibrary((HMODULE)handle) != 0) {
  4645. result = 0;
  4646. } else {
  4647. result = -1;
  4648. }
  4649. return result;
  4650. }
  4651. #if defined(GCC_DIAGNOSTIC)
  4652. /* Enable unused function warning again */
  4653. #pragma GCC diagnostic pop
  4654. #endif
  4655. #endif
  4656. #if !defined(NO_CGI)
  4657. #define SIGKILL (0)
  4658. static int
  4659. kill(pid_t pid, int sig_num)
  4660. {
  4661. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4662. (void)CloseHandle((HANDLE)pid);
  4663. return 0;
  4664. }
  4665. #if !defined(WNOHANG)
  4666. #define WNOHANG (1)
  4667. #endif
  4668. static pid_t
  4669. waitpid(pid_t pid, int *status, int flags)
  4670. {
  4671. DWORD timeout = INFINITE;
  4672. DWORD waitres;
  4673. (void)status; /* Currently not used by any client here */
  4674. if ((flags | WNOHANG) == WNOHANG) {
  4675. timeout = 0;
  4676. }
  4677. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4678. if (waitres == WAIT_OBJECT_0) {
  4679. return pid;
  4680. }
  4681. if (waitres == WAIT_TIMEOUT) {
  4682. return 0;
  4683. }
  4684. return (pid_t)-1;
  4685. }
  4686. static void
  4687. trim_trailing_whitespaces(char *s)
  4688. {
  4689. char *e = s + strlen(s);
  4690. while ((e > s) && isspace((unsigned char)e[-1])) {
  4691. *(--e) = '\0';
  4692. }
  4693. }
  4694. static pid_t
  4695. spawn_process(struct mg_connection *conn,
  4696. const char *prog,
  4697. char *envblk,
  4698. char *envp[],
  4699. int fdin[2],
  4700. int fdout[2],
  4701. int fderr[2],
  4702. const char *dir,
  4703. int cgi_config_idx)
  4704. {
  4705. HANDLE me;
  4706. char *interp;
  4707. char *interp_arg = 0;
  4708. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4709. int truncated;
  4710. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4711. STARTUPINFOA si;
  4712. PROCESS_INFORMATION pi = {0};
  4713. (void)envp;
  4714. memset(&si, 0, sizeof(si));
  4715. si.cb = sizeof(si);
  4716. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4717. si.wShowWindow = SW_HIDE;
  4718. me = GetCurrentProcess();
  4719. DuplicateHandle(me,
  4720. (HANDLE)_get_osfhandle(fdin[0]),
  4721. me,
  4722. &si.hStdInput,
  4723. 0,
  4724. TRUE,
  4725. DUPLICATE_SAME_ACCESS);
  4726. DuplicateHandle(me,
  4727. (HANDLE)_get_osfhandle(fdout[1]),
  4728. me,
  4729. &si.hStdOutput,
  4730. 0,
  4731. TRUE,
  4732. DUPLICATE_SAME_ACCESS);
  4733. DuplicateHandle(me,
  4734. (HANDLE)_get_osfhandle(fderr[1]),
  4735. me,
  4736. &si.hStdError,
  4737. 0,
  4738. TRUE,
  4739. DUPLICATE_SAME_ACCESS);
  4740. /* Mark handles that should not be inherited. See
  4741. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4742. */
  4743. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4744. HANDLE_FLAG_INHERIT,
  4745. 0);
  4746. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4747. HANDLE_FLAG_INHERIT,
  4748. 0);
  4749. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4750. HANDLE_FLAG_INHERIT,
  4751. 0);
  4752. /* First check, if there is a CGI interpreter configured for all CGI
  4753. * scripts. */
  4754. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4755. if (interp != NULL) {
  4756. /* If there is a configured interpreter, check for additional arguments
  4757. */
  4758. interp_arg =
  4759. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4760. } else {
  4761. /* Otherwise, the interpreter must be stated in the first line of the
  4762. * CGI script file, after a #! (shebang) mark. */
  4763. buf[0] = buf[1] = '\0';
  4764. /* Get the full script path */
  4765. mg_snprintf(
  4766. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4767. if (truncated) {
  4768. pi.hProcess = (pid_t)-1;
  4769. goto spawn_cleanup;
  4770. }
  4771. /* Open the script file, to read the first line */
  4772. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4773. /* Read the first line of the script into the buffer */
  4774. mg_fgets(buf, sizeof(buf), &file);
  4775. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4776. buf[sizeof(buf) - 1] = '\0';
  4777. }
  4778. if ((buf[0] == '#') && (buf[1] == '!')) {
  4779. trim_trailing_whitespaces(buf + 2);
  4780. } else {
  4781. buf[2] = '\0';
  4782. }
  4783. interp = buf + 2;
  4784. }
  4785. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4786. if (interp[0] != '\0') {
  4787. /* This is an interpreted script file. We must call the interpreter. */
  4788. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4789. mg_snprintf(conn,
  4790. &truncated,
  4791. cmdline,
  4792. sizeof(cmdline),
  4793. "\"%s\" %s \"%s\\%s\"",
  4794. interp,
  4795. interp_arg,
  4796. full_dir,
  4797. prog);
  4798. } else {
  4799. mg_snprintf(conn,
  4800. &truncated,
  4801. cmdline,
  4802. sizeof(cmdline),
  4803. "\"%s\" \"%s\\%s\"",
  4804. interp,
  4805. full_dir,
  4806. prog);
  4807. }
  4808. } else {
  4809. /* This is (probably) a compiled program. We call it directly. */
  4810. mg_snprintf(conn,
  4811. &truncated,
  4812. cmdline,
  4813. sizeof(cmdline),
  4814. "\"%s\\%s\"",
  4815. full_dir,
  4816. prog);
  4817. }
  4818. if (truncated) {
  4819. pi.hProcess = (pid_t)-1;
  4820. goto spawn_cleanup;
  4821. }
  4822. DEBUG_TRACE("Running [%s]", cmdline);
  4823. if (CreateProcessA(NULL,
  4824. cmdline,
  4825. NULL,
  4826. NULL,
  4827. TRUE,
  4828. CREATE_NEW_PROCESS_GROUP,
  4829. envblk,
  4830. NULL,
  4831. &si,
  4832. &pi)
  4833. == 0) {
  4834. mg_cry_internal(
  4835. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4836. pi.hProcess = (pid_t)-1;
  4837. /* goto spawn_cleanup; */
  4838. }
  4839. spawn_cleanup:
  4840. (void)CloseHandle(si.hStdOutput);
  4841. (void)CloseHandle(si.hStdError);
  4842. (void)CloseHandle(si.hStdInput);
  4843. if (pi.hThread != NULL) {
  4844. (void)CloseHandle(pi.hThread);
  4845. }
  4846. return (pid_t)pi.hProcess;
  4847. }
  4848. #endif /* !NO_CGI */
  4849. static int
  4850. set_blocking_mode(SOCKET sock)
  4851. {
  4852. unsigned long non_blocking = 0;
  4853. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4854. }
  4855. static int
  4856. set_non_blocking_mode(SOCKET sock)
  4857. {
  4858. unsigned long non_blocking = 1;
  4859. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4860. }
  4861. #else
  4862. #if !defined(NO_FILESYSTEMS)
  4863. static int
  4864. mg_stat(const struct mg_connection *conn,
  4865. const char *path,
  4866. struct mg_file_stat *filep)
  4867. {
  4868. struct stat st;
  4869. if (!filep) {
  4870. return 0;
  4871. }
  4872. memset(filep, 0, sizeof(*filep));
  4873. if (mg_path_suspicious(conn, path)) {
  4874. return 0;
  4875. }
  4876. if (0 == stat(path, &st)) {
  4877. filep->size = (uint64_t)(st.st_size);
  4878. filep->last_modified = st.st_mtime;
  4879. filep->is_directory = S_ISDIR(st.st_mode);
  4880. return 1;
  4881. }
  4882. return 0;
  4883. }
  4884. #endif /* NO_FILESYSTEMS */
  4885. static void
  4886. set_close_on_exec(int fd,
  4887. const struct mg_connection *conn /* may be null */,
  4888. struct mg_context *ctx /* may be null */)
  4889. {
  4890. #if defined(__ZEPHYR__)
  4891. (void)fd;
  4892. (void)conn;
  4893. (void)ctx;
  4894. #else
  4895. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4896. if (conn || ctx) {
  4897. struct mg_connection fc;
  4898. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4899. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4900. __func__,
  4901. strerror(ERRNO));
  4902. }
  4903. }
  4904. #endif
  4905. }
  4906. CIVETWEB_API int
  4907. mg_start_thread(mg_thread_func_t func, void *param)
  4908. {
  4909. pthread_t thread_id;
  4910. pthread_attr_t attr;
  4911. int result;
  4912. (void)pthread_attr_init(&attr);
  4913. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4914. #if defined(__ZEPHYR__)
  4915. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4916. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4917. /* Compile-time option to control stack size,
  4918. * e.g. -DUSE_STACK_SIZE=16384 */
  4919. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4920. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4921. result = pthread_create(&thread_id, &attr, func, param);
  4922. pthread_attr_destroy(&attr);
  4923. return result;
  4924. }
  4925. /* Start a thread storing the thread context. */
  4926. static int
  4927. mg_start_thread_with_id(mg_thread_func_t func,
  4928. void *param,
  4929. pthread_t *threadidptr)
  4930. {
  4931. pthread_t thread_id;
  4932. pthread_attr_t attr;
  4933. int result;
  4934. (void)pthread_attr_init(&attr);
  4935. #if defined(__ZEPHYR__)
  4936. pthread_attr_setstack(&attr,
  4937. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4938. ZEPHYR_STACK_SIZE);
  4939. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4940. /* Compile-time option to control stack size,
  4941. * e.g. -DUSE_STACK_SIZE=16384 */
  4942. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4943. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4944. result = pthread_create(&thread_id, &attr, func, param);
  4945. pthread_attr_destroy(&attr);
  4946. if ((result == 0) && (threadidptr != NULL)) {
  4947. *threadidptr = thread_id;
  4948. }
  4949. return result;
  4950. }
  4951. /* Wait for a thread to finish. */
  4952. static int
  4953. mg_join_thread(pthread_t threadid)
  4954. {
  4955. int result;
  4956. result = pthread_join(threadid, NULL);
  4957. return result;
  4958. }
  4959. #if !defined(NO_CGI)
  4960. static pid_t
  4961. spawn_process(struct mg_connection *conn,
  4962. const char *prog,
  4963. char *envblk,
  4964. char *envp[],
  4965. int fdin[2],
  4966. int fdout[2],
  4967. int fderr[2],
  4968. const char *dir,
  4969. int cgi_config_idx)
  4970. {
  4971. pid_t pid;
  4972. const char *interp;
  4973. (void)envblk;
  4974. if ((pid = fork()) == -1) {
  4975. /* Parent */
  4976. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4977. } else if (pid != 0) {
  4978. /* Make sure children close parent-side descriptors.
  4979. * The caller will close the child-side immediately. */
  4980. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4981. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4982. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4983. } else {
  4984. /* Child */
  4985. if (chdir(dir) != 0) {
  4986. mg_cry_internal(
  4987. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4988. } else if (dup2(fdin[0], 0) == -1) {
  4989. mg_cry_internal(conn,
  4990. "%s: dup2(%d, 0): %s",
  4991. __func__,
  4992. fdin[0],
  4993. strerror(ERRNO));
  4994. } else if (dup2(fdout[1], 1) == -1) {
  4995. mg_cry_internal(conn,
  4996. "%s: dup2(%d, 1): %s",
  4997. __func__,
  4998. fdout[1],
  4999. strerror(ERRNO));
  5000. } else if (dup2(fderr[1], 2) == -1) {
  5001. mg_cry_internal(conn,
  5002. "%s: dup2(%d, 2): %s",
  5003. __func__,
  5004. fderr[1],
  5005. strerror(ERRNO));
  5006. } else {
  5007. struct sigaction sa;
  5008. /* Keep stderr and stdout in two different pipes.
  5009. * Stdout will be sent back to the client,
  5010. * stderr should go into a server error log. */
  5011. (void)close(fdin[0]);
  5012. (void)close(fdout[1]);
  5013. (void)close(fderr[1]);
  5014. /* Close write end fdin and read end fdout and fderr */
  5015. (void)close(fdin[1]);
  5016. (void)close(fdout[0]);
  5017. (void)close(fderr[0]);
  5018. /* After exec, all signal handlers are restored to their default
  5019. * values, with one exception of SIGCHLD. According to
  5020. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5021. * will leave unchanged after exec if it was set to be ignored.
  5022. * Restore it to default action. */
  5023. memset(&sa, 0, sizeof(sa));
  5024. sa.sa_handler = SIG_DFL;
  5025. sigaction(SIGCHLD, &sa, NULL);
  5026. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  5027. if (interp == NULL) {
  5028. /* no interpreter configured, call the program directly */
  5029. (void)execle(prog, prog, NULL, envp);
  5030. mg_cry_internal(conn,
  5031. "%s: execle(%s): %s",
  5032. __func__,
  5033. prog,
  5034. strerror(ERRNO));
  5035. } else {
  5036. /* call the configured interpreter */
  5037. const char *interp_args =
  5038. conn->dom_ctx
  5039. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5040. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5041. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5042. } else {
  5043. (void)execle(interp, interp, prog, NULL, envp);
  5044. }
  5045. mg_cry_internal(conn,
  5046. "%s: execle(%s %s): %s",
  5047. __func__,
  5048. interp,
  5049. prog,
  5050. strerror(ERRNO));
  5051. }
  5052. }
  5053. exit(EXIT_FAILURE);
  5054. }
  5055. return pid;
  5056. }
  5057. #endif /* !NO_CGI */
  5058. static int
  5059. set_non_blocking_mode(SOCKET sock)
  5060. {
  5061. int flags = fcntl(sock, F_GETFL, 0);
  5062. if (flags < 0) {
  5063. return -1;
  5064. }
  5065. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5066. return -1;
  5067. }
  5068. return 0;
  5069. }
  5070. static int
  5071. set_blocking_mode(SOCKET sock)
  5072. {
  5073. int flags = fcntl(sock, F_GETFL, 0);
  5074. if (flags < 0) {
  5075. return -1;
  5076. }
  5077. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5078. return -1;
  5079. }
  5080. return 0;
  5081. }
  5082. #endif /* _WIN32 / else */
  5083. /* End of initial operating system specific define block. */
  5084. /* Get a random number (independent of C rand function) */
  5085. static uint64_t
  5086. get_random(void)
  5087. {
  5088. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5089. static uint64_t lcg = 0; /* Linear congruential generator */
  5090. uint64_t now = mg_get_current_time_ns();
  5091. if (lfsr == 0) {
  5092. /* lfsr will be only 0 if has not been initialized,
  5093. * so this code is called only once. */
  5094. lfsr = mg_get_current_time_ns();
  5095. lcg = mg_get_current_time_ns();
  5096. } else {
  5097. /* Get the next step of both random number generators. */
  5098. lfsr = (lfsr >> 1)
  5099. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5100. << 63);
  5101. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5102. }
  5103. /* Combining two pseudo-random number generators and a high resolution
  5104. * part
  5105. * of the current server time will make it hard (impossible?) to guess
  5106. * the
  5107. * next number. */
  5108. return (lfsr ^ lcg ^ now);
  5109. }
  5110. static int
  5111. mg_poll(struct mg_pollfd *pfd,
  5112. unsigned int n,
  5113. int milliseconds,
  5114. const stop_flag_t *stop_flag)
  5115. {
  5116. /* Call poll, but only for a maximum time of a few seconds.
  5117. * This will allow to stop the server after some seconds, instead
  5118. * of having to wait for a long socket timeout. */
  5119. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5120. int check_pollerr = 0;
  5121. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5122. /* If we wait for only one file descriptor, wait on error as well */
  5123. pfd[0].events |= POLLERR;
  5124. check_pollerr = 1;
  5125. }
  5126. do {
  5127. int result;
  5128. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5129. /* Shut down signal */
  5130. return -2;
  5131. }
  5132. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5133. ms_now = milliseconds;
  5134. }
  5135. result = poll(pfd, n, ms_now);
  5136. if (result != 0) {
  5137. int err = ERRNO;
  5138. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5139. /* Poll returned either success (1) or error (-1).
  5140. * Forward both to the caller. */
  5141. if ((check_pollerr)
  5142. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5143. == POLLERR)) {
  5144. /* One and only file descriptor returned error */
  5145. return -1;
  5146. }
  5147. return result;
  5148. }
  5149. }
  5150. /* Poll returned timeout (0). */
  5151. if (milliseconds > 0) {
  5152. milliseconds -= ms_now;
  5153. }
  5154. } while (milliseconds > 0);
  5155. /* timeout: return 0 */
  5156. return 0;
  5157. }
  5158. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5159. * descriptor.
  5160. * Return value:
  5161. * >=0 .. number of bytes successfully written
  5162. * -1 .. timeout
  5163. * -2 .. error
  5164. */
  5165. static int
  5166. push_inner(struct mg_context *ctx,
  5167. FILE *fp,
  5168. SOCKET sock,
  5169. SSL *ssl,
  5170. const char *buf,
  5171. int len,
  5172. double timeout)
  5173. {
  5174. uint64_t start = 0, now = 0, timeout_ns = 0;
  5175. int n, err;
  5176. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5177. #if defined(_WIN32)
  5178. typedef int len_t;
  5179. #else
  5180. typedef size_t len_t;
  5181. #endif
  5182. if (timeout > 0) {
  5183. now = mg_get_current_time_ns();
  5184. start = now;
  5185. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5186. }
  5187. if (ctx == NULL) {
  5188. return -2;
  5189. }
  5190. #if defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  5191. if (ssl) {
  5192. return -2;
  5193. }
  5194. #endif
  5195. /* Try to read until it succeeds, fails, times out, or the server
  5196. * shuts down. */
  5197. for (;;) {
  5198. #if defined(USE_MBEDTLS)
  5199. if (ssl != NULL) {
  5200. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5201. if (n <= 0) {
  5202. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5203. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5204. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5205. n = 0;
  5206. } else {
  5207. fprintf(stderr, "SSL write failed, error %d\n", n);
  5208. return -2;
  5209. }
  5210. } else {
  5211. err = 0;
  5212. }
  5213. } else
  5214. #elif defined(USE_GNUTLS)
  5215. if (ssl != NULL) {
  5216. n = gtls_ssl_write(ssl, (const unsigned char *)buf, (size_t)len);
  5217. if (n < 0) {
  5218. fprintf(stderr,
  5219. "SSL write failed (%d): %s",
  5220. n,
  5221. gnutls_strerror(n));
  5222. return -2;
  5223. } else {
  5224. err = 0;
  5225. }
  5226. } else
  5227. #elif !defined(NO_SSL)
  5228. if (ssl != NULL) {
  5229. ERR_clear_error();
  5230. n = SSL_write(ssl, buf, len);
  5231. if (n <= 0) {
  5232. err = SSL_get_error(ssl, n);
  5233. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5234. err = ERRNO;
  5235. } else if ((err == SSL_ERROR_WANT_READ)
  5236. || (err == SSL_ERROR_WANT_WRITE)) {
  5237. n = 0;
  5238. } else {
  5239. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5240. ERR_clear_error();
  5241. return -2;
  5242. }
  5243. ERR_clear_error();
  5244. } else {
  5245. err = 0;
  5246. }
  5247. } else
  5248. #endif
  5249. if (fp != NULL) {
  5250. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5251. if (ferror(fp)) {
  5252. n = -1;
  5253. err = ERRNO;
  5254. } else {
  5255. err = 0;
  5256. }
  5257. } else {
  5258. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5259. err = (n < 0) ? ERRNO : 0;
  5260. if (ERROR_TRY_AGAIN(err)) {
  5261. err = 0;
  5262. n = 0;
  5263. }
  5264. if (n < 0) {
  5265. /* shutdown of the socket at client side */
  5266. return -2;
  5267. }
  5268. }
  5269. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5270. return -2;
  5271. }
  5272. if ((n > 0) || ((n == 0) && (len == 0))) {
  5273. /* some data has been read, or no data was requested */
  5274. return n;
  5275. }
  5276. if (n < 0) {
  5277. /* socket error - check errno */
  5278. DEBUG_TRACE("send() failed, error %d", err);
  5279. /* TODO (mid): error handling depending on the error code.
  5280. * These codes are different between Windows and Linux.
  5281. * Currently there is no problem with failing send calls,
  5282. * if there is a reproducible situation, it should be
  5283. * investigated in detail.
  5284. */
  5285. return -2;
  5286. }
  5287. /* Only in case n=0 (timeout), repeat calling the write function */
  5288. /* If send failed, wait before retry */
  5289. if (fp != NULL) {
  5290. /* For files, just wait a fixed time.
  5291. * Maybe it helps, maybe not. */
  5292. mg_sleep(5);
  5293. } else {
  5294. /* For sockets, wait for the socket using poll */
  5295. struct mg_pollfd pfd[2];
  5296. int pollres;
  5297. unsigned int num_sock = 1;
  5298. pfd[0].fd = sock;
  5299. pfd[0].events = POLLOUT;
  5300. if (ctx->context_type == CONTEXT_SERVER) {
  5301. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  5302. pfd[num_sock].events = POLLIN;
  5303. num_sock++;
  5304. }
  5305. pollres = mg_poll(pfd, num_sock, (int)(ms_wait), &(ctx->stop_flag));
  5306. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5307. return -2;
  5308. }
  5309. if (pollres > 0) {
  5310. continue;
  5311. }
  5312. }
  5313. if (timeout > 0) {
  5314. now = mg_get_current_time_ns();
  5315. if ((now - start) > timeout_ns) {
  5316. /* Timeout */
  5317. break;
  5318. }
  5319. }
  5320. }
  5321. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5322. used */
  5323. return -1;
  5324. }
  5325. static int
  5326. push_all(struct mg_context *ctx,
  5327. FILE *fp,
  5328. SOCKET sock,
  5329. SSL *ssl,
  5330. const char *buf,
  5331. int len)
  5332. {
  5333. double timeout = -1.0;
  5334. int n, nwritten = 0;
  5335. if (ctx == NULL) {
  5336. return -1;
  5337. }
  5338. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5339. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5340. }
  5341. if (timeout <= 0.0) {
  5342. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5343. / 1000.0;
  5344. }
  5345. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5346. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5347. if (n < 0) {
  5348. if (nwritten == 0) {
  5349. nwritten = -1; /* Propagate the error */
  5350. }
  5351. break;
  5352. } else if (n == 0) {
  5353. break; /* No more data to write */
  5354. } else {
  5355. nwritten += n;
  5356. len -= n;
  5357. }
  5358. }
  5359. return nwritten;
  5360. }
  5361. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5362. * Return value:
  5363. * >=0 .. number of bytes successfully read
  5364. * -1 .. timeout
  5365. * -2 .. error
  5366. */
  5367. static int
  5368. pull_inner(FILE *fp,
  5369. struct mg_connection *conn,
  5370. char *buf,
  5371. int len,
  5372. double timeout)
  5373. {
  5374. int nread, err = 0;
  5375. #if defined(_WIN32)
  5376. typedef int len_t;
  5377. #else
  5378. typedef size_t len_t;
  5379. #endif
  5380. /* We need an additional wait loop around this, because in some cases
  5381. * with TLSwe may get data from the socket but not from SSL_read.
  5382. * In this case we need to repeat at least once.
  5383. */
  5384. if (fp != NULL) {
  5385. /* Use read() instead of fread(), because if we're reading from the
  5386. * CGI pipe, fread() may block until IO buffer is filled up. We
  5387. * cannot afford to block and must pass all read bytes immediately
  5388. * to the client. */
  5389. nread = (int)read(fileno(fp), buf, (size_t)len);
  5390. err = (nread < 0) ? ERRNO : 0;
  5391. if ((nread == 0) && (len > 0)) {
  5392. /* Should get data, but got EOL */
  5393. return -2;
  5394. }
  5395. #if defined(USE_MBEDTLS)
  5396. } else if (conn->ssl != NULL) {
  5397. struct mg_pollfd pfd[2];
  5398. int to_read;
  5399. int pollres;
  5400. unsigned int num_sock = 1;
  5401. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5402. if (to_read > 0) {
  5403. /* We already know there is no more data buffered in conn->buf
  5404. * but there is more available in the SSL layer. So don't poll
  5405. * conn->client.sock yet. */
  5406. pollres = 1;
  5407. if (to_read > len)
  5408. to_read = len;
  5409. } else {
  5410. pfd[0].fd = conn->client.sock;
  5411. pfd[0].events = POLLIN;
  5412. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5413. pfd[num_sock].fd =
  5414. conn->phys_ctx->thread_shutdown_notification_socket;
  5415. pfd[num_sock].events = POLLIN;
  5416. num_sock++;
  5417. }
  5418. to_read = len;
  5419. pollres = mg_poll(pfd,
  5420. num_sock,
  5421. (int)(timeout * 1000.0),
  5422. &(conn->phys_ctx->stop_flag));
  5423. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5424. return -2;
  5425. }
  5426. }
  5427. if (pollres > 0) {
  5428. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5429. if (nread <= 0) {
  5430. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5431. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5432. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5433. nread = 0;
  5434. } else {
  5435. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5436. return -2;
  5437. }
  5438. } else {
  5439. err = 0;
  5440. }
  5441. } else if (pollres < 0) {
  5442. /* Error */
  5443. return -2;
  5444. } else {
  5445. /* pollres = 0 means timeout */
  5446. nread = 0;
  5447. }
  5448. #elif defined(USE_GNUTLS)
  5449. } else if (conn->ssl != NULL) {
  5450. struct mg_pollfd pfd[2];
  5451. size_t to_read;
  5452. int pollres;
  5453. unsigned int num_sock = 1;
  5454. to_read = gnutls_record_check_pending(conn->ssl->sess);
  5455. if (to_read > 0) {
  5456. /* We already know there is no more data buffered in conn->buf
  5457. * but there is more available in the SSL layer. So don't poll
  5458. * conn->client.sock yet. */
  5459. pollres = 1;
  5460. if (to_read > (size_t)len)
  5461. to_read = (size_t)len;
  5462. } else {
  5463. pfd[0].fd = conn->client.sock;
  5464. pfd[0].events = POLLIN;
  5465. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5466. pfd[num_sock].fd =
  5467. conn->phys_ctx->thread_shutdown_notification_socket;
  5468. pfd[num_sock].events = POLLIN;
  5469. num_sock++;
  5470. }
  5471. to_read = (size_t)len;
  5472. pollres = mg_poll(pfd,
  5473. num_sock,
  5474. (int)(timeout * 1000.0),
  5475. &(conn->phys_ctx->stop_flag));
  5476. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5477. return -2;
  5478. }
  5479. }
  5480. if (pollres > 0) {
  5481. nread = gtls_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5482. if (nread < 0) {
  5483. fprintf(stderr,
  5484. "SSL read failed (%d): %s",
  5485. nread,
  5486. gnutls_strerror(nread));
  5487. return -2;
  5488. } else {
  5489. err = 0;
  5490. }
  5491. } else if (pollres < 0) {
  5492. /* Error */
  5493. return -2;
  5494. } else {
  5495. /* pollres = 0 means timeout */
  5496. nread = 0;
  5497. }
  5498. #elif !defined(NO_SSL)
  5499. } else if (conn->ssl != NULL) {
  5500. int ssl_pending;
  5501. struct mg_pollfd pfd[2];
  5502. int pollres;
  5503. unsigned int num_sock = 1;
  5504. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5505. /* We already know there is no more data buffered in conn->buf
  5506. * but there is more available in the SSL layer. So don't poll
  5507. * conn->client.sock yet. */
  5508. if (ssl_pending > len) {
  5509. ssl_pending = len;
  5510. }
  5511. pollres = 1;
  5512. } else {
  5513. pfd[0].fd = conn->client.sock;
  5514. pfd[0].events = POLLIN;
  5515. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5516. pfd[num_sock].fd =
  5517. conn->phys_ctx->thread_shutdown_notification_socket;
  5518. pfd[num_sock].events = POLLIN;
  5519. num_sock++;
  5520. }
  5521. pollres = mg_poll(pfd,
  5522. num_sock,
  5523. (int)(timeout * 1000.0),
  5524. &(conn->phys_ctx->stop_flag));
  5525. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5526. return -2;
  5527. }
  5528. }
  5529. if (pollres > 0) {
  5530. ERR_clear_error();
  5531. nread =
  5532. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5533. if (nread <= 0) {
  5534. err = SSL_get_error(conn->ssl, nread);
  5535. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5536. err = ERRNO;
  5537. } else if ((err == SSL_ERROR_WANT_READ)
  5538. || (err == SSL_ERROR_WANT_WRITE)) {
  5539. nread = 0;
  5540. } else {
  5541. /* All errors should return -2 */
  5542. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5543. ERR_clear_error();
  5544. return -2;
  5545. }
  5546. ERR_clear_error();
  5547. } else {
  5548. err = 0;
  5549. }
  5550. } else if (pollres < 0) {
  5551. /* Error */
  5552. return -2;
  5553. } else {
  5554. /* pollres = 0 means timeout */
  5555. nread = 0;
  5556. }
  5557. #endif
  5558. } else {
  5559. struct mg_pollfd pfd[2];
  5560. int pollres;
  5561. unsigned int num_sock = 1;
  5562. pfd[0].fd = conn->client.sock;
  5563. pfd[0].events = POLLIN;
  5564. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  5565. pfd[num_sock].fd =
  5566. conn->phys_ctx->thread_shutdown_notification_socket;
  5567. pfd[num_sock].events = POLLIN;
  5568. num_sock++;
  5569. }
  5570. pollres = mg_poll(pfd,
  5571. num_sock,
  5572. (int)(timeout * 1000.0),
  5573. &(conn->phys_ctx->stop_flag));
  5574. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5575. return -2;
  5576. }
  5577. if (pollres > 0) {
  5578. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5579. err = (nread < 0) ? ERRNO : 0;
  5580. if (nread <= 0) {
  5581. /* shutdown of the socket at client side */
  5582. return -2;
  5583. }
  5584. } else if (pollres < 0) {
  5585. /* error calling poll */
  5586. return -2;
  5587. } else {
  5588. /* pollres = 0 means timeout */
  5589. nread = 0;
  5590. }
  5591. }
  5592. if (conn != NULL && !STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5593. return -2;
  5594. }
  5595. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5596. /* some data has been read, or no data was requested */
  5597. return nread;
  5598. }
  5599. if (nread < 0) {
  5600. /* socket error - check errno */
  5601. #if defined(_WIN32)
  5602. if (err == WSAEWOULDBLOCK) {
  5603. /* TODO (low): check if this is still required */
  5604. /* standard case if called from close_socket_gracefully */
  5605. return -2;
  5606. } else if (err == WSAETIMEDOUT) {
  5607. /* TODO (low): check if this is still required */
  5608. /* timeout is handled by the while loop */
  5609. return 0;
  5610. } else if (err == WSAECONNABORTED) {
  5611. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5612. return -2;
  5613. } else {
  5614. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5615. return -2;
  5616. }
  5617. #else
  5618. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5619. * if the timeout is reached and if the socket was set to non-
  5620. * blocking in close_socket_gracefully, so we can not distinguish
  5621. * here. We have to wait for the timeout in both cases for now.
  5622. */
  5623. if (ERROR_TRY_AGAIN(err)) {
  5624. /* TODO (low): check if this is still required */
  5625. /* EAGAIN/EWOULDBLOCK:
  5626. * standard case if called from close_socket_gracefully
  5627. * => should return -1 */
  5628. /* or timeout occurred
  5629. * => the code must stay in the while loop */
  5630. /* EINTR can be generated on a socket with a timeout set even
  5631. * when SA_RESTART is effective for all relevant signals
  5632. * (see signal(7)).
  5633. * => stay in the while loop */
  5634. } else {
  5635. DEBUG_TRACE("read()/recv() failed, error %d", err);
  5636. return -2;
  5637. }
  5638. #endif
  5639. }
  5640. /* Timeout occurred, but no data available. */
  5641. return -1;
  5642. }
  5643. static int
  5644. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5645. {
  5646. int n, nread = 0;
  5647. double timeout = -1.0;
  5648. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5649. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5650. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5651. }
  5652. if (timeout <= 0.0) {
  5653. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5654. / 1000.0;
  5655. }
  5656. start_time = mg_get_current_time_ns();
  5657. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5658. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5659. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5660. if (n == -2) {
  5661. if (nread == 0) {
  5662. nread = -1; /* Propagate the error */
  5663. }
  5664. break;
  5665. } else if (n == -1) {
  5666. /* timeout */
  5667. if (timeout >= 0.0) {
  5668. now = mg_get_current_time_ns();
  5669. if ((now - start_time) <= timeout_ns) {
  5670. continue;
  5671. }
  5672. }
  5673. break;
  5674. } else if (n == 0) {
  5675. break; /* No more data to read */
  5676. } else {
  5677. nread += n;
  5678. len -= n;
  5679. }
  5680. }
  5681. return nread;
  5682. }
  5683. static void
  5684. discard_unread_request_data(struct mg_connection *conn)
  5685. {
  5686. char buf[MG_BUF_LEN];
  5687. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5688. ;
  5689. }
  5690. static int
  5691. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5692. {
  5693. int64_t content_len, n, buffered_len, nread;
  5694. int64_t len64 =
  5695. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5696. * int, we may not read more
  5697. * bytes */
  5698. const char *body;
  5699. if (conn == NULL) {
  5700. return 0;
  5701. }
  5702. /* If Content-Length is not set for a response with body data,
  5703. * we do not know in advance how much data should be read. */
  5704. content_len = conn->content_len;
  5705. if (content_len < 0) {
  5706. /* The body data is completed when the connection is closed. */
  5707. content_len = INT64_MAX;
  5708. }
  5709. nread = 0;
  5710. if (conn->consumed_content < content_len) {
  5711. /* Adjust number of bytes to read. */
  5712. int64_t left_to_read = content_len - conn->consumed_content;
  5713. if (left_to_read < len64) {
  5714. /* Do not read more than the total content length of the
  5715. * request.
  5716. */
  5717. len64 = left_to_read;
  5718. }
  5719. /* Return buffered data */
  5720. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5721. - conn->consumed_content;
  5722. if (buffered_len > 0) {
  5723. if (len64 < buffered_len) {
  5724. buffered_len = len64;
  5725. }
  5726. body = conn->buf + conn->request_len + conn->consumed_content;
  5727. memcpy(buf, body, (size_t)buffered_len);
  5728. len64 -= buffered_len;
  5729. conn->consumed_content += buffered_len;
  5730. nread += buffered_len;
  5731. buf = (char *)buf + buffered_len;
  5732. }
  5733. /* We have returned all buffered data. Read new data from the remote
  5734. * socket.
  5735. */
  5736. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5737. conn->consumed_content += n;
  5738. nread += n;
  5739. } else {
  5740. nread = ((nread > 0) ? nread : n);
  5741. }
  5742. }
  5743. return (int)nread;
  5744. }
  5745. /* Forward declarations */
  5746. static void handle_request(struct mg_connection *);
  5747. static void log_access(const struct mg_connection *);
  5748. /* Handle request, update statistics and call access log */
  5749. static void
  5750. handle_request_stat_log(struct mg_connection *conn)
  5751. {
  5752. #if defined(USE_SERVER_STATS)
  5753. struct timespec tnow;
  5754. conn->conn_state = 4; /* processing */
  5755. #endif
  5756. handle_request(conn);
  5757. #if defined(USE_SERVER_STATS)
  5758. conn->conn_state = 5; /* processed */
  5759. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5760. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5761. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5762. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5763. conn->num_bytes_sent);
  5764. #endif
  5765. DEBUG_TRACE("%s", "handle_request done");
  5766. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5767. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5768. DEBUG_TRACE("%s", "end_request callback done");
  5769. }
  5770. log_access(conn);
  5771. }
  5772. #if defined(USE_HTTP2)
  5773. #if defined(NO_SSL)
  5774. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5775. #endif
  5776. #define USE_ALPN
  5777. #include "http2.inl"
  5778. /* Not supported with HTTP/2 */
  5779. #define HTTP1_only \
  5780. { \
  5781. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5782. http2_must_use_http1(conn); \
  5783. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5784. return; \
  5785. } \
  5786. }
  5787. #else
  5788. #define HTTP1_only
  5789. #endif
  5790. CIVETWEB_API int
  5791. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5792. {
  5793. if (len > INT_MAX) {
  5794. len = INT_MAX;
  5795. }
  5796. if (conn == NULL) {
  5797. return 0;
  5798. }
  5799. if (conn->is_chunked) {
  5800. size_t all_read = 0;
  5801. while (len > 0) {
  5802. if (conn->is_chunked >= 3) {
  5803. /* No more data left to read */
  5804. return 0;
  5805. }
  5806. if (conn->is_chunked != 1) {
  5807. /* Has error */
  5808. return -1;
  5809. }
  5810. if (conn->consumed_content != conn->content_len) {
  5811. /* copy from the current chunk */
  5812. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5813. if (read_ret < 1) {
  5814. /* read error */
  5815. conn->is_chunked = 2;
  5816. return -1;
  5817. }
  5818. all_read += (size_t)read_ret;
  5819. len -= (size_t)read_ret;
  5820. if (conn->consumed_content == conn->content_len) {
  5821. /* Add data bytes in the current chunk have been read,
  5822. * so we are expecting \r\n now. */
  5823. char x[2];
  5824. conn->content_len += 2;
  5825. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5826. || (x[1] != '\n')) {
  5827. /* Protocol violation */
  5828. conn->is_chunked = 2;
  5829. return -1;
  5830. }
  5831. }
  5832. } else {
  5833. /* fetch a new chunk */
  5834. size_t i;
  5835. char lenbuf[64];
  5836. char *end = NULL;
  5837. unsigned long chunkSize = 0;
  5838. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5839. conn->content_len++;
  5840. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5841. lenbuf[i] = 0;
  5842. }
  5843. if ((i > 0) && (lenbuf[i] == ';')) {
  5844. // chunk extension --> skip chars until next CR
  5845. //
  5846. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5847. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5848. //
  5849. // chunk = chunk-size [ chunk-extension ] CRLF
  5850. // chunk-data CRLF
  5851. // ...
  5852. // chunk-extension= *( ";" chunk-ext-name [ "="
  5853. // chunk-ext-val ] )
  5854. do
  5855. ++conn->content_len;
  5856. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5857. && lenbuf[i] != '\r');
  5858. }
  5859. if ((i > 0) && (lenbuf[i] == '\r')
  5860. && (lenbuf[i - 1] != '\r')) {
  5861. continue;
  5862. }
  5863. if ((i > 1) && (lenbuf[i] == '\n')
  5864. && (lenbuf[i - 1] == '\r')) {
  5865. lenbuf[i + 1] = 0;
  5866. chunkSize = strtoul(lenbuf, &end, 16);
  5867. if (chunkSize == 0) {
  5868. /* regular end of content */
  5869. conn->is_chunked = 3;
  5870. }
  5871. break;
  5872. }
  5873. if (!isxdigit((unsigned char)lenbuf[i])) {
  5874. /* illegal character for chunk length */
  5875. conn->is_chunked = 2;
  5876. return -1;
  5877. }
  5878. }
  5879. if ((end == NULL) || (*end != '\r')) {
  5880. /* chunksize not set correctly */
  5881. conn->is_chunked = 2;
  5882. return -1;
  5883. }
  5884. if (conn->is_chunked == 3) {
  5885. /* try discarding trailer for keep-alive */
  5886. // We found the last chunk (length 0) including the
  5887. // CRLF that terminates that chunk. Now follows a possibly
  5888. // empty trailer and a final CRLF.
  5889. //
  5890. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5891. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5892. //
  5893. // Chunked-Body = *chunk
  5894. // last-chunk
  5895. // trailer
  5896. // CRLF
  5897. // ...
  5898. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5899. // ...
  5900. // trailer = *(entity-header CRLF)
  5901. int crlf_count = 2; // one CRLF already determined
  5902. while (crlf_count < 4 && conn->is_chunked == 3) {
  5903. ++conn->content_len;
  5904. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5905. if ((crlf_count == 0 || crlf_count == 2)) {
  5906. if (lenbuf[0] == '\r')
  5907. ++crlf_count;
  5908. else
  5909. crlf_count = 0;
  5910. } else {
  5911. // previous character was a CR
  5912. // --> next character must be LF
  5913. if (lenbuf[0] == '\n')
  5914. ++crlf_count;
  5915. else
  5916. conn->is_chunked = 2;
  5917. }
  5918. } else
  5919. // premature end of trailer
  5920. conn->is_chunked = 2;
  5921. }
  5922. if (conn->is_chunked == 2)
  5923. return -1;
  5924. else
  5925. conn->is_chunked = 4;
  5926. break;
  5927. }
  5928. /* append a new chunk */
  5929. conn->content_len += (int64_t)chunkSize;
  5930. }
  5931. }
  5932. return (int)all_read;
  5933. }
  5934. return mg_read_inner(conn, buf, len);
  5935. }
  5936. CIVETWEB_API int
  5937. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5938. {
  5939. time_t now;
  5940. int n, total, allowed;
  5941. if (conn == NULL) {
  5942. return 0;
  5943. }
  5944. if (len > INT_MAX) {
  5945. return -1;
  5946. }
  5947. /* Mark connection as "data sent" */
  5948. conn->request_state = 10;
  5949. #if defined(USE_HTTP2)
  5950. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5951. http2_data_frame_head(conn, len, 0);
  5952. }
  5953. #endif
  5954. if (conn->throttle > 0) {
  5955. if ((now = time(NULL)) != conn->last_throttle_time) {
  5956. conn->last_throttle_time = now;
  5957. conn->last_throttle_bytes = 0;
  5958. }
  5959. allowed = conn->throttle - conn->last_throttle_bytes;
  5960. if (allowed > (int)len) {
  5961. allowed = (int)len;
  5962. }
  5963. total = push_all(conn->phys_ctx,
  5964. NULL,
  5965. conn->client.sock,
  5966. conn->ssl,
  5967. (const char *)buf,
  5968. allowed);
  5969. if (total == allowed) {
  5970. buf = (const char *)buf + total;
  5971. conn->last_throttle_bytes += total;
  5972. while ((total < (int)len)
  5973. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5974. allowed = (conn->throttle > ((int)len - total))
  5975. ? (int)len - total
  5976. : conn->throttle;
  5977. n = push_all(conn->phys_ctx,
  5978. NULL,
  5979. conn->client.sock,
  5980. conn->ssl,
  5981. (const char *)buf,
  5982. allowed);
  5983. if (n != allowed) {
  5984. break;
  5985. }
  5986. sleep(1);
  5987. conn->last_throttle_bytes = allowed;
  5988. conn->last_throttle_time = time(NULL);
  5989. buf = (const char *)buf + n;
  5990. total += n;
  5991. }
  5992. }
  5993. } else {
  5994. total = push_all(conn->phys_ctx,
  5995. NULL,
  5996. conn->client.sock,
  5997. conn->ssl,
  5998. (const char *)buf,
  5999. (int)len);
  6000. }
  6001. if (total > 0) {
  6002. conn->num_bytes_sent += total;
  6003. }
  6004. return total;
  6005. }
  6006. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  6007. CIVETWEB_API int
  6008. mg_send_chunk(struct mg_connection *conn,
  6009. const char *chunk,
  6010. unsigned int chunk_len)
  6011. {
  6012. char lenbuf[16];
  6013. size_t lenbuf_len;
  6014. int ret;
  6015. int t;
  6016. /* First store the length information in a text buffer. */
  6017. sprintf(lenbuf, "%x\r\n", chunk_len);
  6018. lenbuf_len = strlen(lenbuf);
  6019. /* Then send length information, chunk and terminating \r\n. */
  6020. ret = mg_write(conn, lenbuf, lenbuf_len);
  6021. if (ret != (int)lenbuf_len) {
  6022. return -1;
  6023. }
  6024. t = ret;
  6025. ret = mg_write(conn, chunk, chunk_len);
  6026. if (ret != (int)chunk_len) {
  6027. return -1;
  6028. }
  6029. t += ret;
  6030. ret = mg_write(conn, "\r\n", 2);
  6031. if (ret != 2) {
  6032. return -1;
  6033. }
  6034. t += ret;
  6035. return t;
  6036. }
  6037. #if defined(GCC_DIAGNOSTIC)
  6038. /* This block forwards format strings to printf implementations,
  6039. * so we need to disable the format-nonliteral warning. */
  6040. #pragma GCC diagnostic push
  6041. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  6042. #endif
  6043. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  6044. static int
  6045. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  6046. {
  6047. va_list ap_copy;
  6048. size_t size = MG_BUF_LEN / 4;
  6049. int len = -1;
  6050. *buf = NULL;
  6051. while (len < 0) {
  6052. if (*buf) {
  6053. mg_free(*buf);
  6054. }
  6055. size *= 4;
  6056. *buf = (char *)mg_malloc(size);
  6057. if (!*buf) {
  6058. break;
  6059. }
  6060. va_copy(ap_copy, ap);
  6061. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  6062. va_end(ap_copy);
  6063. (*buf)[size - 1] = 0;
  6064. }
  6065. return len;
  6066. }
  6067. /* Print message to buffer. If buffer is large enough to hold the message,
  6068. * return buffer. If buffer is to small, allocate large enough buffer on
  6069. * heap,
  6070. * and return allocated buffer. */
  6071. static int
  6072. alloc_vprintf(char **out_buf,
  6073. char *prealloc_buf,
  6074. size_t prealloc_size,
  6075. const char *fmt,
  6076. va_list ap)
  6077. {
  6078. va_list ap_copy;
  6079. int len;
  6080. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  6081. * buffer is too small. Also, older versions of msvcrt.dll do not have
  6082. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  6083. * Therefore, we make two passes: on first pass, get required message
  6084. * length.
  6085. * On second pass, actually print the message. */
  6086. va_copy(ap_copy, ap);
  6087. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  6088. va_end(ap_copy);
  6089. if (len < 0) {
  6090. /* C runtime is not standard compliant, vsnprintf() returned -1.
  6091. * Switch to alternative code path that uses incremental
  6092. * allocations.
  6093. */
  6094. va_copy(ap_copy, ap);
  6095. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  6096. va_end(ap_copy);
  6097. } else if ((size_t)(len) >= prealloc_size) {
  6098. /* The pre-allocated buffer not large enough. */
  6099. /* Allocate a new buffer. */
  6100. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  6101. if (!*out_buf) {
  6102. /* Allocation failed. Return -1 as "out of memory" error. */
  6103. return -1;
  6104. }
  6105. /* Buffer allocation successful. Store the string there. */
  6106. va_copy(ap_copy, ap);
  6107. IGNORE_UNUSED_RESULT(
  6108. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  6109. va_end(ap_copy);
  6110. } else {
  6111. /* The pre-allocated buffer is large enough.
  6112. * Use it to store the string and return the address. */
  6113. va_copy(ap_copy, ap);
  6114. IGNORE_UNUSED_RESULT(
  6115. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  6116. va_end(ap_copy);
  6117. *out_buf = prealloc_buf;
  6118. }
  6119. return len;
  6120. }
  6121. static int
  6122. alloc_printf(char **out_buf, const char *fmt, ...)
  6123. {
  6124. va_list ap;
  6125. int result;
  6126. va_start(ap, fmt);
  6127. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6128. va_end(ap);
  6129. return result;
  6130. }
  6131. #if defined(GCC_DIAGNOSTIC)
  6132. /* Enable format-nonliteral warning again. */
  6133. #pragma GCC diagnostic pop
  6134. #endif
  6135. static int
  6136. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6137. {
  6138. char mem[MG_BUF_LEN];
  6139. char *buf = NULL;
  6140. int len;
  6141. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6142. len = mg_write(conn, buf, (size_t)len);
  6143. }
  6144. if (buf != mem) {
  6145. mg_free(buf);
  6146. }
  6147. return len;
  6148. }
  6149. CIVETWEB_API int
  6150. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6151. {
  6152. va_list ap;
  6153. int result;
  6154. va_start(ap, fmt);
  6155. result = mg_vprintf(conn, fmt, ap);
  6156. va_end(ap);
  6157. return result;
  6158. }
  6159. CIVETWEB_API int
  6160. mg_url_decode(const char *src,
  6161. int src_len,
  6162. char *dst,
  6163. int dst_len,
  6164. int is_form_url_encoded)
  6165. {
  6166. int i, j, a, b;
  6167. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6168. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6169. if ((i < src_len - 2) && (src[i] == '%')
  6170. && isxdigit((unsigned char)src[i + 1])
  6171. && isxdigit((unsigned char)src[i + 2])) {
  6172. a = tolower((unsigned char)src[i + 1]);
  6173. b = tolower((unsigned char)src[i + 2]);
  6174. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6175. i += 2;
  6176. } else if (is_form_url_encoded && (src[i] == '+')) {
  6177. dst[j] = ' ';
  6178. } else if ((unsigned char)src[i] <= ' ') {
  6179. return -1; /* invalid character */
  6180. } else {
  6181. dst[j] = src[i];
  6182. }
  6183. }
  6184. #undef HEXTOI
  6185. dst[j] = '\0'; /* Null-terminate the destination */
  6186. return (i >= src_len) ? j : -1;
  6187. }
  6188. /* form url decoding of an entire string */
  6189. static void
  6190. url_decode_in_place(char *buf)
  6191. {
  6192. int len = (int)strlen(buf);
  6193. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6194. }
  6195. CIVETWEB_API int
  6196. mg_get_var(const char *data,
  6197. size_t data_len,
  6198. const char *name,
  6199. char *dst,
  6200. size_t dst_len)
  6201. {
  6202. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6203. }
  6204. CIVETWEB_API int
  6205. mg_get_var2(const char *data,
  6206. size_t data_len,
  6207. const char *name,
  6208. char *dst,
  6209. size_t dst_len,
  6210. size_t occurrence)
  6211. {
  6212. const char *p, *e, *s;
  6213. size_t name_len;
  6214. int len;
  6215. if ((dst == NULL) || (dst_len == 0)) {
  6216. len = -2;
  6217. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6218. len = -1;
  6219. dst[0] = '\0';
  6220. } else {
  6221. name_len = strlen(name);
  6222. e = data + data_len;
  6223. len = -1;
  6224. dst[0] = '\0';
  6225. /* data is "var1=val1&var2=val2...". Find variable first */
  6226. for (p = data; p + name_len < e; p++) {
  6227. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6228. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6229. /* Point p to variable value */
  6230. p += name_len + 1;
  6231. /* Point s to the end of the value */
  6232. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6233. if (s == NULL) {
  6234. s = e;
  6235. }
  6236. DEBUG_ASSERT(s >= p);
  6237. if (s < p) {
  6238. return -3;
  6239. }
  6240. /* Decode variable into destination buffer */
  6241. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6242. /* Redirect error code from -1 to -2 (destination buffer too
  6243. * small). */
  6244. if (len == -1) {
  6245. len = -2;
  6246. }
  6247. break;
  6248. }
  6249. }
  6250. }
  6251. return len;
  6252. }
  6253. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6254. CIVETWEB_API int
  6255. mg_split_form_urlencoded(char *data,
  6256. struct mg_header *form_fields,
  6257. unsigned num_form_fields)
  6258. {
  6259. char *b;
  6260. int i;
  6261. int num = 0;
  6262. if (data == NULL) {
  6263. /* parameter error */
  6264. return -1;
  6265. }
  6266. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6267. /* determine the number of expected fields */
  6268. if (data[0] == 0) {
  6269. return 0;
  6270. }
  6271. /* count number of & to return the number of key-value-pairs */
  6272. num = 1;
  6273. while (*data) {
  6274. if (*data == '&') {
  6275. num++;
  6276. }
  6277. data++;
  6278. }
  6279. return num;
  6280. }
  6281. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6282. /* parameter error */
  6283. return -1;
  6284. }
  6285. for (i = 0; i < (int)num_form_fields; i++) {
  6286. /* extract key-value pairs from input data */
  6287. while ((*data == ' ') || (*data == '\t')) {
  6288. /* skip initial spaces */
  6289. data++;
  6290. }
  6291. if (*data == 0) {
  6292. /* end of string reached */
  6293. break;
  6294. }
  6295. form_fields[num].name = data;
  6296. /* find & or = */
  6297. b = data;
  6298. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6299. b++;
  6300. }
  6301. if (*b == 0) {
  6302. /* last key without value */
  6303. form_fields[num].value = NULL;
  6304. } else if (*b == '&') {
  6305. /* mid key without value */
  6306. form_fields[num].value = NULL;
  6307. } else {
  6308. /* terminate string */
  6309. *b = 0;
  6310. /* value starts after '=' */
  6311. data = b + 1;
  6312. form_fields[num].value = data;
  6313. }
  6314. /* new field is stored */
  6315. num++;
  6316. /* find a next key */
  6317. b = strchr(data, '&');
  6318. if (b == 0) {
  6319. /* no more data */
  6320. break;
  6321. } else {
  6322. /* terminate value of last field at '&' */
  6323. *b = 0;
  6324. /* next key-value-pairs starts after '&' */
  6325. data = b + 1;
  6326. }
  6327. }
  6328. /* Decode all values */
  6329. for (i = 0; i < num; i++) {
  6330. if (form_fields[i].name) {
  6331. url_decode_in_place((char *)form_fields[i].name);
  6332. }
  6333. if (form_fields[i].value) {
  6334. url_decode_in_place((char *)form_fields[i].value);
  6335. }
  6336. }
  6337. /* return number of fields found */
  6338. return num;
  6339. }
  6340. /* HCP24: some changes to compare whole var_name */
  6341. CIVETWEB_API int
  6342. mg_get_cookie(const char *cookie_header,
  6343. const char *var_name,
  6344. char *dst,
  6345. size_t dst_size)
  6346. {
  6347. const char *s, *p, *end;
  6348. int name_len, len = -1;
  6349. if ((dst == NULL) || (dst_size == 0)) {
  6350. return -2;
  6351. }
  6352. dst[0] = '\0';
  6353. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6354. return -1;
  6355. }
  6356. name_len = (int)strlen(var_name);
  6357. end = s + strlen(s);
  6358. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6359. if (s[name_len] == '=') {
  6360. /* HCP24: now check is it a substring or a full cookie name */
  6361. if ((s == cookie_header) || (s[-1] == ' ')) {
  6362. s += name_len + 1;
  6363. if ((p = strchr(s, ' ')) == NULL) {
  6364. p = end;
  6365. }
  6366. if (p[-1] == ';') {
  6367. p--;
  6368. }
  6369. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6370. s++;
  6371. p--;
  6372. }
  6373. if ((size_t)(p - s) < dst_size) {
  6374. len = (int)(p - s);
  6375. mg_strlcpy(dst, s, (size_t)len + 1);
  6376. } else {
  6377. len = -3;
  6378. }
  6379. break;
  6380. }
  6381. }
  6382. }
  6383. return len;
  6384. }
  6385. CIVETWEB_API int
  6386. mg_base64_encode(const unsigned char *src,
  6387. size_t src_len,
  6388. char *dst,
  6389. size_t *dst_len)
  6390. {
  6391. static const char *b64 =
  6392. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6393. size_t i, j;
  6394. int a, b, c;
  6395. if (dst_len != NULL) {
  6396. /* Expected length including 0 termination: */
  6397. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6398. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6399. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6400. if (*dst_len < expected_len) {
  6401. if (*dst_len > 0) {
  6402. dst[0] = '\0';
  6403. }
  6404. *dst_len = expected_len;
  6405. return 0;
  6406. }
  6407. }
  6408. for (i = j = 0; i < src_len; i += 3) {
  6409. a = src[i];
  6410. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6411. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6412. dst[j++] = b64[a >> 2];
  6413. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6414. if (i + 1 < src_len) {
  6415. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6416. }
  6417. if (i + 2 < src_len) {
  6418. dst[j++] = b64[c & 63];
  6419. }
  6420. }
  6421. while (j % 4 != 0) {
  6422. dst[j++] = '=';
  6423. }
  6424. dst[j++] = '\0';
  6425. if (dst_len != NULL) {
  6426. *dst_len = (size_t)j;
  6427. }
  6428. /* Return -1 for "OK" */
  6429. return -1;
  6430. }
  6431. static unsigned char
  6432. b64reverse(char letter)
  6433. {
  6434. if ((letter >= 'A') && (letter <= 'Z')) {
  6435. return (unsigned char)(letter - 'A');
  6436. }
  6437. if ((letter >= 'a') && (letter <= 'z')) {
  6438. return (unsigned char)(letter - 'a' + 26);
  6439. }
  6440. if ((letter >= '0') && (letter <= '9')) {
  6441. return (unsigned char)(letter - '0' + 52);
  6442. }
  6443. if (letter == '+') {
  6444. return 62;
  6445. }
  6446. if (letter == '/') {
  6447. return 63;
  6448. }
  6449. if (letter == '=') {
  6450. return 255; /* normal end */
  6451. }
  6452. return 254; /* error */
  6453. }
  6454. CIVETWEB_API int
  6455. mg_base64_decode(const char *src,
  6456. size_t src_len,
  6457. unsigned char *dst,
  6458. size_t *dst_len)
  6459. {
  6460. size_t i;
  6461. unsigned char a, b, c, d;
  6462. size_t dst_len_limit = (size_t)-1;
  6463. size_t dst_len_used = 0;
  6464. if (dst_len != NULL) {
  6465. dst_len_limit = *dst_len;
  6466. *dst_len = 0;
  6467. }
  6468. for (i = 0; i < src_len; i += 4) {
  6469. /* Read 4 characters from BASE64 string */
  6470. a = b64reverse(src[i]);
  6471. if (a >= 254) {
  6472. return (int)i;
  6473. }
  6474. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6475. if (b >= 254) {
  6476. return (int)i + 1;
  6477. }
  6478. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6479. if (c == 254) {
  6480. return (int)i + 2;
  6481. }
  6482. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6483. if (d == 254) {
  6484. return (int)i + 3;
  6485. }
  6486. /* Add first (of 3) decoded character */
  6487. if (dst_len_used < dst_len_limit) {
  6488. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6489. + (unsigned char)(b >> 4));
  6490. }
  6491. dst_len_used++;
  6492. if (c != 255) {
  6493. if (dst_len_used < dst_len_limit) {
  6494. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6495. + (unsigned char)(c >> 2));
  6496. }
  6497. dst_len_used++;
  6498. if (d != 255) {
  6499. if (dst_len_used < dst_len_limit) {
  6500. dst[dst_len_used] =
  6501. (unsigned char)((unsigned char)(c << 6) + d);
  6502. }
  6503. dst_len_used++;
  6504. }
  6505. }
  6506. }
  6507. /* Add terminating zero */
  6508. if (dst_len_used < dst_len_limit) {
  6509. dst[dst_len_used] = '\0';
  6510. }
  6511. dst_len_used++;
  6512. if (dst_len != NULL) {
  6513. *dst_len = dst_len_used;
  6514. }
  6515. if (dst_len_used > dst_len_limit) {
  6516. /* Out of memory */
  6517. return 0;
  6518. }
  6519. /* Return -1 for "OK" */
  6520. return -1;
  6521. }
  6522. static int
  6523. is_put_or_delete_method(const struct mg_connection *conn)
  6524. {
  6525. if (conn) {
  6526. const char *s = conn->request_info.request_method;
  6527. if (s != NULL) {
  6528. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6529. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6530. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6531. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6532. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6533. || !strcmp(s, "COPY"));
  6534. }
  6535. }
  6536. return 0;
  6537. }
  6538. static int
  6539. is_civetweb_webdav_method(const struct mg_connection *conn)
  6540. {
  6541. /* Note: Here we only have to identify the WebDav methods that need special
  6542. * handling in the CivetWeb code - not all methods used in WebDav. In
  6543. * particular, methods used on directories (when using Windows Explorer as
  6544. * WebDav client).
  6545. */
  6546. if (conn) {
  6547. const char *s = conn->request_info.request_method;
  6548. if (s != NULL) {
  6549. /* These are the civetweb builtin DAV methods */
  6550. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6551. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6552. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6553. }
  6554. }
  6555. return 0;
  6556. }
  6557. #if !defined(NO_FILES)
  6558. static int
  6559. extention_matches_script(
  6560. struct mg_connection *conn, /* in: request (must be valid) */
  6561. const char *filename /* in: filename (must be valid) */
  6562. )
  6563. {
  6564. #if !defined(NO_CGI)
  6565. int cgi_config_idx, inc, max;
  6566. #endif
  6567. #if defined(USE_LUA)
  6568. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6569. filename)
  6570. > 0) {
  6571. return 1;
  6572. }
  6573. #endif
  6574. #if defined(USE_DUKTAPE)
  6575. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6576. filename)
  6577. > 0) {
  6578. return 1;
  6579. }
  6580. #endif
  6581. #if !defined(NO_CGI)
  6582. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6583. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6584. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6585. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6586. && (match_prefix_strlen(
  6587. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6588. filename)
  6589. > 0)) {
  6590. return 1;
  6591. }
  6592. }
  6593. #endif
  6594. /* filename and conn could be unused, if all preocessor conditions
  6595. * are false (no script language supported). */
  6596. (void)filename;
  6597. (void)conn;
  6598. return 0;
  6599. }
  6600. static int
  6601. extention_matches_template_text(
  6602. struct mg_connection *conn, /* in: request (must be valid) */
  6603. const char *filename /* in: filename (must be valid) */
  6604. )
  6605. {
  6606. #if defined(USE_LUA)
  6607. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6608. filename)
  6609. > 0) {
  6610. return 1;
  6611. }
  6612. #endif
  6613. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6614. > 0) {
  6615. return 1;
  6616. }
  6617. return 0;
  6618. }
  6619. /* For given directory path, substitute it to valid index file.
  6620. * Return 1 if index file has been found, 0 if not found.
  6621. * If the file is found, it's stats is returned in stp. */
  6622. static int
  6623. substitute_index_file_aux(struct mg_connection *conn,
  6624. char *path,
  6625. size_t path_len,
  6626. struct mg_file_stat *filestat)
  6627. {
  6628. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6629. struct vec filename_vec;
  6630. size_t n = strlen(path);
  6631. int found = 0;
  6632. /* The 'path' given to us points to the directory. Remove all trailing
  6633. * directory separator characters from the end of the path, and
  6634. * then append single directory separator character. */
  6635. while ((n > 0) && (path[n - 1] == '/')) {
  6636. n--;
  6637. }
  6638. path[n] = '/';
  6639. /* Traverse index files list. For each entry, append it to the given
  6640. * path and see if the file exists. If it exists, break the loop */
  6641. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6642. /* Ignore too long entries that may overflow path buffer */
  6643. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6644. continue;
  6645. }
  6646. /* Prepare full path to the index file */
  6647. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6648. /* Does it exist? */
  6649. if (mg_stat(conn, path, filestat)) {
  6650. /* Yes it does, break the loop */
  6651. found = 1;
  6652. break;
  6653. }
  6654. }
  6655. /* If no index file exists, restore directory path */
  6656. if (!found) {
  6657. path[n] = '\0';
  6658. }
  6659. return found;
  6660. }
  6661. /* Same as above, except if the first try fails and a fallback-root is
  6662. * configured, we'll try there also */
  6663. static int
  6664. substitute_index_file(struct mg_connection *conn,
  6665. char *path,
  6666. size_t path_len,
  6667. struct mg_file_stat *filestat)
  6668. {
  6669. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6670. if (ret == 0) {
  6671. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6672. const char *fallback_root_prefix =
  6673. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6674. if ((root_prefix) && (fallback_root_prefix)) {
  6675. const size_t root_prefix_len = strlen(root_prefix);
  6676. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6677. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6678. side effects if we fail */
  6679. size_t sub_path_len;
  6680. const size_t fallback_root_prefix_len =
  6681. strlen(fallback_root_prefix);
  6682. const char *sub_path = path + root_prefix_len;
  6683. while (*sub_path == '/') {
  6684. sub_path++;
  6685. }
  6686. sub_path_len = strlen(sub_path);
  6687. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6688. < sizeof(scratch_path))) {
  6689. /* The concatenations below are all safe because we
  6690. * pre-verified string lengths above */
  6691. char *nul;
  6692. strcpy(scratch_path, fallback_root_prefix);
  6693. nul = strchr(scratch_path, '\0');
  6694. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6695. *nul++ = '/';
  6696. *nul = '\0';
  6697. }
  6698. strcat(scratch_path, sub_path);
  6699. if (substitute_index_file_aux(conn,
  6700. scratch_path,
  6701. sizeof(scratch_path),
  6702. filestat)) {
  6703. mg_strlcpy(path, scratch_path, path_len);
  6704. return 1;
  6705. }
  6706. }
  6707. }
  6708. }
  6709. }
  6710. return ret;
  6711. }
  6712. #endif
  6713. static void
  6714. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6715. char *filename, /* out: filename */
  6716. size_t filename_buf_len, /* in: size of filename buffer */
  6717. struct mg_file_stat *filestat, /* out: file status structure */
  6718. int *is_found, /* out: file found (directly) */
  6719. int *is_script_resource, /* out: handled by a script? */
  6720. int *is_websocket_request, /* out: websocket connection? */
  6721. int *is_put_or_delete_request, /* out: put/delete a file? */
  6722. int *is_webdav_request, /* out: webdav request? */
  6723. int *is_template_text /* out: SSI file or LSP file? */
  6724. )
  6725. {
  6726. char const *accept_encoding;
  6727. #if !defined(NO_FILES)
  6728. const char *uri = conn->request_info.local_uri;
  6729. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6730. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6731. NULL};
  6732. int fileExists = 0;
  6733. const char *rewrite;
  6734. struct vec a, b;
  6735. ptrdiff_t match_len;
  6736. char gz_path[UTF8_PATH_MAX];
  6737. int truncated;
  6738. int i;
  6739. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6740. char *tmp_str;
  6741. size_t tmp_str_len, sep_pos;
  6742. int allow_substitute_script_subresources;
  6743. #endif
  6744. #else
  6745. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6746. #endif
  6747. /* Step 1: Set all initially unknown outputs to zero */
  6748. memset(filestat, 0, sizeof(*filestat));
  6749. *filename = 0;
  6750. *is_found = 0;
  6751. *is_script_resource = 0;
  6752. *is_template_text = 0;
  6753. /* Step 2: Classify the request method */
  6754. /* Step 2a: Check if the request attempts to modify the file system */
  6755. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6756. /* Step 2b: Check if the request uses WebDav method that requires special
  6757. * handling */
  6758. *is_webdav_request = is_civetweb_webdav_method(conn);
  6759. /* Step 3: Check if it is a websocket request, and modify the document
  6760. * root if required */
  6761. #if defined(USE_WEBSOCKET)
  6762. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6763. #if !defined(NO_FILES)
  6764. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6765. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6766. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6767. }
  6768. #endif /* !NO_FILES */
  6769. #else /* USE_WEBSOCKET */
  6770. *is_websocket_request = 0;
  6771. #endif /* USE_WEBSOCKET */
  6772. /* Step 4: Check if gzip encoded response is allowed */
  6773. conn->accept_gzip = 0;
  6774. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6775. if (strstr(accept_encoding, "gzip") != NULL) {
  6776. conn->accept_gzip = 1;
  6777. }
  6778. }
  6779. #if !defined(NO_FILES)
  6780. /* Step 5: If there is no root directory, don't look for files. */
  6781. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6782. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6783. * config is not required. */
  6784. if (roots[0] == NULL) {
  6785. /* all file related outputs have already been set to 0, just return
  6786. */
  6787. return;
  6788. }
  6789. for (i = 0; roots[i] != NULL; i++) {
  6790. /* Step 6: Determine the local file path from the root path and the
  6791. * request uri. */
  6792. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6793. * part of the path one byte on the right. */
  6794. truncated = 0;
  6795. mg_snprintf(conn,
  6796. &truncated,
  6797. filename,
  6798. filename_buf_len - 1,
  6799. "%s%s",
  6800. roots[i],
  6801. uri);
  6802. if (truncated) {
  6803. goto interpret_cleanup;
  6804. }
  6805. /* Step 7: URI rewriting */
  6806. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6807. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6808. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6809. mg_snprintf(conn,
  6810. &truncated,
  6811. filename,
  6812. filename_buf_len - 1,
  6813. "%.*s%s",
  6814. (int)b.len,
  6815. b.ptr,
  6816. uri + match_len);
  6817. break;
  6818. }
  6819. }
  6820. if (truncated) {
  6821. goto interpret_cleanup;
  6822. }
  6823. /* Step 8: Check if the file exists at the server */
  6824. /* Local file path and name, corresponding to requested URI
  6825. * is now stored in "filename" variable. */
  6826. if (mg_stat(conn, filename, filestat)) {
  6827. fileExists = 1;
  6828. break;
  6829. }
  6830. }
  6831. if (fileExists) {
  6832. int uri_len = (int)strlen(uri);
  6833. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6834. /* 8.1: File exists. */
  6835. *is_found = 1;
  6836. /* 8.2: Check if it is a script type. */
  6837. if (extention_matches_script(conn, filename)) {
  6838. /* The request addresses a CGI resource, Lua script or
  6839. * server-side javascript.
  6840. * The URI corresponds to the script itself (like
  6841. * /path/script.cgi), and there is no additional resource
  6842. * path (like /path/script.cgi/something).
  6843. * Requests that modify (replace or delete) a resource, like
  6844. * PUT and DELETE requests, should replace/delete the script
  6845. * file.
  6846. * Requests that read or write from/to a resource, like GET and
  6847. * POST requests, should call the script and return the
  6848. * generated response. */
  6849. *is_script_resource = (!*is_put_or_delete_request);
  6850. }
  6851. /* 8.3: Check for SSI and LSP files */
  6852. if (extention_matches_template_text(conn, filename)) {
  6853. /* Same as above, but for *.lsp and *.shtml files. */
  6854. /* A "template text" is a file delivered directly to the client,
  6855. * but with some text tags replaced by dynamic content.
  6856. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6857. * (LP, LSP) file. */
  6858. *is_template_text = (!*is_put_or_delete_request);
  6859. }
  6860. /* 8.4: If the request target is a directory, there could be
  6861. * a substitute file (index.html, index.cgi, ...). */
  6862. /* But do not substitute a directory for a WebDav request */
  6863. if (filestat->is_directory && is_uri_end_slash
  6864. && (!*is_webdav_request)) {
  6865. /* Use a local copy here, since substitute_index_file will
  6866. * change the content of the file status */
  6867. struct mg_file_stat tmp_filestat;
  6868. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6869. if (substitute_index_file(
  6870. conn, filename, filename_buf_len, &tmp_filestat)) {
  6871. /* Substitute file found. Copy stat to the output, then
  6872. * check if the file is a script file */
  6873. *filestat = tmp_filestat;
  6874. if (extention_matches_script(conn, filename)) {
  6875. /* Substitute file is a script file */
  6876. *is_script_resource = 1;
  6877. } else if (extention_matches_template_text(conn, filename)) {
  6878. /* Substitute file is a LSP or SSI file */
  6879. *is_template_text = 1;
  6880. } else {
  6881. /* Substitute file is a regular file */
  6882. *is_script_resource = 0;
  6883. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6884. }
  6885. }
  6886. /* If there is no substitute file, the server could return
  6887. * a directory listing in a later step */
  6888. }
  6889. return;
  6890. }
  6891. /* Step 9: Check for zipped files: */
  6892. /* If we can't find the actual file, look for the file
  6893. * with the same name but a .gz extension. If we find it,
  6894. * use that and set the gzipped flag in the file struct
  6895. * to indicate that the response need to have the content-
  6896. * encoding: gzip header.
  6897. * We can only do this if the browser declares support. */
  6898. if (conn->accept_gzip) {
  6899. mg_snprintf(
  6900. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6901. if (truncated) {
  6902. goto interpret_cleanup;
  6903. }
  6904. if (mg_stat(conn, gz_path, filestat)) {
  6905. if (filestat) {
  6906. filestat->is_gzipped = 1;
  6907. *is_found = 1;
  6908. }
  6909. /* Currently gz files can not be scripts. */
  6910. return;
  6911. }
  6912. }
  6913. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6914. /* Step 10: Script resources may handle sub-resources */
  6915. /* Support PATH_INFO for CGI scripts. */
  6916. tmp_str_len = strlen(filename);
  6917. tmp_str =
  6918. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6919. if (!tmp_str) {
  6920. /* Out of memory */
  6921. goto interpret_cleanup;
  6922. }
  6923. memcpy(tmp_str, filename, tmp_str_len + 1);
  6924. /* Check config, if index scripts may have sub-resources */
  6925. allow_substitute_script_subresources =
  6926. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6927. "yes");
  6928. if (*is_webdav_request) {
  6929. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6930. * PROPFIND for their subresources? */
  6931. /* allow_substitute_script_subresources = 0; */
  6932. }
  6933. sep_pos = tmp_str_len;
  6934. while (sep_pos > 0) {
  6935. sep_pos--;
  6936. if (tmp_str[sep_pos] == '/') {
  6937. int is_script = 0, does_exist = 0;
  6938. tmp_str[sep_pos] = 0;
  6939. if (tmp_str[0]) {
  6940. is_script = extention_matches_script(conn, tmp_str);
  6941. does_exist = mg_stat(conn, tmp_str, filestat);
  6942. }
  6943. if (does_exist && is_script) {
  6944. filename[sep_pos] = 0;
  6945. memmove(filename + sep_pos + 2,
  6946. filename + sep_pos + 1,
  6947. strlen(filename + sep_pos + 1) + 1);
  6948. conn->path_info = filename + sep_pos + 1;
  6949. filename[sep_pos + 1] = '/';
  6950. *is_script_resource = 1;
  6951. *is_found = 1;
  6952. break;
  6953. }
  6954. if (allow_substitute_script_subresources) {
  6955. if (substitute_index_file(
  6956. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6957. /* some intermediate directory has an index file */
  6958. if (extention_matches_script(conn, tmp_str)) {
  6959. size_t script_name_len = strlen(tmp_str);
  6960. /* subres_name read before this memory locatio will be
  6961. overwritten */
  6962. char *subres_name = filename + sep_pos;
  6963. size_t subres_name_len = strlen(subres_name);
  6964. DEBUG_TRACE("Substitute script %s serving path %s",
  6965. tmp_str,
  6966. filename);
  6967. /* this index file is a script */
  6968. if ((script_name_len + subres_name_len + 2)
  6969. >= filename_buf_len) {
  6970. mg_free(tmp_str);
  6971. goto interpret_cleanup;
  6972. }
  6973. conn->path_info =
  6974. filename + script_name_len + 1; /* new target */
  6975. memmove(conn->path_info, subres_name, subres_name_len);
  6976. conn->path_info[subres_name_len] = 0;
  6977. memcpy(filename, tmp_str, script_name_len + 1);
  6978. *is_script_resource = 1;
  6979. *is_found = 1;
  6980. break;
  6981. } else {
  6982. DEBUG_TRACE("Substitute file %s serving path %s",
  6983. tmp_str,
  6984. filename);
  6985. /* non-script files will not have sub-resources */
  6986. filename[sep_pos] = 0;
  6987. conn->path_info = 0;
  6988. *is_script_resource = 0;
  6989. *is_found = 0;
  6990. break;
  6991. }
  6992. }
  6993. }
  6994. tmp_str[sep_pos] = '/';
  6995. }
  6996. }
  6997. mg_free(tmp_str);
  6998. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6999. #endif /* !defined(NO_FILES) */
  7000. return;
  7001. #if !defined(NO_FILES)
  7002. /* Reset all outputs */
  7003. interpret_cleanup:
  7004. memset(filestat, 0, sizeof(*filestat));
  7005. *filename = 0;
  7006. *is_found = 0;
  7007. *is_script_resource = 0;
  7008. *is_websocket_request = 0;
  7009. *is_put_or_delete_request = 0;
  7010. #endif /* !defined(NO_FILES) */
  7011. }
  7012. /* Check whether full request is buffered. Return:
  7013. * -1 if request or response is malformed
  7014. * 0 if request or response is not yet fully buffered
  7015. * >0 actual request length, including last \r\n\r\n */
  7016. static int
  7017. get_http_header_len(const char *buf, int buflen)
  7018. {
  7019. int i;
  7020. for (i = 0; i < buflen; i++) {
  7021. /* Do an unsigned comparison in some conditions below */
  7022. const unsigned char c = (unsigned char)buf[i];
  7023. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  7024. && !isprint(c)) {
  7025. /* abort scan as soon as one malformed character is found */
  7026. return -1;
  7027. }
  7028. if (i < buflen - 1) {
  7029. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  7030. /* Two newline, no carriage return - not standard compliant,
  7031. * but it should be accepted */
  7032. return i + 2;
  7033. }
  7034. }
  7035. if (i < buflen - 3) {
  7036. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  7037. && (buf[i + 3] == '\n')) {
  7038. /* Two \r\n - standard compliant */
  7039. return i + 4;
  7040. }
  7041. }
  7042. }
  7043. return 0;
  7044. }
  7045. #if !defined(NO_CACHING)
  7046. /* Convert month to the month number. Return -1 on error, or month number */
  7047. static int
  7048. get_month_index(const char *s)
  7049. {
  7050. size_t i;
  7051. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  7052. if (!strcmp(s, month_names[i])) {
  7053. return (int)i;
  7054. }
  7055. }
  7056. return -1;
  7057. }
  7058. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7059. static time_t
  7060. parse_date_string(const char *datetime)
  7061. {
  7062. char month_str[32] = {0};
  7063. int second, minute, hour, day, month, year;
  7064. time_t result = (time_t)0;
  7065. struct tm tm;
  7066. if ((sscanf(datetime,
  7067. "%d/%3s/%d %d:%d:%d",
  7068. &day,
  7069. month_str,
  7070. &year,
  7071. &hour,
  7072. &minute,
  7073. &second)
  7074. == 6)
  7075. || (sscanf(datetime,
  7076. "%d %3s %d %d:%d:%d",
  7077. &day,
  7078. month_str,
  7079. &year,
  7080. &hour,
  7081. &minute,
  7082. &second)
  7083. == 6)
  7084. || (sscanf(datetime,
  7085. "%*3s, %d %3s %d %d:%d:%d",
  7086. &day,
  7087. month_str,
  7088. &year,
  7089. &hour,
  7090. &minute,
  7091. &second)
  7092. == 6)
  7093. || (sscanf(datetime,
  7094. "%d-%3s-%d %d:%d:%d",
  7095. &day,
  7096. month_str,
  7097. &year,
  7098. &hour,
  7099. &minute,
  7100. &second)
  7101. == 6)) {
  7102. month = get_month_index(month_str);
  7103. if ((month >= 0) && (year >= 1970)) {
  7104. memset(&tm, 0, sizeof(tm));
  7105. tm.tm_year = year - 1900;
  7106. tm.tm_mon = month;
  7107. tm.tm_mday = day;
  7108. tm.tm_hour = hour;
  7109. tm.tm_min = minute;
  7110. tm.tm_sec = second;
  7111. result = timegm(&tm);
  7112. }
  7113. }
  7114. return result;
  7115. }
  7116. #endif /* !NO_CACHING */
  7117. /* Pre-process URIs according to RFC + protect against directory disclosure
  7118. * attacks by removing '..', excessive '/' and '\' characters */
  7119. static void
  7120. remove_dot_segments(char *inout)
  7121. {
  7122. /* Windows backend protection
  7123. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  7124. * in URI by slash */
  7125. char *out_end = inout;
  7126. char *in = inout;
  7127. if (!in) {
  7128. /* Param error. */
  7129. return;
  7130. }
  7131. while (*in) {
  7132. if (*in == '\\') {
  7133. *in = '/';
  7134. }
  7135. in++;
  7136. }
  7137. /* Algorithm "remove_dot_segments" from
  7138. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7139. /* Step 1:
  7140. * The input buffer is initialized.
  7141. * The output buffer is initialized to the empty string.
  7142. */
  7143. in = inout;
  7144. /* Step 2:
  7145. * While the input buffer is not empty, loop as follows:
  7146. */
  7147. /* Less than out_end of the inout buffer is used as output, so keep
  7148. * condition: out_end <= in */
  7149. while (*in) {
  7150. /* Step 2a:
  7151. * If the input buffer begins with a prefix of "../" or "./",
  7152. * then remove that prefix from the input buffer;
  7153. */
  7154. if (!strncmp(in, "../", 3)) {
  7155. in += 3;
  7156. } else if (!strncmp(in, "./", 2)) {
  7157. in += 2;
  7158. }
  7159. /* otherwise */
  7160. /* Step 2b:
  7161. * if the input buffer begins with a prefix of "/./" or "/.",
  7162. * where "." is a complete path segment, then replace that
  7163. * prefix with "/" in the input buffer;
  7164. */
  7165. else if (!strncmp(in, "/./", 3)) {
  7166. in += 2;
  7167. } else if (!strcmp(in, "/.")) {
  7168. in[1] = 0;
  7169. }
  7170. /* otherwise */
  7171. /* Step 2c:
  7172. * if the input buffer begins with a prefix of "/../" or "/..",
  7173. * where ".." is a complete path segment, then replace that
  7174. * prefix with "/" in the input buffer and remove the last
  7175. * segment and its preceding "/" (if any) from the output
  7176. * buffer;
  7177. */
  7178. else if (!strncmp(in, "/../", 4)) {
  7179. in += 3;
  7180. if (inout != out_end) {
  7181. /* remove last segment */
  7182. do {
  7183. out_end--;
  7184. } while ((inout != out_end) && (*out_end != '/'));
  7185. }
  7186. } else if (!strcmp(in, "/..")) {
  7187. in[1] = 0;
  7188. if (inout != out_end) {
  7189. /* remove last segment */
  7190. do {
  7191. out_end--;
  7192. } while ((inout != out_end) && (*out_end != '/'));
  7193. }
  7194. }
  7195. /* otherwise */
  7196. /* Step 2d:
  7197. * if the input buffer consists only of "." or "..", then remove
  7198. * that from the input buffer;
  7199. */
  7200. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7201. *in = 0;
  7202. }
  7203. /* otherwise */
  7204. /* Step 2e:
  7205. * move the first path segment in the input buffer to the end of
  7206. * the output buffer, including the initial "/" character (if
  7207. * any) and any subsequent characters up to, but not including,
  7208. * the next "/" character or the end of the input buffer.
  7209. */
  7210. else {
  7211. do {
  7212. *out_end = *in;
  7213. out_end++;
  7214. in++;
  7215. } while ((*in != 0) && (*in != '/'));
  7216. }
  7217. }
  7218. /* Step 3:
  7219. * Finally, the output buffer is returned as the result of
  7220. * remove_dot_segments.
  7221. */
  7222. /* Terminate output */
  7223. *out_end = 0;
  7224. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7225. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7226. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7227. * or "//" anymore.
  7228. */
  7229. out_end = in = inout;
  7230. while (*in) {
  7231. if (*in == '.') {
  7232. /* remove . at the end or preceding of / */
  7233. char *in_ahead = in;
  7234. do {
  7235. in_ahead++;
  7236. } while (*in_ahead == '.');
  7237. if (*in_ahead == '/') {
  7238. in = in_ahead;
  7239. if ((out_end != inout) && (out_end[-1] == '/')) {
  7240. /* remove generated // */
  7241. out_end--;
  7242. }
  7243. } else if (*in_ahead == 0) {
  7244. in = in_ahead;
  7245. } else {
  7246. do {
  7247. *out_end++ = '.';
  7248. in++;
  7249. } while (in != in_ahead);
  7250. }
  7251. } else if (*in == '/') {
  7252. /* replace // by / */
  7253. *out_end++ = '/';
  7254. do {
  7255. in++;
  7256. } while (*in == '/');
  7257. } else {
  7258. *out_end++ = *in;
  7259. in++;
  7260. }
  7261. }
  7262. *out_end = 0;
  7263. }
  7264. static const struct {
  7265. const char *extension;
  7266. size_t ext_len;
  7267. const char *mime_type;
  7268. } builtin_mime_types[] = {
  7269. /* IANA registered MIME types
  7270. * (http://www.iana.org/assignments/media-types)
  7271. * application types */
  7272. {".bin", 4, "application/octet-stream"},
  7273. {".cer", 4, "application/pkix-cert"},
  7274. {".crl", 4, "application/pkix-crl"},
  7275. {".crt", 4, "application/pkix-cert"},
  7276. {".deb", 4, "application/octet-stream"},
  7277. {".dmg", 4, "application/octet-stream"},
  7278. {".dll", 4, "application/octet-stream"},
  7279. {".doc", 4, "application/msword"},
  7280. {".eps", 4, "application/postscript"},
  7281. {".exe", 4, "application/octet-stream"},
  7282. {".iso", 4, "application/octet-stream"},
  7283. {".js", 3, "application/javascript"},
  7284. {".json", 5, "application/json"},
  7285. {".mjs", 4, "application/javascript"},
  7286. {".msi", 4, "application/octet-stream"},
  7287. {".pem", 4, "application/x-pem-file"},
  7288. {".pdf", 4, "application/pdf"},
  7289. {".ps", 3, "application/postscript"},
  7290. {".rtf", 4, "application/rtf"},
  7291. {".wasm", 5, "application/wasm"},
  7292. {".xhtml", 6, "application/xhtml+xml"},
  7293. {".xsl", 4, "application/xml"},
  7294. {".xslt", 5, "application/xml"},
  7295. /* fonts */
  7296. {".ttf", 4, "application/font-sfnt"},
  7297. {".cff", 4, "application/font-sfnt"},
  7298. {".otf", 4, "application/font-sfnt"},
  7299. {".aat", 4, "application/font-sfnt"},
  7300. {".sil", 4, "application/font-sfnt"},
  7301. {".pfr", 4, "application/font-tdpfr"},
  7302. {".woff", 5, "application/font-woff"},
  7303. {".woff2", 6, "application/font-woff2"},
  7304. /* audio */
  7305. {".mp3", 4, "audio/mpeg"},
  7306. {".oga", 4, "audio/ogg"},
  7307. {".ogg", 4, "audio/ogg"},
  7308. /* image */
  7309. {".gif", 4, "image/gif"},
  7310. {".ief", 4, "image/ief"},
  7311. {".jpeg", 5, "image/jpeg"},
  7312. {".jpg", 4, "image/jpeg"},
  7313. {".jpm", 4, "image/jpm"},
  7314. {".jpx", 4, "image/jpx"},
  7315. {".png", 4, "image/png"},
  7316. {".svg", 4, "image/svg+xml"},
  7317. {".tif", 4, "image/tiff"},
  7318. {".tiff", 5, "image/tiff"},
  7319. /* model */
  7320. {".wrl", 4, "model/vrml"},
  7321. /* text */
  7322. {".css", 4, "text/css"},
  7323. {".csv", 4, "text/csv"},
  7324. {".htm", 4, "text/html"},
  7325. {".html", 5, "text/html"},
  7326. {".sgm", 4, "text/sgml"},
  7327. {".shtm", 5, "text/html"},
  7328. {".shtml", 6, "text/html"},
  7329. {".txt", 4, "text/plain"},
  7330. {".xml", 4, "text/xml"},
  7331. /* video */
  7332. {".mov", 4, "video/quicktime"},
  7333. {".mp4", 4, "video/mp4"},
  7334. {".mpeg", 5, "video/mpeg"},
  7335. {".mpg", 4, "video/mpeg"},
  7336. {".ogv", 4, "video/ogg"},
  7337. {".qt", 3, "video/quicktime"},
  7338. /* not registered types
  7339. * (http://reference.sitepoint.com/html/mime-types-full,
  7340. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7341. {".arj", 4, "application/x-arj-compressed"},
  7342. {".gz", 3, "application/x-gunzip"},
  7343. {".rar", 4, "application/x-arj-compressed"},
  7344. {".swf", 4, "application/x-shockwave-flash"},
  7345. {".tar", 4, "application/x-tar"},
  7346. {".tgz", 4, "application/x-tar-gz"},
  7347. {".torrent", 8, "application/x-bittorrent"},
  7348. {".ppt", 4, "application/x-mspowerpoint"},
  7349. {".xls", 4, "application/x-msexcel"},
  7350. {".zip", 4, "application/x-zip-compressed"},
  7351. {".aac",
  7352. 4,
  7353. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7354. {".flac", 5, "audio/flac"},
  7355. {".aif", 4, "audio/x-aif"},
  7356. {".m3u", 4, "audio/x-mpegurl"},
  7357. {".mid", 4, "audio/x-midi"},
  7358. {".ra", 3, "audio/x-pn-realaudio"},
  7359. {".ram", 4, "audio/x-pn-realaudio"},
  7360. {".wav", 4, "audio/x-wav"},
  7361. {".bmp", 4, "image/bmp"},
  7362. {".ico", 4, "image/x-icon"},
  7363. {".pct", 4, "image/x-pct"},
  7364. {".pict", 5, "image/pict"},
  7365. {".rgb", 4, "image/x-rgb"},
  7366. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7367. {".asf", 4, "video/x-ms-asf"},
  7368. {".avi", 4, "video/x-msvideo"},
  7369. {".m4v", 4, "video/x-m4v"},
  7370. {NULL, 0, NULL}};
  7371. CIVETWEB_API const char *
  7372. mg_get_builtin_mime_type(const char *path)
  7373. {
  7374. const char *ext;
  7375. size_t i, path_len;
  7376. path_len = strlen(path);
  7377. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7378. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7379. if ((path_len > builtin_mime_types[i].ext_len)
  7380. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7381. return builtin_mime_types[i].mime_type;
  7382. }
  7383. }
  7384. return "text/plain";
  7385. }
  7386. /* Look at the "path" extension and figure what mime type it has.
  7387. * Store mime type in the vector. */
  7388. static void
  7389. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7390. {
  7391. struct vec ext_vec, mime_vec;
  7392. const char *list, *ext;
  7393. size_t path_len;
  7394. path_len = strlen(path);
  7395. if ((conn == NULL) || (vec == NULL)) {
  7396. if (vec != NULL) {
  7397. memset(vec, '\0', sizeof(struct vec));
  7398. }
  7399. return;
  7400. }
  7401. /* Scan user-defined mime types first, in case user wants to
  7402. * override default mime types. */
  7403. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7404. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7405. /* ext now points to the path suffix */
  7406. ext = path + path_len - ext_vec.len;
  7407. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7408. *vec = mime_vec;
  7409. return;
  7410. }
  7411. }
  7412. vec->ptr = mg_get_builtin_mime_type(path);
  7413. vec->len = strlen(vec->ptr);
  7414. }
  7415. /* Stringify binary data. Output buffer must be twice as big as input,
  7416. * because each byte takes 2 bytes in string representation */
  7417. static void
  7418. bin2str(char *to, const unsigned char *p, size_t len)
  7419. {
  7420. static const char *hex = "0123456789abcdef";
  7421. for (; len--; p++) {
  7422. *to++ = hex[p[0] >> 4];
  7423. *to++ = hex[p[0] & 0x0f];
  7424. }
  7425. *to = '\0';
  7426. }
  7427. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7428. */
  7429. CIVETWEB_API char *
  7430. mg_md5(char buf[33], ...)
  7431. {
  7432. md5_byte_t hash[16];
  7433. const char *p;
  7434. va_list ap;
  7435. md5_state_t ctx;
  7436. md5_init(&ctx);
  7437. va_start(ap, buf);
  7438. while ((p = va_arg(ap, const char *)) != NULL) {
  7439. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7440. }
  7441. va_end(ap);
  7442. md5_finish(&ctx, hash);
  7443. bin2str(buf, hash, sizeof(hash));
  7444. return buf;
  7445. }
  7446. /* Check the user's password, return 1 if OK */
  7447. static int
  7448. check_password_digest(const char *method,
  7449. const char *ha1,
  7450. const char *uri,
  7451. const char *nonce,
  7452. const char *nc,
  7453. const char *cnonce,
  7454. const char *qop,
  7455. const char *response)
  7456. {
  7457. char ha2[32 + 1], expected_response[32 + 1];
  7458. /* Some of the parameters may be NULL */
  7459. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7460. || (qop == NULL) || (response == NULL)) {
  7461. return 0;
  7462. }
  7463. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7464. if (strlen(response) != 32) {
  7465. return 0;
  7466. }
  7467. mg_md5(ha2, method, ":", uri, NULL);
  7468. mg_md5(expected_response,
  7469. ha1,
  7470. ":",
  7471. nonce,
  7472. ":",
  7473. nc,
  7474. ":",
  7475. cnonce,
  7476. ":",
  7477. qop,
  7478. ":",
  7479. ha2,
  7480. NULL);
  7481. return mg_strcasecmp(response, expected_response) == 0;
  7482. }
  7483. #if !defined(NO_FILESYSTEMS)
  7484. /* Use the global passwords file, if specified by auth_gpass option,
  7485. * or search for .htpasswd in the requested directory. */
  7486. static void
  7487. open_auth_file(struct mg_connection *conn,
  7488. const char *path,
  7489. struct mg_file *filep)
  7490. {
  7491. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7492. char name[UTF8_PATH_MAX];
  7493. const char *p, *e,
  7494. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7495. int truncated;
  7496. if (gpass != NULL) {
  7497. /* Use global passwords file */
  7498. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7499. #if defined(DEBUG)
  7500. /* Use mg_cry_internal here, since gpass has been
  7501. * configured. */
  7502. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7503. #endif
  7504. }
  7505. /* Important: using local struct mg_file to test path for
  7506. * is_directory flag. If filep is used, mg_stat() makes it
  7507. * appear as if auth file was opened.
  7508. * TODO(mid): Check if this is still required after rewriting
  7509. * mg_stat */
  7510. } else if (mg_stat(conn, path, &filep->stat)
  7511. && filep->stat.is_directory) {
  7512. mg_snprintf(conn,
  7513. &truncated,
  7514. name,
  7515. sizeof(name),
  7516. "%s/%s",
  7517. path,
  7518. PASSWORDS_FILE_NAME);
  7519. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7520. #if defined(DEBUG)
  7521. /* Don't use mg_cry_internal here, but only a trace, since
  7522. * this is a typical case. It will occur for every directory
  7523. * without a password file. */
  7524. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7525. #endif
  7526. }
  7527. } else {
  7528. /* Try to find .htpasswd in requested directory. */
  7529. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7530. if (e[0] == '/') {
  7531. break;
  7532. }
  7533. }
  7534. mg_snprintf(conn,
  7535. &truncated,
  7536. name,
  7537. sizeof(name),
  7538. "%.*s/%s",
  7539. (int)(e - p),
  7540. p,
  7541. PASSWORDS_FILE_NAME);
  7542. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7543. #if defined(DEBUG)
  7544. /* Don't use mg_cry_internal here, but only a trace, since
  7545. * this is a typical case. It will occur for every directory
  7546. * without a password file. */
  7547. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7548. #endif
  7549. }
  7550. }
  7551. }
  7552. }
  7553. #endif /* NO_FILESYSTEMS */
  7554. /* Parsed Authorization header */
  7555. struct auth_header {
  7556. char *user;
  7557. int type; /* 1 = basic, 2 = digest */
  7558. char *plain_password; /* Basic only */
  7559. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7560. };
  7561. /* Return 1 on success. Always initializes the auth_header structure. */
  7562. static int
  7563. parse_auth_header(struct mg_connection *conn,
  7564. char *buf,
  7565. size_t buf_size,
  7566. struct auth_header *auth_header)
  7567. {
  7568. char *name, *value, *s;
  7569. const char *ah;
  7570. uint64_t nonce;
  7571. if (!auth_header || !conn) {
  7572. return 0;
  7573. }
  7574. (void)memset(auth_header, 0, sizeof(*auth_header));
  7575. ah = mg_get_header(conn, "Authorization");
  7576. if (ah == NULL) {
  7577. /* No Authorization header at all */
  7578. return 0;
  7579. }
  7580. if (0 == mg_strncasecmp(ah, "Basic ", 6)) {
  7581. /* Basic Auth (we never asked for this, but some client may send it) */
  7582. char *split;
  7583. const char *userpw_b64 = ah + 6;
  7584. size_t userpw_b64_len = strlen(userpw_b64);
  7585. size_t buf_len_r = buf_size;
  7586. if (mg_base64_decode(
  7587. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7588. != -1) {
  7589. return 0; /* decode error */
  7590. }
  7591. split = strchr(buf, ':');
  7592. if (!split) {
  7593. return 0; /* Format error */
  7594. }
  7595. /* Separate string at ':' */
  7596. *split = 0;
  7597. /* User name is before ':', Password is after ':' */
  7598. auth_header->user = buf;
  7599. auth_header->type = 1;
  7600. auth_header->plain_password = split + 1;
  7601. return 1;
  7602. } else if (0 == mg_strncasecmp(ah, "Digest ", 7)) {
  7603. /* Digest Auth ... implemented below */
  7604. auth_header->type = 2;
  7605. } else {
  7606. /* Unknown or invalid Auth method */
  7607. return 0;
  7608. }
  7609. /* Make modifiable copy of the auth header */
  7610. (void)mg_strlcpy(buf, ah + 7, buf_size);
  7611. s = buf;
  7612. /* Parse authorization header */
  7613. for (;;) {
  7614. /* Gobble initial spaces */
  7615. while (isspace((unsigned char)*s)) {
  7616. s++;
  7617. }
  7618. name = skip_quoted(&s, "=", " ", 0);
  7619. /* Value is either quote-delimited, or ends at first comma or space.
  7620. */
  7621. if (s[0] == '\"') {
  7622. s++;
  7623. value = skip_quoted(&s, "\"", " ", '\\');
  7624. if (s[0] == ',') {
  7625. s++;
  7626. }
  7627. } else {
  7628. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7629. * uses spaces */
  7630. }
  7631. if (*name == '\0') {
  7632. break;
  7633. }
  7634. if (!strcmp(name, "username")) {
  7635. auth_header->user = value;
  7636. } else if (!strcmp(name, "cnonce")) {
  7637. auth_header->cnonce = value;
  7638. } else if (!strcmp(name, "response")) {
  7639. auth_header->response = value;
  7640. } else if (!strcmp(name, "uri")) {
  7641. auth_header->uri = value;
  7642. } else if (!strcmp(name, "qop")) {
  7643. auth_header->qop = value;
  7644. } else if (!strcmp(name, "nc")) {
  7645. auth_header->nc = value;
  7646. } else if (!strcmp(name, "nonce")) {
  7647. auth_header->nonce = value;
  7648. }
  7649. }
  7650. #if !defined(NO_NONCE_CHECK)
  7651. /* Read the nonce from the response. */
  7652. if (auth_header->nonce == NULL) {
  7653. return 0;
  7654. }
  7655. s = NULL;
  7656. nonce = strtoull(auth_header->nonce, &s, 10);
  7657. if ((s == NULL) || (*s != 0)) {
  7658. return 0;
  7659. }
  7660. /* Convert the nonce from the client to a number. */
  7661. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7662. /* The converted number corresponds to the time the nounce has been
  7663. * created. This should not be earlier than the server start. */
  7664. /* Server side nonce check is valuable in all situations but one:
  7665. * if the server restarts frequently, but the client should not see
  7666. * that, so the server should accept nonces from previous starts. */
  7667. /* However, the reasonable default is to not accept a nonce from a
  7668. * previous start, so if anyone changed the access rights between
  7669. * two restarts, a new login is required. */
  7670. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7671. /* nonce is from a previous start of the server and no longer valid
  7672. * (replay attack?) */
  7673. return 0;
  7674. }
  7675. /* Check if the nonce is too high, so it has not (yet) been used by the
  7676. * server. */
  7677. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7678. + conn->dom_ctx->nonce_count)) {
  7679. return 0;
  7680. }
  7681. #else
  7682. (void)nonce;
  7683. #endif
  7684. return (auth_header->user != NULL);
  7685. }
  7686. static const char *
  7687. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7688. {
  7689. if (!filep) {
  7690. return NULL;
  7691. }
  7692. if (filep->access.fp != NULL) {
  7693. return fgets(buf, (int)size, filep->access.fp);
  7694. } else {
  7695. return NULL;
  7696. }
  7697. }
  7698. /* Define the initial recursion depth for procesesing htpasswd files that
  7699. * include other htpasswd
  7700. * (or even the same) files. It is not difficult to provide a file or files
  7701. * s.t. they force civetweb
  7702. * to infinitely recurse and then crash.
  7703. */
  7704. #define INITIAL_DEPTH 9
  7705. #if INITIAL_DEPTH <= 0
  7706. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7707. #endif
  7708. #if !defined(NO_FILESYSTEMS)
  7709. struct read_auth_file_struct {
  7710. struct mg_connection *conn;
  7711. struct auth_header auth_header;
  7712. const char *domain;
  7713. char buf[256 + 256 + 40];
  7714. const char *f_user;
  7715. const char *f_domain;
  7716. const char *f_ha1;
  7717. };
  7718. static int
  7719. read_auth_file(struct mg_file *filep,
  7720. struct read_auth_file_struct *workdata,
  7721. int depth)
  7722. {
  7723. int is_authorized = 0;
  7724. struct mg_file fp;
  7725. size_t l;
  7726. if (!filep || !workdata || (0 == depth)) {
  7727. return 0;
  7728. }
  7729. /* Loop over passwords file */
  7730. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7731. l = strlen(workdata->buf);
  7732. while (l > 0) {
  7733. if (isspace((unsigned char)workdata->buf[l - 1])
  7734. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7735. l--;
  7736. workdata->buf[l] = 0;
  7737. } else
  7738. break;
  7739. }
  7740. if (l < 1) {
  7741. continue;
  7742. }
  7743. workdata->f_user = workdata->buf;
  7744. if (workdata->f_user[0] == ':') {
  7745. /* user names may not contain a ':' and may not be empty,
  7746. * so lines starting with ':' may be used for a special purpose
  7747. */
  7748. if (workdata->f_user[1] == '#') {
  7749. /* :# is a comment */
  7750. continue;
  7751. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7752. if (mg_fopen(workdata->conn,
  7753. workdata->f_user + 9,
  7754. MG_FOPEN_MODE_READ,
  7755. &fp)) {
  7756. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7757. (void)mg_fclose(
  7758. &fp.access); /* ignore error on read only file */
  7759. /* No need to continue processing files once we have a
  7760. * match, since nothing will reset it back
  7761. * to 0.
  7762. */
  7763. if (is_authorized) {
  7764. return is_authorized;
  7765. }
  7766. } else {
  7767. mg_cry_internal(workdata->conn,
  7768. "%s: cannot open authorization file: %s",
  7769. __func__,
  7770. workdata->buf);
  7771. }
  7772. continue;
  7773. }
  7774. /* everything is invalid for the moment (might change in the
  7775. * future) */
  7776. mg_cry_internal(workdata->conn,
  7777. "%s: syntax error in authorization file: %s",
  7778. __func__,
  7779. workdata->buf);
  7780. continue;
  7781. }
  7782. workdata->f_domain = strchr(workdata->f_user, ':');
  7783. if (workdata->f_domain == NULL) {
  7784. mg_cry_internal(workdata->conn,
  7785. "%s: syntax error in authorization file: %s",
  7786. __func__,
  7787. workdata->buf);
  7788. continue;
  7789. }
  7790. *(char *)(workdata->f_domain) = 0;
  7791. (workdata->f_domain)++;
  7792. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7793. if (workdata->f_ha1 == NULL) {
  7794. mg_cry_internal(workdata->conn,
  7795. "%s: syntax error in authorization file: %s",
  7796. __func__,
  7797. workdata->buf);
  7798. continue;
  7799. }
  7800. *(char *)(workdata->f_ha1) = 0;
  7801. (workdata->f_ha1)++;
  7802. if (!strcmp(workdata->auth_header.user, workdata->f_user)
  7803. && !strcmp(workdata->domain, workdata->f_domain)) {
  7804. switch (workdata->auth_header.type) {
  7805. case 1: /* Basic */
  7806. {
  7807. char md5[33];
  7808. mg_md5(md5,
  7809. workdata->f_user,
  7810. ":",
  7811. workdata->domain,
  7812. ":",
  7813. workdata->auth_header.plain_password,
  7814. NULL);
  7815. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7816. }
  7817. case 2: /* Digest */
  7818. return check_password_digest(
  7819. workdata->conn->request_info.request_method,
  7820. workdata->f_ha1,
  7821. workdata->auth_header.uri,
  7822. workdata->auth_header.nonce,
  7823. workdata->auth_header.nc,
  7824. workdata->auth_header.cnonce,
  7825. workdata->auth_header.qop,
  7826. workdata->auth_header.response);
  7827. default: /* None/Other/Unknown */
  7828. return 0;
  7829. }
  7830. }
  7831. }
  7832. return is_authorized;
  7833. }
  7834. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7835. static int
  7836. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7837. {
  7838. struct read_auth_file_struct workdata;
  7839. char buf[MG_BUF_LEN];
  7840. if (!conn || !conn->dom_ctx) {
  7841. return 0;
  7842. }
  7843. memset(&workdata, 0, sizeof(workdata));
  7844. workdata.conn = conn;
  7845. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.auth_header)) {
  7846. return 0;
  7847. }
  7848. /* CGI needs it as REMOTE_USER */
  7849. conn->request_info.remote_user =
  7850. mg_strdup_ctx(workdata.auth_header.user, conn->phys_ctx);
  7851. if (realm) {
  7852. workdata.domain = realm;
  7853. } else {
  7854. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7855. }
  7856. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7857. }
  7858. /* Public function to check http digest authentication header */
  7859. CIVETWEB_API int
  7860. mg_check_digest_access_authentication(struct mg_connection *conn,
  7861. const char *realm,
  7862. const char *filename)
  7863. {
  7864. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7865. int auth;
  7866. if (!conn || !filename) {
  7867. return -1;
  7868. }
  7869. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7870. return -2;
  7871. }
  7872. auth = authorize(conn, &file, realm);
  7873. mg_fclose(&file.access);
  7874. return auth;
  7875. }
  7876. #endif /* NO_FILESYSTEMS */
  7877. /* Return 1 if request is authorised, 0 otherwise. */
  7878. static int
  7879. check_authorization(struct mg_connection *conn, const char *path)
  7880. {
  7881. #if !defined(NO_FILESYSTEMS)
  7882. char fname[UTF8_PATH_MAX];
  7883. struct vec uri_vec, filename_vec;
  7884. const char *list;
  7885. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7886. int authorized = 1, truncated;
  7887. if (!conn || !conn->dom_ctx) {
  7888. return 0;
  7889. }
  7890. list = conn->dom_ctx->config[PROTECT_URI];
  7891. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7892. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7893. mg_snprintf(conn,
  7894. &truncated,
  7895. fname,
  7896. sizeof(fname),
  7897. "%.*s",
  7898. (int)filename_vec.len,
  7899. filename_vec.ptr);
  7900. if (truncated
  7901. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7902. mg_cry_internal(conn,
  7903. "%s: cannot open %s: %s",
  7904. __func__,
  7905. fname,
  7906. strerror(errno));
  7907. }
  7908. break;
  7909. }
  7910. }
  7911. if (!is_file_opened(&file.access)) {
  7912. open_auth_file(conn, path, &file);
  7913. }
  7914. if (is_file_opened(&file.access)) {
  7915. authorized = authorize(conn, &file, NULL);
  7916. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7917. }
  7918. return authorized;
  7919. #else
  7920. (void)conn;
  7921. (void)path;
  7922. return 1;
  7923. #endif /* NO_FILESYSTEMS */
  7924. }
  7925. /* Internal function. Assumes conn is valid */
  7926. static void
  7927. send_authorization_request(struct mg_connection *conn, const char *realm)
  7928. {
  7929. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7930. int trunc = 0;
  7931. char buf[128];
  7932. if (!realm) {
  7933. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7934. }
  7935. mg_lock_context(conn->phys_ctx);
  7936. nonce += conn->dom_ctx->nonce_count;
  7937. ++conn->dom_ctx->nonce_count;
  7938. mg_unlock_context(conn->phys_ctx);
  7939. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7940. conn->must_close = 1;
  7941. /* Create 401 response */
  7942. mg_response_header_start(conn, 401);
  7943. send_no_cache_header(conn);
  7944. send_additional_header(conn);
  7945. mg_response_header_add(conn, "Content-Length", "0", -1);
  7946. /* Content for "WWW-Authenticate" header */
  7947. mg_snprintf(conn,
  7948. &trunc,
  7949. buf,
  7950. sizeof(buf),
  7951. "Digest qop=\"auth\", realm=\"%s\", "
  7952. "nonce=\"%" UINT64_FMT "\"",
  7953. realm,
  7954. nonce);
  7955. if (!trunc) {
  7956. /* !trunc should always be true */
  7957. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7958. }
  7959. /* Send all headers */
  7960. mg_response_header_send(conn);
  7961. }
  7962. /* Interface function. Parameters are provided by the user, so do
  7963. * at least some basic checks.
  7964. */
  7965. CIVETWEB_API int
  7966. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7967. const char *realm)
  7968. {
  7969. if (conn && conn->dom_ctx) {
  7970. send_authorization_request(conn, realm);
  7971. return 0;
  7972. }
  7973. return -1;
  7974. }
  7975. #if !defined(NO_FILES)
  7976. static int
  7977. is_authorized_for_put(struct mg_connection *conn)
  7978. {
  7979. int ret = 0;
  7980. if (conn) {
  7981. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7982. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7983. if (passfile != NULL
  7984. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7985. ret = authorize(conn, &file, NULL);
  7986. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7987. }
  7988. }
  7989. DEBUG_TRACE("file write authorization: %i", ret);
  7990. return ret;
  7991. }
  7992. #endif
  7993. CIVETWEB_API int
  7994. mg_modify_passwords_file_ha1(const char *fname,
  7995. const char *domain,
  7996. const char *user,
  7997. const char *ha1)
  7998. {
  7999. int found = 0, i, result = 1;
  8000. char line[512], u[256], d[256], h[256];
  8001. struct stat st = {0};
  8002. FILE *fp = NULL;
  8003. char *temp_file = NULL;
  8004. int temp_file_offs = 0;
  8005. /* Regard empty password as no password - remove user record. */
  8006. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  8007. ha1 = NULL;
  8008. }
  8009. /* Other arguments must not be empty */
  8010. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8011. return 0;
  8012. }
  8013. /* Using the given file format, user name and domain must not contain
  8014. * the ':' character */
  8015. if (strchr(user, ':') != NULL) {
  8016. return 0;
  8017. }
  8018. if (strchr(domain, ':') != NULL) {
  8019. return 0;
  8020. }
  8021. /* Do not allow control characters like newline in user name and domain.
  8022. * Do not allow excessively long names either. */
  8023. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  8024. if (iscntrl((unsigned char)user[i])) {
  8025. return 0;
  8026. }
  8027. }
  8028. if (user[i]) {
  8029. return 0; /* user name too long */
  8030. }
  8031. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  8032. if (iscntrl((unsigned char)domain[i])) {
  8033. return 0;
  8034. }
  8035. }
  8036. if (domain[i]) {
  8037. return 0; /* domain name too long */
  8038. }
  8039. /* The maximum length of the path to the password file is limited */
  8040. if (strlen(fname) >= UTF8_PATH_MAX) {
  8041. return 0;
  8042. }
  8043. /* Check if the file exists, and get file size */
  8044. if (0 == stat(fname, &st)) {
  8045. int temp_buf_len;
  8046. if (st.st_size > 10485760) {
  8047. /* Some funster provided a >10 MB text file */
  8048. return 0;
  8049. }
  8050. /* Add enough space for one more line */
  8051. temp_buf_len = (int)st.st_size + 1024;
  8052. /* Allocate memory (instead of using a temporary file) */
  8053. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  8054. if (!temp_file) {
  8055. /* Out of memory */
  8056. return 0;
  8057. }
  8058. /* File exists. Read it into a memory buffer. */
  8059. fp = fopen(fname, "r");
  8060. if (fp == NULL) {
  8061. /* Cannot read file. No permission? */
  8062. mg_free(temp_file);
  8063. return 0;
  8064. }
  8065. /* Read content and store in memory */
  8066. while ((fgets(line, sizeof(line), fp) != NULL)
  8067. && ((temp_file_offs + 600) < temp_buf_len)) {
  8068. /* file format is "user:domain:hash\n" */
  8069. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  8070. continue;
  8071. }
  8072. u[255] = 0;
  8073. d[255] = 0;
  8074. h[255] = 0;
  8075. if (!strcmp(u, user) && !strcmp(d, domain)) {
  8076. /* Found the user: change the password hash or drop the user
  8077. */
  8078. if ((ha1 != NULL) && (!found)) {
  8079. i = sprintf(temp_file + temp_file_offs,
  8080. "%s:%s:%s\n",
  8081. user,
  8082. domain,
  8083. ha1);
  8084. if (i < 1) {
  8085. fclose(fp);
  8086. mg_free(temp_file);
  8087. return 0;
  8088. }
  8089. temp_file_offs += i;
  8090. }
  8091. found = 1;
  8092. } else {
  8093. /* Copy existing user, including password hash */
  8094. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  8095. if (i < 1) {
  8096. fclose(fp);
  8097. mg_free(temp_file);
  8098. return 0;
  8099. }
  8100. temp_file_offs += i;
  8101. }
  8102. }
  8103. fclose(fp);
  8104. }
  8105. /* Create new file */
  8106. fp = fopen(fname, "w");
  8107. if (!fp) {
  8108. mg_free(temp_file);
  8109. return 0;
  8110. }
  8111. #if !defined(_WIN32)
  8112. /* On Linux & co., restrict file read/write permissions to the owner */
  8113. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  8114. result = 0;
  8115. }
  8116. #endif
  8117. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  8118. /* Store buffered content of old file */
  8119. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  8120. != (size_t)temp_file_offs) {
  8121. result = 0;
  8122. }
  8123. }
  8124. /* If new user, just add it */
  8125. if ((ha1 != NULL) && (!found)) {
  8126. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  8127. result = 0;
  8128. }
  8129. }
  8130. /* All data written */
  8131. if (fclose(fp) != 0) {
  8132. result = 0;
  8133. }
  8134. mg_free(temp_file);
  8135. return result;
  8136. }
  8137. CIVETWEB_API int
  8138. mg_modify_passwords_file(const char *fname,
  8139. const char *domain,
  8140. const char *user,
  8141. const char *pass)
  8142. {
  8143. char ha1buf[33];
  8144. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8145. return 0;
  8146. }
  8147. if ((pass == NULL) || (pass[0] == 0)) {
  8148. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8149. }
  8150. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8151. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8152. }
  8153. static int
  8154. is_valid_port(unsigned long port)
  8155. {
  8156. return (port <= 0xffff);
  8157. }
  8158. static int
  8159. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8160. {
  8161. struct addrinfo hints, *res, *ressave;
  8162. int func_ret = 0;
  8163. int gai_ret;
  8164. memset(&hints, 0, sizeof(struct addrinfo));
  8165. hints.ai_family = af;
  8166. if (!resolve_src) {
  8167. hints.ai_flags = AI_NUMERICHOST;
  8168. }
  8169. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8170. if (gai_ret != 0) {
  8171. /* gai_strerror could be used to convert gai_ret to a string */
  8172. /* POSIX return values: see
  8173. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8174. */
  8175. /* Windows return values: see
  8176. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8177. */
  8178. return 0;
  8179. }
  8180. ressave = res;
  8181. while (res) {
  8182. if ((dstlen >= (size_t)res->ai_addrlen)
  8183. && (res->ai_addr->sa_family == af)) {
  8184. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8185. func_ret = 1;
  8186. }
  8187. res = res->ai_next;
  8188. }
  8189. freeaddrinfo(ressave);
  8190. return func_ret;
  8191. }
  8192. static int
  8193. connect_socket(
  8194. struct mg_context *ctx /* may be NULL */,
  8195. const char *host,
  8196. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8197. int use_ssl, /* 0 or 1 */
  8198. struct mg_error_data *error,
  8199. SOCKET *sock /* output: socket, must not be NULL */,
  8200. union usa *sa /* output: socket address, must not be NULL */
  8201. )
  8202. {
  8203. int ip_ver = 0;
  8204. int conn_ret = -1;
  8205. int sockerr = 0;
  8206. *sock = INVALID_SOCKET;
  8207. memset(sa, 0, sizeof(*sa));
  8208. if (host == NULL) {
  8209. if (error != NULL) {
  8210. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8211. mg_snprintf(NULL,
  8212. NULL, /* No truncation check for ebuf */
  8213. error->text,
  8214. error->text_buffer_size,
  8215. "%s",
  8216. "NULL host");
  8217. }
  8218. return 0;
  8219. }
  8220. #if defined(USE_X_DOM_SOCKET)
  8221. if (port == -99) {
  8222. /* Unix domain socket */
  8223. size_t hostlen = strlen(host);
  8224. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8225. if (error != NULL) {
  8226. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8227. mg_snprintf(NULL,
  8228. NULL, /* No truncation check for ebuf */
  8229. error->text,
  8230. error->text_buffer_size,
  8231. "%s",
  8232. "host length exceeds limit");
  8233. }
  8234. return 0;
  8235. }
  8236. } else
  8237. #endif
  8238. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8239. if (error != NULL) {
  8240. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8241. mg_snprintf(NULL,
  8242. NULL, /* No truncation check for ebuf */
  8243. error->text,
  8244. error->text_buffer_size,
  8245. "%s",
  8246. "invalid port");
  8247. }
  8248. return 0;
  8249. }
  8250. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) \
  8251. && !defined(NO_SSL_DL)
  8252. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8253. if (use_ssl && (TLS_client_method == NULL)) {
  8254. if (error != NULL) {
  8255. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8256. mg_snprintf(NULL,
  8257. NULL, /* No truncation check for ebuf */
  8258. error->text,
  8259. error->text_buffer_size,
  8260. "%s",
  8261. "SSL is not initialized");
  8262. }
  8263. return 0;
  8264. }
  8265. #else
  8266. if (use_ssl && (SSLv23_client_method == NULL)) {
  8267. if (error != 0) {
  8268. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8269. mg_snprintf(NULL,
  8270. NULL, /* No truncation check for ebuf */
  8271. error->text,
  8272. error->text_buffer_size,
  8273. "%s",
  8274. "SSL is not initialized");
  8275. }
  8276. return 0;
  8277. }
  8278. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8279. #else
  8280. (void)use_ssl;
  8281. #endif /* NO SSL */
  8282. #if defined(USE_X_DOM_SOCKET)
  8283. if (port == -99) {
  8284. size_t hostlen = strlen(host);
  8285. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8286. ip_ver = -99;
  8287. sa->sun.sun_family = AF_UNIX;
  8288. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8289. memcpy(sa->sun.sun_path, host, hostlen);
  8290. } else
  8291. #endif
  8292. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8293. sa->sin.sin_port = htons((uint16_t)port);
  8294. ip_ver = 4;
  8295. #if defined(USE_IPV6)
  8296. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8297. sa->sin6.sin6_port = htons((uint16_t)port);
  8298. ip_ver = 6;
  8299. } else if (host[0] == '[') {
  8300. /* While getaddrinfo on Windows will work with [::1],
  8301. * getaddrinfo on Linux only works with ::1 (without []). */
  8302. size_t l = strlen(host + 1);
  8303. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8304. if (h) {
  8305. h[l - 1] = 0;
  8306. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8307. sa->sin6.sin6_port = htons((uint16_t)port);
  8308. ip_ver = 6;
  8309. }
  8310. mg_free(h);
  8311. }
  8312. #endif
  8313. }
  8314. if (ip_ver == 0) {
  8315. if (error != NULL) {
  8316. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8317. mg_snprintf(NULL,
  8318. NULL, /* No truncation check for ebuf */
  8319. error->text,
  8320. error->text_buffer_size,
  8321. "%s",
  8322. "host not found");
  8323. }
  8324. return 0;
  8325. }
  8326. if (ip_ver == 4) {
  8327. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8328. }
  8329. #if defined(USE_IPV6)
  8330. else if (ip_ver == 6) {
  8331. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8332. }
  8333. #endif
  8334. #if defined(USE_X_DOM_SOCKET)
  8335. else if (ip_ver == -99) {
  8336. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8337. }
  8338. #endif
  8339. if (*sock == INVALID_SOCKET) {
  8340. if (error != NULL) {
  8341. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8342. error->code_sub = (unsigned)ERRNO;
  8343. mg_snprintf(NULL,
  8344. NULL, /* No truncation check for ebuf */
  8345. error->text,
  8346. error->text_buffer_size,
  8347. "socket(): %s",
  8348. strerror(ERRNO));
  8349. }
  8350. return 0;
  8351. }
  8352. if (0 != set_non_blocking_mode(*sock)) {
  8353. if (error != NULL) {
  8354. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8355. error->code_sub = (unsigned)ERRNO;
  8356. mg_snprintf(NULL,
  8357. NULL, /* No truncation check for ebuf */
  8358. error->text,
  8359. error->text_buffer_size,
  8360. "Cannot set socket to non-blocking: %s",
  8361. strerror(ERRNO));
  8362. }
  8363. closesocket(*sock);
  8364. *sock = INVALID_SOCKET;
  8365. return 0;
  8366. }
  8367. set_close_on_exec(*sock, NULL, ctx);
  8368. if (ip_ver == 4) {
  8369. /* connected with IPv4 */
  8370. conn_ret = connect(*sock,
  8371. (struct sockaddr *)((void *)&sa->sin),
  8372. sizeof(sa->sin));
  8373. }
  8374. #if defined(USE_IPV6)
  8375. else if (ip_ver == 6) {
  8376. /* connected with IPv6 */
  8377. conn_ret = connect(*sock,
  8378. (struct sockaddr *)((void *)&sa->sin6),
  8379. sizeof(sa->sin6));
  8380. }
  8381. #endif
  8382. #if defined(USE_X_DOM_SOCKET)
  8383. else if (ip_ver == -99) {
  8384. /* connected to domain socket */
  8385. conn_ret = connect(*sock,
  8386. (struct sockaddr *)((void *)&sa->sun),
  8387. sizeof(sa->sun));
  8388. }
  8389. #endif
  8390. if (conn_ret != 0) {
  8391. sockerr = ERRNO;
  8392. }
  8393. #if defined(_WIN32)
  8394. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8395. #else
  8396. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8397. #endif
  8398. /* Data for getsockopt */
  8399. void *psockerr = &sockerr;
  8400. int ret;
  8401. #if defined(_WIN32)
  8402. int len = (int)sizeof(sockerr);
  8403. #else
  8404. socklen_t len = (socklen_t)sizeof(sockerr);
  8405. #endif
  8406. /* Data for poll */
  8407. struct mg_pollfd pfd[2];
  8408. int pollres;
  8409. int ms_wait = 10000; /* 10 second timeout */
  8410. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8411. unsigned int num_sock = 1; /* use one or two sockets */
  8412. /* For a non-blocking socket, the connect sequence is:
  8413. * 1) call connect (will not block)
  8414. * 2) wait until the socket is ready for writing (select or poll)
  8415. * 3) check connection state with getsockopt
  8416. */
  8417. pfd[0].fd = *sock;
  8418. pfd[0].events = POLLOUT;
  8419. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8420. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8421. pfd[num_sock].events = POLLIN;
  8422. num_sock++;
  8423. }
  8424. pollres =
  8425. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8426. if (pollres != 1) {
  8427. /* Not connected */
  8428. if (error != NULL) {
  8429. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8430. mg_snprintf(NULL,
  8431. NULL, /* No truncation check for ebuf */
  8432. error->text,
  8433. error->text_buffer_size,
  8434. "connect(%s:%d): timeout",
  8435. host,
  8436. port);
  8437. }
  8438. closesocket(*sock);
  8439. *sock = INVALID_SOCKET;
  8440. return 0;
  8441. }
  8442. #if defined(_WIN32)
  8443. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8444. #else
  8445. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8446. #endif
  8447. if ((ret == 0) && (sockerr == 0)) {
  8448. conn_ret = 0;
  8449. }
  8450. }
  8451. if (conn_ret != 0) {
  8452. /* Not connected */
  8453. if (error != NULL) {
  8454. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8455. error->code_sub = (unsigned)ERRNO;
  8456. mg_snprintf(NULL,
  8457. NULL, /* No truncation check for ebuf */
  8458. error->text,
  8459. error->text_buffer_size,
  8460. "connect(%s:%d): error %s",
  8461. host,
  8462. port,
  8463. strerror(sockerr));
  8464. }
  8465. closesocket(*sock);
  8466. *sock = INVALID_SOCKET;
  8467. return 0;
  8468. }
  8469. return 1;
  8470. }
  8471. CIVETWEB_API int
  8472. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8473. {
  8474. static const char *dont_escape = "._-$,;~()";
  8475. static const char *hex = "0123456789abcdef";
  8476. char *pos = dst;
  8477. const char *end = dst + dst_len - 1;
  8478. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8479. if (isalnum((unsigned char)*src)
  8480. || (strchr(dont_escape, *src) != NULL)) {
  8481. *pos = *src;
  8482. } else if (pos + 2 < end) {
  8483. pos[0] = '%';
  8484. pos[1] = hex[(unsigned char)*src >> 4];
  8485. pos[2] = hex[(unsigned char)*src & 0xf];
  8486. pos += 2;
  8487. } else {
  8488. break;
  8489. }
  8490. }
  8491. *pos = '\0';
  8492. return (*src == '\0') ? (int)(pos - dst) : -1;
  8493. }
  8494. /* Return 0 on success, non-zero if an error occurs. */
  8495. static int
  8496. print_dir_entry(struct mg_connection *conn, struct de *de)
  8497. {
  8498. size_t namesize, escsize, i;
  8499. char *href, *esc, *p;
  8500. char size[64], mod[64];
  8501. #if defined(REENTRANT_TIME)
  8502. struct tm _tm;
  8503. struct tm *tm = &_tm;
  8504. #else
  8505. struct tm *tm;
  8506. #endif
  8507. /* Estimate worst case size for encoding and escaping */
  8508. namesize = strlen(de->file_name) + 1;
  8509. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8510. href = (char *)mg_malloc(namesize * 3 + escsize);
  8511. if (href == NULL) {
  8512. return -1;
  8513. }
  8514. mg_url_encode(de->file_name, href, namesize * 3);
  8515. esc = NULL;
  8516. if (escsize > 0) {
  8517. /* HTML escaping needed */
  8518. esc = href + namesize * 3;
  8519. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8520. mg_strlcpy(p, de->file_name + i, 2);
  8521. if (*p == '&') {
  8522. strcpy(p, "&amp;");
  8523. } else if (*p == '<') {
  8524. strcpy(p, "&lt;");
  8525. } else if (*p == '>') {
  8526. strcpy(p, "&gt;");
  8527. }
  8528. }
  8529. }
  8530. if (de->file.is_directory) {
  8531. mg_snprintf(conn,
  8532. NULL, /* Buffer is big enough */
  8533. size,
  8534. sizeof(size),
  8535. "%s",
  8536. "[DIRECTORY]");
  8537. } else {
  8538. /* We use (signed) cast below because MSVC 6 compiler cannot
  8539. * convert unsigned __int64 to double. Sigh. */
  8540. if (de->file.size < 1024) {
  8541. mg_snprintf(conn,
  8542. NULL, /* Buffer is big enough */
  8543. size,
  8544. sizeof(size),
  8545. "%d",
  8546. (int)de->file.size);
  8547. } else if (de->file.size < 0x100000) {
  8548. mg_snprintf(conn,
  8549. NULL, /* Buffer is big enough */
  8550. size,
  8551. sizeof(size),
  8552. "%.1fk",
  8553. (double)de->file.size / 1024.0);
  8554. } else if (de->file.size < 0x40000000) {
  8555. mg_snprintf(conn,
  8556. NULL, /* Buffer is big enough */
  8557. size,
  8558. sizeof(size),
  8559. "%.1fM",
  8560. (double)de->file.size / 1048576);
  8561. } else {
  8562. mg_snprintf(conn,
  8563. NULL, /* Buffer is big enough */
  8564. size,
  8565. sizeof(size),
  8566. "%.1fG",
  8567. (double)de->file.size / 1073741824);
  8568. }
  8569. }
  8570. /* Note: mg_snprintf will not cause a buffer overflow above.
  8571. * So, string truncation checks are not required here. */
  8572. #if defined(REENTRANT_TIME)
  8573. localtime_r(&de->file.last_modified, tm);
  8574. #else
  8575. tm = localtime(&de->file.last_modified);
  8576. #endif
  8577. if (tm != NULL) {
  8578. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8579. } else {
  8580. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8581. }
  8582. mg_printf(conn,
  8583. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8584. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8585. href,
  8586. de->file.is_directory ? "/" : "",
  8587. esc ? esc : de->file_name,
  8588. de->file.is_directory ? "/" : "",
  8589. mod,
  8590. size);
  8591. mg_free(href);
  8592. return 0;
  8593. }
  8594. /* This function is called from send_directory() and used for
  8595. * sorting directory entries by size, name, or modification time. */
  8596. static int
  8597. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8598. {
  8599. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8600. if (p1 && p2) {
  8601. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8602. int cmp_result = 0;
  8603. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8604. query_string = "n";
  8605. }
  8606. /* Sort Directories vs Files */
  8607. if (a->file.is_directory && !b->file.is_directory) {
  8608. return -1; /* Always put directories on top */
  8609. } else if (!a->file.is_directory && b->file.is_directory) {
  8610. return 1; /* Always put directories on top */
  8611. }
  8612. /* Sort by size or date */
  8613. if (*query_string == 's') {
  8614. cmp_result = (a->file.size == b->file.size)
  8615. ? 0
  8616. : ((a->file.size > b->file.size) ? 1 : -1);
  8617. } else if (*query_string == 'd') {
  8618. cmp_result =
  8619. (a->file.last_modified == b->file.last_modified)
  8620. ? 0
  8621. : ((a->file.last_modified > b->file.last_modified) ? 1
  8622. : -1);
  8623. }
  8624. /* Sort by name:
  8625. * if (*query_string == 'n') ...
  8626. * but also sort files of same size/date by name as secondary criterion.
  8627. */
  8628. if (cmp_result == 0) {
  8629. cmp_result = strcmp(a->file_name, b->file_name);
  8630. }
  8631. /* For descending order, invert result */
  8632. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8633. }
  8634. return 0;
  8635. }
  8636. static int
  8637. must_hide_file(struct mg_connection *conn, const char *path)
  8638. {
  8639. if (conn && conn->dom_ctx) {
  8640. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8641. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8642. return (match_prefix_strlen(pw_pattern, path) > 0)
  8643. || (match_prefix_strlen(pattern, path) > 0);
  8644. }
  8645. return 0;
  8646. }
  8647. #if !defined(NO_FILESYSTEMS)
  8648. static int
  8649. scan_directory(struct mg_connection *conn,
  8650. const char *dir,
  8651. void *data,
  8652. int (*cb)(struct de *, void *))
  8653. {
  8654. char path[UTF8_PATH_MAX];
  8655. struct dirent *dp;
  8656. DIR *dirp;
  8657. struct de de;
  8658. int truncated;
  8659. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8660. return 0;
  8661. } else {
  8662. while ((dp = mg_readdir(dirp)) != NULL) {
  8663. /* Do not show current dir and hidden files */
  8664. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8665. || must_hide_file(conn, dp->d_name)) {
  8666. continue;
  8667. }
  8668. mg_snprintf(
  8669. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8670. /* If we don't memset stat structure to zero, mtime will have
  8671. * garbage and strftime() will segfault later on in
  8672. * print_dir_entry(). memset is required only if mg_stat()
  8673. * fails. For more details, see
  8674. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8675. memset(&de.file, 0, sizeof(de.file));
  8676. if (truncated) {
  8677. /* If the path is not complete, skip processing. */
  8678. continue;
  8679. }
  8680. if (!mg_stat(conn, path, &de.file)) {
  8681. mg_cry_internal(conn,
  8682. "%s: mg_stat(%s) failed: %s",
  8683. __func__,
  8684. path,
  8685. strerror(ERRNO));
  8686. }
  8687. de.file_name = dp->d_name;
  8688. if (cb(&de, data)) {
  8689. /* stopped */
  8690. break;
  8691. }
  8692. }
  8693. (void)mg_closedir(dirp);
  8694. }
  8695. return 1;
  8696. }
  8697. #endif /* NO_FILESYSTEMS */
  8698. #if !defined(NO_FILES)
  8699. static int
  8700. remove_directory(struct mg_connection *conn, const char *dir)
  8701. {
  8702. char path[UTF8_PATH_MAX];
  8703. struct dirent *dp;
  8704. DIR *dirp;
  8705. struct de de;
  8706. int truncated;
  8707. int ok = 1;
  8708. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8709. return 0;
  8710. } else {
  8711. while ((dp = mg_readdir(dirp)) != NULL) {
  8712. /* Do not show current dir (but show hidden files as they will
  8713. * also be removed) */
  8714. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8715. continue;
  8716. }
  8717. mg_snprintf(
  8718. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8719. /* If we don't memset stat structure to zero, mtime will have
  8720. * garbage and strftime() will segfault later on in
  8721. * print_dir_entry(). memset is required only if mg_stat()
  8722. * fails. For more details, see
  8723. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8724. memset(&de.file, 0, sizeof(de.file));
  8725. if (truncated) {
  8726. /* Do not delete anything shorter */
  8727. ok = 0;
  8728. continue;
  8729. }
  8730. if (!mg_stat(conn, path, &de.file)) {
  8731. mg_cry_internal(conn,
  8732. "%s: mg_stat(%s) failed: %s",
  8733. __func__,
  8734. path,
  8735. strerror(ERRNO));
  8736. ok = 0;
  8737. }
  8738. if (de.file.is_directory) {
  8739. if (remove_directory(conn, path) == 0) {
  8740. ok = 0;
  8741. }
  8742. } else {
  8743. /* This will fail file is the file is in memory */
  8744. if (mg_remove(conn, path) == 0) {
  8745. ok = 0;
  8746. }
  8747. }
  8748. }
  8749. (void)mg_closedir(dirp);
  8750. IGNORE_UNUSED_RESULT(rmdir(dir));
  8751. }
  8752. return ok;
  8753. }
  8754. #endif
  8755. struct dir_scan_data {
  8756. struct de *entries;
  8757. size_t num_entries;
  8758. size_t arr_size;
  8759. };
  8760. #if !defined(NO_FILESYSTEMS)
  8761. static int
  8762. dir_scan_callback(struct de *de, void *data)
  8763. {
  8764. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8765. struct de *entries = dsd->entries;
  8766. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8767. /* Here "entries" is a temporary pointer and can be replaced,
  8768. * "dsd->entries" is the original pointer */
  8769. entries =
  8770. (struct de *)mg_realloc(entries,
  8771. dsd->arr_size * 2 * sizeof(entries[0]));
  8772. if (entries == NULL) {
  8773. /* stop scan */
  8774. return 1;
  8775. }
  8776. dsd->entries = entries;
  8777. dsd->arr_size *= 2;
  8778. }
  8779. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8780. if (entries[dsd->num_entries].file_name == NULL) {
  8781. /* stop scan */
  8782. return 1;
  8783. }
  8784. entries[dsd->num_entries].file = de->file;
  8785. dsd->num_entries++;
  8786. return 0;
  8787. }
  8788. static void
  8789. handle_directory_request(struct mg_connection *conn, const char *dir)
  8790. {
  8791. size_t i;
  8792. int sort_direction;
  8793. struct dir_scan_data data = {NULL, 0, 128};
  8794. char date[64], *esc, *p;
  8795. const char *title;
  8796. time_t curtime = time(NULL);
  8797. if (!conn) {
  8798. return;
  8799. }
  8800. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8801. mg_send_http_error(conn,
  8802. 500,
  8803. "Error: Cannot open directory\nopendir(%s): %s",
  8804. dir,
  8805. strerror(ERRNO));
  8806. return;
  8807. }
  8808. gmt_time_string(date, sizeof(date), &curtime);
  8809. esc = NULL;
  8810. title = conn->request_info.local_uri;
  8811. if (title[strcspn(title, "&<>")]) {
  8812. /* HTML escaping needed */
  8813. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8814. if (esc) {
  8815. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8816. mg_strlcpy(p, title + i, 2);
  8817. if (*p == '&') {
  8818. strcpy(p, "&amp;");
  8819. } else if (*p == '<') {
  8820. strcpy(p, "&lt;");
  8821. } else if (*p == '>') {
  8822. strcpy(p, "&gt;");
  8823. }
  8824. }
  8825. } else {
  8826. title = "";
  8827. }
  8828. }
  8829. sort_direction = ((conn->request_info.query_string != NULL)
  8830. && (conn->request_info.query_string[0] != '\0')
  8831. && (conn->request_info.query_string[1] == 'd'))
  8832. ? 'a'
  8833. : 'd';
  8834. conn->must_close = 1;
  8835. /* Create 200 OK response */
  8836. mg_response_header_start(conn, 200);
  8837. send_static_cache_header(conn);
  8838. send_additional_header(conn);
  8839. mg_response_header_add(conn,
  8840. "Content-Type",
  8841. "text/html; charset=utf-8",
  8842. -1);
  8843. /* Send all headers */
  8844. mg_response_header_send(conn);
  8845. /* Body */
  8846. mg_printf(conn,
  8847. "<!DOCTYPE html>"
  8848. "<html><head><title>Index of %s</title>"
  8849. "<style>th {text-align: left;}</style></head>"
  8850. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8851. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8852. "<th><a href=\"?d%c\">Modified</a></th>"
  8853. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8854. "<tr><td colspan=\"3\"><hr></td></tr>",
  8855. esc ? esc : title,
  8856. esc ? esc : title,
  8857. sort_direction,
  8858. sort_direction,
  8859. sort_direction);
  8860. mg_free(esc);
  8861. /* Print first entry - link to a parent directory */
  8862. mg_printf(conn,
  8863. "<tr><td><a href=\"%s\">%s</a></td>"
  8864. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8865. "..",
  8866. "Parent directory",
  8867. "-",
  8868. "-");
  8869. /* Sort and print directory entries */
  8870. if (data.entries != NULL) {
  8871. mg_sort(data.entries,
  8872. data.num_entries,
  8873. sizeof(data.entries[0]),
  8874. compare_dir_entries,
  8875. (void *)conn->request_info.query_string);
  8876. for (i = 0; i < data.num_entries; i++) {
  8877. print_dir_entry(conn, &data.entries[i]);
  8878. mg_free(data.entries[i].file_name);
  8879. }
  8880. mg_free(data.entries);
  8881. }
  8882. mg_printf(conn, "%s", "</table></pre></body></html>");
  8883. conn->status_code = 200;
  8884. }
  8885. #endif /* NO_FILESYSTEMS */
  8886. /* Send len bytes from the opened file to the client. */
  8887. static void
  8888. send_file_data(struct mg_connection *conn,
  8889. struct mg_file *filep,
  8890. int64_t offset,
  8891. int64_t len,
  8892. int no_buffering)
  8893. {
  8894. char buf[MG_BUF_LEN];
  8895. int to_read, num_read, num_written;
  8896. int64_t size;
  8897. if (!filep || !conn) {
  8898. return;
  8899. }
  8900. /* Sanity check the offset */
  8901. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8902. : (int64_t)(filep->stat.size);
  8903. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8904. if (len > 0 && filep->access.fp != NULL) {
  8905. /* file stored on disk */
  8906. #if defined(__linux__)
  8907. /* sendfile is only available for Linux */
  8908. if ((conn->ssl == 0) && (conn->throttle == 0)
  8909. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8910. "yes"))) {
  8911. off_t sf_offs = (off_t)offset;
  8912. ssize_t sf_sent;
  8913. int sf_file = fileno(filep->access.fp);
  8914. int loop_cnt = 0;
  8915. do {
  8916. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8917. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8918. size_t sf_tosend =
  8919. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8920. sf_sent =
  8921. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8922. if (sf_sent > 0) {
  8923. len -= sf_sent;
  8924. offset += sf_sent;
  8925. } else if (loop_cnt == 0) {
  8926. /* This file can not be sent using sendfile.
  8927. * This might be the case for pseudo-files in the
  8928. * /sys/ and /proc/ file system.
  8929. * Use the regular user mode copy code instead. */
  8930. break;
  8931. } else if (sf_sent == 0) {
  8932. /* No error, but 0 bytes sent. May be EOF? */
  8933. return;
  8934. }
  8935. loop_cnt++;
  8936. } while ((len > 0) && (sf_sent >= 0));
  8937. if (sf_sent > 0) {
  8938. return; /* OK */
  8939. }
  8940. /* sf_sent<0 means error, thus fall back to the classic way */
  8941. /* This is always the case, if sf_file is not a "normal" file,
  8942. * e.g., for sending data from the output of a CGI process. */
  8943. offset = (int64_t)sf_offs;
  8944. }
  8945. #endif
  8946. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8947. mg_cry_internal(conn,
  8948. "%s: fseeko() failed: %s",
  8949. __func__,
  8950. strerror(ERRNO));
  8951. mg_send_http_error(
  8952. conn,
  8953. 500,
  8954. "%s",
  8955. "Error: Unable to access file at requested position.");
  8956. } else {
  8957. while (len > 0) {
  8958. /* Calculate how much to read from the file into the buffer. */
  8959. /* If no_buffering is set, we should not wait until the
  8960. * CGI->Server buffer is filled, but send everything
  8961. * immediately. In theory buffering could be turned off using
  8962. * setbuf(filep->access.fp, NULL);
  8963. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8964. * but in practice this does not work. A "Linux only" solution
  8965. * may be to use select(). The only portable way is to read byte
  8966. * by byte, but this is quite inefficient from a performance
  8967. * point of view. */
  8968. to_read = no_buffering ? 1 : sizeof(buf);
  8969. if ((int64_t)to_read > len) {
  8970. to_read = (int)len;
  8971. }
  8972. /* Read from file, exit the loop on error */
  8973. if ((num_read = pull_inner(filep->access.fp,
  8974. NULL,
  8975. buf,
  8976. to_read,
  8977. /* unused */ 0.0))
  8978. <= 0) {
  8979. break;
  8980. }
  8981. /* Send read bytes to the client, exit the loop on error */
  8982. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8983. != num_read) {
  8984. break;
  8985. }
  8986. /* Both read and were successful, adjust counters */
  8987. len -= num_written;
  8988. }
  8989. }
  8990. }
  8991. }
  8992. static int
  8993. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8994. {
  8995. return sscanf(header,
  8996. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8997. a,
  8998. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8999. // to an integer value, but function will not report
  9000. // conversion errors; consider using 'strtol' instead
  9001. }
  9002. static void
  9003. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  9004. {
  9005. if ((filestat != NULL) && (buf != NULL)) {
  9006. mg_snprintf(NULL,
  9007. NULL, /* All calls to construct_etag use 64 byte buffer */
  9008. buf,
  9009. buf_len,
  9010. "\"%lx.%" INT64_FMT "\"",
  9011. (unsigned long)filestat->last_modified,
  9012. filestat->size);
  9013. }
  9014. }
  9015. static void
  9016. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  9017. {
  9018. if (filep != NULL && filep->fp != NULL) {
  9019. #if defined(_WIN32)
  9020. (void)conn; /* Unused. */
  9021. #else
  9022. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  9023. mg_cry_internal(conn,
  9024. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  9025. __func__,
  9026. strerror(ERRNO));
  9027. }
  9028. #endif
  9029. }
  9030. }
  9031. #if defined(USE_ZLIB)
  9032. #include "mod_zlib.inl"
  9033. #endif
  9034. #if !defined(NO_FILESYSTEMS)
  9035. static void
  9036. handle_static_file_request(struct mg_connection *conn,
  9037. const char *path,
  9038. struct mg_file *filep,
  9039. const char *mime_type,
  9040. const char *additional_headers)
  9041. {
  9042. char lm[64], etag[64];
  9043. char range[128]; /* large enough, so there will be no overflow */
  9044. const char *range_hdr;
  9045. int64_t cl, r1, r2;
  9046. struct vec mime_vec;
  9047. int n, truncated;
  9048. char gz_path[UTF8_PATH_MAX];
  9049. const char *encoding = 0;
  9050. int is_head_request;
  9051. #if defined(USE_ZLIB)
  9052. /* Compression is allowed, unless there is a reason not to use
  9053. * compression. If the file is already compressed, too small or a
  9054. * "range" request was made, on the fly compression is not possible. */
  9055. int allow_on_the_fly_compression = 1;
  9056. #endif
  9057. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  9058. return;
  9059. }
  9060. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  9061. if (mime_type == NULL) {
  9062. get_mime_type(conn, path, &mime_vec);
  9063. } else {
  9064. mime_vec.ptr = mime_type;
  9065. mime_vec.len = strlen(mime_type);
  9066. }
  9067. if (filep->stat.size > INT64_MAX) {
  9068. mg_send_http_error(conn,
  9069. 500,
  9070. "Error: File size is too large to send\n%" INT64_FMT,
  9071. filep->stat.size);
  9072. return;
  9073. }
  9074. cl = (int64_t)filep->stat.size;
  9075. conn->status_code = 200;
  9076. range[0] = '\0';
  9077. #if defined(USE_ZLIB)
  9078. /* if this file is in fact a pre-gzipped file, rewrite its filename
  9079. * it's important to rewrite the filename after resolving
  9080. * the mime type from it, to preserve the actual file's type */
  9081. if (!conn->accept_gzip) {
  9082. allow_on_the_fly_compression = 0;
  9083. }
  9084. #endif
  9085. /* Check if there is a range header */
  9086. range_hdr = mg_get_header(conn, "Range");
  9087. /* For gzipped files, add *.gz */
  9088. if (filep->stat.is_gzipped) {
  9089. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9090. if (truncated) {
  9091. mg_send_http_error(conn,
  9092. 500,
  9093. "Error: Path of zipped file too long (%s)",
  9094. path);
  9095. return;
  9096. }
  9097. path = gz_path;
  9098. encoding = "gzip";
  9099. #if defined(USE_ZLIB)
  9100. /* File is already compressed. No "on the fly" compression. */
  9101. allow_on_the_fly_compression = 0;
  9102. #endif
  9103. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  9104. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  9105. struct mg_file_stat file_stat;
  9106. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  9107. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  9108. && !file_stat.is_directory) {
  9109. file_stat.is_gzipped = 1;
  9110. filep->stat = file_stat;
  9111. cl = (int64_t)filep->stat.size;
  9112. path = gz_path;
  9113. encoding = "gzip";
  9114. #if defined(USE_ZLIB)
  9115. /* File is already compressed. No "on the fly" compression. */
  9116. allow_on_the_fly_compression = 0;
  9117. #endif
  9118. }
  9119. }
  9120. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9121. mg_send_http_error(conn,
  9122. 500,
  9123. "Error: Cannot open file\nfopen(%s): %s",
  9124. path,
  9125. strerror(ERRNO));
  9126. return;
  9127. }
  9128. fclose_on_exec(&filep->access, conn);
  9129. /* If "Range" request was made: parse header, send only selected part
  9130. * of the file. */
  9131. r1 = r2 = 0;
  9132. if ((range_hdr != NULL)
  9133. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9134. && (r2 >= 0)) {
  9135. /* actually, range requests don't play well with a pre-gzipped
  9136. * file (since the range is specified in the uncompressed space) */
  9137. if (filep->stat.is_gzipped) {
  9138. mg_send_http_error(
  9139. conn,
  9140. 416, /* 416 = Range Not Satisfiable */
  9141. "%s",
  9142. "Error: Range requests in gzipped files are not supported");
  9143. (void)mg_fclose(
  9144. &filep->access); /* ignore error on read only file */
  9145. return;
  9146. }
  9147. conn->status_code = 206;
  9148. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9149. mg_snprintf(conn,
  9150. NULL, /* range buffer is big enough */
  9151. range,
  9152. sizeof(range),
  9153. "bytes "
  9154. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9155. r1,
  9156. r1 + cl - 1,
  9157. filep->stat.size);
  9158. #if defined(USE_ZLIB)
  9159. /* Do not compress ranges. */
  9160. allow_on_the_fly_compression = 0;
  9161. #endif
  9162. }
  9163. /* Do not compress small files. Small files do not benefit from file
  9164. * compression, but there is still some overhead. */
  9165. #if defined(USE_ZLIB)
  9166. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9167. /* File is below the size limit. */
  9168. allow_on_the_fly_compression = 0;
  9169. }
  9170. #endif
  9171. /* Prepare Etag, and Last-Modified headers. */
  9172. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9173. construct_etag(etag, sizeof(etag), &filep->stat);
  9174. /* Create 2xx (200, 206) response */
  9175. mg_response_header_start(conn, conn->status_code);
  9176. send_static_cache_header(conn);
  9177. send_additional_header(conn);
  9178. send_cors_header(conn);
  9179. mg_response_header_add(conn,
  9180. "Content-Type",
  9181. mime_vec.ptr,
  9182. (int)mime_vec.len);
  9183. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9184. mg_response_header_add(conn, "Etag", etag, -1);
  9185. #if defined(USE_ZLIB)
  9186. /* On the fly compression allowed */
  9187. if (allow_on_the_fly_compression) {
  9188. /* For on the fly compression, we don't know the content size in
  9189. * advance, so we have to use chunked encoding */
  9190. encoding = "gzip";
  9191. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9192. /* HTTP/2 is always using "chunks" (frames) */
  9193. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9194. }
  9195. } else
  9196. #endif
  9197. {
  9198. /* Without on-the-fly compression, we know the content-length
  9199. * and we can use ranges (with on-the-fly compression we cannot).
  9200. * So we send these response headers only in this case. */
  9201. char len[32];
  9202. int trunc = 0;
  9203. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9204. if (!trunc) {
  9205. mg_response_header_add(conn, "Content-Length", len, -1);
  9206. }
  9207. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9208. }
  9209. if (encoding) {
  9210. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9211. }
  9212. if (range[0] != 0) {
  9213. mg_response_header_add(conn, "Content-Range", range, -1);
  9214. }
  9215. /* The code above does not add any header starting with X- to make
  9216. * sure no one of the additional_headers is included twice */
  9217. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9218. mg_response_header_add_lines(conn, additional_headers);
  9219. }
  9220. /* Send all headers */
  9221. mg_response_header_send(conn);
  9222. if (!is_head_request) {
  9223. #if defined(USE_ZLIB)
  9224. if (allow_on_the_fly_compression) {
  9225. /* Compress and send */
  9226. send_compressed_data(conn, filep);
  9227. } else
  9228. #endif
  9229. {
  9230. /* Send file directly */
  9231. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9232. }
  9233. }
  9234. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9235. }
  9236. CIVETWEB_API int
  9237. mg_send_file_body(struct mg_connection *conn, const char *path)
  9238. {
  9239. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9240. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9241. return -1;
  9242. }
  9243. fclose_on_exec(&file.access, conn);
  9244. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9245. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9246. return 0; /* >= 0 for OK */
  9247. }
  9248. #endif /* NO_FILESYSTEMS */
  9249. #if !defined(NO_CACHING)
  9250. /* Return True if we should reply 304 Not Modified. */
  9251. static int
  9252. is_not_modified(const struct mg_connection *conn,
  9253. const struct mg_file_stat *filestat)
  9254. {
  9255. char etag[64];
  9256. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9257. const char *inm = mg_get_header(conn, "If-None-Match");
  9258. construct_etag(etag, sizeof(etag), filestat);
  9259. if (inm) {
  9260. return !mg_strcasecmp(etag, inm);
  9261. }
  9262. if (ims) {
  9263. return (filestat->last_modified <= parse_date_string(ims));
  9264. }
  9265. return 0;
  9266. }
  9267. static void
  9268. handle_not_modified_static_file_request(struct mg_connection *conn,
  9269. struct mg_file *filep)
  9270. {
  9271. char lm[64], etag[64];
  9272. if ((conn == NULL) || (filep == NULL)) {
  9273. return;
  9274. }
  9275. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9276. construct_etag(etag, sizeof(etag), &filep->stat);
  9277. /* Create 304 "not modified" response */
  9278. mg_response_header_start(conn, 304);
  9279. send_static_cache_header(conn);
  9280. send_additional_header(conn);
  9281. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9282. mg_response_header_add(conn, "Etag", etag, -1);
  9283. /* Send all headers */
  9284. mg_response_header_send(conn);
  9285. }
  9286. #endif
  9287. #if !defined(NO_FILESYSTEMS)
  9288. CIVETWEB_API void
  9289. mg_send_file(struct mg_connection *conn, const char *path)
  9290. {
  9291. mg_send_mime_file2(conn, path, NULL, NULL);
  9292. }
  9293. CIVETWEB_API void
  9294. mg_send_mime_file(struct mg_connection *conn,
  9295. const char *path,
  9296. const char *mime_type)
  9297. {
  9298. mg_send_mime_file2(conn, path, mime_type, NULL);
  9299. }
  9300. CIVETWEB_API void
  9301. mg_send_mime_file2(struct mg_connection *conn,
  9302. const char *path,
  9303. const char *mime_type,
  9304. const char *additional_headers)
  9305. {
  9306. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9307. if (!conn) {
  9308. /* No conn */
  9309. return;
  9310. }
  9311. if (mg_stat(conn, path, &file.stat)) {
  9312. #if !defined(NO_CACHING)
  9313. if (is_not_modified(conn, &file.stat)) {
  9314. /* Send 304 "Not Modified" - this must not send any body data */
  9315. handle_not_modified_static_file_request(conn, &file);
  9316. } else
  9317. #endif /* NO_CACHING */
  9318. if (file.stat.is_directory) {
  9319. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9320. "yes")) {
  9321. handle_directory_request(conn, path);
  9322. } else {
  9323. mg_send_http_error(conn,
  9324. 403,
  9325. "%s",
  9326. "Error: Directory listing denied");
  9327. }
  9328. } else {
  9329. handle_static_file_request(
  9330. conn, path, &file, mime_type, additional_headers);
  9331. }
  9332. } else {
  9333. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9334. }
  9335. }
  9336. /* For a given PUT path, create all intermediate subdirectories.
  9337. * Return 0 if the path itself is a directory.
  9338. * Return 1 if the path leads to a file.
  9339. * Return -1 for if the path is too long.
  9340. * Return -2 if path can not be created.
  9341. */
  9342. static int
  9343. put_dir(struct mg_connection *conn, const char *path)
  9344. {
  9345. char buf[UTF8_PATH_MAX];
  9346. const char *s, *p;
  9347. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9348. size_t len;
  9349. int res = 1;
  9350. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9351. len = (size_t)(p - path);
  9352. if (len >= sizeof(buf)) {
  9353. /* path too long */
  9354. res = -1;
  9355. break;
  9356. }
  9357. memcpy(buf, path, len);
  9358. buf[len] = '\0';
  9359. /* Try to create intermediate directory */
  9360. DEBUG_TRACE("mkdir(%s)", buf);
  9361. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9362. /* path does not exist and can not be created */
  9363. res = -2;
  9364. break;
  9365. }
  9366. /* Is path itself a directory? */
  9367. if (p[1] == '\0') {
  9368. res = 0;
  9369. }
  9370. }
  9371. return res;
  9372. }
  9373. static void
  9374. remove_bad_file(const struct mg_connection *conn, const char *path)
  9375. {
  9376. int r = mg_remove(conn, path);
  9377. if (r != 0) {
  9378. mg_cry_internal(conn,
  9379. "%s: Cannot remove invalid file %s",
  9380. __func__,
  9381. path);
  9382. }
  9383. }
  9384. CIVETWEB_API long long
  9385. mg_store_body(struct mg_connection *conn, const char *path)
  9386. {
  9387. char buf[MG_BUF_LEN];
  9388. long long len = 0;
  9389. int ret, n;
  9390. struct mg_file fi;
  9391. if (conn->consumed_content != 0) {
  9392. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9393. return -11;
  9394. }
  9395. ret = put_dir(conn, path);
  9396. if (ret < 0) {
  9397. /* -1 for path too long,
  9398. * -2 for path can not be created. */
  9399. return ret;
  9400. }
  9401. if (ret != 1) {
  9402. /* Return 0 means, path itself is a directory. */
  9403. return 0;
  9404. }
  9405. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9406. return -12;
  9407. }
  9408. ret = mg_read(conn, buf, sizeof(buf));
  9409. while (ret > 0) {
  9410. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9411. if (n != ret) {
  9412. (void)mg_fclose(
  9413. &fi.access); /* File is bad and will be removed anyway. */
  9414. remove_bad_file(conn, path);
  9415. return -13;
  9416. }
  9417. len += ret;
  9418. ret = mg_read(conn, buf, sizeof(buf));
  9419. }
  9420. /* File is open for writing. If fclose fails, there was probably an
  9421. * error flushing the buffer to disk, so the file on disk might be
  9422. * broken. Delete it and return an error to the caller. */
  9423. if (mg_fclose(&fi.access) != 0) {
  9424. remove_bad_file(conn, path);
  9425. return -14;
  9426. }
  9427. return len;
  9428. }
  9429. #endif /* NO_FILESYSTEMS */
  9430. /* Parse a buffer:
  9431. * Forward the string pointer till the end of a word, then
  9432. * terminate it and forward till the begin of the next word.
  9433. */
  9434. static int
  9435. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9436. {
  9437. /* Forward until a space is found - use isgraph here */
  9438. /* Extended ASCII characters are also treated as word characters. */
  9439. /* See http://www.cplusplus.com/reference/cctype/ */
  9440. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9441. (*ppw)++;
  9442. }
  9443. /* Check end of word */
  9444. if (eol) {
  9445. /* must be a end of line */
  9446. if ((**ppw != '\r') && (**ppw != '\n')) {
  9447. return -1;
  9448. }
  9449. } else {
  9450. /* must be a end of a word, but not a line */
  9451. if (**ppw != ' ') {
  9452. return -1;
  9453. }
  9454. }
  9455. /* Terminate and forward to the next word */
  9456. do {
  9457. **ppw = 0;
  9458. (*ppw)++;
  9459. } while (isspace((unsigned char)**ppw));
  9460. /* Check after term */
  9461. if (!eol) {
  9462. /* if it's not the end of line, there must be a next word */
  9463. if (!isgraph((unsigned char)**ppw)) {
  9464. return -1;
  9465. }
  9466. }
  9467. /* ok */
  9468. return 1;
  9469. }
  9470. /* Parse HTTP headers from the given buffer, advance buf pointer
  9471. * to the point where parsing stopped.
  9472. * All parameters must be valid pointers (not NULL).
  9473. * Return <0 on error. */
  9474. static int
  9475. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9476. {
  9477. int i;
  9478. int num_headers = 0;
  9479. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9480. char *dp = *buf;
  9481. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9482. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9483. dp++;
  9484. }
  9485. if (dp == *buf) {
  9486. /* End of headers reached. */
  9487. break;
  9488. }
  9489. /* Drop all spaces after header name before : */
  9490. while (*dp == ' ') {
  9491. *dp = 0;
  9492. dp++;
  9493. }
  9494. if (*dp != ':') {
  9495. /* This is not a valid field. */
  9496. return -1;
  9497. }
  9498. /* End of header key (*dp == ':') */
  9499. /* Truncate here and set the key name */
  9500. *dp = 0;
  9501. hdr[i].name = *buf;
  9502. /* Skip all spaces */
  9503. do {
  9504. dp++;
  9505. } while ((*dp == ' ') || (*dp == '\t'));
  9506. /* The rest of the line is the value */
  9507. hdr[i].value = dp;
  9508. /* Find end of line */
  9509. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9510. dp++;
  9511. };
  9512. /* eliminate \r */
  9513. if (*dp == '\r') {
  9514. *dp = 0;
  9515. dp++;
  9516. if (*dp != '\n') {
  9517. /* This is not a valid line. */
  9518. return -1;
  9519. }
  9520. }
  9521. /* here *dp is either 0 or '\n' */
  9522. /* in any case, we have found a complete header */
  9523. num_headers = i + 1;
  9524. if (*dp) {
  9525. *dp = 0;
  9526. dp++;
  9527. *buf = dp;
  9528. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9529. /* We've had CRLF twice in a row
  9530. * This is the end of the headers */
  9531. break;
  9532. }
  9533. /* continue within the loop, find the next header */
  9534. } else {
  9535. *buf = dp;
  9536. break;
  9537. }
  9538. }
  9539. return num_headers;
  9540. }
  9541. struct mg_http_method_info {
  9542. const char *name;
  9543. int request_has_body;
  9544. int response_has_body;
  9545. int is_safe;
  9546. int is_idempotent;
  9547. int is_cacheable;
  9548. };
  9549. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9550. static const struct mg_http_method_info http_methods[] = {
  9551. /* HTTP (RFC 2616) */
  9552. {"GET", 0, 1, 1, 1, 1},
  9553. {"POST", 1, 1, 0, 0, 0},
  9554. {"PUT", 1, 0, 0, 1, 0},
  9555. {"DELETE", 0, 0, 0, 1, 0},
  9556. {"HEAD", 0, 0, 1, 1, 1},
  9557. {"OPTIONS", 0, 0, 1, 1, 0},
  9558. {"CONNECT", 1, 1, 0, 0, 0},
  9559. /* TRACE method (RFC 2616) is not supported for security reasons */
  9560. /* PATCH method (RFC 5789) */
  9561. {"PATCH", 1, 0, 0, 0, 0},
  9562. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9563. /* WEBDAV (RFC 2518) */
  9564. {"PROPFIND", 0, 1, 1, 1, 0},
  9565. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9566. * Some PROPFIND results MAY be cached, with care,
  9567. * as there is no cache validation mechanism for
  9568. * most properties. This method is both safe and
  9569. * idempotent (see Section 9.1 of [RFC2616]). */
  9570. {"MKCOL", 0, 0, 0, 1, 0},
  9571. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9572. * When MKCOL is invoked without a request body,
  9573. * the newly created collection SHOULD have no
  9574. * members. A MKCOL request message may contain
  9575. * a message body. The precise behavior of a MKCOL
  9576. * request when the body is present is undefined,
  9577. * ... ==> We do not support MKCOL with body data.
  9578. * This method is idempotent, but not safe (see
  9579. * Section 9.1 of [RFC2616]). Responses to this
  9580. * method MUST NOT be cached. */
  9581. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9582. {"LOCK", 1, 1, 0, 0, 0},
  9583. {"UNLOCK", 1, 0, 0, 0, 0},
  9584. {"PROPPATCH", 1, 1, 0, 0, 0},
  9585. {"COPY", 1, 0, 0, 0, 0},
  9586. {"MOVE", 1, 1, 0, 0, 0},
  9587. /* Unsupported WEBDAV Methods: */
  9588. /* + 11 methods from RFC 3253 */
  9589. /* ORDERPATCH (RFC 3648) */
  9590. /* ACL (RFC 3744) */
  9591. /* SEARCH (RFC 5323) */
  9592. /* + MicroSoft extensions
  9593. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9594. /* REPORT method (RFC 3253) */
  9595. {"REPORT", 1, 1, 1, 1, 1},
  9596. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9597. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9598. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9599. * to be useful for REST in case a "GET request with body" is
  9600. * required. */
  9601. {NULL, 0, 0, 0, 0, 0}
  9602. /* end of list */
  9603. };
  9604. /* All method names */
  9605. static char *all_methods = NULL; /* Built by mg_init_library */
  9606. static const struct mg_http_method_info *
  9607. get_http_method_info(const char *method)
  9608. {
  9609. /* Check if the method is known to the server. The list of all known
  9610. * HTTP methods can be found here at
  9611. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9612. */
  9613. const struct mg_http_method_info *m = http_methods;
  9614. while (m->name) {
  9615. if (!strcmp(m->name, method)) {
  9616. return m;
  9617. }
  9618. m++;
  9619. }
  9620. return NULL;
  9621. }
  9622. static int
  9623. is_valid_http_method(const char *method)
  9624. {
  9625. return (get_http_method_info(method) != NULL);
  9626. }
  9627. /* Parse HTTP request, fill in mg_request_info structure.
  9628. * This function modifies the buffer by NUL-terminating
  9629. * HTTP request components, header names and header values.
  9630. * Parameters:
  9631. * buf (in/out): pointer to the HTTP header to parse and split
  9632. * len (in): length of HTTP header buffer
  9633. * re (out): parsed header as mg_request_info
  9634. * buf and ri must be valid pointers (not NULL), len>0.
  9635. * Returns <0 on error. */
  9636. static int
  9637. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9638. {
  9639. int request_length;
  9640. int init_skip = 0;
  9641. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9642. * remote_port */
  9643. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9644. NULL;
  9645. ri->num_headers = 0;
  9646. /* RFC says that all initial whitespaces should be ignored */
  9647. /* This included all leading \r and \n (isspace) */
  9648. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9649. while ((len > 0) && isspace((unsigned char)*buf)) {
  9650. buf++;
  9651. len--;
  9652. init_skip++;
  9653. }
  9654. if (len == 0) {
  9655. /* Incomplete request */
  9656. return 0;
  9657. }
  9658. /* Control characters are not allowed, including zero */
  9659. if (iscntrl((unsigned char)*buf)) {
  9660. return -1;
  9661. }
  9662. /* Find end of HTTP header */
  9663. request_length = get_http_header_len(buf, len);
  9664. if (request_length <= 0) {
  9665. return request_length;
  9666. }
  9667. buf[request_length - 1] = '\0';
  9668. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9669. return -1;
  9670. }
  9671. /* The first word has to be the HTTP method */
  9672. ri->request_method = buf;
  9673. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9674. return -1;
  9675. }
  9676. /* The second word is the URI */
  9677. ri->request_uri = buf;
  9678. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9679. return -1;
  9680. }
  9681. /* Next would be the HTTP version */
  9682. ri->http_version = buf;
  9683. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9684. return -1;
  9685. }
  9686. /* Check for a valid HTTP version key */
  9687. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9688. /* Invalid request */
  9689. return -1;
  9690. }
  9691. ri->http_version += 5;
  9692. /* Check for a valid http method */
  9693. if (!is_valid_http_method(ri->request_method)) {
  9694. return -1;
  9695. }
  9696. /* Parse all HTTP headers */
  9697. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9698. if (ri->num_headers < 0) {
  9699. /* Error while parsing headers */
  9700. return -1;
  9701. }
  9702. return request_length + init_skip;
  9703. }
  9704. static int
  9705. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9706. {
  9707. int response_length;
  9708. int init_skip = 0;
  9709. char *tmp, *tmp2;
  9710. long l;
  9711. /* Initialize elements. */
  9712. ri->http_version = ri->status_text = NULL;
  9713. ri->num_headers = ri->status_code = 0;
  9714. /* RFC says that all initial whitespaces should be ignored */
  9715. /* This included all leading \r and \n (isspace) */
  9716. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9717. while ((len > 0) && isspace((unsigned char)*buf)) {
  9718. buf++;
  9719. len--;
  9720. init_skip++;
  9721. }
  9722. if (len == 0) {
  9723. /* Incomplete request */
  9724. return 0;
  9725. }
  9726. /* Control characters are not allowed, including zero */
  9727. if (iscntrl((unsigned char)*buf)) {
  9728. return -1;
  9729. }
  9730. /* Find end of HTTP header */
  9731. response_length = get_http_header_len(buf, len);
  9732. if (response_length <= 0) {
  9733. return response_length;
  9734. }
  9735. buf[response_length - 1] = '\0';
  9736. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9737. return -1;
  9738. }
  9739. /* The first word is the HTTP version */
  9740. /* Check for a valid HTTP version key */
  9741. if (strncmp(buf, "HTTP/", 5) != 0) {
  9742. /* Invalid request */
  9743. return -1;
  9744. }
  9745. buf += 5;
  9746. if (!isgraph((unsigned char)buf[0])) {
  9747. /* Invalid request */
  9748. return -1;
  9749. }
  9750. ri->http_version = buf;
  9751. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9752. return -1;
  9753. }
  9754. /* The second word is the status as a number */
  9755. tmp = buf;
  9756. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9757. return -1;
  9758. }
  9759. l = strtol(tmp, &tmp2, 10);
  9760. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9761. /* Everything else but a 3 digit code is invalid */
  9762. return -1;
  9763. }
  9764. ri->status_code = (int)l;
  9765. /* The rest of the line is the status text */
  9766. ri->status_text = buf;
  9767. /* Find end of status text */
  9768. /* isgraph or isspace = isprint */
  9769. while (isprint((unsigned char)*buf)) {
  9770. buf++;
  9771. }
  9772. if ((*buf != '\r') && (*buf != '\n')) {
  9773. return -1;
  9774. }
  9775. /* Terminate string and forward buf to next line */
  9776. do {
  9777. *buf = 0;
  9778. buf++;
  9779. } while (isspace((unsigned char)*buf));
  9780. /* Parse all HTTP headers */
  9781. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9782. if (ri->num_headers < 0) {
  9783. /* Error while parsing headers */
  9784. return -1;
  9785. }
  9786. return response_length + init_skip;
  9787. }
  9788. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9789. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9790. * buffer (which marks the end of HTTP request). Buffer buf may already
  9791. * have some data. The length of the data is stored in nread.
  9792. * Upon every read operation, increase nread by the number of bytes read. */
  9793. static int
  9794. read_message(FILE *fp,
  9795. struct mg_connection *conn,
  9796. char *buf,
  9797. int bufsiz,
  9798. int *nread)
  9799. {
  9800. int request_len, n = 0;
  9801. struct timespec last_action_time;
  9802. double request_timeout;
  9803. if (!conn) {
  9804. return 0;
  9805. }
  9806. memset(&last_action_time, 0, sizeof(last_action_time));
  9807. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9808. /* value of request_timeout is in seconds, config in milliseconds */
  9809. request_timeout =
  9810. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9811. } else {
  9812. request_timeout =
  9813. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9814. / 1000.0;
  9815. }
  9816. if (conn->handled_requests > 0) {
  9817. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9818. request_timeout =
  9819. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9820. / 1000.0;
  9821. }
  9822. }
  9823. request_len = get_http_header_len(buf, *nread);
  9824. while (request_len == 0) {
  9825. /* Full request not yet received */
  9826. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9827. /* Server is to be stopped. */
  9828. return -1;
  9829. }
  9830. if (*nread >= bufsiz) {
  9831. /* Request too long */
  9832. return -2;
  9833. }
  9834. n = pull_inner(
  9835. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9836. if (n == -2) {
  9837. /* Receive error */
  9838. return -1;
  9839. }
  9840. /* update clock after every read request */
  9841. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9842. if (n > 0) {
  9843. *nread += n;
  9844. request_len = get_http_header_len(buf, *nread);
  9845. }
  9846. if ((n <= 0) && (request_timeout >= 0)) {
  9847. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9848. > request_timeout) {
  9849. /* Timeout */
  9850. return -3;
  9851. }
  9852. }
  9853. }
  9854. return request_len;
  9855. }
  9856. #if !defined(NO_CGI) || !defined(NO_FILES)
  9857. static int
  9858. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9859. {
  9860. const char *expect;
  9861. char buf[MG_BUF_LEN];
  9862. int success = 0;
  9863. if (!conn) {
  9864. return 0;
  9865. }
  9866. expect = mg_get_header(conn, "Expect");
  9867. DEBUG_ASSERT(fp != NULL);
  9868. if (!fp) {
  9869. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9870. return 0;
  9871. }
  9872. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9873. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9874. */
  9875. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9876. } else {
  9877. if (expect != NULL) {
  9878. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9879. conn->status_code = 100;
  9880. } else {
  9881. conn->status_code = 200;
  9882. }
  9883. DEBUG_ASSERT(conn->consumed_content == 0);
  9884. if (conn->consumed_content != 0) {
  9885. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9886. return 0;
  9887. }
  9888. for (;;) {
  9889. int nread = mg_read(conn, buf, sizeof(buf));
  9890. if (nread <= 0) {
  9891. success = (nread == 0);
  9892. break;
  9893. }
  9894. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9895. break;
  9896. }
  9897. }
  9898. /* Each error code path in this function must send an error */
  9899. if (!success) {
  9900. /* NOTE: Maybe some data has already been sent. */
  9901. /* TODO (low): If some data has been sent, a correct error
  9902. * reply can no longer be sent, so just close the connection */
  9903. mg_send_http_error(conn, 500, "%s", "");
  9904. }
  9905. }
  9906. return success;
  9907. }
  9908. #endif
  9909. #if defined(USE_TIMERS)
  9910. #define TIMER_API static
  9911. #include "timer.inl"
  9912. #endif /* USE_TIMERS */
  9913. #if !defined(NO_CGI)
  9914. /* This structure helps to create an environment for the spawned CGI
  9915. * program.
  9916. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9917. * last element must be NULL.
  9918. * However, on Windows there is a requirement that all these
  9919. * VARIABLE=VALUE\0
  9920. * strings must reside in a contiguous buffer. The end of the buffer is
  9921. * marked by two '\0' characters.
  9922. * We satisfy both worlds: we create an envp array (which is vars), all
  9923. * entries are actually pointers inside buf. */
  9924. struct cgi_environment {
  9925. struct mg_connection *conn;
  9926. /* Data block */
  9927. char *buf; /* Environment buffer */
  9928. size_t buflen; /* Space available in buf */
  9929. size_t bufused; /* Space taken in buf */
  9930. /* Index block */
  9931. char **var; /* char **envp */
  9932. size_t varlen; /* Number of variables available in var */
  9933. size_t varused; /* Number of variables stored in var */
  9934. };
  9935. static void addenv(struct cgi_environment *env,
  9936. PRINTF_FORMAT_STRING(const char *fmt),
  9937. ...) PRINTF_ARGS(2, 3);
  9938. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9939. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9940. static void
  9941. addenv(struct cgi_environment *env, const char *fmt, ...)
  9942. {
  9943. size_t i, n, space;
  9944. int truncated = 0;
  9945. char *added;
  9946. va_list ap;
  9947. if ((env->varlen - env->varused) < 2) {
  9948. mg_cry_internal(env->conn,
  9949. "%s: Cannot register CGI variable [%s]",
  9950. __func__,
  9951. fmt);
  9952. return;
  9953. }
  9954. /* Calculate how much space is left in the buffer */
  9955. space = (env->buflen - env->bufused);
  9956. do {
  9957. /* Space for "\0\0" is always needed. */
  9958. if (space <= 2) {
  9959. /* Allocate new buffer */
  9960. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9961. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9962. if (!added) {
  9963. /* Out of memory */
  9964. mg_cry_internal(
  9965. env->conn,
  9966. "%s: Cannot allocate memory for CGI variable [%s]",
  9967. __func__,
  9968. fmt);
  9969. return;
  9970. }
  9971. /* Retarget pointers */
  9972. env->buf = added;
  9973. env->buflen = n;
  9974. for (i = 0, n = 0; i < env->varused; i++) {
  9975. env->var[i] = added + n;
  9976. n += strlen(added + n) + 1;
  9977. }
  9978. space = (env->buflen - env->bufused);
  9979. }
  9980. /* Make a pointer to the free space int the buffer */
  9981. added = env->buf + env->bufused;
  9982. /* Copy VARIABLE=VALUE\0 string into the free space */
  9983. va_start(ap, fmt);
  9984. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9985. va_end(ap);
  9986. /* Do not add truncated strings to the environment */
  9987. if (truncated) {
  9988. /* Reallocate the buffer */
  9989. space = 0;
  9990. }
  9991. } while (truncated);
  9992. /* Calculate number of bytes added to the environment */
  9993. n = strlen(added) + 1;
  9994. env->bufused += n;
  9995. /* Append a pointer to the added string into the envp array */
  9996. env->var[env->varused] = added;
  9997. env->varused++;
  9998. }
  9999. /* Return 0 on success, non-zero if an error occurs. */
  10000. static int
  10001. prepare_cgi_environment(struct mg_connection *conn,
  10002. const char *prog,
  10003. struct cgi_environment *env,
  10004. int cgi_config_idx)
  10005. {
  10006. const char *s;
  10007. struct vec var_vec;
  10008. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  10009. int i, truncated, uri_len;
  10010. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  10011. return -1;
  10012. }
  10013. env->conn = conn;
  10014. env->buflen = CGI_ENVIRONMENT_SIZE;
  10015. env->bufused = 0;
  10016. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  10017. if (env->buf == NULL) {
  10018. mg_cry_internal(conn,
  10019. "%s: Not enough memory for environmental buffer",
  10020. __func__);
  10021. return -1;
  10022. }
  10023. env->varlen = MAX_CGI_ENVIR_VARS;
  10024. env->varused = 0;
  10025. env->var =
  10026. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  10027. if (env->var == NULL) {
  10028. mg_cry_internal(conn,
  10029. "%s: Not enough memory for environmental variables",
  10030. __func__);
  10031. mg_free(env->buf);
  10032. return -1;
  10033. }
  10034. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  10035. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10036. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10037. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  10038. addenv(env,
  10039. "FALLBACK_DOCUMENT_ROOT=%s",
  10040. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  10041. }
  10042. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  10043. /* Prepare the environment block */
  10044. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  10045. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  10046. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  10047. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  10048. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  10049. addenv(env, "REMOTE_ADDR=%s", src_addr);
  10050. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  10051. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  10052. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  10053. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  10054. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  10055. /* SCRIPT_NAME */
  10056. uri_len = (int)strlen(conn->request_info.local_uri);
  10057. if (conn->path_info == NULL) {
  10058. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  10059. /* URI: /path_to_script/script.cgi */
  10060. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  10061. } else {
  10062. /* URI: /path_to_script/ ... using index.cgi */
  10063. const char *index_file = strrchr(prog, '/');
  10064. if (index_file) {
  10065. addenv(env,
  10066. "SCRIPT_NAME=%s%s",
  10067. conn->request_info.local_uri,
  10068. index_file + 1);
  10069. }
  10070. }
  10071. } else {
  10072. /* URI: /path_to_script/script.cgi/path_info */
  10073. addenv(env,
  10074. "SCRIPT_NAME=%.*s",
  10075. uri_len - (int)strlen(conn->path_info),
  10076. conn->request_info.local_uri);
  10077. }
  10078. addenv(env, "SCRIPT_FILENAME=%s", prog);
  10079. if (conn->path_info == NULL) {
  10080. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  10081. } else {
  10082. addenv(env,
  10083. "PATH_TRANSLATED=%s%s",
  10084. conn->dom_ctx->config[DOCUMENT_ROOT],
  10085. conn->path_info);
  10086. }
  10087. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  10088. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  10089. addenv(env, "CONTENT_TYPE=%s", s);
  10090. }
  10091. if (conn->request_info.query_string != NULL) {
  10092. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  10093. }
  10094. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  10095. addenv(env, "CONTENT_LENGTH=%s", s);
  10096. }
  10097. if ((s = getenv("PATH")) != NULL) {
  10098. addenv(env, "PATH=%s", s);
  10099. }
  10100. if (conn->path_info != NULL) {
  10101. addenv(env, "PATH_INFO=%s", conn->path_info);
  10102. }
  10103. if (conn->status_code > 0) {
  10104. /* CGI error handler should show the status code */
  10105. addenv(env, "STATUS=%d", conn->status_code);
  10106. }
  10107. #if defined(_WIN32)
  10108. if ((s = getenv("COMSPEC")) != NULL) {
  10109. addenv(env, "COMSPEC=%s", s);
  10110. }
  10111. if ((s = getenv("SYSTEMROOT")) != NULL) {
  10112. addenv(env, "SYSTEMROOT=%s", s);
  10113. }
  10114. if ((s = getenv("SystemDrive")) != NULL) {
  10115. addenv(env, "SystemDrive=%s", s);
  10116. }
  10117. if ((s = getenv("ProgramFiles")) != NULL) {
  10118. addenv(env, "ProgramFiles=%s", s);
  10119. }
  10120. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  10121. addenv(env, "ProgramFiles(x86)=%s", s);
  10122. }
  10123. #else
  10124. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  10125. addenv(env, "LD_LIBRARY_PATH=%s", s);
  10126. }
  10127. #endif /* _WIN32 */
  10128. if ((s = getenv("PERLLIB")) != NULL) {
  10129. addenv(env, "PERLLIB=%s", s);
  10130. }
  10131. if (conn->request_info.remote_user != NULL) {
  10132. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  10133. addenv(env, "%s", "AUTH_TYPE=Digest");
  10134. }
  10135. /* Add all headers as HTTP_* variables */
  10136. for (i = 0; i < conn->request_info.num_headers; i++) {
  10137. (void)mg_snprintf(conn,
  10138. &truncated,
  10139. http_var_name,
  10140. sizeof(http_var_name),
  10141. "HTTP_%s",
  10142. conn->request_info.http_headers[i].name);
  10143. if (truncated) {
  10144. mg_cry_internal(conn,
  10145. "%s: HTTP header variable too long [%s]",
  10146. __func__,
  10147. conn->request_info.http_headers[i].name);
  10148. continue;
  10149. }
  10150. /* Convert variable name into uppercase, and change - to _ */
  10151. for (p = http_var_name; *p != '\0'; p++) {
  10152. if (*p == '-') {
  10153. *p = '_';
  10154. }
  10155. *p = (char)toupper((unsigned char)*p);
  10156. }
  10157. addenv(env,
  10158. "%s=%s",
  10159. http_var_name,
  10160. conn->request_info.http_headers[i].value);
  10161. }
  10162. /* Add user-specified variables */
  10163. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10164. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10165. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10166. }
  10167. env->var[env->varused] = NULL;
  10168. env->buf[env->bufused] = '\0';
  10169. return 0;
  10170. }
  10171. /* Data for CGI process control: PID and number of references */
  10172. struct process_control_data {
  10173. pid_t pid;
  10174. ptrdiff_t references;
  10175. };
  10176. static int
  10177. abort_cgi_process(void *data)
  10178. {
  10179. /* Waitpid checks for child status and won't work for a pid that does
  10180. * not identify a child of the current process. Thus, if the pid is
  10181. * reused, we will not affect a different process. */
  10182. struct process_control_data *proc = (struct process_control_data *)data;
  10183. int status = 0;
  10184. ptrdiff_t refs;
  10185. pid_t ret_pid;
  10186. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10187. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10188. /* Stop child process */
  10189. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10190. kill(proc->pid, SIGABRT);
  10191. /* Wait until process is terminated (don't leave zombies) */
  10192. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10193. ;
  10194. } else {
  10195. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10196. }
  10197. /* Dec reference counter */
  10198. refs = mg_atomic_dec(&proc->references);
  10199. if (refs == 0) {
  10200. /* no more references - free data */
  10201. mg_free(data);
  10202. }
  10203. return 0;
  10204. }
  10205. /* Local (static) function assumes all arguments are valid. */
  10206. static void
  10207. handle_cgi_request(struct mg_connection *conn,
  10208. const char *prog,
  10209. int cgi_config_idx)
  10210. {
  10211. char *buf;
  10212. size_t buflen;
  10213. int headers_len, data_len, i, truncated;
  10214. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10215. const char *status, *status_text;
  10216. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10217. struct mg_request_info ri;
  10218. struct cgi_environment blk;
  10219. FILE *in = NULL, *out = NULL, *err = NULL;
  10220. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10221. pid_t pid = (pid_t)-1;
  10222. struct process_control_data *proc = NULL;
  10223. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10224. int no_buffering = 0;
  10225. #if defined(USE_TIMERS)
  10226. double cgi_timeout;
  10227. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10228. /* Get timeout in seconds */
  10229. cgi_timeout =
  10230. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10231. } else {
  10232. cgi_timeout =
  10233. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10234. }
  10235. #endif
  10236. if (cfg_buffering != NULL) {
  10237. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10238. no_buffering = 1;
  10239. }
  10240. }
  10241. buf = NULL;
  10242. buflen = conn->phys_ctx->max_request_size;
  10243. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10244. if (i != 0) {
  10245. blk.buf = NULL;
  10246. blk.var = NULL;
  10247. goto done;
  10248. }
  10249. /* CGI must be executed in its own directory. 'dir' must point to the
  10250. * directory containing executable program, 'p' must point to the
  10251. * executable program name relative to 'dir'. */
  10252. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10253. if (truncated) {
  10254. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10255. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10256. goto done;
  10257. }
  10258. if ((p = strrchr(dir, '/')) != NULL) {
  10259. *p++ = '\0';
  10260. } else {
  10261. dir[0] = '.';
  10262. dir[1] = '\0';
  10263. p = (char *)prog;
  10264. }
  10265. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10266. status = strerror(ERRNO);
  10267. mg_cry_internal(
  10268. conn,
  10269. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10270. prog,
  10271. status);
  10272. mg_send_http_error(conn,
  10273. 500,
  10274. "Error: Cannot create CGI pipe: %s",
  10275. status);
  10276. goto done;
  10277. }
  10278. proc = (struct process_control_data *)
  10279. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10280. if (proc == NULL) {
  10281. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10282. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10283. goto done;
  10284. }
  10285. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10286. pid = spawn_process(
  10287. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10288. if (pid == (pid_t)-1) {
  10289. status = strerror(ERRNO);
  10290. mg_cry_internal(
  10291. conn,
  10292. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10293. prog,
  10294. status);
  10295. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10296. mg_free(proc);
  10297. proc = NULL;
  10298. goto done;
  10299. }
  10300. /* Store data in shared process_control_data */
  10301. proc->pid = pid;
  10302. proc->references = 1;
  10303. #if defined(USE_TIMERS)
  10304. if (cgi_timeout > 0.0) {
  10305. proc->references = 2;
  10306. // Start a timer for CGI
  10307. timer_add(conn->phys_ctx,
  10308. cgi_timeout /* in seconds */,
  10309. 0.0,
  10310. 1,
  10311. abort_cgi_process,
  10312. (void *)proc,
  10313. NULL);
  10314. }
  10315. #endif
  10316. /* Parent closes only one side of the pipes.
  10317. * If we don't mark them as closed, close() attempt before
  10318. * return from this function throws an exception on Windows.
  10319. * Windows does not like when closed descriptor is closed again. */
  10320. (void)close(fdin[0]);
  10321. (void)close(fdout[1]);
  10322. (void)close(fderr[1]);
  10323. fdin[0] = fdout[1] = fderr[1] = -1;
  10324. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10325. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10326. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10327. status = strerror(ERRNO);
  10328. mg_cry_internal(conn,
  10329. "Error: CGI program \"%s\": Can not open fd: %s",
  10330. prog,
  10331. status);
  10332. mg_send_http_error(conn,
  10333. 500,
  10334. "Error: CGI can not open fd\nfdopen: %s",
  10335. status);
  10336. goto done;
  10337. }
  10338. setbuf(in, NULL);
  10339. setbuf(out, NULL);
  10340. setbuf(err, NULL);
  10341. fout.access.fp = out;
  10342. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10343. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10344. conn->content_len);
  10345. /* This is a POST/PUT request, or another request with body data. */
  10346. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10347. /* Error sending the body data */
  10348. mg_cry_internal(
  10349. conn,
  10350. "Error: CGI program \"%s\": Forward body data failed",
  10351. prog);
  10352. goto done;
  10353. }
  10354. }
  10355. /* Close so child gets an EOF. */
  10356. fclose(in);
  10357. in = NULL;
  10358. fdin[1] = -1;
  10359. /* Now read CGI reply into a buffer. We need to set correct
  10360. * status code, thus we need to see all HTTP headers first.
  10361. * Do not send anything back to client, until we buffer in all
  10362. * HTTP headers. */
  10363. data_len = 0;
  10364. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10365. if (buf == NULL) {
  10366. mg_send_http_error(conn,
  10367. 500,
  10368. "Error: Not enough memory for CGI buffer (%u bytes)",
  10369. (unsigned int)buflen);
  10370. mg_cry_internal(
  10371. conn,
  10372. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10373. "bytes)",
  10374. prog,
  10375. (unsigned int)buflen);
  10376. goto done;
  10377. }
  10378. DEBUG_TRACE("CGI: %s", "wait for response");
  10379. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10380. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10381. if (headers_len <= 0) {
  10382. /* Could not parse the CGI response. Check if some error message on
  10383. * stderr. */
  10384. i = pull_all(err, conn, buf, (int)buflen);
  10385. if (i > 0) {
  10386. /* CGI program explicitly sent an error */
  10387. /* Write the error message to the internal log */
  10388. mg_cry_internal(conn,
  10389. "Error: CGI program \"%s\" sent error "
  10390. "message: [%.*s]",
  10391. prog,
  10392. i,
  10393. buf);
  10394. /* Don't send the error message back to the client */
  10395. mg_send_http_error(conn,
  10396. 500,
  10397. "Error: CGI program \"%s\" failed.",
  10398. prog);
  10399. } else {
  10400. /* CGI program did not explicitly send an error, but a broken
  10401. * respon header */
  10402. mg_cry_internal(conn,
  10403. "Error: CGI program sent malformed or too big "
  10404. "(>%u bytes) HTTP headers: [%.*s]",
  10405. (unsigned)buflen,
  10406. data_len,
  10407. buf);
  10408. mg_send_http_error(conn,
  10409. 500,
  10410. "Error: CGI program sent malformed or too big "
  10411. "(>%u bytes) HTTP headers: [%.*s]",
  10412. (unsigned)buflen,
  10413. data_len,
  10414. buf);
  10415. }
  10416. /* in both cases, abort processing CGI */
  10417. goto done;
  10418. }
  10419. pbuf = buf;
  10420. buf[headers_len - 1] = '\0';
  10421. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10422. /* Make up and send the status line */
  10423. status_text = "OK";
  10424. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10425. != NULL) {
  10426. conn->status_code = atoi(status);
  10427. status_text = status;
  10428. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10429. status_text++;
  10430. }
  10431. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10432. != NULL) {
  10433. conn->status_code = 307;
  10434. } else {
  10435. conn->status_code = 200;
  10436. }
  10437. if (!should_keep_alive(conn)) {
  10438. conn->must_close = 1;
  10439. }
  10440. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10441. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10442. /* Send headers */
  10443. for (i = 0; i < ri.num_headers; i++) {
  10444. DEBUG_TRACE("CGI header: %s: %s",
  10445. ri.http_headers[i].name,
  10446. ri.http_headers[i].value);
  10447. mg_printf(conn,
  10448. "%s: %s\r\n",
  10449. ri.http_headers[i].name,
  10450. ri.http_headers[i].value);
  10451. }
  10452. mg_write(conn, "\r\n", 2);
  10453. /* Send chunk of data that may have been read after the headers */
  10454. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10455. /* Read the rest of CGI output and send to the client */
  10456. DEBUG_TRACE("CGI: %s", "forward all data");
  10457. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10458. DEBUG_TRACE("CGI: %s", "all data sent");
  10459. done:
  10460. mg_free(blk.var);
  10461. mg_free(blk.buf);
  10462. if (pid != (pid_t)-1) {
  10463. abort_cgi_process((void *)proc);
  10464. }
  10465. if (fdin[0] != -1) {
  10466. close(fdin[0]);
  10467. }
  10468. if (fdout[1] != -1) {
  10469. close(fdout[1]);
  10470. }
  10471. if (fderr[1] != -1) {
  10472. close(fderr[1]);
  10473. }
  10474. if (in != NULL) {
  10475. fclose(in);
  10476. } else if (fdin[1] != -1) {
  10477. close(fdin[1]);
  10478. }
  10479. if (out != NULL) {
  10480. fclose(out);
  10481. } else if (fdout[0] != -1) {
  10482. close(fdout[0]);
  10483. }
  10484. if (err != NULL) {
  10485. fclose(err);
  10486. } else if (fderr[0] != -1) {
  10487. close(fderr[0]);
  10488. }
  10489. mg_free(buf);
  10490. }
  10491. #endif /* !NO_CGI */
  10492. #if !defined(NO_FILES)
  10493. static void
  10494. dav_mkcol(struct mg_connection *conn, const char *path)
  10495. {
  10496. int rc, body_len;
  10497. struct de de;
  10498. if (conn == NULL) {
  10499. return;
  10500. }
  10501. /* TODO (mid): Check the mg_send_http_error situations in this function
  10502. */
  10503. memset(&de.file, 0, sizeof(de.file));
  10504. if (!mg_stat(conn, path, &de.file)) {
  10505. mg_cry_internal(conn,
  10506. "%s: mg_stat(%s) failed: %s",
  10507. __func__,
  10508. path,
  10509. strerror(ERRNO));
  10510. }
  10511. if (de.file.last_modified) {
  10512. /* TODO (mid): This check does not seem to make any sense ! */
  10513. /* TODO (mid): Add a webdav unit test first, before changing
  10514. * anything here. */
  10515. mg_send_http_error(
  10516. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10517. return;
  10518. }
  10519. body_len = conn->data_len - conn->request_len;
  10520. if (body_len > 0) {
  10521. mg_send_http_error(
  10522. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10523. return;
  10524. }
  10525. rc = mg_mkdir(conn, path, 0755);
  10526. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10527. if (rc == 0) {
  10528. /* Create 201 "Created" response */
  10529. mg_response_header_start(conn, 201);
  10530. send_static_cache_header(conn);
  10531. send_additional_header(conn);
  10532. mg_response_header_add(conn, "Content-Length", "0", -1);
  10533. /* Send all headers - there is no body */
  10534. mg_response_header_send(conn);
  10535. } else {
  10536. int http_status = 500;
  10537. switch (errno) {
  10538. case EEXIST:
  10539. http_status = 405;
  10540. break;
  10541. case EACCES:
  10542. http_status = 403;
  10543. break;
  10544. case ENOENT:
  10545. http_status = 409;
  10546. break;
  10547. }
  10548. mg_send_http_error(conn,
  10549. http_status,
  10550. "Error processing %s: %s",
  10551. path,
  10552. strerror(ERRNO));
  10553. }
  10554. }
  10555. /* Forward decrlaration */
  10556. static int get_uri_type(const char *uri);
  10557. static const char *
  10558. get_rel_url_at_current_server(const char *uri,
  10559. const struct mg_connection *conn);
  10560. static void
  10561. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10562. {
  10563. const char *overwrite_hdr;
  10564. const char *destination_hdr;
  10565. const char *root;
  10566. int rc, dest_uri_type;
  10567. int http_status = 400;
  10568. int do_overwrite = 0;
  10569. int destination_ok = 0;
  10570. char dest_path[UTF8_PATH_MAX];
  10571. struct mg_file_stat ignored;
  10572. if (conn == NULL) {
  10573. return;
  10574. }
  10575. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10576. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10577. destination_hdr = mg_get_header(conn, "Destination");
  10578. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10579. do_overwrite = 1;
  10580. }
  10581. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10582. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10583. return;
  10584. }
  10585. if (root != NULL) {
  10586. char *local_dest = NULL;
  10587. dest_uri_type = get_uri_type(destination_hdr);
  10588. if (dest_uri_type == 2) {
  10589. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10590. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10591. const char *h =
  10592. get_rel_url_at_current_server(destination_hdr, conn);
  10593. if (h) {
  10594. size_t len = strlen(h);
  10595. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10596. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10597. }
  10598. }
  10599. if (local_dest != NULL) {
  10600. remove_dot_segments(local_dest);
  10601. if (local_dest[0] == '/') {
  10602. int trunc_check = 0;
  10603. mg_snprintf(conn,
  10604. &trunc_check,
  10605. dest_path,
  10606. sizeof(dest_path),
  10607. "%s/%s",
  10608. root,
  10609. local_dest);
  10610. if (trunc_check == 0) {
  10611. destination_ok = 1;
  10612. }
  10613. }
  10614. mg_free(local_dest);
  10615. }
  10616. }
  10617. if (!destination_ok) {
  10618. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10619. return;
  10620. }
  10621. /* Check now if this file exists */
  10622. if (mg_stat(conn, dest_path, &ignored)) {
  10623. /* File exists */
  10624. if (do_overwrite) {
  10625. /* Overwrite allowed: delete the file first */
  10626. if (0 != remove(dest_path)) {
  10627. /* No overwrite: return error */
  10628. mg_send_http_error(conn,
  10629. 403,
  10630. "Cannot overwrite file: %s",
  10631. dest_path);
  10632. return;
  10633. }
  10634. } else {
  10635. /* No overwrite: return error */
  10636. mg_send_http_error(conn,
  10637. 412,
  10638. "Destination already exists: %s",
  10639. dest_path);
  10640. return;
  10641. }
  10642. }
  10643. /* Copy / Move / Rename operation. */
  10644. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10645. #if defined(_WIN32)
  10646. {
  10647. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10648. wchar_t wSource[UTF16_PATH_MAX];
  10649. wchar_t wDest[UTF16_PATH_MAX];
  10650. BOOL ok;
  10651. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10652. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10653. if (do_copy) {
  10654. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10655. } else {
  10656. ok = MoveFileExW(wSource,
  10657. wDest,
  10658. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10659. }
  10660. if (ok) {
  10661. rc = 0;
  10662. } else {
  10663. DWORD lastErr = GetLastError();
  10664. if (lastErr == ERROR_ALREADY_EXISTS) {
  10665. mg_send_http_error(conn,
  10666. 412,
  10667. "Destination already exists: %s",
  10668. dest_path);
  10669. return;
  10670. }
  10671. rc = -1;
  10672. http_status = 400;
  10673. }
  10674. }
  10675. #else
  10676. {
  10677. /* Linux uses already UTF-8, we don't need to convert file names. */
  10678. if (do_copy) {
  10679. /* TODO: COPY for Linux. */
  10680. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10681. return;
  10682. }
  10683. rc = rename(path, dest_path);
  10684. if (rc) {
  10685. switch (errno) {
  10686. case EEXIST:
  10687. http_status = 412;
  10688. break;
  10689. case EACCES:
  10690. http_status = 403;
  10691. break;
  10692. case ENOENT:
  10693. http_status = 409;
  10694. break;
  10695. }
  10696. }
  10697. }
  10698. #endif
  10699. if (rc == 0) {
  10700. /* Create 204 "No Content" response */
  10701. mg_response_header_start(conn, 204);
  10702. mg_response_header_add(conn, "Content-Length", "0", -1);
  10703. /* Send all headers - there is no body */
  10704. mg_response_header_send(conn);
  10705. } else {
  10706. mg_send_http_error(conn, http_status, "Operation failed");
  10707. }
  10708. }
  10709. static void
  10710. put_file(struct mg_connection *conn, const char *path)
  10711. {
  10712. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10713. const char *range;
  10714. int64_t r1, r2;
  10715. int rc;
  10716. if (conn == NULL) {
  10717. return;
  10718. }
  10719. DEBUG_TRACE("store %s", path);
  10720. if (mg_stat(conn, path, &file.stat)) {
  10721. /* File already exists */
  10722. conn->status_code = 200;
  10723. if (file.stat.is_directory) {
  10724. /* This is an already existing directory,
  10725. * so there is nothing to do for the server. */
  10726. rc = 0;
  10727. } else {
  10728. /* File exists and is not a directory. */
  10729. /* Can it be replaced? */
  10730. /* Check if the server may write this file */
  10731. if (access(path, W_OK) == 0) {
  10732. /* Access granted */
  10733. rc = 1;
  10734. } else {
  10735. mg_send_http_error(
  10736. conn,
  10737. 403,
  10738. "Error: Put not possible\nReplacing %s is not allowed",
  10739. path);
  10740. return;
  10741. }
  10742. }
  10743. } else {
  10744. /* File should be created */
  10745. conn->status_code = 201;
  10746. rc = put_dir(conn, path);
  10747. }
  10748. if (rc == 0) {
  10749. /* put_dir returns 0 if path is a directory */
  10750. /* Create response */
  10751. mg_response_header_start(conn, conn->status_code);
  10752. send_no_cache_header(conn);
  10753. send_additional_header(conn);
  10754. mg_response_header_add(conn, "Content-Length", "0", -1);
  10755. /* Send all headers - there is no body */
  10756. mg_response_header_send(conn);
  10757. /* Request to create a directory has been fulfilled successfully.
  10758. * No need to put a file. */
  10759. return;
  10760. }
  10761. if (rc == -1) {
  10762. /* put_dir returns -1 if the path is too long */
  10763. mg_send_http_error(conn,
  10764. 414,
  10765. "Error: Path too long\nput_dir(%s): %s",
  10766. path,
  10767. strerror(ERRNO));
  10768. return;
  10769. }
  10770. if (rc == -2) {
  10771. /* put_dir returns -2 if the directory can not be created */
  10772. mg_send_http_error(conn,
  10773. 500,
  10774. "Error: Can not create directory\nput_dir(%s): %s",
  10775. path,
  10776. strerror(ERRNO));
  10777. return;
  10778. }
  10779. /* A file should be created or overwritten. */
  10780. /* Currently CivetWeb does not need read+write access. */
  10781. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10782. || file.access.fp == NULL) {
  10783. (void)mg_fclose(&file.access);
  10784. mg_send_http_error(conn,
  10785. 500,
  10786. "Error: Can not create file\nfopen(%s): %s",
  10787. path,
  10788. strerror(ERRNO));
  10789. return;
  10790. }
  10791. fclose_on_exec(&file.access, conn);
  10792. range = mg_get_header(conn, "Content-Range");
  10793. r1 = r2 = 0;
  10794. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10795. conn->status_code = 206; /* Partial content */
  10796. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10797. mg_send_http_error(conn,
  10798. 500,
  10799. "Error: Internal error processing file %s",
  10800. path);
  10801. return;
  10802. }
  10803. }
  10804. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10805. /* forward_body_data failed.
  10806. * The error code has already been sent to the client,
  10807. * and conn->status_code is already set. */
  10808. (void)mg_fclose(&file.access);
  10809. return;
  10810. }
  10811. if (mg_fclose(&file.access) != 0) {
  10812. /* fclose failed. This might have different reasons, but a likely
  10813. * one is "no space on disk", http 507. */
  10814. conn->status_code = 507;
  10815. }
  10816. /* Create response (status_code has been set before) */
  10817. mg_response_header_start(conn, conn->status_code);
  10818. send_no_cache_header(conn);
  10819. send_additional_header(conn);
  10820. mg_response_header_add(conn, "Content-Length", "0", -1);
  10821. /* Send all headers - there is no body */
  10822. mg_response_header_send(conn);
  10823. }
  10824. static void
  10825. delete_file(struct mg_connection *conn, const char *path)
  10826. {
  10827. struct de de;
  10828. memset(&de.file, 0, sizeof(de.file));
  10829. if (!mg_stat(conn, path, &de.file)) {
  10830. /* mg_stat returns 0 if the file does not exist */
  10831. mg_send_http_error(conn,
  10832. 404,
  10833. "Error: Cannot delete file\nFile %s not found",
  10834. path);
  10835. return;
  10836. }
  10837. DEBUG_TRACE("delete %s", path);
  10838. if (de.file.is_directory) {
  10839. if (remove_directory(conn, path)) {
  10840. /* Delete is successful: Return 204 without content. */
  10841. mg_send_http_error(conn, 204, "%s", "");
  10842. } else {
  10843. /* Delete is not successful: Return 500 (Server error). */
  10844. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10845. }
  10846. return;
  10847. }
  10848. /* This is an existing file (not a directory).
  10849. * Check if write permission is granted. */
  10850. if (access(path, W_OK) != 0) {
  10851. /* File is read only */
  10852. mg_send_http_error(
  10853. conn,
  10854. 403,
  10855. "Error: Delete not possible\nDeleting %s is not allowed",
  10856. path);
  10857. return;
  10858. }
  10859. /* Try to delete it. */
  10860. if (mg_remove(conn, path) == 0) {
  10861. /* Delete was successful: Return 204 without content. */
  10862. mg_response_header_start(conn, 204);
  10863. send_no_cache_header(conn);
  10864. send_additional_header(conn);
  10865. mg_response_header_add(conn, "Content-Length", "0", -1);
  10866. mg_response_header_send(conn);
  10867. } else {
  10868. /* Delete not successful (file locked). */
  10869. mg_send_http_error(conn,
  10870. 423,
  10871. "Error: Cannot delete file\nremove(%s): %s",
  10872. path,
  10873. strerror(ERRNO));
  10874. }
  10875. }
  10876. #endif /* !NO_FILES */
  10877. #if !defined(NO_FILESYSTEMS)
  10878. static void
  10879. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10880. static void
  10881. do_ssi_include(struct mg_connection *conn,
  10882. const char *ssi,
  10883. char *tag,
  10884. int include_level)
  10885. {
  10886. char file_name[MG_BUF_LEN], path[512], *p;
  10887. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10888. size_t len;
  10889. int truncated = 0;
  10890. if (conn == NULL) {
  10891. return;
  10892. }
  10893. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10894. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10895. * always < MG_BUF_LEN. */
  10896. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10897. /* File name is relative to the webserver root */
  10898. file_name[511] = 0;
  10899. (void)mg_snprintf(conn,
  10900. &truncated,
  10901. path,
  10902. sizeof(path),
  10903. "%s/%s",
  10904. conn->dom_ctx->config[DOCUMENT_ROOT],
  10905. file_name);
  10906. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10907. /* File name is relative to the webserver working directory
  10908. * or it is absolute system path */
  10909. file_name[511] = 0;
  10910. (void)
  10911. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10912. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10913. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10914. /* File name is relative to the current document */
  10915. file_name[511] = 0;
  10916. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10917. if (!truncated) {
  10918. if ((p = strrchr(path, '/')) != NULL) {
  10919. p[1] = '\0';
  10920. }
  10921. len = strlen(path);
  10922. (void)mg_snprintf(conn,
  10923. &truncated,
  10924. path + len,
  10925. sizeof(path) - len,
  10926. "%s",
  10927. file_name);
  10928. }
  10929. } else {
  10930. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10931. return;
  10932. }
  10933. if (truncated) {
  10934. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10935. return;
  10936. }
  10937. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10938. mg_cry_internal(conn,
  10939. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10940. tag,
  10941. path,
  10942. strerror(ERRNO));
  10943. } else {
  10944. fclose_on_exec(&file.access, conn);
  10945. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10946. > 0) {
  10947. send_ssi_file(conn, path, &file, include_level + 1);
  10948. } else {
  10949. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10950. }
  10951. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10952. }
  10953. }
  10954. #if !defined(NO_POPEN)
  10955. static void
  10956. do_ssi_exec(struct mg_connection *conn, char *tag)
  10957. {
  10958. char cmd[1024] = "";
  10959. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10960. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10961. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10962. } else {
  10963. cmd[1023] = 0;
  10964. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10965. mg_cry_internal(conn,
  10966. "Cannot SSI #exec: [%s]: %s",
  10967. cmd,
  10968. strerror(ERRNO));
  10969. } else {
  10970. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10971. pclose(file.access.fp);
  10972. }
  10973. }
  10974. }
  10975. #endif /* !NO_POPEN */
  10976. static int
  10977. mg_fgetc(struct mg_file *filep)
  10978. {
  10979. if (filep == NULL) {
  10980. return EOF;
  10981. }
  10982. if (filep->access.fp != NULL) {
  10983. return fgetc(filep->access.fp);
  10984. } else {
  10985. return EOF;
  10986. }
  10987. }
  10988. static void
  10989. send_ssi_file(struct mg_connection *conn,
  10990. const char *path,
  10991. struct mg_file *filep,
  10992. int include_level)
  10993. {
  10994. char buf[MG_BUF_LEN];
  10995. int ch, len, in_tag, in_ssi_tag;
  10996. if (include_level > 10) {
  10997. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10998. return;
  10999. }
  11000. in_tag = in_ssi_tag = len = 0;
  11001. /* Read file, byte by byte, and look for SSI include tags */
  11002. while ((ch = mg_fgetc(filep)) != EOF) {
  11003. if (in_tag) {
  11004. /* We are in a tag, either SSI tag or html tag */
  11005. if (ch == '>') {
  11006. /* Tag is closing */
  11007. buf[len++] = '>';
  11008. if (in_ssi_tag) {
  11009. /* Handle SSI tag */
  11010. buf[len] = 0;
  11011. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  11012. do_ssi_include(conn, path, buf + 12, include_level + 1);
  11013. #if !defined(NO_POPEN)
  11014. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  11015. do_ssi_exec(conn, buf + 9);
  11016. #endif /* !NO_POPEN */
  11017. } else {
  11018. mg_cry_internal(conn,
  11019. "%s: unknown SSI "
  11020. "command: \"%s\"",
  11021. path,
  11022. buf);
  11023. }
  11024. len = 0;
  11025. in_ssi_tag = in_tag = 0;
  11026. } else {
  11027. /* Not an SSI tag */
  11028. /* Flush buffer */
  11029. (void)mg_write(conn, buf, (size_t)len);
  11030. len = 0;
  11031. in_tag = 0;
  11032. }
  11033. } else {
  11034. /* Tag is still open */
  11035. buf[len++] = (char)(ch & 0xff);
  11036. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  11037. /* All SSI tags start with <!--# */
  11038. in_ssi_tag = 1;
  11039. }
  11040. if ((len + 2) > (int)sizeof(buf)) {
  11041. /* Tag to long for buffer */
  11042. mg_cry_internal(conn, "%s: tag is too large", path);
  11043. return;
  11044. }
  11045. }
  11046. } else {
  11047. /* We are not in a tag yet. */
  11048. if (ch == '<') {
  11049. /* Tag is opening */
  11050. in_tag = 1;
  11051. if (len > 0) {
  11052. /* Flush current buffer.
  11053. * Buffer is filled with "len" bytes. */
  11054. (void)mg_write(conn, buf, (size_t)len);
  11055. }
  11056. /* Store the < */
  11057. len = 1;
  11058. buf[0] = '<';
  11059. } else {
  11060. /* No Tag */
  11061. /* Add data to buffer */
  11062. buf[len++] = (char)(ch & 0xff);
  11063. /* Flush if buffer is full */
  11064. if (len == (int)sizeof(buf)) {
  11065. mg_write(conn, buf, (size_t)len);
  11066. len = 0;
  11067. }
  11068. }
  11069. }
  11070. }
  11071. /* Send the rest of buffered data */
  11072. if (len > 0) {
  11073. mg_write(conn, buf, (size_t)len);
  11074. }
  11075. }
  11076. static void
  11077. handle_ssi_file_request(struct mg_connection *conn,
  11078. const char *path,
  11079. struct mg_file *filep)
  11080. {
  11081. char date[64];
  11082. time_t curtime = time(NULL);
  11083. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  11084. return;
  11085. }
  11086. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  11087. /* File exists (precondition for calling this function),
  11088. * but can not be opened by the server. */
  11089. mg_send_http_error(conn,
  11090. 500,
  11091. "Error: Cannot read file\nfopen(%s): %s",
  11092. path,
  11093. strerror(ERRNO));
  11094. } else {
  11095. /* Set "must_close" for HTTP/1.x, since we do not know the
  11096. * content length */
  11097. conn->must_close = 1;
  11098. gmt_time_string(date, sizeof(date), &curtime);
  11099. fclose_on_exec(&filep->access, conn);
  11100. /* 200 OK response */
  11101. mg_response_header_start(conn, 200);
  11102. send_no_cache_header(conn);
  11103. send_additional_header(conn);
  11104. send_cors_header(conn);
  11105. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11106. mg_response_header_send(conn);
  11107. /* Header sent, now send body */
  11108. send_ssi_file(conn, path, filep, 0);
  11109. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  11110. }
  11111. }
  11112. #endif /* NO_FILESYSTEMS */
  11113. #if !defined(NO_FILES)
  11114. static void
  11115. send_options(struct mg_connection *conn)
  11116. {
  11117. if (!conn || !all_methods) {
  11118. return;
  11119. }
  11120. /* We do not set a "Cache-Control" header here, but leave the default.
  11121. * Since browsers do not send an OPTIONS request, we can not test the
  11122. * effect anyway. */
  11123. mg_response_header_start(conn, 200);
  11124. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  11125. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  11126. /* Use the same as before */
  11127. mg_response_header_add(conn, "Allow", all_methods, -1);
  11128. mg_response_header_add(conn, "DAV", "1", -1);
  11129. } else {
  11130. /* TODO: Check this later for HTTP/2 */
  11131. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  11132. }
  11133. send_additional_header(conn);
  11134. mg_response_header_send(conn);
  11135. }
  11136. /* Writes PROPFIND properties for a collection element */
  11137. static int
  11138. print_props(struct mg_connection *conn,
  11139. const char *uri,
  11140. const char *name,
  11141. struct mg_file_stat *filep)
  11142. {
  11143. size_t i;
  11144. char mtime[64];
  11145. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11146. char *link_concat;
  11147. size_t link_concat_len;
  11148. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11149. return 0;
  11150. }
  11151. link_concat_len = strlen(uri) + strlen(name) + 1;
  11152. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11153. if (!link_concat) {
  11154. return 0;
  11155. }
  11156. strcpy(link_concat, uri);
  11157. strcat(link_concat, name);
  11158. /* Get full link used in request */
  11159. mg_construct_local_link(
  11160. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11161. /*
  11162. OutputDebugStringA("print_props:\n uri: ");
  11163. OutputDebugStringA(uri);
  11164. OutputDebugStringA("\n name: ");
  11165. OutputDebugStringA(name);
  11166. OutputDebugStringA("\n link: ");
  11167. OutputDebugStringA(link_buf);
  11168. OutputDebugStringA("\n");
  11169. */
  11170. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11171. mg_printf(conn,
  11172. "<d:response>"
  11173. "<d:href>%s</d:href>"
  11174. "<d:propstat>"
  11175. "<d:prop>"
  11176. "<d:resourcetype>%s</d:resourcetype>"
  11177. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11178. "<d:getlastmodified>%s</d:getlastmodified>"
  11179. "<d:lockdiscovery>",
  11180. link_buf,
  11181. filep->is_directory ? "<d:collection/>" : "",
  11182. filep->size,
  11183. mtime);
  11184. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11185. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11186. if (!strcmp(dav_lock[i].path, link_buf)) {
  11187. mg_printf(conn,
  11188. "<d:activelock>"
  11189. "<d:locktype><d:write/></d:locktype>"
  11190. "<d:lockscope><d:exclusive/></d:lockscope>"
  11191. "<d:depth>0</d:depth>"
  11192. "<d:owner>%s</d:owner>"
  11193. "<d:timeout>Second-%u</d:timeout>"
  11194. "<d:locktoken>"
  11195. "<d:href>%s</d:href>"
  11196. "</d:locktoken>"
  11197. "</d:activelock>\n",
  11198. dav_lock[i].user,
  11199. (unsigned)LOCK_DURATION_S,
  11200. dav_lock[i].token);
  11201. }
  11202. }
  11203. mg_printf(conn,
  11204. "</d:lockdiscovery>"
  11205. "</d:prop>"
  11206. "<d:status>HTTP/1.1 200 OK</d:status>"
  11207. "</d:propstat>"
  11208. "</d:response>\n");
  11209. mg_free(link_concat);
  11210. return 1;
  11211. }
  11212. static int
  11213. print_dav_dir_entry(struct de *de, void *data)
  11214. {
  11215. struct mg_connection *conn = (struct mg_connection *)data;
  11216. if (!de || !conn
  11217. || !print_props(
  11218. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11219. /* stop scan */
  11220. return 1;
  11221. }
  11222. return 0;
  11223. }
  11224. static void
  11225. handle_propfind(struct mg_connection *conn,
  11226. const char *path,
  11227. struct mg_file_stat *filep)
  11228. {
  11229. const char *depth = mg_get_header(conn, "Depth");
  11230. if (!conn || !path || !filep || !conn->dom_ctx) {
  11231. return;
  11232. }
  11233. /* return 207 "Multi-Status" */
  11234. conn->must_close = 1;
  11235. mg_response_header_start(conn, 207);
  11236. send_static_cache_header(conn);
  11237. send_additional_header(conn);
  11238. mg_response_header_add(conn,
  11239. "Content-Type",
  11240. "application/xml; charset=utf-8",
  11241. -1);
  11242. mg_response_header_send(conn);
  11243. /* Content */
  11244. mg_printf(conn,
  11245. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11246. "<d:multistatus xmlns:d='DAV:'>\n");
  11247. /* Print properties for the requested resource itself */
  11248. print_props(conn, conn->request_info.local_uri, "", filep);
  11249. /* If it is a directory, print directory entries too if Depth is not 0
  11250. */
  11251. if (filep->is_directory
  11252. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11253. "yes")
  11254. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11255. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11256. }
  11257. mg_printf(conn, "%s\n", "</d:multistatus>");
  11258. }
  11259. static void
  11260. dav_lock_file(struct mg_connection *conn, const char *path)
  11261. {
  11262. /* internal function - therefore conn is assumed to be valid */
  11263. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11264. uint64_t new_locktime;
  11265. int lock_index = -1;
  11266. int i;
  11267. uint64_t LOCK_DURATION_NS =
  11268. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11269. struct twebdav_lock *dav_lock = NULL;
  11270. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11271. || !conn->phys_ctx) {
  11272. return;
  11273. }
  11274. dav_lock = conn->phys_ctx->webdav_lock;
  11275. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11276. /* const char *refresh = mg_get_header(conn, "If"); */
  11277. /* Link refresh should have an "If" header:
  11278. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11279. * But it seems Windows Explorer does not send them.
  11280. */
  11281. mg_lock_context(conn->phys_ctx);
  11282. new_locktime = mg_get_current_time_ns();
  11283. /* Find a slot for a lock */
  11284. while (lock_index < 0) {
  11285. /* find existing lock */
  11286. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11287. if (!strcmp(dav_lock[i].path, link_buf)) {
  11288. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11289. /* locked by the same user */
  11290. dav_lock[i].locktime = new_locktime;
  11291. lock_index = i;
  11292. break;
  11293. } else {
  11294. /* already locked by someone else */
  11295. if (new_locktime
  11296. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11297. /* Lock expired */
  11298. dav_lock[i].path[0] = 0;
  11299. } else {
  11300. /* Lock still valid */
  11301. mg_unlock_context(conn->phys_ctx);
  11302. mg_send_http_error(conn, 423, "%s", "Already locked");
  11303. return;
  11304. }
  11305. }
  11306. }
  11307. }
  11308. /* create new lock token */
  11309. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11310. if (dav_lock[i].path[0] == 0) {
  11311. char s[32];
  11312. dav_lock[i].locktime = mg_get_current_time_ns();
  11313. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11314. mg_md5(dav_lock[i].token,
  11315. link_buf,
  11316. "\x01",
  11317. s,
  11318. "\x01",
  11319. conn->request_info.remote_user,
  11320. NULL);
  11321. mg_strlcpy(dav_lock[i].path,
  11322. link_buf,
  11323. sizeof(dav_lock[i].path));
  11324. mg_strlcpy(dav_lock[i].user,
  11325. conn->request_info.remote_user,
  11326. sizeof(dav_lock[i].user));
  11327. lock_index = i;
  11328. break;
  11329. }
  11330. }
  11331. if (lock_index < 0) {
  11332. /* too many locks. Find oldest lock */
  11333. uint64_t oldest_locktime = dav_lock[0].locktime;
  11334. lock_index = 0;
  11335. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11336. if (dav_lock[i].locktime < oldest_locktime) {
  11337. oldest_locktime = dav_lock[i].locktime;
  11338. lock_index = i;
  11339. }
  11340. }
  11341. /* invalidate oldest lock */
  11342. dav_lock[lock_index].path[0] = 0;
  11343. }
  11344. }
  11345. mg_unlock_context(conn->phys_ctx);
  11346. /* return 200 "OK" */
  11347. conn->must_close = 1;
  11348. mg_response_header_start(conn, 200);
  11349. send_static_cache_header(conn);
  11350. send_additional_header(conn);
  11351. mg_response_header_add(conn,
  11352. "Content-Type",
  11353. "application/xml; charset=utf-8",
  11354. -1);
  11355. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11356. mg_response_header_send(conn);
  11357. /* Content */
  11358. mg_printf(conn,
  11359. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11360. "<d:prop xmlns:d=\"DAV:\">\n"
  11361. " <d:lockdiscovery>\n"
  11362. " <d:activelock>\n"
  11363. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11364. " <d:locktype><d:write/></d:locktype>\n"
  11365. " <d:owner>\n"
  11366. " <d:href>%s</d:href>\n"
  11367. " </d:owner>\n"
  11368. " <d:timeout>Second-%u</d:timeout>\n"
  11369. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11370. " <d:lockroot>\n"
  11371. " <d:href>%s</d:href>\n"
  11372. " </d:lockroot>\n"
  11373. " </d:activelock>\n"
  11374. " </d:lockdiscovery>\n"
  11375. " </d:prop>\n",
  11376. dav_lock[lock_index].user,
  11377. (LOCK_DURATION_S),
  11378. dav_lock[lock_index].token,
  11379. dav_lock[lock_index].path);
  11380. }
  11381. static void
  11382. dav_unlock_file(struct mg_connection *conn, const char *path)
  11383. {
  11384. /* internal function - therefore conn is assumed to be valid */
  11385. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11386. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11387. int lock_index;
  11388. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11389. return;
  11390. }
  11391. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11392. mg_lock_context(conn->phys_ctx);
  11393. /* find existing lock */
  11394. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11395. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11396. /* Success: return 204 "No Content" */
  11397. mg_unlock_context(conn->phys_ctx);
  11398. conn->must_close = 1;
  11399. mg_response_header_start(conn, 204);
  11400. mg_response_header_send(conn);
  11401. return;
  11402. }
  11403. }
  11404. mg_unlock_context(conn->phys_ctx);
  11405. /* Error: Cannot unlock a resource that is not locked */
  11406. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11407. }
  11408. static void
  11409. dav_proppatch(struct mg_connection *conn, const char *path)
  11410. {
  11411. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11412. if (!conn || !path || !conn->dom_ctx) {
  11413. return;
  11414. }
  11415. /* return 207 "Multi-Status" */
  11416. conn->must_close = 1;
  11417. mg_response_header_start(conn, 207);
  11418. send_static_cache_header(conn);
  11419. send_additional_header(conn);
  11420. mg_response_header_add(conn,
  11421. "Content-Type",
  11422. "application/xml; charset=utf-8",
  11423. -1);
  11424. mg_response_header_send(conn);
  11425. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11426. /* Content */
  11427. mg_printf(conn,
  11428. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11429. "<d:multistatus xmlns:d='DAV:'>\n"
  11430. "<d:response>\n<d:href>%s</d:href>\n",
  11431. link_buf);
  11432. mg_printf(conn,
  11433. "<d:propstat><d:status>HTTP/1.1 403 "
  11434. "Forbidden</d:status></d:propstat>\n");
  11435. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11436. }
  11437. #endif
  11438. CIVETWEB_API void
  11439. mg_lock_connection(struct mg_connection *conn)
  11440. {
  11441. if (conn) {
  11442. (void)pthread_mutex_lock(&conn->mutex);
  11443. }
  11444. }
  11445. CIVETWEB_API void
  11446. mg_unlock_connection(struct mg_connection *conn)
  11447. {
  11448. if (conn) {
  11449. (void)pthread_mutex_unlock(&conn->mutex);
  11450. }
  11451. }
  11452. CIVETWEB_API void
  11453. mg_lock_context(struct mg_context *ctx)
  11454. {
  11455. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11456. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11457. }
  11458. }
  11459. CIVETWEB_API void
  11460. mg_unlock_context(struct mg_context *ctx)
  11461. {
  11462. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11463. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11464. }
  11465. }
  11466. #if defined(USE_LUA)
  11467. #include "mod_lua.inl"
  11468. #endif /* USE_LUA */
  11469. #if defined(USE_DUKTAPE)
  11470. #include "mod_duktape.inl"
  11471. #endif /* USE_DUKTAPE */
  11472. #if defined(USE_WEBSOCKET)
  11473. #if !defined(NO_SSL_DL)
  11474. #if !defined(OPENSSL_API_3_0)
  11475. #define SHA_API static
  11476. #include "sha1.inl"
  11477. #endif
  11478. #endif
  11479. static int
  11480. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11481. {
  11482. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11483. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11484. size_t dst_len = sizeof(b64_sha);
  11485. #if !defined(OPENSSL_API_3_0)
  11486. SHA_CTX sha_ctx;
  11487. #endif
  11488. int truncated;
  11489. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11490. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11491. if (truncated) {
  11492. conn->must_close = 1;
  11493. return 0;
  11494. }
  11495. DEBUG_TRACE("%s", "Send websocket handshake");
  11496. #if defined(OPENSSL_API_3_0)
  11497. EVP_Digest((unsigned char *)buf,
  11498. (uint32_t)strlen(buf),
  11499. (unsigned char *)sha,
  11500. NULL,
  11501. EVP_get_digestbyname("sha1"),
  11502. NULL);
  11503. #else
  11504. SHA1_Init(&sha_ctx);
  11505. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11506. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11507. #endif
  11508. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11509. mg_printf(conn,
  11510. "HTTP/1.1 101 Switching Protocols\r\n"
  11511. "Upgrade: websocket\r\n"
  11512. "Connection: Upgrade\r\n"
  11513. "Sec-WebSocket-Accept: %s\r\n",
  11514. b64_sha);
  11515. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11516. // Send negotiated compression extension parameters
  11517. websocket_deflate_response(conn);
  11518. #endif
  11519. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11520. mg_printf(conn,
  11521. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11522. conn->request_info.acceptedWebSocketSubprotocol);
  11523. } else {
  11524. mg_printf(conn, "%s", "\r\n");
  11525. }
  11526. return 1;
  11527. }
  11528. #if !defined(MG_MAX_UNANSWERED_PING)
  11529. /* Configuration of the maximum number of websocket PINGs that might
  11530. * stay unanswered before the connection is considered broken.
  11531. * Note: The name of this define may still change (until it is
  11532. * defined as a compile parameter in a documentation).
  11533. */
  11534. #define MG_MAX_UNANSWERED_PING (5)
  11535. #endif
  11536. static void
  11537. read_websocket(struct mg_connection *conn,
  11538. mg_websocket_data_handler ws_data_handler,
  11539. void *callback_data)
  11540. {
  11541. /* Pointer to the beginning of the portion of the incoming websocket
  11542. * message queue.
  11543. * The original websocket upgrade request is never removed, so the queue
  11544. * begins after it. */
  11545. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11546. int n, error, exit_by_callback;
  11547. int ret;
  11548. /* body_len is the length of the entire queue in bytes
  11549. * len is the length of the current message
  11550. * data_len is the length of the current message's data payload
  11551. * header_len is the length of the current message's header */
  11552. size_t i, len, mask_len = 0, header_len, body_len;
  11553. uint64_t data_len = 0;
  11554. /* "The masking key is a 32-bit value chosen at random by the client."
  11555. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11556. */
  11557. unsigned char mask[4];
  11558. /* data points to the place where the message is stored when passed to
  11559. * the websocket_data callback. This is either mem on the stack, or a
  11560. * dynamically allocated buffer if it is too large. */
  11561. unsigned char mem[4096];
  11562. unsigned char mop; /* mask flag and opcode */
  11563. /* Variables used for connection monitoring */
  11564. double timeout = -1.0;
  11565. int enable_ping_pong = 0;
  11566. int ping_count = 0;
  11567. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11568. enable_ping_pong =
  11569. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11570. "yes");
  11571. }
  11572. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11573. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11574. }
  11575. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11576. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11577. }
  11578. if (timeout <= 0.0) {
  11579. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11580. }
  11581. /* Enter data processing loop */
  11582. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11583. conn->request_info.remote_addr,
  11584. conn->request_info.remote_port);
  11585. conn->in_websocket_handling = 1;
  11586. mg_set_thread_name("wsock");
  11587. /* Loop continuously, reading messages from the socket, invoking the
  11588. * callback, and waiting repeatedly until an error occurs. */
  11589. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11590. && (!conn->must_close)) {
  11591. header_len = 0;
  11592. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11593. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11594. len = buf[1] & 127;
  11595. mask_len = (buf[1] & 128) ? 4 : 0;
  11596. if ((len < 126) && (body_len >= mask_len)) {
  11597. /* inline 7-bit length field */
  11598. data_len = len;
  11599. header_len = 2 + mask_len;
  11600. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11601. /* 16-bit length field */
  11602. header_len = 4 + mask_len;
  11603. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11604. } else if (body_len >= (10 + mask_len)) {
  11605. /* 64-bit length field */
  11606. uint32_t l1, l2;
  11607. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11608. memcpy(&l2, &buf[6], 4);
  11609. header_len = 10 + mask_len;
  11610. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11611. if (data_len > (uint64_t)0x7FFF0000ul) {
  11612. /* no can do */
  11613. mg_cry_internal(
  11614. conn,
  11615. "%s",
  11616. "websocket out of memory; closing connection");
  11617. break;
  11618. }
  11619. }
  11620. }
  11621. if ((header_len > 0) && (body_len >= header_len)) {
  11622. /* Allocate space to hold websocket payload */
  11623. unsigned char *data = mem;
  11624. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11625. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11626. conn->phys_ctx);
  11627. if (data == NULL) {
  11628. /* Allocation failed, exit the loop and then close the
  11629. * connection */
  11630. mg_cry_internal(
  11631. conn,
  11632. "%s",
  11633. "websocket out of memory; closing connection");
  11634. break;
  11635. }
  11636. }
  11637. /* Copy the mask before we shift the queue and destroy it */
  11638. if (mask_len > 0) {
  11639. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11640. } else {
  11641. memset(mask, 0, sizeof(mask));
  11642. }
  11643. /* Read frame payload from the first message in the queue into
  11644. * data and advance the queue by moving the memory in place. */
  11645. DEBUG_ASSERT(body_len >= header_len);
  11646. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11647. mop = buf[0]; /* current mask and opcode */
  11648. /* Overflow case */
  11649. len = body_len - header_len;
  11650. memcpy(data, buf + header_len, len);
  11651. error = 0;
  11652. while ((uint64_t)len < data_len) {
  11653. n = pull_inner(NULL,
  11654. conn,
  11655. (char *)(data + len),
  11656. (int)(data_len - len),
  11657. timeout);
  11658. if (n <= -2) {
  11659. error = 1;
  11660. break;
  11661. } else if (n > 0) {
  11662. len += (size_t)n;
  11663. } else {
  11664. /* Timeout: should retry */
  11665. /* TODO: retry condition */
  11666. }
  11667. }
  11668. if (error) {
  11669. mg_cry_internal(
  11670. conn,
  11671. "%s",
  11672. "Websocket pull failed; closing connection");
  11673. if (data != mem) {
  11674. mg_free(data);
  11675. }
  11676. break;
  11677. }
  11678. conn->data_len = conn->request_len;
  11679. } else {
  11680. mop = buf[0]; /* current mask and opcode, overwritten by
  11681. * memmove() */
  11682. /* Length of the message being read at the front of the
  11683. * queue. Cast to 31 bit is OK, since we limited
  11684. * data_len before. */
  11685. len = (size_t)data_len + header_len;
  11686. /* Copy the data payload into the data pointer for the
  11687. * callback. Cast to 31 bit is OK, since we
  11688. * limited data_len */
  11689. memcpy(data, buf + header_len, (size_t)data_len);
  11690. /* Move the queue forward len bytes */
  11691. memmove(buf, buf + len, body_len - len);
  11692. /* Mark the queue as advanced */
  11693. conn->data_len -= (int)len;
  11694. }
  11695. /* Apply mask if necessary */
  11696. if (mask_len > 0) {
  11697. for (i = 0; i < (size_t)data_len; i++) {
  11698. data[i] ^= mask[i & 3];
  11699. }
  11700. }
  11701. exit_by_callback = 0;
  11702. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11703. /* filter PONG messages */
  11704. DEBUG_TRACE("PONG from %s:%u",
  11705. conn->request_info.remote_addr,
  11706. conn->request_info.remote_port);
  11707. /* No unanwered PINGs left */
  11708. ping_count = 0;
  11709. } else if (enable_ping_pong
  11710. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11711. /* reply PING messages */
  11712. DEBUG_TRACE("Reply PING from %s:%u",
  11713. conn->request_info.remote_addr,
  11714. conn->request_info.remote_port);
  11715. ret = mg_websocket_write(conn,
  11716. MG_WEBSOCKET_OPCODE_PONG,
  11717. (char *)data,
  11718. (size_t)data_len);
  11719. if (ret <= 0) {
  11720. /* Error: send failed */
  11721. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11722. break;
  11723. }
  11724. } else {
  11725. /* Exit the loop if callback signals to exit (server side),
  11726. * or "connection close" opcode received (client side). */
  11727. if (ws_data_handler != NULL) {
  11728. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11729. if (mop & 0x40) {
  11730. /* Inflate the data received if bit RSV1 is set. */
  11731. if (!conn->websocket_deflate_initialized) {
  11732. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11733. exit_by_callback = 1;
  11734. }
  11735. if (!exit_by_callback) {
  11736. size_t inflate_buf_size_old = 0;
  11737. size_t inflate_buf_size =
  11738. data_len
  11739. * 4; // Initial guess of the inflated message
  11740. // size. We double the memory when needed.
  11741. Bytef *inflated = NULL;
  11742. Bytef *new_mem = NULL;
  11743. conn->websocket_inflate_state.avail_in =
  11744. (uInt)(data_len + 4);
  11745. conn->websocket_inflate_state.next_in = data;
  11746. // Add trailing 0x00 0x00 0xff 0xff bytes
  11747. data[data_len] = '\x00';
  11748. data[data_len + 1] = '\x00';
  11749. data[data_len + 2] = '\xff';
  11750. data[data_len + 3] = '\xff';
  11751. do {
  11752. if (inflate_buf_size_old == 0) {
  11753. new_mem =
  11754. (Bytef *)mg_calloc(inflate_buf_size,
  11755. sizeof(Bytef));
  11756. } else {
  11757. inflate_buf_size *= 2;
  11758. new_mem =
  11759. (Bytef *)mg_realloc(inflated,
  11760. inflate_buf_size);
  11761. }
  11762. if (new_mem == NULL) {
  11763. mg_cry_internal(
  11764. conn,
  11765. "Out of memory: Cannot allocate "
  11766. "inflate buffer of %lu bytes",
  11767. (unsigned long)inflate_buf_size);
  11768. exit_by_callback = 1;
  11769. break;
  11770. }
  11771. inflated = new_mem;
  11772. conn->websocket_inflate_state.avail_out =
  11773. (uInt)(inflate_buf_size
  11774. - inflate_buf_size_old);
  11775. conn->websocket_inflate_state.next_out =
  11776. inflated + inflate_buf_size_old;
  11777. ret = inflate(&conn->websocket_inflate_state,
  11778. Z_SYNC_FLUSH);
  11779. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11780. || ret == Z_MEM_ERROR) {
  11781. mg_cry_internal(
  11782. conn,
  11783. "ZLIB inflate error: %i %s",
  11784. ret,
  11785. (conn->websocket_inflate_state.msg
  11786. ? conn->websocket_inflate_state.msg
  11787. : "<no error message>"));
  11788. exit_by_callback = 1;
  11789. break;
  11790. }
  11791. inflate_buf_size_old = inflate_buf_size;
  11792. } while (conn->websocket_inflate_state.avail_out
  11793. == 0);
  11794. inflate_buf_size -=
  11795. conn->websocket_inflate_state.avail_out;
  11796. if (!ws_data_handler(conn,
  11797. mop,
  11798. (char *)inflated,
  11799. inflate_buf_size,
  11800. callback_data)) {
  11801. exit_by_callback = 1;
  11802. }
  11803. mg_free(inflated);
  11804. }
  11805. } else
  11806. #endif
  11807. if (!ws_data_handler(conn,
  11808. mop,
  11809. (char *)data,
  11810. (size_t)data_len,
  11811. callback_data)) {
  11812. exit_by_callback = 1;
  11813. }
  11814. }
  11815. }
  11816. /* It a buffer has been allocated, free it again */
  11817. if (data != mem) {
  11818. mg_free(data);
  11819. }
  11820. if (exit_by_callback) {
  11821. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11822. conn->request_info.remote_addr,
  11823. conn->request_info.remote_port);
  11824. break;
  11825. }
  11826. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11827. /* Opcode == 8, connection close */
  11828. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11829. conn->request_info.remote_addr,
  11830. conn->request_info.remote_port);
  11831. break;
  11832. }
  11833. /* Not breaking the loop, process next websocket frame. */
  11834. } else {
  11835. /* Read from the socket into the next available location in the
  11836. * message queue. */
  11837. n = pull_inner(NULL,
  11838. conn,
  11839. conn->buf + conn->data_len,
  11840. conn->buf_size - conn->data_len,
  11841. timeout);
  11842. if (n <= -2) {
  11843. /* Error, no bytes read */
  11844. DEBUG_TRACE("PULL from %s:%u failed",
  11845. conn->request_info.remote_addr,
  11846. conn->request_info.remote_port);
  11847. break;
  11848. }
  11849. if (n > 0) {
  11850. conn->data_len += n;
  11851. /* Reset open PING count */
  11852. ping_count = 0;
  11853. } else {
  11854. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11855. && (!conn->must_close)) {
  11856. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11857. /* Stop sending PING */
  11858. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11859. "- closing connection",
  11860. ping_count,
  11861. conn->request_info.remote_addr,
  11862. conn->request_info.remote_port);
  11863. break;
  11864. }
  11865. if (enable_ping_pong) {
  11866. /* Send Websocket PING message */
  11867. DEBUG_TRACE("PING to %s:%u",
  11868. conn->request_info.remote_addr,
  11869. conn->request_info.remote_port);
  11870. ret = mg_websocket_write(conn,
  11871. MG_WEBSOCKET_OPCODE_PING,
  11872. NULL,
  11873. 0);
  11874. if (ret <= 0) {
  11875. /* Error: send failed */
  11876. DEBUG_TRACE("Send PING failed (%i)", ret);
  11877. break;
  11878. }
  11879. ping_count++;
  11880. }
  11881. }
  11882. /* Timeout: should retry */
  11883. /* TODO: get timeout def */
  11884. }
  11885. }
  11886. }
  11887. /* Leave data processing loop */
  11888. mg_set_thread_name("worker");
  11889. conn->in_websocket_handling = 0;
  11890. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11891. conn->request_info.remote_addr,
  11892. conn->request_info.remote_port);
  11893. }
  11894. static int
  11895. mg_websocket_write_exec(struct mg_connection *conn,
  11896. int opcode,
  11897. const char *data,
  11898. size_t dataLen,
  11899. uint32_t masking_key)
  11900. {
  11901. unsigned char header[14];
  11902. size_t headerLen;
  11903. int retval;
  11904. #if defined(GCC_DIAGNOSTIC)
  11905. /* Disable spurious conversion warning for GCC */
  11906. #pragma GCC diagnostic push
  11907. #pragma GCC diagnostic ignored "-Wconversion"
  11908. #endif
  11909. /* Note that POSIX/Winsock's send() is threadsafe
  11910. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11911. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11912. * push(), although that is only a problem if the packet is large or
  11913. * outgoing buffer is full). */
  11914. /* TODO: Check if this lock should be moved to user land.
  11915. * Currently the server sets this lock for websockets, but
  11916. * not for any other connection. It must be set for every
  11917. * conn read/written by more than one thread, no matter if
  11918. * it is a websocket or regular connection. */
  11919. (void)mg_lock_connection(conn);
  11920. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11921. size_t deflated_size = 0;
  11922. Bytef *deflated = 0;
  11923. // Deflate websocket messages over 100kb
  11924. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11925. if (use_deflate) {
  11926. if (!conn->websocket_deflate_initialized) {
  11927. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11928. return 0;
  11929. }
  11930. // Deflating the message
  11931. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11932. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11933. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11934. deflated_size = (size_t)compressBound((uLong)dataLen);
  11935. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11936. if (deflated == NULL) {
  11937. mg_cry_internal(
  11938. conn,
  11939. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11940. (unsigned long)deflated_size);
  11941. mg_unlock_connection(conn);
  11942. return -1;
  11943. }
  11944. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11945. conn->websocket_deflate_state.next_out = deflated;
  11946. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11947. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11948. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11949. } else
  11950. #endif
  11951. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11952. #if defined(GCC_DIAGNOSTIC)
  11953. #pragma GCC diagnostic pop
  11954. #endif
  11955. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11956. if (dataLen < 126) {
  11957. /* inline 7-bit length field */
  11958. header[1] = (unsigned char)dataLen;
  11959. headerLen = 2;
  11960. } else if (dataLen <= 0xFFFF) {
  11961. /* 16-bit length field */
  11962. uint16_t len = htons((uint16_t)dataLen);
  11963. header[1] = 126;
  11964. memcpy(header + 2, &len, 2);
  11965. headerLen = 4;
  11966. } else {
  11967. /* 64-bit length field */
  11968. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11969. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11970. header[1] = 127;
  11971. memcpy(header + 2, &len1, 4);
  11972. memcpy(header + 6, &len2, 4);
  11973. headerLen = 10;
  11974. }
  11975. if (masking_key) {
  11976. /* add mask */
  11977. header[1] |= 0x80;
  11978. memcpy(header + headerLen, &masking_key, 4);
  11979. headerLen += 4;
  11980. }
  11981. retval = mg_write(conn, header, headerLen);
  11982. if (retval != (int)headerLen) {
  11983. /* Did not send complete header */
  11984. retval = -1;
  11985. } else {
  11986. if (dataLen > 0) {
  11987. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11988. if (use_deflate) {
  11989. retval = mg_write(conn, deflated, dataLen);
  11990. mg_free(deflated);
  11991. } else
  11992. #endif
  11993. retval = mg_write(conn, data, dataLen);
  11994. }
  11995. /* if dataLen == 0, the header length (2) is returned */
  11996. }
  11997. /* TODO: Remove this unlock as well, when lock is removed. */
  11998. mg_unlock_connection(conn);
  11999. return retval;
  12000. }
  12001. CIVETWEB_API int
  12002. mg_websocket_write(struct mg_connection *conn,
  12003. int opcode,
  12004. const char *data,
  12005. size_t dataLen)
  12006. {
  12007. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  12008. }
  12009. static void
  12010. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  12011. {
  12012. size_t i = 0;
  12013. i = 0;
  12014. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  12015. /* Convert in 32 bit words, if data is 4 byte aligned */
  12016. while (i < (in_len - 3)) {
  12017. *(uint32_t *)(void *)(out + i) =
  12018. *(uint32_t *)(void *)(in + i) ^ masking_key;
  12019. i += 4;
  12020. }
  12021. }
  12022. if (i != in_len) {
  12023. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  12024. while (i < in_len) {
  12025. *(uint8_t *)(void *)(out + i) =
  12026. *(uint8_t *)(void *)(in + i)
  12027. ^ *(((uint8_t *)&masking_key) + (i % 4));
  12028. i++;
  12029. }
  12030. }
  12031. }
  12032. CIVETWEB_API int
  12033. mg_websocket_client_write(struct mg_connection *conn,
  12034. int opcode,
  12035. const char *data,
  12036. size_t dataLen)
  12037. {
  12038. int retval = -1;
  12039. char *masked_data =
  12040. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  12041. uint32_t masking_key = 0;
  12042. if (masked_data == NULL) {
  12043. /* Return -1 in an error case */
  12044. mg_cry_internal(conn,
  12045. "%s",
  12046. "Cannot allocate buffer for masked websocket response: "
  12047. "Out of memory");
  12048. return -1;
  12049. }
  12050. do {
  12051. /* Get a masking key - but not 0 */
  12052. masking_key = (uint32_t)get_random();
  12053. } while (masking_key == 0);
  12054. mask_data(data, dataLen, masking_key, masked_data);
  12055. retval = mg_websocket_write_exec(
  12056. conn, opcode, masked_data, dataLen, masking_key);
  12057. mg_free(masked_data);
  12058. return retval;
  12059. }
  12060. static void
  12061. handle_websocket_request(struct mg_connection *conn,
  12062. const char *path,
  12063. int is_callback_resource,
  12064. struct mg_websocket_subprotocols *subprotocols,
  12065. mg_websocket_connect_handler ws_connect_handler,
  12066. mg_websocket_ready_handler ws_ready_handler,
  12067. mg_websocket_data_handler ws_data_handler,
  12068. mg_websocket_close_handler ws_close_handler,
  12069. void *cbData)
  12070. {
  12071. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  12072. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  12073. ptrdiff_t lua_websock = 0;
  12074. #if !defined(USE_LUA)
  12075. (void)path;
  12076. #endif
  12077. /* Step 1: Check websocket protocol version. */
  12078. /* Step 1.1: Check Sec-WebSocket-Key. */
  12079. if (!websock_key) {
  12080. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  12081. * requires a Sec-WebSocket-Key header.
  12082. */
  12083. /* It could be the hixie draft version
  12084. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  12085. */
  12086. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  12087. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  12088. char key3[8];
  12089. if ((key1 != NULL) && (key2 != NULL)) {
  12090. /* This version uses 8 byte body data in a GET request */
  12091. conn->content_len = 8;
  12092. if (8 == mg_read(conn, key3, 8)) {
  12093. /* This is the hixie version */
  12094. mg_send_http_error(conn,
  12095. 426,
  12096. "%s",
  12097. "Protocol upgrade to RFC 6455 required");
  12098. return;
  12099. }
  12100. }
  12101. /* This is an unknown version */
  12102. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  12103. return;
  12104. }
  12105. /* Step 1.2: Check websocket protocol version. */
  12106. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  12107. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  12108. /* Reject wrong versions */
  12109. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  12110. return;
  12111. }
  12112. /* Step 1.3: Could check for "Host", but we do not really need this
  12113. * value for anything, so just ignore it. */
  12114. /* Step 2: If a callback is responsible, call it. */
  12115. if (is_callback_resource) {
  12116. /* Step 2.1 check and select subprotocol */
  12117. const char *protocols[64]; // max 64 headers
  12118. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  12119. "Sec-WebSocket-Protocol",
  12120. protocols,
  12121. 64);
  12122. if ((nbSubprotocolHeader > 0) && subprotocols) {
  12123. int headerNo, idx;
  12124. size_t len;
  12125. const char *sep, *curSubProtocol,
  12126. *acceptedWebSocketSubprotocol = NULL;
  12127. /* look for matching subprotocol */
  12128. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  12129. /* There might be multiple headers ... */
  12130. const char *protocol = protocols[headerNo];
  12131. curSubProtocol = protocol;
  12132. /* ... and in every header there might be a , separated list */
  12133. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  12134. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  12135. curSubProtocol++;
  12136. sep = strchr(curSubProtocol, ',');
  12137. if (sep) {
  12138. len = (size_t)(sep - curSubProtocol);
  12139. } else {
  12140. len = strlen(curSubProtocol);
  12141. }
  12142. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12143. // COMPARE: curSubProtocol ==
  12144. // subprotocols->subprotocols[idx]
  12145. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12146. && (strncmp(curSubProtocol,
  12147. subprotocols->subprotocols[idx],
  12148. len)
  12149. == 0)) {
  12150. acceptedWebSocketSubprotocol =
  12151. subprotocols->subprotocols[idx];
  12152. break;
  12153. }
  12154. }
  12155. curSubProtocol += len;
  12156. }
  12157. }
  12158. conn->request_info.acceptedWebSocketSubprotocol =
  12159. acceptedWebSocketSubprotocol;
  12160. }
  12161. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12162. websocket_deflate_negotiate(conn);
  12163. #endif
  12164. if ((ws_connect_handler != NULL)
  12165. && (ws_connect_handler(conn, cbData) != 0)) {
  12166. /* C callback has returned non-zero, do not proceed with
  12167. * handshake.
  12168. */
  12169. /* Note that C callbacks are no longer called when Lua is
  12170. * responsible, so C can no longer filter callbacks for Lua. */
  12171. return;
  12172. }
  12173. }
  12174. #if defined(USE_LUA)
  12175. /* Step 3: No callback. Check if Lua is responsible. */
  12176. else {
  12177. /* Step 3.1: Check if Lua is responsible. */
  12178. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12179. lua_websock = match_prefix_strlen(
  12180. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12181. }
  12182. if (lua_websock > 0) {
  12183. /* Step 3.2: Lua is responsible: call it. */
  12184. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12185. if (!conn->lua_websocket_state) {
  12186. /* Lua rejected the new client */
  12187. return;
  12188. }
  12189. }
  12190. }
  12191. #endif
  12192. /* Step 4: Check if there is a responsible websocket handler. */
  12193. if (!is_callback_resource && !lua_websock) {
  12194. /* There is no callback, and Lua is not responsible either. */
  12195. /* Reply with a 404 Not Found. We are still at a standard
  12196. * HTTP request here, before the websocket handshake, so
  12197. * we can still send standard HTTP error replies. */
  12198. mg_send_http_error(conn, 404, "%s", "Not found");
  12199. return;
  12200. }
  12201. /* Step 5: The websocket connection has been accepted */
  12202. if (!send_websocket_handshake(conn, websock_key)) {
  12203. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12204. return;
  12205. }
  12206. /* Step 6: Call the ready handler */
  12207. if (is_callback_resource) {
  12208. if (ws_ready_handler != NULL) {
  12209. ws_ready_handler(conn, cbData);
  12210. }
  12211. #if defined(USE_LUA)
  12212. } else if (lua_websock) {
  12213. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12214. /* the ready handler returned false */
  12215. return;
  12216. }
  12217. #endif
  12218. }
  12219. /* Step 7: Enter the read loop */
  12220. if (is_callback_resource) {
  12221. read_websocket(conn, ws_data_handler, cbData);
  12222. #if defined(USE_LUA)
  12223. } else if (lua_websock) {
  12224. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12225. #endif
  12226. }
  12227. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12228. /* Step 8: Close the deflate & inflate buffers */
  12229. if (conn->websocket_deflate_initialized) {
  12230. deflateEnd(&conn->websocket_deflate_state);
  12231. inflateEnd(&conn->websocket_inflate_state);
  12232. }
  12233. #endif
  12234. /* Step 9: Call the close handler */
  12235. if (ws_close_handler) {
  12236. ws_close_handler(conn, cbData);
  12237. }
  12238. }
  12239. #endif /* !USE_WEBSOCKET */
  12240. /* Is upgrade request:
  12241. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12242. * 1 = upgrade to websocket
  12243. * 2 = upgrade to HTTP/2
  12244. * -1 = upgrade to unknown protocol
  12245. */
  12246. static int
  12247. should_switch_to_protocol(const struct mg_connection *conn)
  12248. {
  12249. const char *connection_headers[8];
  12250. const char *upgrade_to;
  12251. int connection_header_count, i, should_upgrade;
  12252. /* A websocket protocol has the following HTTP headers:
  12253. *
  12254. * Connection: Upgrade
  12255. * Upgrade: Websocket
  12256. *
  12257. * It seems some clients use multiple headers:
  12258. * see https://github.com/civetweb/civetweb/issues/1083
  12259. */
  12260. connection_header_count = get_req_headers(&conn->request_info,
  12261. "Connection",
  12262. connection_headers,
  12263. 8);
  12264. should_upgrade = 0;
  12265. for (i = 0; i < connection_header_count; i++) {
  12266. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12267. should_upgrade = 1;
  12268. }
  12269. }
  12270. if (!should_upgrade) {
  12271. return PROTOCOL_TYPE_HTTP1;
  12272. }
  12273. upgrade_to = mg_get_header(conn, "Upgrade");
  12274. if (upgrade_to == NULL) {
  12275. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12276. return -1;
  12277. }
  12278. /* Upgrade to ... */
  12279. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12280. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12281. * "Sec-WebSocket-Version" are also required.
  12282. * Don't check them here, since even an unsupported websocket protocol
  12283. * request still IS a websocket request (in contrast to a standard HTTP
  12284. * request). It will fail later in handle_websocket_request.
  12285. */
  12286. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12287. }
  12288. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12289. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12290. }
  12291. /* Upgrade to another protocol */
  12292. return -1;
  12293. }
  12294. static int
  12295. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12296. {
  12297. int n;
  12298. unsigned int a, b, c, d, slash;
  12299. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12300. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12301. // integer value, but function will not report conversion
  12302. // errors; consider using 'strtol' instead
  12303. slash = 32;
  12304. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12305. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12306. // an integer value, but function will not report conversion
  12307. // errors; consider using 'strtol' instead
  12308. n = 0;
  12309. }
  12310. }
  12311. if ((n > 0) && ((size_t)n == vec->len)) {
  12312. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12313. /* IPv4 format */
  12314. if (sa->sa.sa_family == AF_INET) {
  12315. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12316. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12317. | ((uint32_t)c << 8) | (uint32_t)d;
  12318. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12319. return (ip & mask) == net;
  12320. }
  12321. return 0;
  12322. }
  12323. }
  12324. #if defined(USE_IPV6)
  12325. else {
  12326. char ad[50];
  12327. const char *p;
  12328. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12329. slash = 128;
  12330. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12331. n = 0;
  12332. }
  12333. }
  12334. if ((n <= 0) && no_strict) {
  12335. /* no square brackets? */
  12336. p = strchr(vec->ptr, '/');
  12337. if (p && (p < (vec->ptr + vec->len))) {
  12338. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12339. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12340. n += (int)(p - vec->ptr);
  12341. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12342. } else {
  12343. n = 0;
  12344. }
  12345. } else if (vec->len < sizeof(ad)) {
  12346. n = (int)vec->len;
  12347. slash = 128;
  12348. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12349. }
  12350. }
  12351. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12352. p = ad;
  12353. c = 0;
  12354. /* zone indexes are unsupported, at least two colons are needed */
  12355. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12356. if (*(p++) == ':') {
  12357. c++;
  12358. }
  12359. }
  12360. if ((*p == '\0') && (c >= 2)) {
  12361. struct sockaddr_in6 sin6;
  12362. unsigned int i;
  12363. /* for strict validation, an actual IPv6 argument is needed */
  12364. if (sa->sa.sa_family != AF_INET6) {
  12365. return 0;
  12366. }
  12367. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12368. /* IPv6 format */
  12369. for (i = 0; i < 16; i++) {
  12370. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12371. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12372. uint8_t mask = 0;
  12373. if (8 * i + 8 < slash) {
  12374. mask = 0xFFu;
  12375. } else if (8 * i < slash) {
  12376. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12377. }
  12378. if ((ip & mask) != net) {
  12379. return 0;
  12380. }
  12381. }
  12382. return 1;
  12383. }
  12384. }
  12385. }
  12386. }
  12387. #else
  12388. (void)no_strict;
  12389. #endif
  12390. /* malformed */
  12391. return -1;
  12392. }
  12393. static int
  12394. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12395. {
  12396. int throttle = 0;
  12397. struct vec vec, val;
  12398. char mult;
  12399. double v;
  12400. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12401. mult = ',';
  12402. if ((val.ptr == NULL)
  12403. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12404. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12405. // to an integer value, but function will not report
  12406. // conversion errors; consider using 'strtol' instead
  12407. || (v < 0)
  12408. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12409. && (mult != ','))) {
  12410. continue;
  12411. }
  12412. v *= (lowercase(&mult) == 'k')
  12413. ? 1024
  12414. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12415. if (vec.len == 1 && vec.ptr[0] == '*') {
  12416. throttle = (int)v;
  12417. } else {
  12418. int matched = parse_match_net(&vec, rsa, 0);
  12419. if (matched >= 0) {
  12420. /* a valid IP subnet */
  12421. if (matched) {
  12422. throttle = (int)v;
  12423. }
  12424. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12425. throttle = (int)v;
  12426. }
  12427. }
  12428. }
  12429. return throttle;
  12430. }
  12431. /* The mg_upload function is superseded by mg_handle_form_request. */
  12432. #include "handle_form.inl"
  12433. static int
  12434. get_first_ssl_listener_index(const struct mg_context *ctx)
  12435. {
  12436. unsigned int i;
  12437. int idx = -1;
  12438. if (ctx) {
  12439. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12440. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12441. }
  12442. }
  12443. return idx;
  12444. }
  12445. /* Return host (without port) */
  12446. static void
  12447. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12448. {
  12449. const char *host_header =
  12450. get_header(ri->http_headers, ri->num_headers, "Host");
  12451. host->ptr = NULL;
  12452. host->len = 0;
  12453. if (host_header != NULL) {
  12454. const char *pos;
  12455. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12456. * is found. */
  12457. if (*host_header == '[') {
  12458. pos = strchr(host_header, ']');
  12459. if (!pos) {
  12460. /* Malformed hostname starts with '[', but no ']' found */
  12461. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12462. return;
  12463. }
  12464. /* terminate after ']' */
  12465. host->ptr = host_header;
  12466. host->len = (size_t)(pos + 1 - host_header);
  12467. } else {
  12468. /* Otherwise, a ':' separates hostname and port number */
  12469. pos = strchr(host_header, ':');
  12470. if (pos != NULL) {
  12471. host->len = (size_t)(pos - host_header);
  12472. } else {
  12473. host->len = strlen(host_header);
  12474. }
  12475. host->ptr = host_header;
  12476. }
  12477. }
  12478. }
  12479. static int
  12480. switch_domain_context(struct mg_connection *conn)
  12481. {
  12482. struct vec host;
  12483. get_host_from_request_info(&host, &conn->request_info);
  12484. if (host.ptr) {
  12485. if (conn->ssl) {
  12486. /* This is a HTTPS connection, maybe we have a hostname
  12487. * from SNI (set in ssl_servername_callback). */
  12488. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12489. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12490. /* We are not using the default domain */
  12491. if ((strlen(sslhost) != host.len)
  12492. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12493. /* Mismatch between SNI domain and HTTP domain */
  12494. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12495. sslhost,
  12496. (int)host.len,
  12497. host.ptr);
  12498. return 0;
  12499. }
  12500. }
  12501. } else {
  12502. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12503. while (dom) {
  12504. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12505. size_t domNameLen = strlen(domName);
  12506. if ((domNameLen == host.len)
  12507. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12508. /* Found matching domain */
  12509. DEBUG_TRACE("HTTP domain %s found",
  12510. dom->config[AUTHENTICATION_DOMAIN]);
  12511. /* TODO: Check if this is a HTTP or HTTPS domain */
  12512. conn->dom_ctx = dom;
  12513. break;
  12514. }
  12515. mg_lock_context(conn->phys_ctx);
  12516. dom = dom->next;
  12517. mg_unlock_context(conn->phys_ctx);
  12518. }
  12519. }
  12520. DEBUG_TRACE("HTTP%s Host: %.*s",
  12521. conn->ssl ? "S" : "",
  12522. (int)host.len,
  12523. host.ptr);
  12524. } else {
  12525. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12526. return 1;
  12527. }
  12528. return 1;
  12529. }
  12530. static void
  12531. redirect_to_https_port(struct mg_connection *conn, int port)
  12532. {
  12533. char target_url[MG_BUF_LEN];
  12534. int truncated = 0;
  12535. const char *expect_proto =
  12536. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12537. /* Use "308 Permanent Redirect" */
  12538. int redirect_code = 308;
  12539. /* In any case, close the current connection */
  12540. conn->must_close = 1;
  12541. /* Send host, port, uri and (if it exists) ?query_string */
  12542. if (mg_construct_local_link(
  12543. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12544. < 0) {
  12545. truncated = 1;
  12546. } else if (conn->request_info.query_string != NULL) {
  12547. size_t slen1 = strlen(target_url);
  12548. size_t slen2 = strlen(conn->request_info.query_string);
  12549. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12550. target_url[slen1] = '?';
  12551. memcpy(target_url + slen1 + 1,
  12552. conn->request_info.query_string,
  12553. slen2);
  12554. target_url[slen1 + slen2 + 1] = 0;
  12555. } else {
  12556. truncated = 1;
  12557. }
  12558. }
  12559. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12560. * is used as buffer size) */
  12561. if (truncated) {
  12562. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12563. return;
  12564. }
  12565. /* Use redirect helper function */
  12566. mg_send_http_redirect(conn, target_url, redirect_code);
  12567. }
  12568. static void
  12569. mg_set_handler_type(struct mg_context *phys_ctx,
  12570. struct mg_domain_context *dom_ctx,
  12571. const char *uri,
  12572. int handler_type,
  12573. int is_delete_request,
  12574. mg_request_handler handler,
  12575. struct mg_websocket_subprotocols *subprotocols,
  12576. mg_websocket_connect_handler connect_handler,
  12577. mg_websocket_ready_handler ready_handler,
  12578. mg_websocket_data_handler data_handler,
  12579. mg_websocket_close_handler close_handler,
  12580. mg_authorization_handler auth_handler,
  12581. void *cbdata)
  12582. {
  12583. struct mg_handler_info *tmp_rh, **lastref;
  12584. size_t urilen = strlen(uri);
  12585. if (handler_type == WEBSOCKET_HANDLER) {
  12586. DEBUG_ASSERT(handler == NULL);
  12587. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12588. || ready_handler != NULL || data_handler != NULL
  12589. || close_handler != NULL);
  12590. DEBUG_ASSERT(auth_handler == NULL);
  12591. if (handler != NULL) {
  12592. return;
  12593. }
  12594. if (!is_delete_request && (connect_handler == NULL)
  12595. && (ready_handler == NULL) && (data_handler == NULL)
  12596. && (close_handler == NULL)) {
  12597. return;
  12598. }
  12599. if (auth_handler != NULL) {
  12600. return;
  12601. }
  12602. } else if (handler_type == REQUEST_HANDLER) {
  12603. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12604. && data_handler == NULL && close_handler == NULL);
  12605. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12606. DEBUG_ASSERT(auth_handler == NULL);
  12607. if ((connect_handler != NULL) || (ready_handler != NULL)
  12608. || (data_handler != NULL) || (close_handler != NULL)) {
  12609. return;
  12610. }
  12611. if (!is_delete_request && (handler == NULL)) {
  12612. return;
  12613. }
  12614. if (auth_handler != NULL) {
  12615. return;
  12616. }
  12617. } else if (handler_type == AUTH_HANDLER) {
  12618. DEBUG_ASSERT(handler == NULL);
  12619. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12620. && data_handler == NULL && close_handler == NULL);
  12621. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12622. if (handler != NULL) {
  12623. return;
  12624. }
  12625. if ((connect_handler != NULL) || (ready_handler != NULL)
  12626. || (data_handler != NULL) || (close_handler != NULL)) {
  12627. return;
  12628. }
  12629. if (!is_delete_request && (auth_handler == NULL)) {
  12630. return;
  12631. }
  12632. } else {
  12633. /* Unknown handler type. */
  12634. return;
  12635. }
  12636. if (!phys_ctx || !dom_ctx) {
  12637. /* no context available */
  12638. return;
  12639. }
  12640. mg_lock_context(phys_ctx);
  12641. /* first try to find an existing handler */
  12642. do {
  12643. lastref = &(dom_ctx->handlers);
  12644. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12645. tmp_rh = tmp_rh->next) {
  12646. if (tmp_rh->handler_type == handler_type
  12647. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12648. if (!is_delete_request) {
  12649. /* update existing handler */
  12650. if (handler_type == REQUEST_HANDLER) {
  12651. /* Wait for end of use before updating */
  12652. if (tmp_rh->refcount) {
  12653. mg_unlock_context(phys_ctx);
  12654. mg_sleep(1);
  12655. mg_lock_context(phys_ctx);
  12656. /* tmp_rh might have been freed, search again. */
  12657. break;
  12658. }
  12659. /* Ok, the handler is no more use -> Update it */
  12660. tmp_rh->handler = handler;
  12661. } else if (handler_type == WEBSOCKET_HANDLER) {
  12662. tmp_rh->subprotocols = subprotocols;
  12663. tmp_rh->connect_handler = connect_handler;
  12664. tmp_rh->ready_handler = ready_handler;
  12665. tmp_rh->data_handler = data_handler;
  12666. tmp_rh->close_handler = close_handler;
  12667. } else { /* AUTH_HANDLER */
  12668. tmp_rh->auth_handler = auth_handler;
  12669. }
  12670. tmp_rh->cbdata = cbdata;
  12671. } else {
  12672. /* remove existing handler */
  12673. if (handler_type == REQUEST_HANDLER) {
  12674. /* Wait for end of use before removing */
  12675. if (tmp_rh->refcount) {
  12676. tmp_rh->removing = 1;
  12677. mg_unlock_context(phys_ctx);
  12678. mg_sleep(1);
  12679. mg_lock_context(phys_ctx);
  12680. /* tmp_rh might have been freed, search again. */
  12681. break;
  12682. }
  12683. /* Ok, the handler is no more used */
  12684. }
  12685. *lastref = tmp_rh->next;
  12686. mg_free(tmp_rh->uri);
  12687. mg_free(tmp_rh);
  12688. }
  12689. mg_unlock_context(phys_ctx);
  12690. return;
  12691. }
  12692. lastref = &(tmp_rh->next);
  12693. }
  12694. } while (tmp_rh != NULL);
  12695. if (is_delete_request) {
  12696. /* no handler to set, this was a remove request to a non-existing
  12697. * handler */
  12698. mg_unlock_context(phys_ctx);
  12699. return;
  12700. }
  12701. tmp_rh =
  12702. (struct mg_handler_info *)mg_calloc_ctx(1,
  12703. sizeof(struct mg_handler_info),
  12704. phys_ctx);
  12705. if (tmp_rh == NULL) {
  12706. mg_unlock_context(phys_ctx);
  12707. mg_cry_ctx_internal(phys_ctx,
  12708. "%s",
  12709. "Cannot create new request handler struct, OOM");
  12710. return;
  12711. }
  12712. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12713. if (!tmp_rh->uri) {
  12714. mg_unlock_context(phys_ctx);
  12715. mg_free(tmp_rh);
  12716. mg_cry_ctx_internal(phys_ctx,
  12717. "%s",
  12718. "Cannot create new request handler struct, OOM");
  12719. return;
  12720. }
  12721. tmp_rh->uri_len = urilen;
  12722. if (handler_type == REQUEST_HANDLER) {
  12723. tmp_rh->refcount = 0;
  12724. tmp_rh->removing = 0;
  12725. tmp_rh->handler = handler;
  12726. } else if (handler_type == WEBSOCKET_HANDLER) {
  12727. tmp_rh->subprotocols = subprotocols;
  12728. tmp_rh->connect_handler = connect_handler;
  12729. tmp_rh->ready_handler = ready_handler;
  12730. tmp_rh->data_handler = data_handler;
  12731. tmp_rh->close_handler = close_handler;
  12732. } else { /* AUTH_HANDLER */
  12733. tmp_rh->auth_handler = auth_handler;
  12734. }
  12735. tmp_rh->cbdata = cbdata;
  12736. tmp_rh->handler_type = handler_type;
  12737. tmp_rh->next = NULL;
  12738. *lastref = tmp_rh;
  12739. mg_unlock_context(phys_ctx);
  12740. }
  12741. CIVETWEB_API void
  12742. mg_set_request_handler(struct mg_context *ctx,
  12743. const char *uri,
  12744. mg_request_handler handler,
  12745. void *cbdata)
  12746. {
  12747. mg_set_handler_type(ctx,
  12748. &(ctx->dd),
  12749. uri,
  12750. REQUEST_HANDLER,
  12751. handler == NULL,
  12752. handler,
  12753. NULL,
  12754. NULL,
  12755. NULL,
  12756. NULL,
  12757. NULL,
  12758. NULL,
  12759. cbdata);
  12760. }
  12761. CIVETWEB_API void
  12762. mg_set_websocket_handler(struct mg_context *ctx,
  12763. const char *uri,
  12764. mg_websocket_connect_handler connect_handler,
  12765. mg_websocket_ready_handler ready_handler,
  12766. mg_websocket_data_handler data_handler,
  12767. mg_websocket_close_handler close_handler,
  12768. void *cbdata)
  12769. {
  12770. mg_set_websocket_handler_with_subprotocols(ctx,
  12771. uri,
  12772. NULL,
  12773. connect_handler,
  12774. ready_handler,
  12775. data_handler,
  12776. close_handler,
  12777. cbdata);
  12778. }
  12779. CIVETWEB_API void
  12780. mg_set_websocket_handler_with_subprotocols(
  12781. struct mg_context *ctx,
  12782. const char *uri,
  12783. struct mg_websocket_subprotocols *subprotocols,
  12784. mg_websocket_connect_handler connect_handler,
  12785. mg_websocket_ready_handler ready_handler,
  12786. mg_websocket_data_handler data_handler,
  12787. mg_websocket_close_handler close_handler,
  12788. void *cbdata)
  12789. {
  12790. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12791. && (data_handler == NULL)
  12792. && (close_handler == NULL);
  12793. mg_set_handler_type(ctx,
  12794. &(ctx->dd),
  12795. uri,
  12796. WEBSOCKET_HANDLER,
  12797. is_delete_request,
  12798. NULL,
  12799. subprotocols,
  12800. connect_handler,
  12801. ready_handler,
  12802. data_handler,
  12803. close_handler,
  12804. NULL,
  12805. cbdata);
  12806. }
  12807. CIVETWEB_API void
  12808. mg_set_auth_handler(struct mg_context *ctx,
  12809. const char *uri,
  12810. mg_authorization_handler handler,
  12811. void *cbdata)
  12812. {
  12813. mg_set_handler_type(ctx,
  12814. &(ctx->dd),
  12815. uri,
  12816. AUTH_HANDLER,
  12817. handler == NULL,
  12818. NULL,
  12819. NULL,
  12820. NULL,
  12821. NULL,
  12822. NULL,
  12823. NULL,
  12824. handler,
  12825. cbdata);
  12826. }
  12827. static int
  12828. get_request_handler(struct mg_connection *conn,
  12829. int handler_type,
  12830. mg_request_handler *handler,
  12831. struct mg_websocket_subprotocols **subprotocols,
  12832. mg_websocket_connect_handler *connect_handler,
  12833. mg_websocket_ready_handler *ready_handler,
  12834. mg_websocket_data_handler *data_handler,
  12835. mg_websocket_close_handler *close_handler,
  12836. mg_authorization_handler *auth_handler,
  12837. void **cbdata,
  12838. struct mg_handler_info **handler_info)
  12839. {
  12840. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12841. if (request_info) {
  12842. const char *uri = request_info->local_uri;
  12843. size_t urilen = strlen(uri);
  12844. struct mg_handler_info *tmp_rh;
  12845. int step, matched;
  12846. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12847. return 0;
  12848. }
  12849. mg_lock_context(conn->phys_ctx);
  12850. for (step = 0; step < 3; step++) {
  12851. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12852. tmp_rh = tmp_rh->next) {
  12853. if (tmp_rh->handler_type != handler_type) {
  12854. continue;
  12855. }
  12856. if (step == 0) {
  12857. /* first try for an exact match */
  12858. matched = (tmp_rh->uri_len == urilen)
  12859. && (strcmp(tmp_rh->uri, uri) == 0);
  12860. } else if (step == 1) {
  12861. /* next try for a partial match, we will accept
  12862. uri/something */
  12863. matched =
  12864. (tmp_rh->uri_len < urilen)
  12865. && (uri[tmp_rh->uri_len] == '/')
  12866. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12867. } else {
  12868. /* finally try for pattern match */
  12869. matched =
  12870. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12871. }
  12872. if (matched) {
  12873. if (handler_type == WEBSOCKET_HANDLER) {
  12874. *subprotocols = tmp_rh->subprotocols;
  12875. *connect_handler = tmp_rh->connect_handler;
  12876. *ready_handler = tmp_rh->ready_handler;
  12877. *data_handler = tmp_rh->data_handler;
  12878. *close_handler = tmp_rh->close_handler;
  12879. } else if (handler_type == REQUEST_HANDLER) {
  12880. if (tmp_rh->removing) {
  12881. /* Treat as none found */
  12882. step = 2;
  12883. break;
  12884. }
  12885. *handler = tmp_rh->handler;
  12886. /* Acquire handler and give it back */
  12887. tmp_rh->refcount++;
  12888. *handler_info = tmp_rh;
  12889. } else { /* AUTH_HANDLER */
  12890. *auth_handler = tmp_rh->auth_handler;
  12891. }
  12892. *cbdata = tmp_rh->cbdata;
  12893. mg_unlock_context(conn->phys_ctx);
  12894. return 1;
  12895. }
  12896. }
  12897. }
  12898. mg_unlock_context(conn->phys_ctx);
  12899. }
  12900. return 0; /* none found */
  12901. }
  12902. /* Check if the script file is in a path, allowed for script files.
  12903. * This can be used if uploading files is possible not only for the server
  12904. * admin, and the upload mechanism does not check the file extension.
  12905. */
  12906. static int
  12907. is_in_script_path(const struct mg_connection *conn, const char *path)
  12908. {
  12909. /* TODO (Feature): Add config value for allowed script path.
  12910. * Default: All allowed. */
  12911. (void)conn;
  12912. (void)path;
  12913. return 1;
  12914. }
  12915. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12916. static int
  12917. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12918. int bits,
  12919. char *data,
  12920. size_t len,
  12921. void *cbdata)
  12922. {
  12923. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12924. if (pcallbacks->websocket_data) {
  12925. return pcallbacks->websocket_data(conn, bits, data, len);
  12926. }
  12927. /* No handler set - assume "OK" */
  12928. return 1;
  12929. }
  12930. static void
  12931. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12932. void *cbdata)
  12933. {
  12934. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12935. if (pcallbacks->connection_close) {
  12936. pcallbacks->connection_close(conn);
  12937. }
  12938. }
  12939. #endif
  12940. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12941. */
  12942. static void
  12943. release_handler_ref(struct mg_connection *conn,
  12944. struct mg_handler_info *handler_info)
  12945. {
  12946. if (handler_info != NULL) {
  12947. /* Use context lock for ref counter */
  12948. mg_lock_context(conn->phys_ctx);
  12949. handler_info->refcount--;
  12950. mg_unlock_context(conn->phys_ctx);
  12951. }
  12952. }
  12953. /* This is the heart of the Civetweb's logic.
  12954. * This function is called when the request is read, parsed and validated,
  12955. * and Civetweb must decide what action to take: serve a file, or
  12956. * a directory, or call embedded function, etcetera. */
  12957. static void
  12958. handle_request(struct mg_connection *conn)
  12959. {
  12960. struct mg_request_info *ri = &conn->request_info;
  12961. char path[UTF8_PATH_MAX];
  12962. int uri_len, ssl_index;
  12963. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12964. is_put_or_delete_request = 0, is_callback_resource = 0,
  12965. is_template_text_file = 0, is_webdav_request = 0;
  12966. int i;
  12967. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12968. mg_request_handler callback_handler = NULL;
  12969. struct mg_handler_info *handler_info = NULL;
  12970. struct mg_websocket_subprotocols *subprotocols;
  12971. mg_websocket_connect_handler ws_connect_handler = NULL;
  12972. mg_websocket_ready_handler ws_ready_handler = NULL;
  12973. mg_websocket_data_handler ws_data_handler = NULL;
  12974. mg_websocket_close_handler ws_close_handler = NULL;
  12975. void *callback_data = NULL;
  12976. mg_authorization_handler auth_handler = NULL;
  12977. void *auth_callback_data = NULL;
  12978. int handler_type;
  12979. time_t curtime = time(NULL);
  12980. char date[64];
  12981. char *tmp;
  12982. path[0] = 0;
  12983. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12984. conn->request_state = 0;
  12985. /* 1. get the request url */
  12986. /* 1.1. split into url and query string */
  12987. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12988. != NULL) {
  12989. *((char *)conn->request_info.query_string++) = '\0';
  12990. }
  12991. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12992. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12993. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12994. if (ssl_index >= 0) {
  12995. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12996. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12997. redirect_to_https_port(conn, port);
  12998. } else {
  12999. /* A http to https forward port has been specified,
  13000. * but no https port to forward to. */
  13001. mg_send_http_error(conn,
  13002. 503,
  13003. "%s",
  13004. "Error: SSL forward not configured properly");
  13005. mg_cry_internal(conn,
  13006. "%s",
  13007. "Can not redirect to SSL, no SSL port available");
  13008. }
  13009. return;
  13010. }
  13011. /* 1.3. decode url (if config says so) */
  13012. if (should_decode_url(conn)) {
  13013. url_decode_in_place((char *)ri->local_uri);
  13014. }
  13015. /* URL decode the query-string only if explicitly set in the configuration
  13016. */
  13017. if (conn->request_info.query_string) {
  13018. if (should_decode_query_string(conn)) {
  13019. url_decode_in_place((char *)conn->request_info.query_string);
  13020. }
  13021. }
  13022. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  13023. * possible. The fact that we cleaned the URI is stored in that the
  13024. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  13025. * ri->local_uri_raw still points to memory allocated in
  13026. * worker_thread_run(). ri->local_uri is private to the request so we
  13027. * don't have to use preallocated memory here. */
  13028. tmp = mg_strdup(ri->local_uri_raw);
  13029. if (!tmp) {
  13030. /* Out of memory. We cannot do anything reasonable here. */
  13031. return;
  13032. }
  13033. remove_dot_segments(tmp);
  13034. ri->local_uri = tmp;
  13035. #if !defined(NO_FILES) /* Only compute if later code can actually use it */
  13036. /* Cache URI length once; recompute only if the buffer changes later. */
  13037. uri_len = (int)strlen(ri->local_uri);
  13038. #endif
  13039. /* step 1. completed, the url is known now */
  13040. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  13041. /* 2. if this ip has limited speed, set it for this connection */
  13042. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  13043. &conn->client.rsa,
  13044. ri->local_uri);
  13045. /* 3. call a "handle everything" callback, if registered */
  13046. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  13047. /* Note that since V1.7 the "begin_request" function is called
  13048. * before an authorization check. If an authorization check is
  13049. * required, use a request_handler instead. */
  13050. i = conn->phys_ctx->callbacks.begin_request(conn);
  13051. if (i > 0) {
  13052. /* callback already processed the request. Store the
  13053. return value as a status code for the access log. */
  13054. conn->status_code = i;
  13055. if (!conn->must_close) {
  13056. discard_unread_request_data(conn);
  13057. }
  13058. DEBUG_TRACE("%s", "begin_request handled request");
  13059. return;
  13060. } else if (i == 0) {
  13061. /* civetweb should process the request */
  13062. } else {
  13063. /* unspecified - may change with the next version */
  13064. DEBUG_TRACE("%s", "done (undocumented behavior)");
  13065. return;
  13066. }
  13067. }
  13068. /* request not yet handled by a handler or redirect, so the request
  13069. * is processed here */
  13070. /* 4. Check for CORS preflight requests and handle them (if configured).
  13071. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  13072. */
  13073. if (!strcmp(ri->request_method, "OPTIONS")) {
  13074. /* Send a response to CORS preflights only if
  13075. * access_control_allow_methods is not NULL and not an empty string.
  13076. * In this case, scripts can still handle CORS. */
  13077. const char *cors_meth_cfg =
  13078. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  13079. const char *cors_orig_cfg =
  13080. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  13081. const char *cors_origin =
  13082. get_header(ri->http_headers, ri->num_headers, "Origin");
  13083. const char *cors_acrm = get_header(ri->http_headers,
  13084. ri->num_headers,
  13085. "Access-Control-Request-Method");
  13086. const char *cors_repl_asterisk_with_orig_cfg =
  13087. conn->dom_ctx->config[REPLACE_ASTERISK_WITH_ORIGIN];
  13088. /* Todo: check if cors_origin is in cors_orig_cfg.
  13089. * Or, let the client check this. */
  13090. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  13091. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  13092. && (cors_origin != NULL) && (cors_acrm != NULL)
  13093. && (cors_repl_asterisk_with_orig_cfg != NULL) && (*cors_repl_asterisk_with_orig_cfg != 0)) {
  13094. int cors_repl_asterisk_with_orig = mg_strcasecmp(cors_repl_asterisk_with_orig_cfg, "yes");
  13095. /* This is a valid CORS preflight, and the server is configured
  13096. * to handle it automatically. */
  13097. const char *cors_acrh =
  13098. get_header(ri->http_headers,
  13099. ri->num_headers,
  13100. "Access-Control-Request-Headers");
  13101. const char *cors_cred_cfg =
  13102. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  13103. const char *cors_exphdr_cfg =
  13104. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  13105. gmt_time_string(date, sizeof(date), &curtime);
  13106. mg_printf(conn,
  13107. "HTTP/1.1 200 OK\r\n"
  13108. "Date: %s\r\n"
  13109. "Access-Control-Allow-Origin: %s\r\n"
  13110. "Access-Control-Allow-Methods: %s\r\n"
  13111. "Content-Length: 0\r\n"
  13112. "Connection: %s\r\n",
  13113. date,
  13114. (cors_repl_asterisk_with_orig == 0 && cors_orig_cfg[0] == '*') ? cors_origin : cors_orig_cfg,
  13115. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  13116. suggest_connection_header(conn));
  13117. if (cors_cred_cfg && *cors_cred_cfg) {
  13118. mg_printf(conn,
  13119. "Access-Control-Allow-Credentials: %s\r\n",
  13120. cors_cred_cfg);
  13121. }
  13122. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  13123. mg_printf(conn,
  13124. "Access-Control-Expose-Headers: %s\r\n",
  13125. cors_exphdr_cfg);
  13126. }
  13127. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  13128. /* CORS request is asking for additional headers */
  13129. const char *cors_hdr_cfg =
  13130. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  13131. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  13132. /* Allow only if access_control_allow_headers is
  13133. * not NULL and not an empty string. If this
  13134. * configuration is set to *, allow everything.
  13135. * Otherwise this configuration must be a list
  13136. * of allowed HTTP header names. */
  13137. mg_printf(conn,
  13138. "Access-Control-Allow-Headers: %s\r\n",
  13139. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  13140. : cors_hdr_cfg));
  13141. }
  13142. }
  13143. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  13144. mg_printf(conn, "\r\n");
  13145. DEBUG_TRACE("%s", "OPTIONS done");
  13146. return;
  13147. }
  13148. }
  13149. /* 5. interpret the url to find out how the request must be handled
  13150. */
  13151. /* 5.1. first test, if the request targets the regular http(s)://
  13152. * protocol namespace or the websocket ws(s):// protocol namespace.
  13153. */
  13154. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13155. #if defined(USE_WEBSOCKET)
  13156. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13157. #else
  13158. handler_type = REQUEST_HANDLER;
  13159. #endif /* defined(USE_WEBSOCKET) */
  13160. if (is_websocket_request) {
  13161. HTTP1_only;
  13162. }
  13163. /* 5.2. check if the request will be handled by a callback */
  13164. if (get_request_handler(conn,
  13165. handler_type,
  13166. &callback_handler,
  13167. &subprotocols,
  13168. &ws_connect_handler,
  13169. &ws_ready_handler,
  13170. &ws_data_handler,
  13171. &ws_close_handler,
  13172. NULL,
  13173. &callback_data,
  13174. &handler_info)) {
  13175. /* 5.2.1. A callback will handle this request. All requests
  13176. * handled by a callback have to be considered as requests
  13177. * to a script resource. */
  13178. is_callback_resource = 1;
  13179. is_script_resource = 1;
  13180. is_put_or_delete_request = is_put_or_delete_method(conn);
  13181. /* Never handle a C callback according to File WebDav rules,
  13182. * even if it is a webdav method */
  13183. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13184. } else {
  13185. no_callback_resource:
  13186. /* 5.2.2. No callback is responsible for this request. The URI
  13187. * addresses a file based resource (static content or Lua/cgi
  13188. * scripts in the file system). */
  13189. is_callback_resource = 0;
  13190. interpret_uri(conn,
  13191. path,
  13192. sizeof(path),
  13193. &file.stat,
  13194. &is_found,
  13195. &is_script_resource,
  13196. &is_websocket_request,
  13197. &is_put_or_delete_request,
  13198. &is_webdav_request,
  13199. &is_template_text_file);
  13200. }
  13201. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13202. if (is_webdav_request) {
  13203. /* TODO: Do we need a config option? */
  13204. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13205. if (webdav_enable[0] != 'y') {
  13206. mg_send_http_error(conn,
  13207. 405,
  13208. "%s method not allowed",
  13209. conn->request_info.request_method);
  13210. DEBUG_TRACE("%s", "webdav rejected");
  13211. return;
  13212. }
  13213. }
  13214. /* 6. authorization check */
  13215. /* 6.1. a custom authorization handler is installed */
  13216. if (get_request_handler(conn,
  13217. AUTH_HANDLER,
  13218. NULL,
  13219. NULL,
  13220. NULL,
  13221. NULL,
  13222. NULL,
  13223. NULL,
  13224. &auth_handler,
  13225. &auth_callback_data,
  13226. NULL)) {
  13227. if (!auth_handler(conn, auth_callback_data)) {
  13228. /* Callback handler will not be used anymore. Release it */
  13229. release_handler_ref(conn, handler_info);
  13230. DEBUG_TRACE("%s", "auth handler rejected request");
  13231. return;
  13232. }
  13233. } else if (is_put_or_delete_request && !is_script_resource
  13234. && !is_callback_resource) {
  13235. HTTP1_only;
  13236. /* 6.2. this request is a PUT/DELETE to a real file */
  13237. /* 6.2.1. thus, the server must have real files */
  13238. #if defined(NO_FILES)
  13239. if (1) {
  13240. #else
  13241. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13242. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13243. #endif
  13244. /* This code path will not be called for request handlers */
  13245. DEBUG_ASSERT(handler_info == NULL);
  13246. /* This server does not have any real files, thus the
  13247. * PUT/DELETE methods are not valid. */
  13248. mg_send_http_error(conn,
  13249. 405,
  13250. "%s method not allowed",
  13251. conn->request_info.request_method);
  13252. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13253. return;
  13254. }
  13255. #if !defined(NO_FILES)
  13256. /* 6.2.2. Check if put authorization for static files is
  13257. * available.
  13258. */
  13259. if (!is_authorized_for_put(conn)) {
  13260. send_authorization_request(conn, NULL);
  13261. DEBUG_TRACE("%s", "file write needs authorization");
  13262. return;
  13263. }
  13264. #endif
  13265. } else {
  13266. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13267. * or it is a PUT or DELETE request to a resource that does not
  13268. * correspond to a file. Check authorization. */
  13269. if (!check_authorization(conn, path)) {
  13270. send_authorization_request(conn, NULL);
  13271. /* Callback handler will not be used anymore. Release it */
  13272. release_handler_ref(conn, handler_info);
  13273. DEBUG_TRACE("%s", "access authorization required");
  13274. return;
  13275. }
  13276. }
  13277. /* request is authorized or does not need authorization */
  13278. /* 7. check if there are request handlers for this uri */
  13279. if (is_callback_resource) {
  13280. HTTP1_only;
  13281. if (!is_websocket_request) {
  13282. i = callback_handler(conn, callback_data);
  13283. /* Callback handler will not be used anymore. Release it */
  13284. release_handler_ref(conn, handler_info);
  13285. if (i > 0) {
  13286. /* Do nothing, callback has served the request. Store
  13287. * then return value as status code for the log and discard
  13288. * all data from the client not used by the callback. */
  13289. conn->status_code = i;
  13290. if (!conn->must_close) {
  13291. discard_unread_request_data(conn);
  13292. }
  13293. } else {
  13294. /* The handler did NOT handle the request. */
  13295. /* Some proper reactions would be:
  13296. * a) close the connections without sending anything
  13297. * b) send a 404 not found
  13298. * c) try if there is a file matching the URI
  13299. * It would be possible to do a, b or c in the callback
  13300. * implementation, and return 1 - we cannot do anything
  13301. * here, that is not possible in the callback.
  13302. *
  13303. * TODO: What would be the best reaction here?
  13304. * (Note: The reaction may change, if there is a better
  13305. * idea.)
  13306. */
  13307. /* For the moment, use option c: We look for a proper file,
  13308. * but since a file request is not always a script resource,
  13309. * the authorization check might be different. */
  13310. callback_handler = NULL;
  13311. /* Here we are at a dead end:
  13312. * According to URI matching, a callback should be
  13313. * responsible for handling the request,
  13314. * we called it, but the callback declared itself
  13315. * not responsible.
  13316. * We use a goto here, to get out of this dead end,
  13317. * and continue with the default handling.
  13318. * A goto here is simpler and better to understand
  13319. * than some curious loop. */
  13320. goto no_callback_resource;
  13321. }
  13322. } else {
  13323. #if defined(USE_WEBSOCKET)
  13324. handle_websocket_request(conn,
  13325. path,
  13326. is_callback_resource,
  13327. subprotocols,
  13328. ws_connect_handler,
  13329. ws_ready_handler,
  13330. ws_data_handler,
  13331. ws_close_handler,
  13332. callback_data);
  13333. #endif
  13334. }
  13335. DEBUG_TRACE("%s", "websocket handling done");
  13336. return;
  13337. }
  13338. /* 8. handle websocket requests */
  13339. #if defined(USE_WEBSOCKET)
  13340. if (is_websocket_request) {
  13341. HTTP1_only;
  13342. if (is_script_resource) {
  13343. if (is_in_script_path(conn, path)) {
  13344. /* Websocket Lua script */
  13345. handle_websocket_request(conn,
  13346. path,
  13347. 0 /* Lua Script */,
  13348. NULL,
  13349. NULL,
  13350. NULL,
  13351. NULL,
  13352. NULL,
  13353. conn->phys_ctx->user_data);
  13354. } else {
  13355. /* Script was in an illegal path */
  13356. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13357. }
  13358. } else {
  13359. mg_send_http_error(conn, 404, "%s", "Not found");
  13360. }
  13361. DEBUG_TRACE("%s", "websocket script done");
  13362. return;
  13363. } else
  13364. #endif
  13365. #if defined(NO_FILES)
  13366. /* 9a. In case the server uses only callbacks, this uri is
  13367. * unknown.
  13368. * Then, all request handling ends here. */
  13369. mg_send_http_error(conn, 404, "%s", "Not Found");
  13370. #else
  13371. /* 9b. This request is either for a static file or resource handled
  13372. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13373. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13374. mg_send_http_error(conn, 404, "%s", "Not Found");
  13375. DEBUG_TRACE("%s", "no document root available");
  13376. return;
  13377. }
  13378. /* 10. Request is handled by a script */
  13379. if (is_script_resource) {
  13380. HTTP1_only;
  13381. handle_file_based_request(conn, path, &file);
  13382. DEBUG_TRACE("%s", "script handling done");
  13383. return;
  13384. }
  13385. /* Request was not handled by a callback or script. It will be
  13386. * handled by a server internal method. */
  13387. /* 11. Handle put/delete/mkcol requests */
  13388. if (is_put_or_delete_request) {
  13389. HTTP1_only;
  13390. /* 11.1. PUT method */
  13391. if (!strcmp(ri->request_method, "PUT")) {
  13392. put_file(conn, path);
  13393. DEBUG_TRACE("handling %s request to %s done",
  13394. ri->request_method,
  13395. path);
  13396. return;
  13397. }
  13398. /* 11.2. DELETE method */
  13399. if (!strcmp(ri->request_method, "DELETE")) {
  13400. delete_file(conn, path);
  13401. DEBUG_TRACE("handling %s request to %s done",
  13402. ri->request_method,
  13403. path);
  13404. return;
  13405. }
  13406. /* 11.3. MKCOL method */
  13407. if (!strcmp(ri->request_method, "MKCOL")) {
  13408. dav_mkcol(conn, path);
  13409. DEBUG_TRACE("handling %s request to %s done",
  13410. ri->request_method,
  13411. path);
  13412. return;
  13413. }
  13414. /* 11.4. MOVE method */
  13415. if (!strcmp(ri->request_method, "MOVE")) {
  13416. dav_move_file(conn, path, 0);
  13417. DEBUG_TRACE("handling %s request to %s done",
  13418. ri->request_method,
  13419. path);
  13420. return;
  13421. }
  13422. if (!strcmp(ri->request_method, "COPY")) {
  13423. dav_move_file(conn, path, 1);
  13424. DEBUG_TRACE("handling %s request to %s done",
  13425. ri->request_method,
  13426. path);
  13427. return;
  13428. }
  13429. /* 11.5. LOCK method */
  13430. if (!strcmp(ri->request_method, "LOCK")) {
  13431. dav_lock_file(conn, path);
  13432. DEBUG_TRACE("handling %s request to %s done",
  13433. ri->request_method,
  13434. path);
  13435. return;
  13436. }
  13437. /* 11.6. UNLOCK method */
  13438. if (!strcmp(ri->request_method, "UNLOCK")) {
  13439. dav_unlock_file(conn, path);
  13440. DEBUG_TRACE("handling %s request to %s done",
  13441. ri->request_method,
  13442. path);
  13443. return;
  13444. }
  13445. /* 11.7. PROPPATCH method */
  13446. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13447. dav_proppatch(conn, path);
  13448. DEBUG_TRACE("handling %s request to %s done",
  13449. ri->request_method,
  13450. path);
  13451. return;
  13452. }
  13453. /* 11.8. Other methods, e.g.: PATCH
  13454. * This method is not supported for static resources,
  13455. * only for scripts (Lua, CGI) and callbacks. */
  13456. mg_send_http_error(conn,
  13457. 405,
  13458. "%s method not allowed",
  13459. conn->request_info.request_method);
  13460. DEBUG_TRACE("method %s on %s is not supported",
  13461. ri->request_method,
  13462. path);
  13463. return;
  13464. }
  13465. /* 11. File does not exist, or it was configured that it should be
  13466. * hidden */
  13467. if (!is_found || (must_hide_file(conn, path))) {
  13468. mg_send_http_error(conn, 404, "%s", "Not found");
  13469. DEBUG_TRACE("handling %s request to %s: file not found",
  13470. ri->request_method,
  13471. path);
  13472. return;
  13473. }
  13474. /* 12. Directory uris should end with a slash */
  13475. if (file.stat.is_directory && (uri_len > 0)
  13476. && (ri->local_uri[uri_len - 1] != '/')) {
  13477. /* Path + server root */
  13478. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13479. char *new_path;
  13480. if (ri->query_string) {
  13481. buflen += strlen(ri->query_string);
  13482. }
  13483. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13484. if (!new_path) {
  13485. mg_send_http_error(conn, 500, "out or memory");
  13486. } else {
  13487. mg_get_request_link(conn, new_path, buflen - 1);
  13488. size_t len = strlen(new_path);
  13489. if (len + 1 < buflen) {
  13490. new_path[len] = '/';
  13491. new_path[len + 1] = '\0';
  13492. len++;
  13493. }
  13494. if (ri->query_string) {
  13495. if (len + 1 < buflen) {
  13496. new_path[len] = '?';
  13497. new_path[len + 1] = '\0';
  13498. len++;
  13499. }
  13500. /* Append with size of space left for query string + null terminator */
  13501. size_t max_append = buflen - len - 1;
  13502. strncat(new_path, ri->query_string, max_append);
  13503. }
  13504. mg_send_http_redirect(conn, new_path, 301);
  13505. mg_free(new_path);
  13506. }
  13507. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13508. ri->request_method,
  13509. path);
  13510. return;
  13511. }
  13512. /* 13. Handle other methods than GET/HEAD */
  13513. /* 13.1. Handle PROPFIND */
  13514. if (!strcmp(ri->request_method, "PROPFIND")) {
  13515. handle_propfind(conn, path, &file.stat);
  13516. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13517. return;
  13518. }
  13519. /* 13.2. Handle OPTIONS for files */
  13520. if (!strcmp(ri->request_method, "OPTIONS")) {
  13521. /* This standard handler is only used for real files.
  13522. * Scripts should support the OPTIONS method themselves, to allow a
  13523. * maximum flexibility.
  13524. * Lua and CGI scripts may fully support CORS this way (including
  13525. * preflights). */
  13526. send_options(conn);
  13527. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13528. return;
  13529. }
  13530. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13531. if ((0 != strcmp(ri->request_method, "GET"))
  13532. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13533. mg_send_http_error(conn,
  13534. 405,
  13535. "%s method not allowed",
  13536. conn->request_info.request_method);
  13537. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13538. return;
  13539. }
  13540. /* 14. directories */
  13541. if (file.stat.is_directory) {
  13542. /* Substitute files have already been handled above. */
  13543. /* Here we can either generate and send a directory listing,
  13544. * or send an "access denied" error. */
  13545. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13546. "yes")) {
  13547. handle_directory_request(conn, path);
  13548. } else {
  13549. mg_send_http_error(conn,
  13550. 403,
  13551. "%s",
  13552. "Error: Directory listing denied");
  13553. }
  13554. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13555. return;
  13556. }
  13557. /* 15. Files with search/replace patterns: LSP and SSI */
  13558. if (is_template_text_file) {
  13559. HTTP1_only;
  13560. handle_file_based_request(conn, path, &file);
  13561. DEBUG_TRACE("handling %s request to %s done (template)",
  13562. ri->request_method,
  13563. path);
  13564. return;
  13565. }
  13566. /* 16. Static file - maybe cached */
  13567. #if !defined(NO_CACHING)
  13568. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13569. /* Send 304 "Not Modified" - this must not send any body data */
  13570. handle_not_modified_static_file_request(conn, &file);
  13571. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13572. ri->request_method,
  13573. path);
  13574. return;
  13575. }
  13576. #endif /* !NO_CACHING */
  13577. /* 17. Static file - not cached */
  13578. handle_static_file_request(conn, path, &file, NULL, NULL);
  13579. DEBUG_TRACE("handling %s request to %s done (static)",
  13580. ri->request_method,
  13581. path);
  13582. #endif /* !defined(NO_FILES) */
  13583. }
  13584. #if !defined(NO_FILESYSTEMS)
  13585. static void
  13586. handle_file_based_request(struct mg_connection *conn,
  13587. const char *path,
  13588. struct mg_file *file)
  13589. {
  13590. #if !defined(NO_CGI)
  13591. int cgi_config_idx, inc, max;
  13592. #endif
  13593. if (!conn || !conn->dom_ctx) {
  13594. return;
  13595. }
  13596. #if defined(USE_LUA)
  13597. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13598. path)
  13599. > 0) {
  13600. if (is_in_script_path(conn, path)) {
  13601. /* Lua server page: an SSI like page containing mostly plain
  13602. * html code plus some tags with server generated contents. */
  13603. handle_lsp_request(conn, path, file, NULL);
  13604. } else {
  13605. /* Script was in an illegal path */
  13606. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13607. }
  13608. return;
  13609. }
  13610. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13611. > 0) {
  13612. if (is_in_script_path(conn, path)) {
  13613. /* Lua in-server module script: a CGI like script used to
  13614. * generate the entire reply. */
  13615. mg_exec_lua_script(conn, path, NULL);
  13616. } else {
  13617. /* Script was in an illegal path */
  13618. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13619. }
  13620. return;
  13621. }
  13622. #endif
  13623. #if defined(USE_DUKTAPE)
  13624. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13625. path)
  13626. > 0) {
  13627. if (is_in_script_path(conn, path)) {
  13628. /* Call duktape to generate the page */
  13629. mg_exec_duktape_script(conn, path);
  13630. } else {
  13631. /* Script was in an illegal path */
  13632. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13633. }
  13634. return;
  13635. }
  13636. #endif
  13637. #if !defined(NO_CGI)
  13638. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13639. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13640. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13641. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13642. if (match_prefix_strlen(
  13643. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13644. path)
  13645. > 0) {
  13646. if (is_in_script_path(conn, path)) {
  13647. /* CGI scripts may support all HTTP methods */
  13648. handle_cgi_request(conn, path, cgi_config_idx);
  13649. } else {
  13650. /* Script was in an illegal path */
  13651. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13652. }
  13653. return;
  13654. }
  13655. }
  13656. }
  13657. #endif /* !NO_CGI */
  13658. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13659. if (is_in_script_path(conn, path)) {
  13660. handle_ssi_file_request(conn, path, file);
  13661. } else {
  13662. /* Script was in an illegal path */
  13663. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13664. }
  13665. return;
  13666. }
  13667. #if !defined(NO_CACHING)
  13668. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13669. /* Send 304 "Not Modified" - this must not send any body data */
  13670. handle_not_modified_static_file_request(conn, file);
  13671. return;
  13672. }
  13673. #endif /* !NO_CACHING */
  13674. handle_static_file_request(conn, path, file, NULL, NULL);
  13675. }
  13676. #endif /* NO_FILESYSTEMS */
  13677. static void
  13678. close_all_listening_sockets(struct mg_context *ctx)
  13679. {
  13680. unsigned int i;
  13681. if (!ctx) {
  13682. return;
  13683. }
  13684. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13685. closesocket(ctx->listening_sockets[i].sock);
  13686. #if defined(USE_X_DOM_SOCKET)
  13687. /* For unix domain sockets, the socket name represents a file that has
  13688. * to be deleted. */
  13689. /* See
  13690. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13691. */
  13692. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13693. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13694. IGNORE_UNUSED_RESULT(
  13695. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13696. }
  13697. #endif
  13698. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13699. }
  13700. mg_free(ctx->listening_sockets);
  13701. ctx->listening_sockets = NULL;
  13702. mg_free(ctx->listening_socket_fds);
  13703. ctx->listening_socket_fds = NULL;
  13704. }
  13705. /* Valid listening port specification is: [ip_address:]port[s]
  13706. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13707. * Examples for IPv6: [::]:80, [::1]:80,
  13708. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13709. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13710. * In order to bind to both, IPv4 and IPv6, you can either add
  13711. * both ports using 8080,[::]:8080, or the short form +8080.
  13712. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13713. * one only accepting IPv4 the other only IPv6. +8080 creates
  13714. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13715. * environment, they might work differently, or might not work
  13716. * at all - it must be tested what options work best in the
  13717. * relevant network environment.
  13718. */
  13719. static int
  13720. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13721. {
  13722. unsigned int a, b, c, d;
  13723. unsigned port;
  13724. unsigned long portUL;
  13725. int len;
  13726. const char *cb;
  13727. char *endptr;
  13728. #if defined(USE_IPV6)
  13729. char buf[100] = {0};
  13730. #endif
  13731. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13732. * Also, all-zeroes in the socket address means binding to all addresses
  13733. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13734. memset(so, 0, sizeof(*so));
  13735. so->lsa.sin.sin_family = AF_INET;
  13736. *ip_version = 0;
  13737. /* Initialize len as invalid. */
  13738. port = 0;
  13739. len = 0;
  13740. /* Test for different ways to format this string */
  13741. if (sscanf(vec->ptr,
  13742. "%u.%u.%u.%u:%u%n",
  13743. &a,
  13744. &b,
  13745. &c,
  13746. &d,
  13747. &port,
  13748. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13749. // to an integer value, but function will not report
  13750. // conversion errors; consider using 'strtol' instead
  13751. == 5) {
  13752. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13753. so->lsa.sin.sin_addr.s_addr =
  13754. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13755. so->lsa.sin.sin_port = htons((uint16_t)port);
  13756. *ip_version = 4;
  13757. #if defined(USE_IPV6)
  13758. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13759. && ((size_t)len <= vec->len)
  13760. && mg_inet_pton(
  13761. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13762. /* IPv6 address, examples: see above */
  13763. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13764. */
  13765. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13766. *ip_version = 6;
  13767. #endif
  13768. } else if ((vec->ptr[0] == '+')
  13769. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13770. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13771. // string to an integer value, but function will not
  13772. // report conversion errors; consider using 'strtol'
  13773. // instead
  13774. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13775. /* Add 1 to len for the + character we skipped before */
  13776. len++;
  13777. #if defined(USE_IPV6)
  13778. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13779. so->lsa.sin6.sin6_family = AF_INET6;
  13780. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13781. *ip_version = 4 + 6;
  13782. #else
  13783. /* Bind to IPv4 only, since IPv6 is not built in. */
  13784. so->lsa.sin.sin_port = htons((uint16_t)port);
  13785. *ip_version = 4;
  13786. #endif
  13787. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13788. && (vec->ptr != endptr)) {
  13789. len = (int)(endptr - vec->ptr);
  13790. port = (uint16_t)portUL;
  13791. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13792. so->lsa.sin.sin_port = htons((uint16_t)port);
  13793. *ip_version = 4;
  13794. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13795. /* String could be a hostname. This check algorithm
  13796. * will only work for RFC 952 compliant hostnames,
  13797. * starting with a letter, containing only letters,
  13798. * digits and hyphen ('-'). Newer specs may allow
  13799. * more, but this is not guaranteed here, since it
  13800. * may interfere with rules for port option lists. */
  13801. /* According to RFC 1035, hostnames are restricted to 255 characters
  13802. * in total (63 between two dots). */
  13803. char hostname[256];
  13804. size_t hostnlen = (size_t)(cb - vec->ptr);
  13805. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13806. /* This would be invalid in any case */
  13807. *ip_version = 0;
  13808. return 0;
  13809. }
  13810. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13811. if (mg_inet_pton(
  13812. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13813. if (sscanf(cb + 1, "%u%n", &port, &len)
  13814. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13815. // string to an integer value, but function will not
  13816. // report conversion errors; consider using 'strtol'
  13817. // instead
  13818. *ip_version = 4;
  13819. so->lsa.sin.sin_port = htons((uint16_t)port);
  13820. len += (int)(hostnlen + 1);
  13821. } else {
  13822. len = 0;
  13823. }
  13824. #if defined(USE_IPV6)
  13825. } else if (mg_inet_pton(AF_INET6,
  13826. hostname,
  13827. &so->lsa.sin6,
  13828. sizeof(so->lsa.sin6),
  13829. 1)) {
  13830. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13831. *ip_version = 6;
  13832. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13833. len += (int)(hostnlen + 1);
  13834. } else {
  13835. len = 0;
  13836. }
  13837. #endif
  13838. } else {
  13839. len = 0;
  13840. }
  13841. #if defined(USE_X_DOM_SOCKET)
  13842. } else if (vec->ptr[0] == 'x') {
  13843. /* unix (linux) domain socket */
  13844. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13845. len = vec->len;
  13846. so->lsa.sun.sun_family = AF_UNIX;
  13847. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13848. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13849. port = 0;
  13850. *ip_version = 99;
  13851. } else {
  13852. /* String too long */
  13853. len = 0;
  13854. }
  13855. #endif
  13856. } else {
  13857. /* Parsing failure. */
  13858. len = 0;
  13859. }
  13860. /* sscanf and the option splitting code ensure the following condition
  13861. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13862. * 'r' */
  13863. if ((len > 0) && (is_valid_port(port))) {
  13864. int bad_suffix = 0;
  13865. size_t i;
  13866. /* Parse any suffix character(s) after the port number */
  13867. for (i = len; i < vec->len; i++) {
  13868. unsigned char *opt = NULL;
  13869. switch (vec->ptr[i]) {
  13870. case 'o':
  13871. opt = &so->is_optional;
  13872. break;
  13873. case 'r':
  13874. opt = &so->ssl_redir;
  13875. break;
  13876. case 's':
  13877. opt = &so->is_ssl;
  13878. break;
  13879. default: /* empty */
  13880. break;
  13881. }
  13882. if ((opt) && (*opt == 0))
  13883. *opt = 1;
  13884. else {
  13885. bad_suffix = 1;
  13886. break;
  13887. }
  13888. }
  13889. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13890. return 1;
  13891. }
  13892. }
  13893. /* Reset ip_version to 0 if there is an error */
  13894. *ip_version = 0;
  13895. return 0;
  13896. }
  13897. /* Is there any SSL port in use? */
  13898. static int
  13899. is_ssl_port_used(const char *ports)
  13900. {
  13901. if (ports) {
  13902. /* There are several different allowed syntax variants:
  13903. * - "80" for a single port using every network interface
  13904. * - "localhost:80" for a single port using only localhost
  13905. * - "80,localhost:8080" for two ports, one bound to localhost
  13906. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13907. * to IPv4 localhost, one to IPv6 localhost
  13908. * - "+80" use port 80 for IPv4 and IPv6
  13909. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13910. * for both: IPv4 and IPv4
  13911. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13912. * additionally port 8080 bound to localhost connections
  13913. *
  13914. * If we just look for 's' anywhere in the string, "localhost:80"
  13915. * will be detected as SSL (false positive).
  13916. * Looking for 's' after a digit may cause false positives in
  13917. * "my24service:8080".
  13918. * Looking from 's' backward if there are only ':' and numbers
  13919. * before will not work for "24service:8080" (non SSL, port 8080)
  13920. * or "24s" (SSL, port 24).
  13921. *
  13922. * Remark: Initially hostnames were not allowed to start with a
  13923. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13924. * Section 2.1).
  13925. *
  13926. * To get this correct, the entire string must be parsed as a whole,
  13927. * reading it as a list element for element and parsing with an
  13928. * algorithm equivalent to parse_port_string.
  13929. *
  13930. * In fact, we use local interface names here, not arbitrary
  13931. * hostnames, so in most cases the only name will be "localhost".
  13932. *
  13933. * So, for now, we use this simple algorithm, that may still return
  13934. * a false positive in bizarre cases.
  13935. */
  13936. int i;
  13937. int portslen = (int)strlen(ports);
  13938. char prevIsNumber = 0;
  13939. for (i = 0; i < portslen; i++) {
  13940. if (prevIsNumber) {
  13941. int suffixCharIdx = (ports[i] == 'o')
  13942. ? (i + 1)
  13943. : i; /* allow "os" and "or" suffixes */
  13944. if (ports[suffixCharIdx] == 's'
  13945. || ports[suffixCharIdx] == 'r') {
  13946. return 1;
  13947. }
  13948. }
  13949. if (ports[i] >= '0' && ports[i] <= '9') {
  13950. prevIsNumber = 1;
  13951. } else {
  13952. prevIsNumber = 0;
  13953. }
  13954. }
  13955. }
  13956. return 0;
  13957. }
  13958. static int
  13959. set_ports_option(struct mg_context *phys_ctx)
  13960. {
  13961. const char *list;
  13962. int on = 1;
  13963. #if defined(USE_IPV6)
  13964. int off = 0;
  13965. #endif
  13966. struct vec vec;
  13967. struct socket so, *ptr;
  13968. struct mg_pollfd *pfd;
  13969. union usa usa;
  13970. socklen_t len;
  13971. int ip_version;
  13972. int portsTotal = 0;
  13973. int portsOk = 0;
  13974. const char *opt_txt;
  13975. long opt_listen_backlog;
  13976. if (!phys_ctx) {
  13977. return 0;
  13978. }
  13979. memset(&so, 0, sizeof(so));
  13980. memset(&usa, 0, sizeof(usa));
  13981. len = sizeof(usa);
  13982. list = phys_ctx->dd.config[LISTENING_PORTS];
  13983. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13984. portsTotal++;
  13985. if (!parse_port_string(&vec, &so, &ip_version)) {
  13986. mg_cry_ctx_internal(
  13987. phys_ctx,
  13988. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13989. (int)vec.len,
  13990. vec.ptr,
  13991. portsTotal,
  13992. "[IP_ADDRESS:]PORT[s|r]");
  13993. continue;
  13994. }
  13995. #if !defined(NO_SSL)
  13996. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13997. mg_cry_ctx_internal(phys_ctx,
  13998. "Cannot add SSL socket (entry %i)",
  13999. portsTotal);
  14000. continue;
  14001. }
  14002. #endif
  14003. /* Create socket. */
  14004. /* For a list of protocol numbers (e.g., TCP==6) see:
  14005. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  14006. */
  14007. if ((so.sock =
  14008. socket(so.lsa.sa.sa_family,
  14009. SOCK_STREAM,
  14010. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  14011. == INVALID_SOCKET) {
  14012. mg_cry_ctx_internal(phys_ctx,
  14013. "cannot create socket (entry %i)",
  14014. portsTotal);
  14015. if (so.is_optional) {
  14016. portsOk++; /* it's okay if we couldn't create a socket,
  14017. this port is optional anyway */
  14018. }
  14019. continue;
  14020. }
  14021. #if defined(_WIN32)
  14022. /* Windows SO_REUSEADDR lets many procs binds to a
  14023. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  14024. * if someone already has the socket -- DTL */
  14025. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  14026. * Windows might need a few seconds before
  14027. * the same port can be used again in the
  14028. * same process, so a short Sleep may be
  14029. * required between mg_stop and mg_start.
  14030. */
  14031. if (setsockopt(so.sock,
  14032. SOL_SOCKET,
  14033. SO_EXCLUSIVEADDRUSE,
  14034. (SOCK_OPT_TYPE)&on,
  14035. sizeof(on))
  14036. != 0) {
  14037. /* Set reuse option, but don't abort on errors. */
  14038. mg_cry_ctx_internal(
  14039. phys_ctx,
  14040. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  14041. portsTotal);
  14042. }
  14043. #else
  14044. if (setsockopt(so.sock,
  14045. SOL_SOCKET,
  14046. SO_REUSEADDR,
  14047. (SOCK_OPT_TYPE)&on,
  14048. sizeof(on))
  14049. != 0) {
  14050. /* Set reuse option, but don't abort on errors. */
  14051. mg_cry_ctx_internal(
  14052. phys_ctx,
  14053. "cannot set socket option SO_REUSEADDR (entry %i)",
  14054. portsTotal);
  14055. }
  14056. #endif
  14057. #if defined(USE_X_DOM_SOCKET)
  14058. if (ip_version == 99) {
  14059. /* Unix domain socket */
  14060. } else
  14061. #endif
  14062. if (ip_version > 4) {
  14063. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  14064. #if defined(USE_IPV6)
  14065. if (ip_version > 6) {
  14066. if (so.lsa.sa.sa_family == AF_INET6
  14067. && setsockopt(so.sock,
  14068. IPPROTO_IPV6,
  14069. IPV6_V6ONLY,
  14070. (void *)&off,
  14071. sizeof(off))
  14072. != 0) {
  14073. /* Set IPv6 only option, but don't abort on errors. */
  14074. mg_cry_ctx_internal(phys_ctx,
  14075. "cannot set socket option "
  14076. "IPV6_V6ONLY=off (entry %i)",
  14077. portsTotal);
  14078. }
  14079. } else {
  14080. if (so.lsa.sa.sa_family == AF_INET6
  14081. && setsockopt(so.sock,
  14082. IPPROTO_IPV6,
  14083. IPV6_V6ONLY,
  14084. (void *)&on,
  14085. sizeof(on))
  14086. != 0) {
  14087. /* Set IPv6 only option, but don't abort on errors. */
  14088. mg_cry_ctx_internal(phys_ctx,
  14089. "cannot set socket option "
  14090. "IPV6_V6ONLY=on (entry %i)",
  14091. portsTotal);
  14092. }
  14093. }
  14094. #else
  14095. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  14096. closesocket(so.sock);
  14097. if (so.is_optional) {
  14098. portsOk++; /* it's okay if we couldn't set the socket option,
  14099. this port is optional anyway */
  14100. }
  14101. so.sock = INVALID_SOCKET;
  14102. continue;
  14103. #endif
  14104. }
  14105. if (so.lsa.sa.sa_family == AF_INET) {
  14106. len = sizeof(so.lsa.sin);
  14107. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14108. mg_cry_ctx_internal(phys_ctx,
  14109. "cannot bind to %.*s: %d (%s)",
  14110. (int)vec.len,
  14111. vec.ptr,
  14112. (int)ERRNO,
  14113. strerror(errno));
  14114. closesocket(so.sock);
  14115. so.sock = INVALID_SOCKET;
  14116. if (so.is_optional) {
  14117. portsOk++; /* it's okay if we couldn't bind, this port is
  14118. optional anyway */
  14119. }
  14120. continue;
  14121. }
  14122. }
  14123. #if defined(USE_IPV6)
  14124. else if (so.lsa.sa.sa_family == AF_INET6) {
  14125. len = sizeof(so.lsa.sin6);
  14126. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14127. mg_cry_ctx_internal(phys_ctx,
  14128. "cannot bind to IPv6 %.*s: %d (%s)",
  14129. (int)vec.len,
  14130. vec.ptr,
  14131. (int)ERRNO,
  14132. strerror(errno));
  14133. closesocket(so.sock);
  14134. so.sock = INVALID_SOCKET;
  14135. if (so.is_optional) {
  14136. portsOk++; /* it's okay if we couldn't bind, this port is
  14137. optional anyway */
  14138. }
  14139. continue;
  14140. }
  14141. }
  14142. #endif
  14143. #if defined(USE_X_DOM_SOCKET)
  14144. else if (so.lsa.sa.sa_family == AF_UNIX) {
  14145. len = sizeof(so.lsa.sun);
  14146. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  14147. mg_cry_ctx_internal(phys_ctx,
  14148. "cannot bind to unix socket %s: %d (%s)",
  14149. so.lsa.sun.sun_path,
  14150. (int)ERRNO,
  14151. strerror(errno));
  14152. closesocket(so.sock);
  14153. so.sock = INVALID_SOCKET;
  14154. if (so.is_optional) {
  14155. portsOk++; /* it's okay if we couldn't bind, this port is
  14156. optional anyway */
  14157. }
  14158. continue;
  14159. }
  14160. }
  14161. #endif
  14162. else {
  14163. mg_cry_ctx_internal(
  14164. phys_ctx,
  14165. "cannot bind: address family not supported (entry %i)",
  14166. portsTotal);
  14167. closesocket(so.sock);
  14168. so.sock = INVALID_SOCKET;
  14169. continue;
  14170. }
  14171. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14172. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14173. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14174. mg_cry_ctx_internal(phys_ctx,
  14175. "%s value \"%s\" is invalid",
  14176. config_options[LISTEN_BACKLOG_SIZE].name,
  14177. opt_txt);
  14178. closesocket(so.sock);
  14179. so.sock = INVALID_SOCKET;
  14180. continue;
  14181. }
  14182. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14183. mg_cry_ctx_internal(phys_ctx,
  14184. "cannot listen to %.*s: %d (%s)",
  14185. (int)vec.len,
  14186. vec.ptr,
  14187. (int)ERRNO,
  14188. strerror(errno));
  14189. closesocket(so.sock);
  14190. so.sock = INVALID_SOCKET;
  14191. continue;
  14192. }
  14193. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14194. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14195. int err = (int)ERRNO;
  14196. mg_cry_ctx_internal(phys_ctx,
  14197. "call to getsockname failed %.*s: %d (%s)",
  14198. (int)vec.len,
  14199. vec.ptr,
  14200. err,
  14201. strerror(errno));
  14202. closesocket(so.sock);
  14203. so.sock = INVALID_SOCKET;
  14204. continue;
  14205. }
  14206. /* Update lsa port in case of random free ports */
  14207. #if defined(USE_IPV6)
  14208. if (so.lsa.sa.sa_family == AF_INET6) {
  14209. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14210. } else
  14211. #endif
  14212. {
  14213. so.lsa.sin.sin_port = usa.sin.sin_port;
  14214. }
  14215. if ((ptr = (struct socket *)
  14216. mg_realloc_ctx(phys_ctx->listening_sockets,
  14217. (phys_ctx->num_listening_sockets + 1)
  14218. * sizeof(phys_ctx->listening_sockets[0]),
  14219. phys_ctx))
  14220. == NULL) {
  14221. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14222. closesocket(so.sock);
  14223. so.sock = INVALID_SOCKET;
  14224. continue;
  14225. }
  14226. /* The +2 below includes the original +1 (for the socket we're about to
  14227. * add), plus another +1 for the thread_shutdown_notification_socket
  14228. * that we'll also want to poll() on so that mg_stop() can return
  14229. * quickly
  14230. */
  14231. if ((pfd = (struct mg_pollfd *)
  14232. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14233. (phys_ctx->num_listening_sockets + 2)
  14234. * sizeof(phys_ctx->listening_socket_fds[0]),
  14235. phys_ctx))
  14236. == NULL) {
  14237. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14238. closesocket(so.sock);
  14239. so.sock = INVALID_SOCKET;
  14240. mg_free(ptr);
  14241. continue;
  14242. }
  14243. set_close_on_exec(so.sock, NULL, phys_ctx);
  14244. phys_ctx->listening_sockets = ptr;
  14245. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14246. phys_ctx->listening_socket_fds = pfd;
  14247. phys_ctx->num_listening_sockets++;
  14248. portsOk++;
  14249. }
  14250. if (portsOk != portsTotal) {
  14251. close_all_listening_sockets(phys_ctx);
  14252. portsOk = 0;
  14253. }
  14254. return portsOk;
  14255. }
  14256. static const char *
  14257. header_val(const struct mg_connection *conn, const char *header)
  14258. {
  14259. const char *header_value;
  14260. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14261. return "-";
  14262. } else {
  14263. return header_value;
  14264. }
  14265. }
  14266. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14267. #include "external_log_access.inl"
  14268. #elif !defined(NO_FILESYSTEMS)
  14269. static void
  14270. log_access(const struct mg_connection *conn)
  14271. {
  14272. const struct mg_request_info *ri;
  14273. struct mg_file fi;
  14274. char date[64], src_addr[IP_ADDR_STR_LEN];
  14275. #if defined(REENTRANT_TIME)
  14276. struct tm _tm;
  14277. struct tm *tm = &_tm;
  14278. #else
  14279. struct tm *tm;
  14280. #endif
  14281. const char *referer;
  14282. const char *user_agent;
  14283. char log_buf[4096];
  14284. if (!conn || !conn->dom_ctx) {
  14285. return;
  14286. }
  14287. /* Set log message to "empty" */
  14288. log_buf[0] = 0;
  14289. #if defined(USE_LUA)
  14290. if (conn->phys_ctx->lua_bg_log_available) {
  14291. int ret;
  14292. struct mg_context *ctx = conn->phys_ctx;
  14293. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14294. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14295. /* call "log()" in Lua */
  14296. lua_getglobal(lstate, "log");
  14297. prepare_lua_request_info_inner(conn, lstate);
  14298. push_lua_response_log_data(conn, lstate);
  14299. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14300. if (ret == 0) {
  14301. int t = lua_type(lstate, -1);
  14302. if (t == LUA_TBOOLEAN) {
  14303. if (lua_toboolean(lstate, -1) == 0) {
  14304. /* log() returned false: do not log */
  14305. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14306. return;
  14307. }
  14308. /* log returned true: continue logging */
  14309. } else if (t == LUA_TSTRING) {
  14310. size_t len;
  14311. const char *txt = lua_tolstring(lstate, -1, &len);
  14312. if ((len == 0) || (*txt == 0)) {
  14313. /* log() returned empty string: do not log */
  14314. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14315. return;
  14316. }
  14317. /* Copy test from Lua into log_buf */
  14318. if (len >= sizeof(log_buf)) {
  14319. len = sizeof(log_buf) - 1;
  14320. }
  14321. memcpy(log_buf, txt, len);
  14322. log_buf[len] = 0;
  14323. }
  14324. } else {
  14325. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14326. }
  14327. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14328. }
  14329. #endif
  14330. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14331. if (mg_fopen(conn,
  14332. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14333. MG_FOPEN_MODE_APPEND,
  14334. &fi)
  14335. == 0) {
  14336. fi.access.fp = NULL;
  14337. }
  14338. } else {
  14339. fi.access.fp = NULL;
  14340. }
  14341. /* Log is written to a file and/or a callback. If both are not set,
  14342. * executing the rest of the function is pointless. */
  14343. if ((fi.access.fp == NULL)
  14344. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14345. return;
  14346. }
  14347. /* If we did not get a log message from Lua, create it here. */
  14348. if (!log_buf[0]) {
  14349. #if defined(REENTRANT_TIME)
  14350. localtime_r(&conn->conn_birth_time, tm);
  14351. #else
  14352. tm = localtime(&conn->conn_birth_time);
  14353. #endif
  14354. if (tm != NULL) {
  14355. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14356. } else {
  14357. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14358. }
  14359. ri = &conn->request_info;
  14360. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14361. referer = header_val(conn, "Referer");
  14362. user_agent = header_val(conn, "User-Agent");
  14363. mg_snprintf(conn,
  14364. NULL, /* Ignore truncation in access log */
  14365. log_buf,
  14366. sizeof(log_buf),
  14367. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14368. " %s %s",
  14369. src_addr,
  14370. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14371. date,
  14372. ri->request_method ? ri->request_method : "-",
  14373. ri->request_uri ? ri->request_uri : "-",
  14374. ri->query_string ? "?" : "",
  14375. ri->query_string ? ri->query_string : "",
  14376. ri->http_version,
  14377. conn->status_code,
  14378. conn->num_bytes_sent,
  14379. referer,
  14380. user_agent);
  14381. }
  14382. /* Here we have a log message in log_buf. Call the callback */
  14383. if (conn->phys_ctx->callbacks.log_access) {
  14384. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14385. /* do not log if callback returns non-zero */
  14386. if (fi.access.fp) {
  14387. mg_fclose(&fi.access);
  14388. }
  14389. return;
  14390. }
  14391. }
  14392. /* Store in file */
  14393. if (fi.access.fp) {
  14394. int ok = 1;
  14395. flockfile(fi.access.fp);
  14396. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14397. ok = 0;
  14398. }
  14399. if (fflush(fi.access.fp) != 0) {
  14400. ok = 0;
  14401. }
  14402. funlockfile(fi.access.fp);
  14403. if (mg_fclose(&fi.access) != 0) {
  14404. ok = 0;
  14405. }
  14406. if (!ok) {
  14407. mg_cry_internal(conn,
  14408. "Error writing log file %s",
  14409. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14410. }
  14411. }
  14412. }
  14413. #else
  14414. #error "Either enable filesystems or provide a custom log_access implementation"
  14415. #endif /* Externally provided function */
  14416. /* Verify given socket address against the ACL.
  14417. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14418. */
  14419. static int
  14420. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14421. {
  14422. int allowed, flag, matched;
  14423. struct vec vec;
  14424. if (phys_ctx) {
  14425. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14426. /* If any ACL is set, deny by default */
  14427. allowed = (list == NULL) ? '+' : '-';
  14428. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14429. flag = vec.ptr[0];
  14430. matched = -1;
  14431. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14432. vec.ptr++;
  14433. vec.len--;
  14434. matched = parse_match_net(&vec, sa, 1);
  14435. }
  14436. if (matched < 0) {
  14437. mg_cry_ctx_internal(phys_ctx,
  14438. "%s: subnet must be [+|-]IP-addr[/x]",
  14439. __func__);
  14440. return -1;
  14441. }
  14442. if (matched) {
  14443. allowed = flag;
  14444. }
  14445. }
  14446. return allowed == '+';
  14447. }
  14448. return -1;
  14449. }
  14450. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14451. static int
  14452. set_uid_option(struct mg_context *phys_ctx)
  14453. {
  14454. int success = 0;
  14455. if (phys_ctx) {
  14456. /* We are currently running as curr_uid. */
  14457. const uid_t curr_uid = getuid();
  14458. /* If set, we want to run as run_as_user. */
  14459. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14460. const struct passwd *to_pw = NULL;
  14461. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14462. /* run_as_user does not exist on the system. We can't proceed
  14463. * further. */
  14464. mg_cry_ctx_internal(phys_ctx,
  14465. "%s: unknown user [%s]",
  14466. __func__,
  14467. run_as_user);
  14468. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14469. /* There was either no request to change user, or we're already
  14470. * running as run_as_user. Nothing else to do.
  14471. */
  14472. success = 1;
  14473. } else {
  14474. /* Valid change request. */
  14475. if (setgid(to_pw->pw_gid) == -1) {
  14476. mg_cry_ctx_internal(phys_ctx,
  14477. "%s: setgid(%s): %s",
  14478. __func__,
  14479. run_as_user,
  14480. strerror(errno));
  14481. } else if (setgroups(0, NULL) == -1) {
  14482. mg_cry_ctx_internal(phys_ctx,
  14483. "%s: setgroups(): %s",
  14484. __func__,
  14485. strerror(errno));
  14486. } else if (setuid(to_pw->pw_uid) == -1) {
  14487. mg_cry_ctx_internal(phys_ctx,
  14488. "%s: setuid(%s): %s",
  14489. __func__,
  14490. run_as_user,
  14491. strerror(errno));
  14492. } else {
  14493. success = 1;
  14494. }
  14495. }
  14496. }
  14497. return success;
  14498. }
  14499. #endif /* !_WIN32 */
  14500. static void
  14501. tls_dtor(void *key)
  14502. {
  14503. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14504. /* key == pthread_getspecific(sTlsKey); */
  14505. if (tls) {
  14506. if (tls->is_master == 2) {
  14507. tls->is_master = -3; /* Mark memory as dead */
  14508. mg_free(tls);
  14509. }
  14510. }
  14511. pthread_setspecific(sTlsKey, NULL);
  14512. }
  14513. #if defined(USE_MBEDTLS)
  14514. /* Check if SSL is required.
  14515. * If so, set up ctx->ssl_ctx pointer. */
  14516. static int
  14517. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14518. {
  14519. if (!phys_ctx) {
  14520. return 0;
  14521. }
  14522. if (!dom_ctx) {
  14523. dom_ctx = &(phys_ctx->dd);
  14524. }
  14525. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14526. /* No SSL port is set. No need to setup SSL. */
  14527. return 1;
  14528. }
  14529. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14530. if (dom_ctx->ssl_ctx == NULL) {
  14531. fprintf(stderr, "ssl_ctx malloc failed\n");
  14532. return 0;
  14533. }
  14534. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14535. == 0
  14536. ? 1
  14537. : 0;
  14538. }
  14539. #elif defined(USE_GNUTLS)
  14540. /* Check if SSL is required.
  14541. * If so, set up ctx->ssl_ctx pointer. */
  14542. static int
  14543. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14544. {
  14545. if (!phys_ctx) {
  14546. return 0;
  14547. }
  14548. if (!dom_ctx) {
  14549. dom_ctx = &(phys_ctx->dd);
  14550. }
  14551. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14552. /* No SSL port is set. No need to setup SSL. */
  14553. return 1;
  14554. }
  14555. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14556. if (dom_ctx->ssl_ctx == NULL) {
  14557. fprintf(stderr, "ssl_ctx malloc failed\n");
  14558. return 0;
  14559. }
  14560. return gtls_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14561. == 0
  14562. ? 1
  14563. : 0;
  14564. }
  14565. #elif !defined(NO_SSL)
  14566. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14567. struct mg_domain_context *dom_ctx,
  14568. const char *pem,
  14569. const char *chain);
  14570. static const char *ssl_error(void);
  14571. static int
  14572. refresh_trust(struct mg_connection *conn)
  14573. {
  14574. struct stat cert_buf;
  14575. int64_t t = 0;
  14576. const char *pem;
  14577. const char *chain;
  14578. int should_verify_peer;
  14579. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14580. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14581. * refresh_trust still can not work. */
  14582. return 0;
  14583. }
  14584. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14585. if (chain == NULL) {
  14586. /* pem is not NULL here */
  14587. chain = pem;
  14588. }
  14589. if (*chain == 0) {
  14590. chain = NULL;
  14591. }
  14592. if (stat(pem, &cert_buf) != -1) {
  14593. t = (int64_t)cert_buf.st_mtime;
  14594. }
  14595. mg_lock_context(conn->phys_ctx);
  14596. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14597. conn->dom_ctx->ssl_cert_last_mtime = t;
  14598. should_verify_peer = 0;
  14599. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14600. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14601. == 0) {
  14602. should_verify_peer = 1;
  14603. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14604. "optional")
  14605. == 0) {
  14606. should_verify_peer = 1;
  14607. }
  14608. }
  14609. if (should_verify_peer) {
  14610. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14611. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14612. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14613. ca_file,
  14614. ca_path)
  14615. != 1) {
  14616. mg_unlock_context(conn->phys_ctx);
  14617. mg_cry_ctx_internal(
  14618. conn->phys_ctx,
  14619. "SSL_CTX_load_verify_locations error: %s "
  14620. "ssl_verify_peer requires setting "
  14621. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14622. "present in "
  14623. "the .conf file?",
  14624. ssl_error());
  14625. return 0;
  14626. }
  14627. }
  14628. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14629. mg_unlock_context(conn->phys_ctx);
  14630. return 0;
  14631. }
  14632. }
  14633. mg_unlock_context(conn->phys_ctx);
  14634. return 1;
  14635. }
  14636. #if defined(OPENSSL_API_1_1)
  14637. #else
  14638. static pthread_mutex_t *ssl_mutexes;
  14639. #endif /* OPENSSL_API_1_1 */
  14640. static int
  14641. sslize(struct mg_connection *conn,
  14642. int (*func)(SSL *),
  14643. const struct mg_client_options *client_options)
  14644. {
  14645. int ret, err;
  14646. int short_trust;
  14647. unsigned timeout = 1024;
  14648. unsigned i;
  14649. if (!conn) {
  14650. return 0;
  14651. }
  14652. short_trust =
  14653. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14654. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14655. if (short_trust) {
  14656. int trust_ret = refresh_trust(conn);
  14657. if (!trust_ret) {
  14658. return trust_ret;
  14659. }
  14660. }
  14661. mg_lock_context(conn->phys_ctx);
  14662. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14663. mg_unlock_context(conn->phys_ctx);
  14664. if (conn->ssl == NULL) {
  14665. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14666. OPENSSL_REMOVE_THREAD_STATE();
  14667. return 0;
  14668. }
  14669. SSL_set_app_data(conn->ssl, (char *)conn);
  14670. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14671. if (ret != 1) {
  14672. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14673. SSL_free(conn->ssl);
  14674. conn->ssl = NULL;
  14675. OPENSSL_REMOVE_THREAD_STATE();
  14676. return 0;
  14677. }
  14678. if (client_options) {
  14679. if (client_options->host_name) {
  14680. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14681. }
  14682. }
  14683. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14684. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14685. /* NOTE: The loop below acts as a back-off, so we can end
  14686. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14687. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14688. if (to >= 0) {
  14689. timeout = (unsigned)to;
  14690. }
  14691. }
  14692. /* SSL functions may fail and require to be called again:
  14693. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14694. * Here "func" could be SSL_connect or SSL_accept. */
  14695. for (i = 0; i <= timeout; i += 50) {
  14696. ERR_clear_error();
  14697. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14698. ret = func(conn->ssl);
  14699. if (ret != 1) {
  14700. err = SSL_get_error(conn->ssl, ret);
  14701. if ((err == SSL_ERROR_WANT_CONNECT)
  14702. || (err == SSL_ERROR_WANT_ACCEPT)
  14703. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14704. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14705. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14706. /* Don't wait if the server is going to be stopped. */
  14707. break;
  14708. }
  14709. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14710. /* Simply retry the function call. */
  14711. mg_sleep(50);
  14712. } else {
  14713. /* Need to retry the function call "later".
  14714. * See https://linux.die.net/man/3/ssl_get_error
  14715. * This is typical for non-blocking sockets. */
  14716. struct mg_pollfd pfd[2];
  14717. int pollres;
  14718. unsigned int num_sock = 1;
  14719. pfd[0].fd = conn->client.sock;
  14720. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14721. || (err == SSL_ERROR_WANT_WRITE))
  14722. ? POLLOUT
  14723. : POLLIN;
  14724. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14725. pfd[num_sock].fd =
  14726. conn->phys_ctx->thread_shutdown_notification_socket;
  14727. pfd[num_sock].events = POLLIN;
  14728. num_sock++;
  14729. }
  14730. pollres = mg_poll(pfd,
  14731. num_sock,
  14732. 50,
  14733. &(conn->phys_ctx->stop_flag));
  14734. if (pollres < 0) {
  14735. /* Break if error occurred (-1)
  14736. * or server shutdown (-2) */
  14737. break;
  14738. }
  14739. }
  14740. } else if (err == SSL_ERROR_SYSCALL) {
  14741. /* This is an IO error. Look at errno. */
  14742. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14743. break;
  14744. } else {
  14745. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14746. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14747. break;
  14748. }
  14749. } else {
  14750. /* success */
  14751. break;
  14752. }
  14753. }
  14754. ERR_clear_error();
  14755. if (ret != 1) {
  14756. SSL_free(conn->ssl);
  14757. conn->ssl = NULL;
  14758. OPENSSL_REMOVE_THREAD_STATE();
  14759. return 0;
  14760. }
  14761. return 1;
  14762. }
  14763. /* Return OpenSSL error message (from CRYPTO lib) */
  14764. static const char *
  14765. ssl_error(void)
  14766. {
  14767. unsigned long err;
  14768. err = ERR_get_error();
  14769. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14770. }
  14771. static int
  14772. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14773. {
  14774. int i;
  14775. const char hexdigit[] = "0123456789abcdef";
  14776. if ((memlen <= 0) || (buflen <= 0)) {
  14777. return 0;
  14778. }
  14779. if (buflen < (3 * memlen)) {
  14780. return 0;
  14781. }
  14782. for (i = 0; i < memlen; i++) {
  14783. if (i > 0) {
  14784. buf[3 * i - 1] = ' ';
  14785. }
  14786. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14787. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14788. }
  14789. buf[3 * memlen - 1] = 0;
  14790. return 1;
  14791. }
  14792. static int
  14793. ssl_get_client_cert_info(const struct mg_connection *conn,
  14794. struct mg_client_cert *client_cert)
  14795. {
  14796. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14797. if (cert) {
  14798. char str_buf[1024];
  14799. unsigned char buf[256];
  14800. char *str_serial = NULL;
  14801. unsigned int ulen;
  14802. int ilen;
  14803. unsigned char *tmp_buf;
  14804. unsigned char *tmp_p;
  14805. /* Handle to algorithm used for fingerprint */
  14806. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14807. /* Get Subject and issuer */
  14808. X509_NAME *subj = X509_get_subject_name(cert);
  14809. X509_NAME *iss = X509_get_issuer_name(cert);
  14810. /* Get serial number */
  14811. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14812. /* Translate serial number to a hex string */
  14813. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14814. if (serial_bn) {
  14815. str_serial = BN_bn2hex(serial_bn);
  14816. BN_free(serial_bn);
  14817. }
  14818. client_cert->serial =
  14819. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14820. /* Translate subject and issuer to a string */
  14821. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14822. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14823. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14824. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14825. /* Calculate SHA1 fingerprint and store as a hex string */
  14826. ulen = 0;
  14827. /* ASN1_digest is deprecated. Do the calculation manually,
  14828. * using EVP_Digest. */
  14829. ilen = i2d_X509(cert, NULL);
  14830. tmp_buf = (ilen > 0)
  14831. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14832. conn->phys_ctx)
  14833. : NULL;
  14834. if (tmp_buf) {
  14835. tmp_p = tmp_buf;
  14836. (void)i2d_X509(cert, &tmp_p);
  14837. if (!EVP_Digest(
  14838. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14839. ulen = 0;
  14840. }
  14841. mg_free(tmp_buf);
  14842. }
  14843. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14844. *str_buf = 0;
  14845. }
  14846. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14847. client_cert->peer_cert = (void *)cert;
  14848. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14849. * see https://linux.die.net/man/3/bn_bn2hex */
  14850. OPENSSL_free(str_serial);
  14851. return 1;
  14852. }
  14853. return 0;
  14854. }
  14855. #if defined(OPENSSL_API_1_1)
  14856. #else
  14857. static void
  14858. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14859. {
  14860. (void)line;
  14861. (void)file;
  14862. if (mode & 1) {
  14863. /* 1 is CRYPTO_LOCK */
  14864. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14865. } else {
  14866. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14867. }
  14868. }
  14869. #endif /* OPENSSL_API_1_1 */
  14870. #if !defined(NO_SSL_DL)
  14871. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14872. static void *
  14873. load_tls_dll(char *ebuf,
  14874. size_t ebuf_len,
  14875. const char *dll_name,
  14876. struct ssl_func *sw,
  14877. int *feature_missing)
  14878. {
  14879. union {
  14880. void *p;
  14881. void (*fp)(void);
  14882. } u;
  14883. void *dll_handle;
  14884. struct ssl_func *fp;
  14885. int ok;
  14886. int truncated = 0;
  14887. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14888. mg_snprintf(NULL,
  14889. NULL, /* No truncation check for ebuf */
  14890. ebuf,
  14891. ebuf_len,
  14892. "%s: cannot load %s",
  14893. __func__,
  14894. dll_name);
  14895. return NULL;
  14896. }
  14897. ok = 1;
  14898. for (fp = sw; fp->name != NULL; fp++) {
  14899. #if defined(_WIN32)
  14900. /* GetProcAddress() returns pointer to function */
  14901. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14902. #else
  14903. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14904. * pointers to function pointers. We need to use a union to make a
  14905. * cast. */
  14906. u.p = dlsym(dll_handle, fp->name);
  14907. #endif /* _WIN32 */
  14908. /* Set pointer (might be NULL) */
  14909. fp->ptr = u.fp;
  14910. if (u.fp == NULL) {
  14911. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14912. if (feature_missing) {
  14913. feature_missing[fp->required]++;
  14914. }
  14915. if (fp->required == TLS_Mandatory) {
  14916. /* Mandatory function is missing */
  14917. if (ok) {
  14918. /* This is the first missing function.
  14919. * Create a new error message. */
  14920. mg_snprintf(NULL,
  14921. &truncated,
  14922. ebuf,
  14923. ebuf_len,
  14924. "%s: %s: cannot find %s",
  14925. __func__,
  14926. dll_name,
  14927. fp->name);
  14928. ok = 0;
  14929. } else {
  14930. /* This is yet anothermissing function.
  14931. * Append existing error message. */
  14932. size_t cur_len = strlen(ebuf);
  14933. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14934. mg_snprintf(NULL,
  14935. &truncated,
  14936. ebuf + cur_len,
  14937. ebuf_len - cur_len - 3,
  14938. ", %s",
  14939. fp->name);
  14940. if (truncated) {
  14941. /* If truncated, add "..." */
  14942. strcat(ebuf, "...");
  14943. }
  14944. }
  14945. }
  14946. }
  14947. }
  14948. }
  14949. if (!ok) {
  14950. (void)dlclose(dll_handle);
  14951. return NULL;
  14952. }
  14953. return dll_handle;
  14954. }
  14955. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14956. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14957. #endif /* NO_SSL_DL */
  14958. #if defined(SSL_ALREADY_INITIALIZED)
  14959. static volatile ptrdiff_t cryptolib_users =
  14960. 1; /* Reference counter for crypto library. */
  14961. #else
  14962. static volatile ptrdiff_t cryptolib_users =
  14963. 0; /* Reference counter for crypto library. */
  14964. #endif
  14965. static int
  14966. initialize_openssl(char *ebuf, size_t ebuf_len)
  14967. {
  14968. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14969. int i, num_locks;
  14970. size_t size;
  14971. #endif
  14972. if (ebuf_len > 0) {
  14973. ebuf[0] = 0;
  14974. }
  14975. #if !defined(NO_SSL_DL)
  14976. if (!cryptolib_dll_handle) {
  14977. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14978. cryptolib_dll_handle = load_tls_dll(
  14979. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14980. if (!cryptolib_dll_handle) {
  14981. mg_snprintf(NULL,
  14982. NULL, /* No truncation check for ebuf */
  14983. ebuf,
  14984. ebuf_len,
  14985. "%s: error loading library %s",
  14986. __func__,
  14987. CRYPTO_LIB);
  14988. DEBUG_TRACE("%s", ebuf);
  14989. return 0;
  14990. }
  14991. }
  14992. #endif /* NO_SSL_DL */
  14993. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14994. return 1;
  14995. }
  14996. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14997. /* Initialize locking callbacks, needed for thread safety.
  14998. * http://www.openssl.org/support/faq.html#PROG1
  14999. */
  15000. num_locks = CRYPTO_num_locks();
  15001. if (num_locks < 0) {
  15002. num_locks = 0;
  15003. }
  15004. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  15005. /* allocate mutex array, if required */
  15006. if (num_locks == 0) {
  15007. /* No mutex array required */
  15008. ssl_mutexes = NULL;
  15009. } else {
  15010. /* Mutex array required - allocate it */
  15011. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  15012. /* Check OOM */
  15013. if (ssl_mutexes == NULL) {
  15014. mg_snprintf(NULL,
  15015. NULL, /* No truncation check for ebuf */
  15016. ebuf,
  15017. ebuf_len,
  15018. "%s: cannot allocate mutexes: %s",
  15019. __func__,
  15020. ssl_error());
  15021. DEBUG_TRACE("%s", ebuf);
  15022. return 0;
  15023. }
  15024. /* initialize mutex array */
  15025. for (i = 0; i < num_locks; i++) {
  15026. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  15027. mg_snprintf(NULL,
  15028. NULL, /* No truncation check for ebuf */
  15029. ebuf,
  15030. ebuf_len,
  15031. "%s: error initializing mutex %i of %i",
  15032. __func__,
  15033. i,
  15034. num_locks);
  15035. DEBUG_TRACE("%s", ebuf);
  15036. mg_free(ssl_mutexes);
  15037. return 0;
  15038. }
  15039. }
  15040. }
  15041. CRYPTO_set_locking_callback(&ssl_locking_callback);
  15042. CRYPTO_set_id_callback(&mg_current_thread_id);
  15043. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15044. #if !defined(NO_SSL_DL)
  15045. if (!ssllib_dll_handle) {
  15046. ssllib_dll_handle =
  15047. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  15048. if (!ssllib_dll_handle) {
  15049. #if !defined(OPENSSL_API_1_1)
  15050. mg_free(ssl_mutexes);
  15051. #endif
  15052. DEBUG_TRACE("%s", ebuf);
  15053. return 0;
  15054. }
  15055. }
  15056. #endif /* NO_SSL_DL */
  15057. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15058. && !defined(NO_SSL_DL)
  15059. /* Initialize SSL library */
  15060. OPENSSL_init_ssl(0, NULL);
  15061. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  15062. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  15063. NULL);
  15064. #else
  15065. /* Initialize SSL library */
  15066. SSL_library_init();
  15067. SSL_load_error_strings();
  15068. #endif
  15069. return 1;
  15070. }
  15071. static int
  15072. ssl_use_pem_file(struct mg_context *phys_ctx,
  15073. struct mg_domain_context *dom_ctx,
  15074. const char *pem,
  15075. const char *chain)
  15076. {
  15077. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15078. mg_cry_ctx_internal(phys_ctx,
  15079. "%s: cannot open certificate file %s: %s",
  15080. __func__,
  15081. pem,
  15082. ssl_error());
  15083. return 0;
  15084. }
  15085. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  15086. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  15087. mg_cry_ctx_internal(phys_ctx,
  15088. "%s: cannot open private key file %s: %s",
  15089. __func__,
  15090. pem,
  15091. ssl_error());
  15092. return 0;
  15093. }
  15094. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  15095. mg_cry_ctx_internal(phys_ctx,
  15096. "%s: certificate and private key do not match: %s",
  15097. __func__,
  15098. pem);
  15099. return 0;
  15100. }
  15101. /* In contrast to OpenSSL, wolfSSL does not support certificate
  15102. * chain files that contain private keys and certificates in
  15103. * SSL_CTX_use_certificate_chain_file.
  15104. * The CivetWeb-Server used pem-Files that contained both information.
  15105. * In order to make wolfSSL work, it is split in two files.
  15106. * One file that contains key and certificate used by the server and
  15107. * an optional chain file for the ssl stack.
  15108. */
  15109. if (chain) {
  15110. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  15111. mg_cry_ctx_internal(phys_ctx,
  15112. "%s: cannot use certificate chain file %s: %s",
  15113. __func__,
  15114. chain,
  15115. ssl_error());
  15116. return 0;
  15117. }
  15118. }
  15119. return 1;
  15120. }
  15121. #if defined(OPENSSL_API_1_1)
  15122. static unsigned long
  15123. ssl_get_protocol(int version_id)
  15124. {
  15125. long unsigned ret = (long unsigned)SSL_OP_ALL;
  15126. if (version_id > 0)
  15127. ret |= SSL_OP_NO_SSLv2;
  15128. if (version_id > 1)
  15129. ret |= SSL_OP_NO_SSLv3;
  15130. if (version_id > 2)
  15131. ret |= SSL_OP_NO_TLSv1;
  15132. if (version_id > 3)
  15133. ret |= SSL_OP_NO_TLSv1_1;
  15134. if (version_id > 4)
  15135. ret |= SSL_OP_NO_TLSv1_2;
  15136. #if defined(SSL_OP_NO_TLSv1_3)
  15137. if (version_id > 5)
  15138. ret |= SSL_OP_NO_TLSv1_3;
  15139. #endif
  15140. return ret;
  15141. }
  15142. #else
  15143. static long
  15144. ssl_get_protocol(int version_id)
  15145. {
  15146. unsigned long ret = (unsigned long)SSL_OP_ALL;
  15147. if (version_id > 0)
  15148. ret |= SSL_OP_NO_SSLv2;
  15149. if (version_id > 1)
  15150. ret |= SSL_OP_NO_SSLv3;
  15151. if (version_id > 2)
  15152. ret |= SSL_OP_NO_TLSv1;
  15153. if (version_id > 3)
  15154. ret |= SSL_OP_NO_TLSv1_1;
  15155. if (version_id > 4)
  15156. ret |= SSL_OP_NO_TLSv1_2;
  15157. #if defined(SSL_OP_NO_TLSv1_3)
  15158. if (version_id > 5)
  15159. ret |= SSL_OP_NO_TLSv1_3;
  15160. #endif
  15161. return (long)ret;
  15162. }
  15163. #endif /* OPENSSL_API_1_1 */
  15164. /* SSL callback documentation:
  15165. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  15166. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  15167. * https://linux.die.net/man/3/ssl_set_info_callback */
  15168. /* Note: There is no "const" for the first argument in the documentation
  15169. * examples, however some (maybe most, but not all) headers of OpenSSL
  15170. * versions / OpenSSL compatibility layers have it. Having a different
  15171. * definition will cause a warning in C and an error in C++. Use "const SSL
  15172. * *", while automatic conversion from "SSL *" works for all compilers,
  15173. * but not other way around */
  15174. static void
  15175. ssl_info_callback(const SSL *ssl, int what, int ret)
  15176. {
  15177. (void)ret;
  15178. if (what & SSL_CB_HANDSHAKE_START) {
  15179. SSL_get_app_data(ssl);
  15180. }
  15181. if (what & SSL_CB_HANDSHAKE_DONE) {
  15182. /* TODO: check for openSSL 1.1 */
  15183. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  15184. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  15185. }
  15186. }
  15187. static int
  15188. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  15189. {
  15190. #if defined(GCC_DIAGNOSTIC)
  15191. #pragma GCC diagnostic push
  15192. #pragma GCC diagnostic ignored "-Wcast-align"
  15193. #endif /* defined(GCC_DIAGNOSTIC) */
  15194. /* We used an aligned pointer in SSL_set_app_data */
  15195. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  15196. #if defined(GCC_DIAGNOSTIC)
  15197. #pragma GCC diagnostic pop
  15198. #endif /* defined(GCC_DIAGNOSTIC) */
  15199. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15200. (void)ad;
  15201. (void)arg;
  15202. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15203. DEBUG_ASSERT(0);
  15204. return SSL_TLSEXT_ERR_NOACK;
  15205. }
  15206. conn->dom_ctx = &(conn->phys_ctx->dd);
  15207. /* Old clients (Win XP) will not support SNI. Then, there
  15208. * is no server name available in the request - we can
  15209. * only work with the default certificate.
  15210. * Multiple HTTPS hosts on one IP+port are only possible
  15211. * with a certificate containing all alternative names.
  15212. */
  15213. if ((servername == NULL) || (*servername == 0)) {
  15214. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15215. mg_lock_context(conn->phys_ctx);
  15216. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15217. mg_unlock_context(conn->phys_ctx);
  15218. return SSL_TLSEXT_ERR_NOACK;
  15219. }
  15220. DEBUG_TRACE("TLS connection to host %s", servername);
  15221. while (conn->dom_ctx) {
  15222. if (!mg_strcasecmp(servername,
  15223. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15224. /* Found matching domain */
  15225. DEBUG_TRACE("TLS domain %s found",
  15226. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15227. break;
  15228. }
  15229. mg_lock_context(conn->phys_ctx);
  15230. conn->dom_ctx = conn->dom_ctx->next;
  15231. mg_unlock_context(conn->phys_ctx);
  15232. }
  15233. if (conn->dom_ctx == NULL) {
  15234. /* Default domain */
  15235. DEBUG_TRACE("TLS default domain %s used",
  15236. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15237. conn->dom_ctx = &(conn->phys_ctx->dd);
  15238. }
  15239. mg_lock_context(conn->phys_ctx);
  15240. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15241. mg_unlock_context(conn->phys_ctx);
  15242. return SSL_TLSEXT_ERR_OK;
  15243. }
  15244. #if defined(USE_ALPN)
  15245. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15246. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15247. alpn_proto_list + 3 + 8,
  15248. NULL};
  15249. #if defined(USE_HTTP2)
  15250. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15251. alpn_proto_list + 3,
  15252. alpn_proto_list + 3 + 8,
  15253. NULL};
  15254. #endif
  15255. static int
  15256. alpn_select_cb(SSL *ssl,
  15257. const unsigned char **out,
  15258. unsigned char *outlen,
  15259. const unsigned char *in,
  15260. unsigned int inlen,
  15261. void *arg)
  15262. {
  15263. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15264. unsigned int i, j, enable_http2 = 0;
  15265. const char **alpn_proto_order = alpn_proto_order_http1;
  15266. struct mg_workerTLS *tls =
  15267. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15268. (void)ssl;
  15269. if (tls == NULL) {
  15270. /* Need to store protocol in Thread Local Storage */
  15271. /* If there is no Thread Local Storage, don't use ALPN */
  15272. return SSL_TLSEXT_ERR_NOACK;
  15273. }
  15274. #if defined(USE_HTTP2)
  15275. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15276. if (enable_http2) {
  15277. alpn_proto_order = alpn_proto_order_http2;
  15278. }
  15279. #endif
  15280. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15281. /* check all accepted protocols in this order */
  15282. const char *alpn_proto = alpn_proto_order[j];
  15283. /* search input for matching protocol */
  15284. for (i = 0; i < inlen; i++) {
  15285. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15286. *out = in + i + 1;
  15287. *outlen = in[i];
  15288. tls->alpn_proto = alpn_proto;
  15289. return SSL_TLSEXT_ERR_OK;
  15290. }
  15291. }
  15292. }
  15293. /* Nothing found */
  15294. return SSL_TLSEXT_ERR_NOACK;
  15295. }
  15296. static int
  15297. next_protos_advertised_cb(SSL *ssl,
  15298. const unsigned char **data,
  15299. unsigned int *len,
  15300. void *arg)
  15301. {
  15302. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15303. *data = (const unsigned char *)alpn_proto_list;
  15304. *len = (unsigned int)strlen((const char *)data);
  15305. (void)ssl;
  15306. (void)dom_ctx;
  15307. return SSL_TLSEXT_ERR_OK;
  15308. }
  15309. static int
  15310. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15311. {
  15312. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15313. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15314. (const unsigned char *)alpn_proto_list,
  15315. alpn_len);
  15316. if (ret != 0) {
  15317. mg_cry_ctx_internal(phys_ctx,
  15318. "SSL_CTX_set_alpn_protos error: %s",
  15319. ssl_error());
  15320. }
  15321. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15322. alpn_select_cb,
  15323. (void *)dom_ctx);
  15324. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15325. next_protos_advertised_cb,
  15326. (void *)dom_ctx);
  15327. return ret;
  15328. }
  15329. #endif
  15330. /* Setup SSL CTX as required by CivetWeb */
  15331. static int
  15332. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15333. struct mg_domain_context *dom_ctx,
  15334. const char *pem,
  15335. const char *chain)
  15336. {
  15337. int callback_ret;
  15338. int should_verify_peer;
  15339. int peer_certificate_optional;
  15340. const char *ca_path;
  15341. const char *ca_file;
  15342. int use_default_verify_paths;
  15343. int verify_depth;
  15344. struct timespec now_mt;
  15345. md5_byte_t ssl_context_id[16];
  15346. md5_state_t md5state;
  15347. int protocol_ver;
  15348. int ssl_cache_timeout;
  15349. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15350. && !defined(NO_SSL_DL)
  15351. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15352. mg_cry_ctx_internal(phys_ctx,
  15353. "SSL_CTX_new (server) error: %s",
  15354. ssl_error());
  15355. return 0;
  15356. }
  15357. #else
  15358. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15359. mg_cry_ctx_internal(phys_ctx,
  15360. "SSL_CTX_new (server) error: %s",
  15361. ssl_error());
  15362. return 0;
  15363. }
  15364. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15365. #if defined(SSL_OP_NO_TLSv1_3)
  15366. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15367. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15368. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15369. | SSL_OP_NO_TLSv1_3);
  15370. #else
  15371. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15372. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15373. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15374. #endif
  15375. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15376. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15377. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15378. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15379. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15380. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15381. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15382. #if defined(SSL_OP_NO_RENEGOTIATION)
  15383. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15384. #endif
  15385. #if !defined(NO_SSL_DL)
  15386. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15387. #endif /* NO_SSL_DL */
  15388. /* In SSL documentation examples callback defined without const
  15389. * specifier 'void (*)(SSL *, int, int)' See:
  15390. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15391. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15392. * But in the source code const SSL is used:
  15393. * 'void (*)(const SSL *, int, int)' See:
  15394. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15395. * Problem about wrong documentation described, but not resolved:
  15396. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15397. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15398. * But when compiled with modern C++ compiler, correct const should be
  15399. * provided
  15400. */
  15401. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15402. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15403. ssl_servername_callback);
  15404. /* If a callback has been specified, call it. */
  15405. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15406. ? 0
  15407. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15408. phys_ctx->user_data));
  15409. /* If callback returns 0, civetweb sets up the SSL certificate.
  15410. * If it returns 1, civetweb assumes the callback already did this.
  15411. * If it returns -1, initializing ssl fails. */
  15412. if (callback_ret < 0) {
  15413. mg_cry_ctx_internal(phys_ctx,
  15414. "SSL callback returned error: %i",
  15415. callback_ret);
  15416. return 0;
  15417. }
  15418. if (callback_ret > 0) {
  15419. /* Callback did everything. */
  15420. return 1;
  15421. }
  15422. /* If a domain callback has been specified, call it. */
  15423. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15424. ? 0
  15425. : (phys_ctx->callbacks.init_ssl_domain(
  15426. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15427. dom_ctx->ssl_ctx,
  15428. phys_ctx->user_data));
  15429. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15430. * If it returns 1, civetweb assumes the callback already did this.
  15431. * If it returns -1, initializing ssl fails. */
  15432. if (callback_ret < 0) {
  15433. mg_cry_ctx_internal(phys_ctx,
  15434. "Domain SSL callback returned error: %i",
  15435. callback_ret);
  15436. return 0;
  15437. }
  15438. if (callback_ret > 0) {
  15439. /* Domain callback did everything. */
  15440. return 1;
  15441. }
  15442. /* Use some combination of start time, domain and port as a SSL
  15443. * context ID. This should be unique on the current machine. */
  15444. md5_init(&md5state);
  15445. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15446. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15447. md5_append(&md5state,
  15448. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15449. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15450. md5_append(&md5state,
  15451. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15452. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15453. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15454. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15455. md5_finish(&md5state, ssl_context_id);
  15456. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15457. (unsigned char *)ssl_context_id,
  15458. sizeof(ssl_context_id));
  15459. if (pem != NULL) {
  15460. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15461. return 0;
  15462. }
  15463. }
  15464. /* Should we support client certificates? */
  15465. /* Default is "no". */
  15466. should_verify_peer = 0;
  15467. peer_certificate_optional = 0;
  15468. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15469. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15470. /* Yes, they are mandatory */
  15471. should_verify_peer = 1;
  15472. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15473. "optional")
  15474. == 0) {
  15475. /* Yes, they are optional */
  15476. should_verify_peer = 1;
  15477. peer_certificate_optional = 1;
  15478. }
  15479. }
  15480. use_default_verify_paths =
  15481. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15482. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15483. == 0);
  15484. if (should_verify_peer) {
  15485. ca_path = dom_ctx->config[SSL_CA_PATH];
  15486. ca_file = dom_ctx->config[SSL_CA_FILE];
  15487. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15488. != 1) {
  15489. mg_cry_ctx_internal(phys_ctx,
  15490. "SSL_CTX_load_verify_locations error: %s "
  15491. "ssl_verify_peer requires setting "
  15492. "either ssl_ca_path or ssl_ca_file. "
  15493. "Is any of them present in the "
  15494. ".conf file?",
  15495. ssl_error());
  15496. return 0;
  15497. }
  15498. if (peer_certificate_optional) {
  15499. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15500. } else {
  15501. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15502. SSL_VERIFY_PEER
  15503. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15504. NULL);
  15505. }
  15506. if (use_default_verify_paths
  15507. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15508. mg_cry_ctx_internal(phys_ctx,
  15509. "SSL_CTX_set_default_verify_paths error: %s",
  15510. ssl_error());
  15511. return 0;
  15512. }
  15513. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15514. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15515. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15516. }
  15517. }
  15518. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15519. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15520. dom_ctx->config[SSL_CIPHER_LIST])
  15521. != 1) {
  15522. mg_cry_ctx_internal(phys_ctx,
  15523. "SSL_CTX_set_cipher_list error: %s",
  15524. ssl_error());
  15525. }
  15526. }
  15527. /* SSL session caching */
  15528. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15529. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15530. : 0);
  15531. if (ssl_cache_timeout > 0) {
  15532. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15533. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15534. * default */
  15535. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15536. }
  15537. #if defined(USE_ALPN)
  15538. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15539. #if !defined(NO_SSL_DL)
  15540. if (!tls_feature_missing[TLS_ALPN])
  15541. #endif
  15542. {
  15543. init_alpn(phys_ctx, dom_ctx);
  15544. }
  15545. #endif
  15546. return 1;
  15547. }
  15548. /* Check if SSL is required.
  15549. * If so, dynamically load SSL library
  15550. * and set up ctx->ssl_ctx pointer. */
  15551. static int
  15552. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15553. {
  15554. void *ssl_ctx = 0;
  15555. int callback_ret;
  15556. const char *pem;
  15557. const char *chain;
  15558. char ebuf[128];
  15559. if (!phys_ctx) {
  15560. return 0;
  15561. }
  15562. if (!dom_ctx) {
  15563. dom_ctx = &(phys_ctx->dd);
  15564. }
  15565. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15566. /* No SSL port is set. No need to setup SSL. */
  15567. return 1;
  15568. }
  15569. /* Check for external SSL_CTX */
  15570. callback_ret =
  15571. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15572. ? 0
  15573. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15574. phys_ctx->user_data));
  15575. if (callback_ret < 0) {
  15576. /* Callback exists and returns <0: Initializing failed. */
  15577. mg_cry_ctx_internal(phys_ctx,
  15578. "external_ssl_ctx callback returned error: %i",
  15579. callback_ret);
  15580. return 0;
  15581. } else if (callback_ret > 0) {
  15582. /* Callback exists and returns >0: Initializing complete,
  15583. * civetweb should not modify the SSL context. */
  15584. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15585. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15586. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15587. return 0;
  15588. }
  15589. return 1;
  15590. }
  15591. /* If the callback does not exist or return 0, civetweb must initialize
  15592. * the SSL context. Handle "domain" callback next. */
  15593. /* Check for external domain SSL_CTX callback. */
  15594. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15595. ? 0
  15596. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15597. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15598. &ssl_ctx,
  15599. phys_ctx->user_data));
  15600. if (callback_ret < 0) {
  15601. /* Callback < 0: Error. Abort init. */
  15602. mg_cry_ctx_internal(
  15603. phys_ctx,
  15604. "external_ssl_ctx_domain callback returned error: %i",
  15605. callback_ret);
  15606. return 0;
  15607. } else if (callback_ret > 0) {
  15608. /* Callback > 0: Consider init done. */
  15609. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15610. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15611. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15612. return 0;
  15613. }
  15614. return 1;
  15615. }
  15616. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15617. * 0, CivetWeb should continue initializing SSL */
  15618. /* If PEM file is not specified and the init_ssl callbacks
  15619. * are not specified, setup will fail. */
  15620. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15621. && (phys_ctx->callbacks.init_ssl == NULL)
  15622. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15623. /* No certificate and no init_ssl callbacks:
  15624. * Essential data to set up TLS is missing.
  15625. */
  15626. mg_cry_ctx_internal(phys_ctx,
  15627. "Initializing SSL failed: -%s is not set",
  15628. config_options[SSL_CERTIFICATE].name);
  15629. return 0;
  15630. }
  15631. /* If a certificate chain is configured, use it. */
  15632. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15633. if (chain == NULL) {
  15634. /* Default: certificate chain in PEM file */
  15635. chain = pem;
  15636. }
  15637. if ((chain != NULL) && (*chain == 0)) {
  15638. /* If the chain is an empty string, don't use it. */
  15639. chain = NULL;
  15640. }
  15641. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15642. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15643. return 0;
  15644. }
  15645. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15646. }
  15647. static void
  15648. uninitialize_openssl(void)
  15649. {
  15650. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15651. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15652. /* Shutdown according to
  15653. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15654. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15655. */
  15656. CONF_modules_unload(1);
  15657. #else
  15658. int i;
  15659. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15660. /* Shutdown according to
  15661. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15662. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15663. */
  15664. CRYPTO_set_locking_callback(NULL);
  15665. CRYPTO_set_id_callback(NULL);
  15666. ENGINE_cleanup();
  15667. CONF_modules_unload(1);
  15668. ERR_free_strings();
  15669. EVP_cleanup();
  15670. CRYPTO_cleanup_all_ex_data();
  15671. OPENSSL_REMOVE_THREAD_STATE();
  15672. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15673. pthread_mutex_destroy(&ssl_mutexes[i]);
  15674. }
  15675. mg_free(ssl_mutexes);
  15676. ssl_mutexes = NULL;
  15677. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15678. }
  15679. }
  15680. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS) */
  15681. #if !defined(NO_FILESYSTEMS)
  15682. static int
  15683. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15684. {
  15685. if (phys_ctx) {
  15686. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15687. const char *path;
  15688. struct mg_connection fc;
  15689. if (!dom_ctx) {
  15690. dom_ctx = &(phys_ctx->dd);
  15691. }
  15692. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15693. if ((path != NULL)
  15694. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15695. mg_cry_ctx_internal(phys_ctx,
  15696. "Cannot open %s: %s",
  15697. path,
  15698. strerror(ERRNO));
  15699. return 0;
  15700. }
  15701. return 1;
  15702. }
  15703. return 0;
  15704. }
  15705. #endif /* NO_FILESYSTEMS */
  15706. static int
  15707. set_acl_option(struct mg_context *phys_ctx)
  15708. {
  15709. union usa sa;
  15710. memset(&sa, 0, sizeof(sa));
  15711. #if defined(USE_IPV6)
  15712. sa.sin6.sin6_family = AF_INET6;
  15713. #else
  15714. sa.sin.sin_family = AF_INET;
  15715. #endif
  15716. return check_acl(phys_ctx, &sa) != -1;
  15717. }
  15718. static void
  15719. reset_per_request_attributes(struct mg_connection *conn)
  15720. {
  15721. if (!conn) {
  15722. return;
  15723. }
  15724. conn->num_bytes_sent = conn->consumed_content = 0;
  15725. conn->path_info = NULL;
  15726. conn->status_code = -1;
  15727. conn->content_len = -1;
  15728. conn->is_chunked = 0;
  15729. conn->must_close = 0;
  15730. conn->request_len = 0;
  15731. conn->request_state = 0;
  15732. conn->throttle = 0;
  15733. conn->accept_gzip = 0;
  15734. conn->response_info.content_length = conn->request_info.content_length = -1;
  15735. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15736. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15737. conn->response_info.status_text = NULL;
  15738. conn->response_info.status_code = 0;
  15739. conn->request_info.remote_user = NULL;
  15740. conn->request_info.request_method = NULL;
  15741. conn->request_info.request_uri = NULL;
  15742. /* Free cleaned local URI (if any) */
  15743. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15744. mg_free((void *)conn->request_info.local_uri);
  15745. conn->request_info.local_uri = NULL;
  15746. }
  15747. conn->request_info.local_uri = NULL;
  15748. #if defined(USE_SERVER_STATS)
  15749. conn->processing_time = 0;
  15750. #endif
  15751. }
  15752. static int
  15753. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15754. {
  15755. if ((so->lsa.sa.sa_family == AF_INET)
  15756. || (so->lsa.sa.sa_family == AF_INET6)) {
  15757. /* Only for TCP sockets */
  15758. if (setsockopt(so->sock,
  15759. IPPROTO_TCP,
  15760. TCP_NODELAY,
  15761. (SOCK_OPT_TYPE)&nodelay_on,
  15762. sizeof(nodelay_on))
  15763. != 0) {
  15764. /* Error */
  15765. return 1;
  15766. }
  15767. }
  15768. /* OK */
  15769. return 0;
  15770. }
  15771. #if !defined(__ZEPHYR__)
  15772. static void
  15773. close_socket_gracefully(struct mg_connection *conn)
  15774. {
  15775. #if defined(_WIN32)
  15776. char buf[MG_BUF_LEN];
  15777. int n;
  15778. #endif
  15779. struct linger linger;
  15780. int error_code = 0;
  15781. int linger_timeout = -2;
  15782. socklen_t opt_len = sizeof(error_code);
  15783. if (!conn) {
  15784. return;
  15785. }
  15786. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15787. * "Note that enabling a nonzero timeout on a nonblocking socket
  15788. * is not recommended.", so set it to blocking now */
  15789. set_blocking_mode(conn->client.sock);
  15790. /* Send FIN to the client */
  15791. shutdown(conn->client.sock, SHUTDOWN_WR);
  15792. #if defined(_WIN32)
  15793. /* Read and discard pending incoming data. If we do not do that and
  15794. * close
  15795. * the socket, the data in the send buffer may be discarded. This
  15796. * behaviour is seen on Windows, when client keeps sending data
  15797. * when server decides to close the connection; then when client
  15798. * does recv() it gets no data back. */
  15799. do {
  15800. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15801. } while (n > 0);
  15802. #endif
  15803. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15804. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15805. }
  15806. /* Set linger option according to configuration */
  15807. if (linger_timeout >= 0) {
  15808. /* Set linger option to avoid socket hanging out after close. This
  15809. * prevent ephemeral port exhaust problem under high QPS. */
  15810. linger.l_onoff = 1;
  15811. #if defined(_MSC_VER)
  15812. #pragma warning(push)
  15813. #pragma warning(disable : 4244)
  15814. #endif
  15815. #if defined(GCC_DIAGNOSTIC)
  15816. #pragma GCC diagnostic push
  15817. #pragma GCC diagnostic ignored "-Wconversion"
  15818. #endif
  15819. /* Data type of linger structure elements may differ,
  15820. * so we don't know what cast we need here.
  15821. * Disable type conversion warnings. */
  15822. linger.l_linger = (linger_timeout + 999) / 1000;
  15823. #if defined(GCC_DIAGNOSTIC)
  15824. #pragma GCC diagnostic pop
  15825. #endif
  15826. #if defined(_MSC_VER)
  15827. #pragma warning(pop)
  15828. #endif
  15829. } else {
  15830. linger.l_onoff = 0;
  15831. linger.l_linger = 0;
  15832. }
  15833. if (linger_timeout < -1) {
  15834. /* Default: don't configure any linger */
  15835. } else if (getsockopt(conn->client.sock,
  15836. SOL_SOCKET,
  15837. SO_ERROR,
  15838. #if defined(_WIN32) /* WinSock uses different data type here */
  15839. (char *)&error_code,
  15840. #else
  15841. &error_code,
  15842. #endif
  15843. &opt_len)
  15844. != 0) {
  15845. /* Cannot determine if socket is already closed. This should
  15846. * not occur and never did in a test. Log an error message
  15847. * and continue. */
  15848. mg_cry_internal(conn,
  15849. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15850. __func__,
  15851. strerror(ERRNO));
  15852. #if defined(_WIN32)
  15853. } else if (error_code == WSAECONNRESET) {
  15854. #else
  15855. } else if (error_code == ECONNRESET) {
  15856. #endif
  15857. /* Socket already closed by client/peer, close socket without linger
  15858. */
  15859. } else {
  15860. /* Set linger timeout */
  15861. if (setsockopt(conn->client.sock,
  15862. SOL_SOCKET,
  15863. SO_LINGER,
  15864. (char *)&linger,
  15865. sizeof(linger))
  15866. != 0) {
  15867. mg_cry_internal(
  15868. conn,
  15869. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15870. __func__,
  15871. linger.l_onoff,
  15872. linger.l_linger,
  15873. strerror(ERRNO));
  15874. }
  15875. }
  15876. /* Now we know that our FIN is ACK-ed, safe to close */
  15877. closesocket(conn->client.sock);
  15878. conn->client.sock = INVALID_SOCKET;
  15879. }
  15880. #endif
  15881. static void
  15882. close_connection(struct mg_connection *conn)
  15883. {
  15884. #if defined(USE_SERVER_STATS)
  15885. conn->conn_state = 6; /* to close */
  15886. #endif
  15887. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15888. if (conn->lua_websocket_state) {
  15889. lua_websocket_close(conn, conn->lua_websocket_state);
  15890. conn->lua_websocket_state = NULL;
  15891. }
  15892. #endif
  15893. mg_lock_connection(conn);
  15894. /* Set close flag, so keep-alive loops will stop */
  15895. conn->must_close = 1;
  15896. /* call the connection_close callback if assigned */
  15897. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15898. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15899. conn->phys_ctx->callbacks.connection_close(conn);
  15900. }
  15901. }
  15902. /* Reset user data, after close callback is called.
  15903. * Do not reuse it. If the user needs a destructor,
  15904. * it must be done in the connection_close callback. */
  15905. mg_set_user_connection_data(conn, NULL);
  15906. #if defined(USE_SERVER_STATS)
  15907. conn->conn_state = 7; /* closing */
  15908. #endif
  15909. #if defined(USE_MBEDTLS)
  15910. if (conn->ssl != NULL) {
  15911. mbed_ssl_close(conn->ssl);
  15912. conn->ssl = NULL;
  15913. }
  15914. #elif defined(USE_GNUTLS)
  15915. if (conn->ssl != NULL) {
  15916. gtls_ssl_close(conn->ssl);
  15917. conn->ssl = NULL;
  15918. }
  15919. #elif !defined(NO_SSL)
  15920. if (conn->ssl != NULL) {
  15921. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15922. */
  15923. SSL_shutdown(conn->ssl);
  15924. SSL_free(conn->ssl);
  15925. OPENSSL_REMOVE_THREAD_STATE();
  15926. conn->ssl = NULL;
  15927. }
  15928. #endif
  15929. if (conn->client.sock != INVALID_SOCKET) {
  15930. #if defined(__ZEPHYR__)
  15931. closesocket(conn->client.sock);
  15932. #else
  15933. close_socket_gracefully(conn);
  15934. #endif
  15935. conn->client.sock = INVALID_SOCKET;
  15936. }
  15937. /* call the connection_closed callback if assigned */
  15938. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15939. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15940. conn->phys_ctx->callbacks.connection_closed(conn);
  15941. }
  15942. }
  15943. mg_unlock_connection(conn);
  15944. #if defined(USE_SERVER_STATS)
  15945. conn->conn_state = 8; /* closed */
  15946. #endif
  15947. }
  15948. CIVETWEB_API void
  15949. mg_close_connection(struct mg_connection *conn)
  15950. {
  15951. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15952. return;
  15953. }
  15954. #if defined(USE_WEBSOCKET)
  15955. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15956. if (conn->in_websocket_handling) {
  15957. /* Set close flag, so the server thread can exit. */
  15958. conn->must_close = 1;
  15959. return;
  15960. }
  15961. }
  15962. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15963. unsigned int i;
  15964. /* client context: loops must end */
  15965. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15966. conn->must_close = 1;
  15967. /* We need to get the client thread out of the select/recv call
  15968. * here. */
  15969. /* Since we use a sleep quantum of some seconds to check for recv
  15970. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15971. /* join worker thread */
  15972. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15973. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15974. }
  15975. }
  15976. #endif /* defined(USE_WEBSOCKET) */
  15977. close_connection(conn);
  15978. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  15979. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  15980. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15981. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15982. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15983. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15984. }
  15985. #endif
  15986. #if defined(USE_WEBSOCKET)
  15987. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15988. mg_free(conn->phys_ctx->worker_threadids);
  15989. (void)pthread_mutex_destroy(&conn->mutex);
  15990. mg_free(conn);
  15991. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15992. (void)pthread_mutex_destroy(&conn->mutex);
  15993. mg_free(conn);
  15994. }
  15995. #else
  15996. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15997. (void)pthread_mutex_destroy(&conn->mutex);
  15998. mg_free(conn);
  15999. }
  16000. #endif /* defined(USE_WEBSOCKET) */
  16001. }
  16002. static struct mg_connection *
  16003. mg_connect_client_impl(const struct mg_client_options *client_options,
  16004. int use_ssl,
  16005. struct mg_init_data *init,
  16006. struct mg_error_data *error)
  16007. {
  16008. struct mg_connection *conn = NULL;
  16009. SOCKET sock;
  16010. union usa sa;
  16011. struct sockaddr *psa;
  16012. socklen_t len;
  16013. unsigned max_req_size =
  16014. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  16015. /* Size of structures, aligned to 8 bytes */
  16016. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  16017. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  16018. size_t alloc_size = conn_size + ctx_size + max_req_size;
  16019. (void)init; /* TODO: Implement required options */
  16020. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  16021. if (error != NULL) {
  16022. error->code = MG_ERROR_DATA_CODE_OK;
  16023. error->code_sub = 0;
  16024. if (error->text_buffer_size > 0) {
  16025. error->text[0] = 0;
  16026. }
  16027. }
  16028. if (conn == NULL) {
  16029. if (error != NULL) {
  16030. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  16031. error->code_sub = (unsigned)alloc_size;
  16032. mg_snprintf(NULL,
  16033. NULL, /* No truncation check for ebuf */
  16034. error->text,
  16035. error->text_buffer_size,
  16036. "calloc(): %s",
  16037. strerror(ERRNO));
  16038. }
  16039. return NULL;
  16040. }
  16041. #if defined(GCC_DIAGNOSTIC)
  16042. #pragma GCC diagnostic push
  16043. #pragma GCC diagnostic ignored "-Wcast-align"
  16044. #endif /* defined(GCC_DIAGNOSTIC) */
  16045. /* conn_size is aligned to 8 bytes */
  16046. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  16047. #if defined(GCC_DIAGNOSTIC)
  16048. #pragma GCC diagnostic pop
  16049. #endif /* defined(GCC_DIAGNOSTIC) */
  16050. conn->buf = (((char *)conn) + conn_size + ctx_size);
  16051. conn->buf_size = (int)max_req_size;
  16052. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  16053. conn->dom_ctx = &(conn->phys_ctx->dd);
  16054. if (!connect_socket(conn->phys_ctx,
  16055. client_options->host,
  16056. client_options->port,
  16057. use_ssl,
  16058. error,
  16059. &sock,
  16060. &sa)) {
  16061. /* "error" will be set by connect_socket. */
  16062. /* free all memory and return NULL; */
  16063. mg_free(conn);
  16064. return NULL;
  16065. }
  16066. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16067. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16068. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  16069. && !defined(NO_SSL_DL)
  16070. if (use_ssl
  16071. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  16072. == NULL) {
  16073. if (error != NULL) {
  16074. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16075. mg_snprintf(NULL,
  16076. NULL, /* No truncation check for ebuf */
  16077. error->text,
  16078. error->text_buffer_size,
  16079. "SSL_CTX_new error: %s",
  16080. ssl_error());
  16081. }
  16082. closesocket(sock);
  16083. mg_free(conn);
  16084. return NULL;
  16085. }
  16086. #else
  16087. if (use_ssl
  16088. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  16089. == NULL) {
  16090. if (error != NULL) {
  16091. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  16092. mg_snprintf(NULL,
  16093. NULL, /* No truncation check for ebuf */
  16094. error->text,
  16095. error->text_buffer_size,
  16096. "SSL_CTX_new error: %s",
  16097. ssl_error());
  16098. }
  16099. closesocket(sock);
  16100. mg_free(conn);
  16101. return NULL;
  16102. }
  16103. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  16104. #endif /* NO_SSL */
  16105. #if defined(USE_IPV6)
  16106. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  16107. : sizeof(conn->client.rsa.sin6);
  16108. psa = (sa.sa.sa_family == AF_INET)
  16109. ? (struct sockaddr *)&(conn->client.rsa.sin)
  16110. : (struct sockaddr *)&(conn->client.rsa.sin6);
  16111. #else
  16112. len = sizeof(conn->client.rsa.sin);
  16113. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  16114. #endif
  16115. conn->client.sock = sock;
  16116. conn->client.lsa = sa;
  16117. if (getsockname(sock, psa, &len) != 0) {
  16118. mg_cry_internal(conn,
  16119. "%s: getsockname() failed: %s",
  16120. __func__,
  16121. strerror(ERRNO));
  16122. }
  16123. conn->client.is_ssl = use_ssl ? 1 : 0;
  16124. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16125. if (error != NULL) {
  16126. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  16127. error->code_sub = (unsigned)ERRNO;
  16128. mg_snprintf(NULL,
  16129. NULL, /* No truncation check for ebuf */
  16130. error->text,
  16131. error->text_buffer_size,
  16132. "Can not create mutex");
  16133. }
  16134. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16135. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16136. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16137. #endif
  16138. closesocket(sock);
  16139. mg_free(conn);
  16140. return NULL;
  16141. }
  16142. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) \
  16143. && !defined(USE_GNUTLS) // TODO: mbedTLS client
  16144. if (use_ssl) {
  16145. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  16146. * SSL_CTX_set_verify call is needed to switch off server
  16147. * certificate checking, which is off by default in OpenSSL and
  16148. * on in yaSSL. */
  16149. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  16150. * SSL_VERIFY_PEER, verify_ssl_server); */
  16151. if (client_options->client_cert) {
  16152. if (!ssl_use_pem_file(conn->phys_ctx,
  16153. conn->dom_ctx,
  16154. client_options->client_cert,
  16155. NULL)) {
  16156. if (error != NULL) {
  16157. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  16158. mg_snprintf(NULL,
  16159. NULL, /* No truncation check for ebuf */
  16160. error->text,
  16161. error->text_buffer_size,
  16162. "Can not use SSL client certificate");
  16163. }
  16164. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16165. closesocket(sock);
  16166. mg_free(conn);
  16167. return NULL;
  16168. }
  16169. }
  16170. if (client_options->server_cert) {
  16171. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  16172. client_options->server_cert,
  16173. NULL)
  16174. != 1) {
  16175. if (error != NULL) {
  16176. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  16177. mg_snprintf(NULL,
  16178. NULL, /* No truncation check for ebuf */
  16179. error->text,
  16180. error->text_buffer_size,
  16181. "SSL_CTX_load_verify_locations error: %s",
  16182. ssl_error());
  16183. }
  16184. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16185. closesocket(sock);
  16186. mg_free(conn);
  16187. return NULL;
  16188. }
  16189. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  16190. } else {
  16191. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  16192. }
  16193. if (!sslize(conn, SSL_connect, client_options)) {
  16194. if (error != NULL) {
  16195. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  16196. mg_snprintf(NULL,
  16197. NULL, /* No truncation check for ebuf */
  16198. error->text,
  16199. error->text_buffer_size,
  16200. "SSL connection error");
  16201. }
  16202. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  16203. closesocket(sock);
  16204. mg_free(conn);
  16205. return NULL;
  16206. }
  16207. }
  16208. #endif
  16209. return conn;
  16210. }
  16211. CIVETWEB_API struct mg_connection *
  16212. mg_connect_client_secure(const struct mg_client_options *client_options,
  16213. char *error_buffer,
  16214. size_t error_buffer_size)
  16215. {
  16216. struct mg_init_data init;
  16217. struct mg_error_data error;
  16218. memset(&init, 0, sizeof(init));
  16219. memset(&error, 0, sizeof(error));
  16220. error.text_buffer_size = error_buffer_size;
  16221. error.text = error_buffer;
  16222. return mg_connect_client_impl(client_options, 1, &init, &error);
  16223. }
  16224. CIVETWEB_API struct mg_connection *
  16225. mg_connect_client(const char *host,
  16226. int port,
  16227. int use_ssl,
  16228. char *error_buffer,
  16229. size_t error_buffer_size)
  16230. {
  16231. struct mg_client_options opts;
  16232. struct mg_init_data init;
  16233. struct mg_error_data error;
  16234. memset(&init, 0, sizeof(init));
  16235. memset(&error, 0, sizeof(error));
  16236. error.text_buffer_size = error_buffer_size;
  16237. error.text = error_buffer;
  16238. memset(&opts, 0, sizeof(opts));
  16239. opts.host = host;
  16240. opts.port = port;
  16241. if (use_ssl) {
  16242. opts.host_name = host;
  16243. }
  16244. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16245. }
  16246. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16247. CIVETWEB_API struct mg_connection *
  16248. mg_connect_client2(const char *host,
  16249. const char *protocol,
  16250. int port,
  16251. const char *path,
  16252. struct mg_init_data *init,
  16253. struct mg_error_data *error)
  16254. {
  16255. (void)path;
  16256. int is_ssl, is_ws;
  16257. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16258. if (error != NULL) {
  16259. error->code = MG_ERROR_DATA_CODE_OK;
  16260. error->code_sub = 0;
  16261. if (error->text_buffer_size > 0) {
  16262. *error->text = 0;
  16263. }
  16264. }
  16265. if ((host == NULL) || (protocol == NULL)) {
  16266. if (error != NULL) {
  16267. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16268. mg_snprintf(NULL,
  16269. NULL, /* No truncation check for error buffers */
  16270. error->text,
  16271. error->text_buffer_size,
  16272. "%s",
  16273. "Invalid parameters");
  16274. }
  16275. return NULL;
  16276. }
  16277. /* check all known protocols */
  16278. if (!mg_strcasecmp(protocol, "http")) {
  16279. is_ssl = 0;
  16280. is_ws = 0;
  16281. } else if (!mg_strcasecmp(protocol, "https")) {
  16282. is_ssl = 1;
  16283. is_ws = 0;
  16284. #if defined(USE_WEBSOCKET)
  16285. } else if (!mg_strcasecmp(protocol, "ws")) {
  16286. is_ssl = 0;
  16287. is_ws = 1;
  16288. } else if (!mg_strcasecmp(protocol, "wss")) {
  16289. is_ssl = 1;
  16290. is_ws = 1;
  16291. #endif
  16292. } else {
  16293. if (error != NULL) {
  16294. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16295. mg_snprintf(NULL,
  16296. NULL, /* No truncation check for error buffers */
  16297. error->text,
  16298. error->text_buffer_size,
  16299. "Protocol %s not supported",
  16300. protocol);
  16301. }
  16302. return NULL;
  16303. }
  16304. /* TODO: The current implementation here just calls the old
  16305. * implementations, without using any new options. This is just a first
  16306. * step to test the new interfaces. */
  16307. #if defined(USE_WEBSOCKET)
  16308. if (is_ws) {
  16309. /* TODO: implement all options */
  16310. return mg_connect_websocket_client(
  16311. host,
  16312. port,
  16313. is_ssl,
  16314. ((error != NULL) ? error->text : NULL),
  16315. ((error != NULL) ? error->text_buffer_size : 0),
  16316. (path ? path : ""),
  16317. NULL /* TODO: origin */,
  16318. experimental_websocket_client_data_wrapper,
  16319. experimental_websocket_client_close_wrapper,
  16320. (void *)init->callbacks);
  16321. }
  16322. #else
  16323. (void)is_ws;
  16324. #endif
  16325. /* TODO: all additional options */
  16326. struct mg_client_options opts;
  16327. memset(&opts, 0, sizeof(opts));
  16328. opts.host = host;
  16329. opts.port = port;
  16330. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16331. }
  16332. #endif
  16333. static const struct {
  16334. const char *proto;
  16335. size_t proto_len;
  16336. unsigned default_port;
  16337. } abs_uri_protocols[] = {{"http://", 7, 80},
  16338. {"https://", 8, 443},
  16339. {"ws://", 5, 80},
  16340. {"wss://", 6, 443},
  16341. {NULL, 0, 0}};
  16342. /* Check if the uri is valid.
  16343. * return 0 for invalid uri,
  16344. * return 1 for *,
  16345. * return 2 for relative uri,
  16346. * return 3 for absolute uri without port,
  16347. * return 4 for absolute uri with port */
  16348. static int
  16349. get_uri_type(const char *uri)
  16350. {
  16351. int i;
  16352. const char *hostend, *portbegin;
  16353. char *portend;
  16354. unsigned long port;
  16355. /* According to the HTTP standard
  16356. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16357. * URI can be an asterisk (*) or should start with slash (relative uri),
  16358. * or it should start with the protocol (absolute uri). */
  16359. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16360. /* asterisk */
  16361. return 1;
  16362. }
  16363. /* Valid URIs according to RFC 3986
  16364. * (https://www.ietf.org/rfc/rfc3986.txt)
  16365. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16366. * and unreserved characters A-Z a-z 0-9 and -._~
  16367. * and % encoded symbols.
  16368. */
  16369. for (i = 0; uri[i] != 0; i++) {
  16370. /* Check for CRLF injection attempts */
  16371. if (uri[i] == '%') {
  16372. if (uri[i+1] == '0' && (uri[i+2] == 'd' || uri[i+2] == 'D')) {
  16373. /* Found %0d (CR) */
  16374. DEBUG_TRACE("CRLF injection attempt detected: %s\r\n", uri);
  16375. return 0;
  16376. }
  16377. if (uri[i+1] == '0' && (uri[i+2] == 'a' || uri[i+2] == 'A')) {
  16378. /* Found %0a (LF) */
  16379. DEBUG_TRACE("CRLF injection attempt detected: %s\r\n", uri);
  16380. return 0;
  16381. }
  16382. }
  16383. if ((unsigned char)uri[i] < 33) {
  16384. /* control characters and spaces are invalid */
  16385. return 0;
  16386. }
  16387. /* Allow everything else here (See #894) */
  16388. }
  16389. /* A relative uri starts with a / character */
  16390. if (uri[0] == '/') {
  16391. /* relative uri */
  16392. return 2;
  16393. }
  16394. /* It could be an absolute uri: */
  16395. /* This function only checks if the uri is valid, not if it is
  16396. * addressing the current server. So civetweb can also be used
  16397. * as a proxy server. */
  16398. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16399. if (mg_strncasecmp(uri,
  16400. abs_uri_protocols[i].proto,
  16401. abs_uri_protocols[i].proto_len)
  16402. == 0) {
  16403. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16404. if (!hostend) {
  16405. return 0;
  16406. }
  16407. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16408. if (!portbegin) {
  16409. return 3;
  16410. }
  16411. port = strtoul(portbegin + 1, &portend, 10);
  16412. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16413. return 0;
  16414. }
  16415. return 4;
  16416. }
  16417. }
  16418. return 0;
  16419. }
  16420. /* Return NULL or the relative uri at the current server */
  16421. static const char *
  16422. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16423. {
  16424. const char *server_domain;
  16425. size_t server_domain_len;
  16426. size_t request_domain_len = 0;
  16427. unsigned long port = 0;
  16428. int i, auth_domain_check_enabled;
  16429. const char *hostbegin = NULL;
  16430. const char *hostend = NULL;
  16431. const char *portbegin;
  16432. char *portend;
  16433. auth_domain_check_enabled =
  16434. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16435. /* DNS is case insensitive, so use case insensitive string compare here
  16436. */
  16437. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16438. if (mg_strncasecmp(uri,
  16439. abs_uri_protocols[i].proto,
  16440. abs_uri_protocols[i].proto_len)
  16441. == 0) {
  16442. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16443. hostend = strchr(hostbegin, '/');
  16444. if (!hostend) {
  16445. return 0;
  16446. }
  16447. portbegin = strchr(hostbegin, ':');
  16448. if ((!portbegin) || (portbegin > hostend)) {
  16449. port = abs_uri_protocols[i].default_port;
  16450. request_domain_len = (size_t)(hostend - hostbegin);
  16451. } else {
  16452. port = strtoul(portbegin + 1, &portend, 10);
  16453. if ((portend != hostend) || (port <= 0)
  16454. || !is_valid_port(port)) {
  16455. return 0;
  16456. }
  16457. request_domain_len = (size_t)(portbegin - hostbegin);
  16458. }
  16459. /* protocol found, port set */
  16460. break;
  16461. }
  16462. }
  16463. if (!port) {
  16464. /* port remains 0 if the protocol is not found */
  16465. return 0;
  16466. }
  16467. /* Check if the request is directed to a different server. */
  16468. /* First check if the port is the same. */
  16469. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16470. /* Request is directed to a different port */
  16471. return 0;
  16472. }
  16473. /* Finally check if the server corresponds to the authentication
  16474. * domain of the server (the server domain).
  16475. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16476. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16477. * but do not allow substrings (like
  16478. * http://notmydomain.com/path/file.ext
  16479. * or http://mydomain.com.fake/path/file.ext).
  16480. */
  16481. if (auth_domain_check_enabled) {
  16482. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16483. server_domain_len = strlen(server_domain);
  16484. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16485. return 0;
  16486. }
  16487. if ((request_domain_len == server_domain_len)
  16488. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16489. /* Request is directed to this server - full name match. */
  16490. } else {
  16491. if (request_domain_len < (server_domain_len + 2)) {
  16492. /* Request is directed to another server: The server name
  16493. * is longer than the request name.
  16494. * Drop this case here to avoid overflows in the
  16495. * following checks. */
  16496. return 0;
  16497. }
  16498. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16499. /* Request is directed to another server: It could be a
  16500. * substring
  16501. * like notmyserver.com */
  16502. return 0;
  16503. }
  16504. if (0
  16505. != memcmp(server_domain,
  16506. hostbegin + request_domain_len - server_domain_len,
  16507. server_domain_len)) {
  16508. /* Request is directed to another server:
  16509. * The server name is different. */
  16510. return 0;
  16511. }
  16512. }
  16513. }
  16514. return hostend;
  16515. }
  16516. static int
  16517. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16518. {
  16519. if (ebuf_len > 0) {
  16520. ebuf[0] = '\0';
  16521. }
  16522. *err = 0;
  16523. reset_per_request_attributes(conn);
  16524. if (!conn) {
  16525. mg_snprintf(conn,
  16526. NULL, /* No truncation check for ebuf */
  16527. ebuf,
  16528. ebuf_len,
  16529. "%s",
  16530. "Internal error");
  16531. *err = 500;
  16532. return 0;
  16533. }
  16534. /* Set the time the request was received. This value should be used for
  16535. * timeouts. */
  16536. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16537. conn->request_len =
  16538. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16539. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16540. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16541. mg_snprintf(conn,
  16542. NULL, /* No truncation check for ebuf */
  16543. ebuf,
  16544. ebuf_len,
  16545. "%s",
  16546. "Invalid message size");
  16547. *err = 500;
  16548. return 0;
  16549. }
  16550. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16551. mg_snprintf(conn,
  16552. NULL, /* No truncation check for ebuf */
  16553. ebuf,
  16554. ebuf_len,
  16555. "%s",
  16556. "Message too large");
  16557. *err = 413;
  16558. return 0;
  16559. }
  16560. if (conn->request_len <= 0) {
  16561. if (conn->data_len > 0) {
  16562. mg_snprintf(conn,
  16563. NULL, /* No truncation check for ebuf */
  16564. ebuf,
  16565. ebuf_len,
  16566. "%s",
  16567. conn->request_len == -3 ? "Request timeout"
  16568. : "Malformed message");
  16569. *err = 400;
  16570. } else {
  16571. /* Server did not recv anything -> just close the connection */
  16572. conn->must_close = 1;
  16573. mg_snprintf(conn,
  16574. NULL, /* No truncation check for ebuf */
  16575. ebuf,
  16576. ebuf_len,
  16577. "%s",
  16578. "No data received");
  16579. *err = 0;
  16580. }
  16581. return 0;
  16582. }
  16583. return 1;
  16584. }
  16585. static int
  16586. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16587. {
  16588. const char *cl;
  16589. conn->connection_type =
  16590. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16591. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16592. return 0;
  16593. }
  16594. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16595. <= 0) {
  16596. mg_snprintf(conn,
  16597. NULL, /* No truncation check for ebuf */
  16598. ebuf,
  16599. ebuf_len,
  16600. "%s",
  16601. "Bad request");
  16602. *err = 400;
  16603. return 0;
  16604. }
  16605. /* Message is a valid request */
  16606. if (!switch_domain_context(conn)) {
  16607. mg_snprintf(conn,
  16608. NULL, /* No truncation check for ebuf */
  16609. ebuf,
  16610. ebuf_len,
  16611. "%s",
  16612. "Bad request: Host mismatch");
  16613. *err = 400;
  16614. return 0;
  16615. }
  16616. #if USE_ZLIB
  16617. if (((cl = get_header(conn->request_info.http_headers,
  16618. conn->request_info.num_headers,
  16619. "Accept-Encoding"))
  16620. != NULL)
  16621. && strstr(cl, "gzip")) {
  16622. conn->accept_gzip = 1;
  16623. }
  16624. #endif
  16625. if (((cl = get_header(conn->request_info.http_headers,
  16626. conn->request_info.num_headers,
  16627. "Transfer-Encoding"))
  16628. != NULL)
  16629. && mg_strcasecmp(cl, "identity")) {
  16630. if (mg_strcasecmp(cl, "chunked")) {
  16631. mg_snprintf(conn,
  16632. NULL, /* No truncation check for ebuf */
  16633. ebuf,
  16634. ebuf_len,
  16635. "%s",
  16636. "Bad request");
  16637. *err = 400;
  16638. return 0;
  16639. }
  16640. conn->is_chunked = 1;
  16641. conn->content_len = 0; /* not yet read */
  16642. } else if ((cl = get_header(conn->request_info.http_headers,
  16643. conn->request_info.num_headers,
  16644. "Content-Length"))
  16645. != NULL) {
  16646. /* Request has content length set */
  16647. char *endptr = NULL;
  16648. conn->content_len = strtoll(cl, &endptr, 10);
  16649. if ((endptr == cl) || (conn->content_len < 0)) {
  16650. mg_snprintf(conn,
  16651. NULL, /* No truncation check for ebuf */
  16652. ebuf,
  16653. ebuf_len,
  16654. "%s",
  16655. "Bad request");
  16656. *err = 411;
  16657. return 0;
  16658. }
  16659. /* Publish the content length back to the request info. */
  16660. conn->request_info.content_length = conn->content_len;
  16661. } else {
  16662. /* There is no exception, see RFC7230. */
  16663. conn->content_len = 0;
  16664. }
  16665. return 1;
  16666. }
  16667. /* conn is assumed to be valid in this internal function */
  16668. static int
  16669. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16670. {
  16671. const char *cl;
  16672. conn->connection_type =
  16673. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16674. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16675. return 0;
  16676. }
  16677. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16678. <= 0) {
  16679. mg_snprintf(conn,
  16680. NULL, /* No truncation check for ebuf */
  16681. ebuf,
  16682. ebuf_len,
  16683. "%s",
  16684. "Bad response");
  16685. *err = 400;
  16686. return 0;
  16687. }
  16688. /* Message is a valid response */
  16689. if (((cl = get_header(conn->response_info.http_headers,
  16690. conn->response_info.num_headers,
  16691. "Transfer-Encoding"))
  16692. != NULL)
  16693. && mg_strcasecmp(cl, "identity")) {
  16694. if (mg_strcasecmp(cl, "chunked")) {
  16695. mg_snprintf(conn,
  16696. NULL, /* No truncation check for ebuf */
  16697. ebuf,
  16698. ebuf_len,
  16699. "%s",
  16700. "Bad request");
  16701. *err = 400;
  16702. return 0;
  16703. }
  16704. conn->is_chunked = 1;
  16705. conn->content_len = 0; /* not yet read */
  16706. } else if ((cl = get_header(conn->response_info.http_headers,
  16707. conn->response_info.num_headers,
  16708. "Content-Length"))
  16709. != NULL) {
  16710. char *endptr = NULL;
  16711. conn->content_len = strtoll(cl, &endptr, 10);
  16712. if ((endptr == cl) || (conn->content_len < 0)) {
  16713. mg_snprintf(conn,
  16714. NULL, /* No truncation check for ebuf */
  16715. ebuf,
  16716. ebuf_len,
  16717. "%s",
  16718. "Bad request");
  16719. *err = 411;
  16720. return 0;
  16721. }
  16722. /* Publish the content length back to the response info. */
  16723. conn->response_info.content_length = conn->content_len;
  16724. /* TODO: check if it is still used in response_info */
  16725. conn->request_info.content_length = conn->content_len;
  16726. /* TODO: we should also consider HEAD method */
  16727. if (conn->response_info.status_code == 304) {
  16728. conn->content_len = 0;
  16729. }
  16730. } else {
  16731. /* TODO: we should also consider HEAD method */
  16732. if (((conn->response_info.status_code >= 100)
  16733. && (conn->response_info.status_code <= 199))
  16734. || (conn->response_info.status_code == 204)
  16735. || (conn->response_info.status_code == 304)) {
  16736. conn->content_len = 0;
  16737. } else {
  16738. conn->content_len = -1; /* unknown content length */
  16739. }
  16740. }
  16741. return 1;
  16742. }
  16743. CIVETWEB_API int
  16744. mg_get_response(struct mg_connection *conn,
  16745. char *ebuf,
  16746. size_t ebuf_len,
  16747. int timeout)
  16748. {
  16749. int err, ret;
  16750. char txt[32]; /* will not overflow */
  16751. char *save_timeout;
  16752. char *new_timeout;
  16753. if (ebuf_len > 0) {
  16754. ebuf[0] = '\0';
  16755. }
  16756. if (!conn) {
  16757. mg_snprintf(conn,
  16758. NULL, /* No truncation check for ebuf */
  16759. ebuf,
  16760. ebuf_len,
  16761. "%s",
  16762. "Parameter error");
  16763. return -1;
  16764. }
  16765. /* Reset the previous responses */
  16766. conn->data_len = 0;
  16767. /* Implementation of API function for HTTP clients */
  16768. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16769. if (timeout >= 0) {
  16770. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16771. new_timeout = txt;
  16772. } else {
  16773. new_timeout = NULL;
  16774. }
  16775. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16776. ret = get_response(conn, ebuf, ebuf_len, &err);
  16777. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16778. /* TODO: here, the URI is the http response code */
  16779. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16780. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16781. /* TODO (mid): Define proper return values - maybe return length?
  16782. * For the first test use <0 for error and >0 for OK */
  16783. return (ret == 0) ? -1 : +1;
  16784. }
  16785. CIVETWEB_API struct mg_connection *
  16786. mg_download(const char *host,
  16787. int port,
  16788. int use_ssl,
  16789. char *ebuf,
  16790. size_t ebuf_len,
  16791. const char *fmt,
  16792. ...)
  16793. {
  16794. struct mg_connection *conn;
  16795. va_list ap;
  16796. int i;
  16797. int reqerr;
  16798. if (ebuf_len > 0) {
  16799. ebuf[0] = '\0';
  16800. }
  16801. va_start(ap, fmt);
  16802. /* open a connection */
  16803. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16804. if (conn != NULL) {
  16805. i = mg_vprintf(conn, fmt, ap);
  16806. if (i <= 0) {
  16807. mg_snprintf(conn,
  16808. NULL, /* No truncation check for ebuf */
  16809. ebuf,
  16810. ebuf_len,
  16811. "%s",
  16812. "Error sending request");
  16813. } else {
  16814. /* make sure the buffer is clear */
  16815. conn->data_len = 0;
  16816. get_response(conn, ebuf, ebuf_len, &reqerr);
  16817. /* TODO: here, the URI is the http response code */
  16818. conn->request_info.local_uri = conn->request_info.request_uri;
  16819. }
  16820. }
  16821. /* if an error occurred, close the connection */
  16822. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16823. mg_close_connection(conn);
  16824. conn = NULL;
  16825. }
  16826. va_end(ap);
  16827. return conn;
  16828. }
  16829. struct websocket_client_thread_data {
  16830. struct mg_connection *conn;
  16831. mg_websocket_data_handler data_handler;
  16832. mg_websocket_close_handler close_handler;
  16833. void *callback_data;
  16834. };
  16835. #if defined(USE_WEBSOCKET)
  16836. #if defined(_WIN32)
  16837. static unsigned __stdcall websocket_client_thread(void *data)
  16838. #else
  16839. static void *
  16840. websocket_client_thread(void *data)
  16841. #endif
  16842. {
  16843. struct websocket_client_thread_data *cdata =
  16844. (struct websocket_client_thread_data *)data;
  16845. void *user_thread_ptr = NULL;
  16846. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16847. struct sigaction sa;
  16848. /* Ignore SIGPIPE */
  16849. memset(&sa, 0, sizeof(sa));
  16850. sa.sa_handler = SIG_IGN;
  16851. sigaction(SIGPIPE, &sa, NULL);
  16852. #endif
  16853. mg_set_thread_name("ws-clnt");
  16854. if (cdata->conn->phys_ctx) {
  16855. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16856. /* 3 indicates a websocket client thread */
  16857. /* TODO: check if conn->phys_ctx can be set */
  16858. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16859. cdata->conn->phys_ctx, 3);
  16860. }
  16861. }
  16862. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16863. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16864. if (cdata->close_handler != NULL) {
  16865. cdata->close_handler(cdata->conn, cdata->callback_data);
  16866. }
  16867. /* The websocket_client context has only this thread. If it runs out,
  16868. set the stop_flag to 2 (= "stopped"). */
  16869. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16870. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16871. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16872. 3,
  16873. user_thread_ptr);
  16874. }
  16875. mg_free((void *)cdata);
  16876. #if defined(_WIN32)
  16877. return 0;
  16878. #else
  16879. return NULL;
  16880. #endif
  16881. }
  16882. #endif
  16883. #if defined(USE_WEBSOCKET)
  16884. static void
  16885. generate_websocket_magic(char *magic25)
  16886. {
  16887. uint64_t rnd;
  16888. unsigned char buffer[2 * sizeof(rnd)];
  16889. rnd = get_random();
  16890. memcpy(buffer, &rnd, sizeof(rnd));
  16891. rnd = get_random();
  16892. memcpy(buffer + sizeof(rnd), &rnd, sizeof(rnd));
  16893. size_t dst_len = 24 + 1;
  16894. mg_base64_encode(buffer, sizeof(buffer), magic25, &dst_len);
  16895. }
  16896. #endif
  16897. static struct mg_connection *
  16898. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16899. int use_ssl,
  16900. char *error_buffer,
  16901. size_t error_buffer_size,
  16902. const char *path,
  16903. const char *origin,
  16904. const char *extensions,
  16905. mg_websocket_data_handler data_func,
  16906. mg_websocket_close_handler close_func,
  16907. void *user_data)
  16908. {
  16909. struct mg_connection *conn = NULL;
  16910. #if defined(USE_WEBSOCKET)
  16911. struct websocket_client_thread_data *thread_data;
  16912. char magic[32];
  16913. generate_websocket_magic(magic);
  16914. const char *host = client_options->host;
  16915. int i;
  16916. struct mg_init_data init;
  16917. struct mg_error_data error;
  16918. memset(&init, 0, sizeof(init));
  16919. memset(&error, 0, sizeof(error));
  16920. error.text_buffer_size = error_buffer_size;
  16921. error.text = error_buffer;
  16922. #if defined(__clang__)
  16923. #pragma clang diagnostic push
  16924. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16925. #endif
  16926. /* Establish the client connection and request upgrade */
  16927. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16928. /* Connection object will be null if something goes wrong */
  16929. if (conn == NULL) {
  16930. /* error_buffer should be already filled ... */
  16931. if (!error_buffer[0]) {
  16932. /* ... if not add an error message */
  16933. mg_snprintf(conn,
  16934. NULL, /* No truncation check for ebuf */
  16935. error_buffer,
  16936. error_buffer_size,
  16937. "Unexpected error");
  16938. }
  16939. return NULL;
  16940. }
  16941. if (origin != NULL) {
  16942. if (extensions != NULL) {
  16943. i = mg_printf(conn,
  16944. "GET %s HTTP/1.1\r\n"
  16945. "Host: %s\r\n"
  16946. "Upgrade: websocket\r\n"
  16947. "Connection: Upgrade\r\n"
  16948. "Sec-WebSocket-Key: %s\r\n"
  16949. "Sec-WebSocket-Version: 13\r\n"
  16950. "Sec-WebSocket-Extensions: %s\r\n"
  16951. "Origin: %s\r\n"
  16952. "\r\n",
  16953. path,
  16954. host,
  16955. magic,
  16956. extensions,
  16957. origin);
  16958. } else {
  16959. i = mg_printf(conn,
  16960. "GET %s HTTP/1.1\r\n"
  16961. "Host: %s\r\n"
  16962. "Upgrade: websocket\r\n"
  16963. "Connection: Upgrade\r\n"
  16964. "Sec-WebSocket-Key: %s\r\n"
  16965. "Sec-WebSocket-Version: 13\r\n"
  16966. "Origin: %s\r\n"
  16967. "\r\n",
  16968. path,
  16969. host,
  16970. magic,
  16971. origin);
  16972. }
  16973. } else {
  16974. if (extensions != NULL) {
  16975. i = mg_printf(conn,
  16976. "GET %s HTTP/1.1\r\n"
  16977. "Host: %s\r\n"
  16978. "Upgrade: websocket\r\n"
  16979. "Connection: Upgrade\r\n"
  16980. "Sec-WebSocket-Key: %s\r\n"
  16981. "Sec-WebSocket-Version: 13\r\n"
  16982. "Sec-WebSocket-Extensions: %s\r\n"
  16983. "\r\n",
  16984. path,
  16985. host,
  16986. magic,
  16987. extensions);
  16988. } else {
  16989. i = mg_printf(conn,
  16990. "GET %s HTTP/1.1\r\n"
  16991. "Host: %s\r\n"
  16992. "Upgrade: websocket\r\n"
  16993. "Connection: Upgrade\r\n"
  16994. "Sec-WebSocket-Key: %s\r\n"
  16995. "Sec-WebSocket-Version: 13\r\n"
  16996. "\r\n",
  16997. path,
  16998. host,
  16999. magic);
  17000. }
  17001. }
  17002. if (i <= 0) {
  17003. mg_snprintf(conn,
  17004. NULL, /* No truncation check for ebuf */
  17005. error_buffer,
  17006. error_buffer_size,
  17007. "%s",
  17008. "Error sending request");
  17009. mg_close_connection(conn);
  17010. return NULL;
  17011. }
  17012. conn->data_len = 0;
  17013. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  17014. mg_close_connection(conn);
  17015. return NULL;
  17016. }
  17017. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  17018. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  17019. #if defined(__clang__)
  17020. #pragma clang diagnostic pop
  17021. #endif
  17022. if (conn->response_info.status_code != 101) {
  17023. /* We sent an "upgrade" request. For a correct websocket
  17024. * protocol handshake, we expect a "101 Continue" response.
  17025. * Otherwise it is a protocol violation. Maybe the HTTP
  17026. * Server does not know websockets. */
  17027. if (!*error_buffer) {
  17028. /* set an error, if not yet set */
  17029. mg_snprintf(conn,
  17030. NULL, /* No truncation check for ebuf */
  17031. error_buffer,
  17032. error_buffer_size,
  17033. "Unexpected server reply");
  17034. }
  17035. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  17036. mg_close_connection(conn);
  17037. return NULL;
  17038. }
  17039. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  17040. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  17041. if (!thread_data) {
  17042. DEBUG_TRACE("%s\r\n", "Out of memory");
  17043. mg_close_connection(conn);
  17044. return NULL;
  17045. }
  17046. thread_data->conn = conn;
  17047. thread_data->data_handler = data_func;
  17048. thread_data->close_handler = close_func;
  17049. thread_data->callback_data = user_data;
  17050. conn->phys_ctx->worker_threadids =
  17051. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  17052. if (!conn->phys_ctx->worker_threadids) {
  17053. DEBUG_TRACE("%s\r\n", "Out of memory");
  17054. mg_free(thread_data);
  17055. mg_close_connection(conn);
  17056. return NULL;
  17057. }
  17058. /* Now upgrade to ws/wss client context */
  17059. conn->phys_ctx->user_data = user_data;
  17060. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  17061. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  17062. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  17063. /* Start a thread to read the websocket client connection
  17064. * This thread will automatically stop when mg_disconnect is
  17065. * called on the client connection */
  17066. if (mg_start_thread_with_id(websocket_client_thread,
  17067. thread_data,
  17068. conn->phys_ctx->worker_threadids)
  17069. != 0) {
  17070. conn->phys_ctx->spawned_worker_threads = 0;
  17071. mg_free(thread_data);
  17072. mg_close_connection(conn);
  17073. conn = NULL;
  17074. DEBUG_TRACE("%s",
  17075. "Websocket client connect thread could not be started\r\n");
  17076. }
  17077. #else
  17078. /* Appease "unused parameter" warnings */
  17079. (void)client_options;
  17080. (void)use_ssl;
  17081. (void)error_buffer;
  17082. (void)error_buffer_size;
  17083. (void)path;
  17084. (void)origin;
  17085. (void)extensions;
  17086. (void)user_data;
  17087. (void)data_func;
  17088. (void)close_func;
  17089. #endif
  17090. return conn;
  17091. }
  17092. CIVETWEB_API struct mg_connection *
  17093. mg_connect_websocket_client(const char *host,
  17094. int port,
  17095. int use_ssl,
  17096. char *error_buffer,
  17097. size_t error_buffer_size,
  17098. const char *path,
  17099. const char *origin,
  17100. mg_websocket_data_handler data_func,
  17101. mg_websocket_close_handler close_func,
  17102. void *user_data)
  17103. {
  17104. struct mg_client_options client_options;
  17105. memset(&client_options, 0, sizeof(client_options));
  17106. client_options.host = host;
  17107. client_options.port = port;
  17108. if (use_ssl) {
  17109. client_options.host_name = host;
  17110. }
  17111. return mg_connect_websocket_client_impl(&client_options,
  17112. use_ssl,
  17113. error_buffer,
  17114. error_buffer_size,
  17115. path,
  17116. origin,
  17117. NULL,
  17118. data_func,
  17119. close_func,
  17120. user_data);
  17121. }
  17122. CIVETWEB_API struct mg_connection *
  17123. mg_connect_websocket_client_secure(
  17124. const struct mg_client_options *client_options,
  17125. char *error_buffer,
  17126. size_t error_buffer_size,
  17127. const char *path,
  17128. const char *origin,
  17129. mg_websocket_data_handler data_func,
  17130. mg_websocket_close_handler close_func,
  17131. void *user_data)
  17132. {
  17133. if (!client_options) {
  17134. return NULL;
  17135. }
  17136. return mg_connect_websocket_client_impl(client_options,
  17137. 1,
  17138. error_buffer,
  17139. error_buffer_size,
  17140. path,
  17141. origin,
  17142. NULL,
  17143. data_func,
  17144. close_func,
  17145. user_data);
  17146. }
  17147. CIVETWEB_API struct mg_connection *
  17148. mg_connect_websocket_client_extensions(const char *host,
  17149. int port,
  17150. int use_ssl,
  17151. char *error_buffer,
  17152. size_t error_buffer_size,
  17153. const char *path,
  17154. const char *origin,
  17155. const char *extensions,
  17156. mg_websocket_data_handler data_func,
  17157. mg_websocket_close_handler close_func,
  17158. void *user_data)
  17159. {
  17160. struct mg_client_options client_options;
  17161. memset(&client_options, 0, sizeof(client_options));
  17162. client_options.host = host;
  17163. client_options.port = port;
  17164. return mg_connect_websocket_client_impl(&client_options,
  17165. use_ssl,
  17166. error_buffer,
  17167. error_buffer_size,
  17168. path,
  17169. origin,
  17170. extensions,
  17171. data_func,
  17172. close_func,
  17173. user_data);
  17174. }
  17175. CIVETWEB_API struct mg_connection *
  17176. mg_connect_websocket_client_secure_extensions(
  17177. const struct mg_client_options *client_options,
  17178. char *error_buffer,
  17179. size_t error_buffer_size,
  17180. const char *path,
  17181. const char *origin,
  17182. const char *extensions,
  17183. mg_websocket_data_handler data_func,
  17184. mg_websocket_close_handler close_func,
  17185. void *user_data)
  17186. {
  17187. if (!client_options) {
  17188. return NULL;
  17189. }
  17190. return mg_connect_websocket_client_impl(client_options,
  17191. 1,
  17192. error_buffer,
  17193. error_buffer_size,
  17194. path,
  17195. origin,
  17196. extensions,
  17197. data_func,
  17198. close_func,
  17199. user_data);
  17200. }
  17201. /* Prepare connection data structure */
  17202. static void
  17203. init_connection(struct mg_connection *conn)
  17204. {
  17205. /* Is keep alive allowed by the server */
  17206. int keep_alive_enabled =
  17207. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  17208. if (!keep_alive_enabled) {
  17209. conn->must_close = 1;
  17210. }
  17211. /* Important: on new connection, reset the receiving buffer. Credit
  17212. * goes to crule42. */
  17213. conn->data_len = 0;
  17214. conn->handled_requests = 0;
  17215. conn->connection_type = CONNECTION_TYPE_INVALID;
  17216. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  17217. mg_set_user_connection_data(conn, NULL);
  17218. #if defined(USE_SERVER_STATS)
  17219. conn->conn_state = 2; /* init */
  17220. #endif
  17221. /* call the init_connection callback if assigned */
  17222. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  17223. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  17224. void *conn_data = NULL;
  17225. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  17226. mg_set_user_connection_data(conn, conn_data);
  17227. }
  17228. }
  17229. }
  17230. /* Process a connection - may handle multiple requests
  17231. * using the same connection.
  17232. * Must be called with a valid connection (conn and
  17233. * conn->phys_ctx must be valid).
  17234. */
  17235. static void
  17236. process_new_connection(struct mg_connection *conn)
  17237. {
  17238. struct mg_request_info *ri = &conn->request_info;
  17239. int keep_alive, discard_len;
  17240. char ebuf[100];
  17241. const char *hostend;
  17242. int reqerr, uri_type;
  17243. #if defined(USE_SERVER_STATS)
  17244. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17245. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17246. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17247. #endif
  17248. DEBUG_TRACE("Start processing connection from %s",
  17249. conn->request_info.remote_addr);
  17250. /* Loop over multiple requests sent using the same connection
  17251. * (while "keep alive"). */
  17252. do {
  17253. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17254. conn->handled_requests + 1);
  17255. #if defined(USE_SERVER_STATS)
  17256. conn->conn_state = 3; /* ready */
  17257. #endif
  17258. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17259. /* The request sent by the client could not be understood by
  17260. * the server, or it was incomplete or a timeout. Send an
  17261. * error message and close the connection. */
  17262. if (reqerr > 0) {
  17263. DEBUG_ASSERT(ebuf[0] != '\0');
  17264. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17265. }
  17266. } else if (strcmp(ri->http_version, "1.0")
  17267. && strcmp(ri->http_version, "1.1")) {
  17268. /* HTTP/2 is not allowed here */
  17269. mg_snprintf(conn,
  17270. NULL, /* No truncation check for ebuf */
  17271. ebuf,
  17272. sizeof(ebuf),
  17273. "Bad HTTP version: [%s]",
  17274. ri->http_version);
  17275. mg_send_http_error(conn, 505, "%s", ebuf);
  17276. }
  17277. if (ebuf[0] == '\0') {
  17278. uri_type = get_uri_type(conn->request_info.request_uri);
  17279. switch (uri_type) {
  17280. case 1:
  17281. /* Asterisk */
  17282. conn->request_info.local_uri_raw = 0;
  17283. /* TODO: Deal with '*'. */
  17284. break;
  17285. case 2:
  17286. /* relative uri */
  17287. conn->request_info.local_uri_raw =
  17288. conn->request_info.request_uri;
  17289. break;
  17290. case 3:
  17291. case 4:
  17292. /* absolute uri (with/without port) */
  17293. hostend = get_rel_url_at_current_server(
  17294. conn->request_info.request_uri, conn);
  17295. if (hostend) {
  17296. conn->request_info.local_uri_raw = hostend;
  17297. } else {
  17298. conn->request_info.local_uri_raw = NULL;
  17299. }
  17300. break;
  17301. default:
  17302. mg_snprintf(conn,
  17303. NULL, /* No truncation check for ebuf */
  17304. ebuf,
  17305. sizeof(ebuf),
  17306. "Invalid URI");
  17307. mg_send_http_error(conn, 400, "%s", ebuf);
  17308. conn->request_info.local_uri_raw = NULL;
  17309. break;
  17310. }
  17311. conn->request_info.local_uri =
  17312. (char *)conn->request_info.local_uri_raw;
  17313. }
  17314. if (ebuf[0] != '\0') {
  17315. conn->protocol_type = -1;
  17316. } else {
  17317. /* HTTP/1 allows protocol upgrade */
  17318. conn->protocol_type = should_switch_to_protocol(conn);
  17319. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17320. /* This will occur, if a HTTP/1.1 request should be upgraded
  17321. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17322. * Since most (all?) major browsers only support HTTP/2 using
  17323. * ALPN, this is hard to test and very low priority.
  17324. * Deactivate it (at least for now).
  17325. */
  17326. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17327. }
  17328. }
  17329. DEBUG_TRACE("http: %s, error: %s",
  17330. (ri->http_version ? ri->http_version : "none"),
  17331. (ebuf[0] ? ebuf : "none"));
  17332. if (ebuf[0] == '\0') {
  17333. if (conn->request_info.local_uri) {
  17334. /* handle request to local server */
  17335. handle_request_stat_log(conn);
  17336. } else {
  17337. /* TODO: handle non-local request (PROXY) */
  17338. conn->must_close = 1;
  17339. }
  17340. } else {
  17341. conn->must_close = 1;
  17342. }
  17343. /* Response complete. Free header buffer */
  17344. free_buffered_response_header_list(conn);
  17345. if (ri->remote_user != NULL) {
  17346. mg_free((void *)ri->remote_user);
  17347. /* Important! When having connections with and without auth
  17348. * would cause double free and then crash */
  17349. ri->remote_user = NULL;
  17350. }
  17351. /* NOTE(lsm): order is important here. should_keep_alive() call
  17352. * is using parsed request, which will be invalid after
  17353. * memmove's below.
  17354. * Therefore, memorize should_keep_alive() result now for later
  17355. * use in loop exit condition. */
  17356. /* Enable it only if this request is completely discardable. */
  17357. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17358. && should_keep_alive(conn) && (conn->content_len >= 0)
  17359. && (conn->request_len > 0)
  17360. && ((conn->is_chunked == 4)
  17361. || (!conn->is_chunked
  17362. && ((conn->consumed_content == conn->content_len)
  17363. || ((conn->request_len + conn->content_len)
  17364. <= conn->data_len))))
  17365. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17366. if (keep_alive) {
  17367. /* Discard all buffered data for this request */
  17368. discard_len =
  17369. ((conn->request_len + conn->content_len) < conn->data_len)
  17370. ? (int)(conn->request_len + conn->content_len)
  17371. : conn->data_len;
  17372. conn->data_len -= discard_len;
  17373. if (conn->data_len > 0) {
  17374. DEBUG_TRACE("discard_len = %d", discard_len);
  17375. memmove(conn->buf,
  17376. conn->buf + discard_len,
  17377. (size_t)conn->data_len);
  17378. }
  17379. }
  17380. DEBUG_ASSERT(conn->data_len >= 0);
  17381. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17382. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17383. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17384. (long int)conn->data_len,
  17385. (long int)conn->buf_size);
  17386. break;
  17387. }
  17388. conn->handled_requests++;
  17389. } while (keep_alive);
  17390. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17391. conn->request_info.remote_addr,
  17392. difftime(time(NULL), conn->conn_birth_time));
  17393. close_connection(conn);
  17394. #if defined(USE_SERVER_STATS)
  17395. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17396. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17397. #endif
  17398. }
  17399. static int
  17400. mg_start_worker_thread(struct mg_context *ctx,
  17401. int only_if_no_idle_threads); /* forward declaration */
  17402. #if defined(ALTERNATIVE_QUEUE)
  17403. static void
  17404. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17405. {
  17406. unsigned int i;
  17407. (void)mg_start_worker_thread(
  17408. ctx, 1); /* will start a worker-thread only if there aren't currently
  17409. any idle worker-threads */
  17410. while (!ctx->stop_flag) {
  17411. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17412. /* find a free worker slot and signal it */
  17413. if (ctx->client_socks[i].in_use == 2) {
  17414. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17415. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17416. ctx->client_socks[i] = *sp;
  17417. ctx->client_socks[i].in_use = 1;
  17418. /* socket has been moved to the consumer */
  17419. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17420. (void)event_signal(ctx->client_wait_events[i]);
  17421. return;
  17422. }
  17423. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17424. }
  17425. }
  17426. /* queue is full */
  17427. mg_sleep(1);
  17428. }
  17429. /* must consume */
  17430. set_blocking_mode(sp->sock);
  17431. closesocket(sp->sock);
  17432. }
  17433. static int
  17434. consume_socket(struct mg_context *ctx,
  17435. struct socket *sp,
  17436. int thread_index,
  17437. int counter_was_preincremented)
  17438. {
  17439. DEBUG_TRACE("%s", "going idle");
  17440. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17441. if (counter_was_preincremented
  17442. == 0) { /* first call only: the master-thread pre-incremented this
  17443. before he spawned us */
  17444. ctx->idle_worker_thread_count++;
  17445. }
  17446. ctx->client_socks[thread_index].in_use = 2;
  17447. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17448. event_wait(ctx->client_wait_events[thread_index]);
  17449. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17450. *sp = ctx->client_socks[thread_index];
  17451. if (ctx->stop_flag) {
  17452. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17453. if (sp->in_use == 1) {
  17454. /* must consume */
  17455. set_blocking_mode(sp->sock);
  17456. closesocket(sp->sock);
  17457. }
  17458. return 0;
  17459. }
  17460. ctx->idle_worker_thread_count--;
  17461. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17462. if (sp->in_use == 1) {
  17463. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17464. return 1;
  17465. }
  17466. /* must not reach here */
  17467. DEBUG_ASSERT(0);
  17468. return 0;
  17469. }
  17470. #else /* ALTERNATIVE_QUEUE */
  17471. /* Worker threads take accepted socket from the queue */
  17472. static int
  17473. consume_socket(struct mg_context *ctx,
  17474. struct socket *sp,
  17475. int thread_index,
  17476. int counter_was_preincremented)
  17477. {
  17478. (void)thread_index;
  17479. DEBUG_TRACE("%s", "going idle");
  17480. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17481. if (counter_was_preincremented
  17482. == 0) { /* first call only: the master-thread pre-incremented this
  17483. before he spawned us */
  17484. ctx->idle_worker_thread_count++;
  17485. }
  17486. /* If the queue is empty, wait. We're idle at this point. */
  17487. while ((ctx->sq_head == ctx->sq_tail)
  17488. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17489. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17490. }
  17491. /* If we're stopping, sq_head may be equal to sq_tail. */
  17492. if (ctx->sq_head > ctx->sq_tail) {
  17493. /* Copy socket from the queue and increment tail */
  17494. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17495. ctx->sq_tail++;
  17496. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17497. /* Wrap pointers if needed */
  17498. while (ctx->sq_tail > ctx->sq_size) {
  17499. ctx->sq_tail -= ctx->sq_size;
  17500. ctx->sq_head -= ctx->sq_size;
  17501. }
  17502. }
  17503. (void)pthread_cond_signal(&ctx->sq_empty);
  17504. ctx->idle_worker_thread_count--;
  17505. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17506. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17507. }
  17508. /* Master thread adds accepted socket to a queue */
  17509. static void
  17510. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17511. {
  17512. int queue_filled;
  17513. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17514. queue_filled = ctx->sq_head - ctx->sq_tail;
  17515. /* If the queue is full, wait */
  17516. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17517. && (queue_filled >= ctx->sq_size)) {
  17518. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17519. #if defined(USE_SERVER_STATS)
  17520. if (queue_filled > ctx->sq_max_fill) {
  17521. ctx->sq_max_fill = queue_filled;
  17522. }
  17523. #endif
  17524. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17525. ctx->sq_blocked = 0; /* Not blocked now */
  17526. queue_filled = ctx->sq_head - ctx->sq_tail;
  17527. }
  17528. if (queue_filled < ctx->sq_size) {
  17529. /* Copy socket to the queue and increment head */
  17530. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17531. ctx->sq_head++;
  17532. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17533. }
  17534. queue_filled = ctx->sq_head - ctx->sq_tail;
  17535. #if defined(USE_SERVER_STATS)
  17536. if (queue_filled > ctx->sq_max_fill) {
  17537. ctx->sq_max_fill = queue_filled;
  17538. }
  17539. #endif
  17540. (void)pthread_cond_signal(&ctx->sq_full);
  17541. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17542. (void)mg_start_worker_thread(
  17543. ctx, 1); /* will start a worker-thread only if there aren't currently
  17544. any idle worker-threads */
  17545. }
  17546. #endif /* ALTERNATIVE_QUEUE */
  17547. static void
  17548. worker_thread_run(struct mg_connection *conn)
  17549. {
  17550. struct mg_context *ctx = conn->phys_ctx;
  17551. int thread_index;
  17552. struct mg_workerTLS tls;
  17553. int first_call_to_consume_socket = 1;
  17554. mg_set_thread_name("worker");
  17555. tls.is_master = 0;
  17556. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17557. #if defined(_WIN32)
  17558. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17559. #endif
  17560. /* Initialize thread local storage before calling any callback */
  17561. pthread_setspecific(sTlsKey, &tls);
  17562. /* Check if there is a user callback */
  17563. if (ctx->callbacks.init_thread) {
  17564. /* call init_thread for a worker thread (type 1), and store the
  17565. * return value */
  17566. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17567. } else {
  17568. /* No callback: set user pointer to NULL */
  17569. tls.user_ptr = NULL;
  17570. }
  17571. /* Connection structure has been pre-allocated */
  17572. thread_index = (int)(conn - ctx->worker_connections);
  17573. if ((thread_index < 0)
  17574. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17575. mg_cry_ctx_internal(ctx,
  17576. "Internal error: Invalid worker index %i",
  17577. thread_index);
  17578. return;
  17579. }
  17580. /* Request buffers are not pre-allocated. They are private to the
  17581. * request and do not contain any state information that might be
  17582. * of interest to anyone observing a server status. */
  17583. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17584. if (conn->buf == NULL) {
  17585. mg_cry_ctx_internal(
  17586. ctx,
  17587. "Out of memory: Cannot allocate buffer for worker %i",
  17588. thread_index);
  17589. return;
  17590. }
  17591. conn->buf_size = (int)ctx->max_request_size;
  17592. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17593. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17594. conn->request_info.user_data = ctx->user_data;
  17595. /* Allocate a mutex for this connection to allow communication both
  17596. * within the request handler and from elsewhere in the application
  17597. */
  17598. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17599. mg_free(conn->buf);
  17600. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17601. return;
  17602. }
  17603. #if defined(USE_SERVER_STATS)
  17604. conn->conn_state = 1; /* not consumed */
  17605. #endif
  17606. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17607. * signal sq_empty condvar to wake up the master waiting in
  17608. * produce_socket() */
  17609. while (consume_socket(
  17610. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17611. first_call_to_consume_socket = 0;
  17612. /* New connections must start with new protocol negotiation */
  17613. tls.alpn_proto = NULL;
  17614. #if defined(USE_SERVER_STATS)
  17615. conn->conn_close_time = 0;
  17616. #endif
  17617. conn->conn_birth_time = time(NULL);
  17618. /* Fill in IP, port info early so even if SSL setup below fails,
  17619. * error handler would have the corresponding info.
  17620. * Thanks to Johannes Winkelmann for the patch.
  17621. */
  17622. conn->request_info.remote_port =
  17623. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17624. conn->request_info.server_port =
  17625. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17626. sockaddr_to_string(conn->request_info.remote_addr,
  17627. sizeof(conn->request_info.remote_addr),
  17628. &conn->client.rsa);
  17629. DEBUG_TRACE("Incoming %sconnection from %s",
  17630. (conn->client.is_ssl ? "SSL " : ""),
  17631. conn->request_info.remote_addr);
  17632. conn->request_info.is_ssl = conn->client.is_ssl;
  17633. if (conn->client.is_ssl) {
  17634. #if defined(USE_MBEDTLS)
  17635. /* HTTPS connection */
  17636. if (mbed_ssl_accept(&(conn->ssl),
  17637. conn->dom_ctx->ssl_ctx,
  17638. (int *)&(conn->client.sock),
  17639. conn->phys_ctx)
  17640. == 0) {
  17641. /* conn->dom_ctx is set in get_request */
  17642. /* process HTTPS connection */
  17643. init_connection(conn);
  17644. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17645. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17646. process_new_connection(conn);
  17647. } else {
  17648. /* make sure the connection is cleaned up on SSL failure */
  17649. close_connection(conn);
  17650. }
  17651. #elif defined(USE_GNUTLS)
  17652. /* HTTPS connection */
  17653. if (gtls_ssl_accept(&(conn->ssl),
  17654. conn->dom_ctx->ssl_ctx,
  17655. conn->client.sock,
  17656. conn->phys_ctx)
  17657. == 0) {
  17658. /* conn->dom_ctx is set in get_request */
  17659. /* process HTTPS connection */
  17660. init_connection(conn);
  17661. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17662. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17663. process_new_connection(conn);
  17664. } else {
  17665. /* make sure the connection is cleaned up on SSL failure */
  17666. close_connection(conn);
  17667. }
  17668. #elif !defined(NO_SSL)
  17669. /* HTTPS connection */
  17670. if (sslize(conn, SSL_accept, NULL)) {
  17671. /* conn->dom_ctx is set in get_request */
  17672. /* Get SSL client certificate information (if set) */
  17673. struct mg_client_cert client_cert;
  17674. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17675. conn->request_info.client_cert = &client_cert;
  17676. }
  17677. /* process HTTPS connection */
  17678. #if defined(USE_HTTP2)
  17679. if ((tls.alpn_proto != NULL)
  17680. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17681. /* process HTTPS/2 connection */
  17682. init_connection(conn);
  17683. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17684. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17685. conn->content_len =
  17686. -1; /* content length is not predefined */
  17687. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17688. process_new_http2_connection(conn);
  17689. } else
  17690. #endif
  17691. {
  17692. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17693. init_connection(conn);
  17694. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17695. /* Start with HTTP, WS will be an "upgrade" request later */
  17696. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17697. process_new_connection(conn);
  17698. }
  17699. /* Free client certificate info */
  17700. if (conn->request_info.client_cert) {
  17701. mg_free((void *)(conn->request_info.client_cert->subject));
  17702. mg_free((void *)(conn->request_info.client_cert->issuer));
  17703. mg_free((void *)(conn->request_info.client_cert->serial));
  17704. mg_free((void *)(conn->request_info.client_cert->finger));
  17705. /* Free certificate memory */
  17706. X509_free(
  17707. (X509 *)conn->request_info.client_cert->peer_cert);
  17708. conn->request_info.client_cert->peer_cert = 0;
  17709. conn->request_info.client_cert->subject = 0;
  17710. conn->request_info.client_cert->issuer = 0;
  17711. conn->request_info.client_cert->serial = 0;
  17712. conn->request_info.client_cert->finger = 0;
  17713. conn->request_info.client_cert = 0;
  17714. }
  17715. } else {
  17716. /* make sure the connection is cleaned up on SSL failure */
  17717. close_connection(conn);
  17718. }
  17719. #endif
  17720. } else {
  17721. /* process HTTP connection */
  17722. init_connection(conn);
  17723. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17724. /* Start with HTTP, WS will be an "upgrade" request later */
  17725. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17726. process_new_connection(conn);
  17727. }
  17728. DEBUG_TRACE("%s", "Connection closed");
  17729. #if defined(USE_SERVER_STATS)
  17730. conn->conn_close_time = time(NULL);
  17731. #endif
  17732. }
  17733. /* Call exit thread user callback */
  17734. if (ctx->callbacks.exit_thread) {
  17735. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17736. }
  17737. /* delete thread local storage objects */
  17738. pthread_setspecific(sTlsKey, NULL);
  17739. #if defined(_WIN32)
  17740. CloseHandle(tls.pthread_cond_helper_mutex);
  17741. #endif
  17742. pthread_mutex_destroy(&conn->mutex);
  17743. /* Free the request buffer. */
  17744. conn->buf_size = 0;
  17745. mg_free(conn->buf);
  17746. conn->buf = NULL;
  17747. /* Free cleaned URI (if any) */
  17748. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17749. mg_free((void *)conn->request_info.local_uri);
  17750. conn->request_info.local_uri = NULL;
  17751. }
  17752. #if defined(USE_SERVER_STATS)
  17753. conn->conn_state = 9; /* done */
  17754. #endif
  17755. DEBUG_TRACE("%s", "exiting");
  17756. }
  17757. /* Threads have different return types on Windows and Unix. */
  17758. #if defined(_WIN32)
  17759. static unsigned __stdcall worker_thread(void *thread_func_param)
  17760. {
  17761. worker_thread_run((struct mg_connection *)thread_func_param);
  17762. return 0;
  17763. }
  17764. #else
  17765. static void *
  17766. worker_thread(void *thread_func_param)
  17767. {
  17768. #if !defined(__ZEPHYR__)
  17769. struct sigaction sa;
  17770. /* Ignore SIGPIPE */
  17771. memset(&sa, 0, sizeof(sa));
  17772. sa.sa_handler = SIG_IGN;
  17773. sigaction(SIGPIPE, &sa, NULL);
  17774. #endif
  17775. worker_thread_run((struct mg_connection *)thread_func_param);
  17776. return NULL;
  17777. }
  17778. #endif /* _WIN32 */
  17779. /* This is an internal function, thus all arguments are expected to be
  17780. * valid - a NULL check is not required. */
  17781. static void
  17782. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17783. {
  17784. struct socket so;
  17785. char src_addr[IP_ADDR_STR_LEN];
  17786. socklen_t len = sizeof(so.rsa);
  17787. #if !defined(__ZEPHYR__)
  17788. int on = 1;
  17789. #endif
  17790. memset(&so, 0, sizeof(so));
  17791. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17792. == INVALID_SOCKET) {
  17793. } else if (check_acl(ctx, &so.rsa) != 1) {
  17794. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17795. mg_cry_ctx_internal(ctx,
  17796. "%s: %s is not allowed to connect",
  17797. __func__,
  17798. src_addr);
  17799. closesocket(so.sock);
  17800. } else {
  17801. /* Put so socket structure into the queue */
  17802. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17803. set_close_on_exec(so.sock, NULL, ctx);
  17804. so.is_ssl = listener->is_ssl;
  17805. so.ssl_redir = listener->ssl_redir;
  17806. so.is_optional = listener->is_optional;
  17807. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17808. mg_cry_ctx_internal(ctx,
  17809. "%s: getsockname() failed: %s",
  17810. __func__,
  17811. strerror(ERRNO));
  17812. }
  17813. #if !defined(__ZEPHYR__)
  17814. if ((so.lsa.sa.sa_family == AF_INET)
  17815. || (so.lsa.sa.sa_family == AF_INET6)) {
  17816. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17817. * This is needed because if HTTP-level keep-alive
  17818. * is enabled, and client resets the connection, server won't get
  17819. * TCP FIN or RST and will keep the connection open forever. With
  17820. * TCP keep-alive, next keep-alive handshake will figure out that
  17821. * the client is down and will close the server end.
  17822. * Thanks to Igor Klopov who suggested the patch. */
  17823. if (setsockopt(so.sock,
  17824. SOL_SOCKET,
  17825. SO_KEEPALIVE,
  17826. (SOCK_OPT_TYPE)&on,
  17827. sizeof(on))
  17828. != 0) {
  17829. mg_cry_ctx_internal(
  17830. ctx,
  17831. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17832. __func__,
  17833. strerror(ERRNO));
  17834. }
  17835. }
  17836. #endif
  17837. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17838. * to effectively fill up the underlying IP packet payload and
  17839. * reduce the overhead of sending lots of small buffers. However
  17840. * this hurts the server's throughput (ie. operations per second)
  17841. * when HTTP 1.1 persistent connections are used and the responses
  17842. * are relatively small (eg. less than 1400 bytes).
  17843. */
  17844. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17845. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17846. if (set_tcp_nodelay(&so, 1) != 0) {
  17847. mg_cry_ctx_internal(
  17848. ctx,
  17849. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17850. __func__,
  17851. strerror(ERRNO));
  17852. }
  17853. }
  17854. /* The "non blocking" property should already be
  17855. * inherited from the parent socket. Set it for
  17856. * non-compliant socket implementations. */
  17857. set_non_blocking_mode(so.sock);
  17858. so.in_use = 0;
  17859. produce_socket(ctx, &so);
  17860. }
  17861. }
  17862. static void
  17863. master_thread_run(struct mg_context *ctx)
  17864. {
  17865. struct mg_workerTLS tls;
  17866. struct mg_pollfd *pfd;
  17867. unsigned int i;
  17868. unsigned int workerthreadcount;
  17869. if (!ctx || !ctx->listening_socket_fds) {
  17870. return;
  17871. }
  17872. mg_set_thread_name("master");
  17873. /* Increase priority of the master thread */
  17874. #if defined(_WIN32)
  17875. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17876. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17877. int min_prio = sched_get_priority_min(SCHED_RR);
  17878. int max_prio = sched_get_priority_max(SCHED_RR);
  17879. if ((min_prio >= 0) && (max_prio >= 0)
  17880. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17881. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17882. struct sched_param sched_param = {0};
  17883. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17884. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17885. }
  17886. #endif
  17887. /* Initialize thread local storage */
  17888. #if defined(_WIN32)
  17889. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17890. #endif
  17891. tls.is_master = 1;
  17892. pthread_setspecific(sTlsKey, &tls);
  17893. if (ctx->callbacks.init_thread) {
  17894. /* Callback for the master thread (type 0) */
  17895. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17896. } else {
  17897. tls.user_ptr = NULL;
  17898. }
  17899. /* Lua background script "start" event */
  17900. #if defined(USE_LUA)
  17901. if (ctx->lua_background_state) {
  17902. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17903. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17904. /* call "start()" in Lua */
  17905. lua_getglobal(lstate, "start");
  17906. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17907. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17908. if (ret != 0) {
  17909. struct mg_connection fc;
  17910. lua_cry(fake_connection(&fc, ctx),
  17911. ret,
  17912. lstate,
  17913. "lua_background_script",
  17914. "start");
  17915. }
  17916. } else {
  17917. lua_pop(lstate, 1);
  17918. }
  17919. /* determine if there is a "log()" function in Lua background script */
  17920. lua_getglobal(lstate, "log");
  17921. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17922. ctx->lua_bg_log_available = 1;
  17923. }
  17924. lua_pop(lstate, 1);
  17925. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17926. }
  17927. #endif
  17928. /* Server starts *now* */
  17929. ctx->start_time = time(NULL);
  17930. /* Server accept loop */
  17931. pfd = ctx->listening_socket_fds;
  17932. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17933. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17934. pfd[i].fd = ctx->listening_sockets[i].sock;
  17935. pfd[i].events = POLLIN;
  17936. }
  17937. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17938. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17939. * of listening_socket_fds[] just to hold this
  17940. */
  17941. pfd[ctx->num_listening_sockets].fd =
  17942. ctx->thread_shutdown_notification_socket;
  17943. pfd[ctx->num_listening_sockets].events = POLLIN;
  17944. if (mg_poll(pfd,
  17945. ctx->num_listening_sockets
  17946. + 1, // +1 for the thread_shutdown_notification_socket
  17947. SOCKET_TIMEOUT_QUANTUM,
  17948. &(ctx->stop_flag))
  17949. > 0) {
  17950. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17951. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17952. * successful poll, and POLLIN is defined as
  17953. * (POLLRDNORM | POLLRDBAND)
  17954. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17955. * pfd[i].revents == POLLIN. */
  17956. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17957. && (pfd[i].revents & POLLIN)) {
  17958. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17959. }
  17960. }
  17961. }
  17962. }
  17963. /* Here stop_flag is 1 - Initiate shutdown. */
  17964. DEBUG_TRACE("%s", "stopping workers");
  17965. /* Stop signal received: somebody called mg_stop. Quit. */
  17966. close_all_listening_sockets(ctx);
  17967. /* Wakeup workers that are waiting for connections to handle. */
  17968. #if defined(ALTERNATIVE_QUEUE)
  17969. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17970. event_signal(ctx->client_wait_events[i]);
  17971. }
  17972. #else
  17973. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17974. pthread_cond_broadcast(&ctx->sq_full);
  17975. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17976. #endif
  17977. /* Join all worker threads to avoid leaking threads. */
  17978. workerthreadcount = ctx->spawned_worker_threads;
  17979. for (i = 0; i < workerthreadcount; i++) {
  17980. if (ctx->worker_threadids[i] != 0) {
  17981. mg_join_thread(ctx->worker_threadids[i]);
  17982. }
  17983. }
  17984. #if defined(USE_LUA)
  17985. /* Free Lua state of lua background task */
  17986. if (ctx->lua_background_state) {
  17987. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17988. ctx->lua_bg_log_available = 0;
  17989. /* call "stop()" in Lua */
  17990. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17991. lua_getglobal(lstate, "stop");
  17992. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17993. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17994. if (ret != 0) {
  17995. struct mg_connection fc;
  17996. lua_cry(fake_connection(&fc, ctx),
  17997. ret,
  17998. lstate,
  17999. "lua_background_script",
  18000. "stop");
  18001. }
  18002. }
  18003. DEBUG_TRACE("Close Lua background state %p", lstate);
  18004. lua_close(lstate);
  18005. ctx->lua_background_state = 0;
  18006. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18007. }
  18008. #endif
  18009. DEBUG_TRACE("%s", "exiting");
  18010. /* call exit thread callback */
  18011. if (ctx->callbacks.exit_thread) {
  18012. /* Callback for the master thread (type 0) */
  18013. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  18014. }
  18015. #if defined(_WIN32)
  18016. CloseHandle(tls.pthread_cond_helper_mutex);
  18017. #endif
  18018. pthread_setspecific(sTlsKey, NULL);
  18019. /* Signal mg_stop() that we're done.
  18020. * WARNING: This must be the very last thing this
  18021. * thread does, as ctx becomes invalid after this line. */
  18022. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  18023. }
  18024. /* Threads have different return types on Windows and Unix. */
  18025. #if defined(_WIN32)
  18026. static unsigned __stdcall master_thread(void *thread_func_param)
  18027. {
  18028. master_thread_run((struct mg_context *)thread_func_param);
  18029. return 0;
  18030. }
  18031. #else
  18032. static void *
  18033. master_thread(void *thread_func_param)
  18034. {
  18035. #if !defined(__ZEPHYR__)
  18036. struct sigaction sa;
  18037. /* Ignore SIGPIPE */
  18038. memset(&sa, 0, sizeof(sa));
  18039. sa.sa_handler = SIG_IGN;
  18040. sigaction(SIGPIPE, &sa, NULL);
  18041. #endif
  18042. master_thread_run((struct mg_context *)thread_func_param);
  18043. return NULL;
  18044. }
  18045. #endif /* _WIN32 */
  18046. static void
  18047. free_context(struct mg_context *ctx)
  18048. {
  18049. int i;
  18050. struct mg_handler_info *tmp_rh;
  18051. if (ctx == NULL) {
  18052. return;
  18053. }
  18054. /* Call user callback */
  18055. if (ctx->callbacks.exit_context) {
  18056. ctx->callbacks.exit_context(ctx);
  18057. }
  18058. /* All threads exited, no sync is needed. Destroy thread mutex and
  18059. * condvars
  18060. */
  18061. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  18062. #if defined(ALTERNATIVE_QUEUE)
  18063. mg_free(ctx->client_socks);
  18064. if (ctx->client_wait_events != NULL) {
  18065. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  18066. event_destroy(ctx->client_wait_events[i]);
  18067. }
  18068. mg_free(ctx->client_wait_events);
  18069. }
  18070. #else
  18071. (void)pthread_cond_destroy(&ctx->sq_empty);
  18072. (void)pthread_cond_destroy(&ctx->sq_full);
  18073. mg_free(ctx->squeue);
  18074. #endif
  18075. /* Destroy other context global data structures mutex */
  18076. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  18077. #if defined(USE_LUA)
  18078. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  18079. #endif
  18080. /* Deallocate shutdown-triggering socket-pair */
  18081. if (ctx->user_shutdown_notification_socket >= 0) {
  18082. closesocket(ctx->user_shutdown_notification_socket);
  18083. }
  18084. if (ctx->thread_shutdown_notification_socket >= 0) {
  18085. closesocket(ctx->thread_shutdown_notification_socket);
  18086. }
  18087. /* Deallocate config parameters */
  18088. for (i = 0; i < NUM_OPTIONS; i++) {
  18089. if (ctx->dd.config[i] != NULL) {
  18090. #if defined(_MSC_VER)
  18091. #pragma warning(suppress : 6001)
  18092. #endif
  18093. mg_free(ctx->dd.config[i]);
  18094. }
  18095. }
  18096. /* Deallocate request handlers */
  18097. while (ctx->dd.handlers) {
  18098. tmp_rh = ctx->dd.handlers;
  18099. ctx->dd.handlers = tmp_rh->next;
  18100. mg_free(tmp_rh->uri);
  18101. mg_free(tmp_rh);
  18102. }
  18103. #if defined(USE_MBEDTLS)
  18104. if (ctx->dd.ssl_ctx != NULL) {
  18105. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  18106. mg_free(ctx->dd.ssl_ctx);
  18107. ctx->dd.ssl_ctx = NULL;
  18108. }
  18109. #elif defined(USE_GNUTLS)
  18110. if (ctx->dd.ssl_ctx != NULL) {
  18111. gtls_sslctx_uninit(ctx->dd.ssl_ctx);
  18112. mg_free(ctx->dd.ssl_ctx);
  18113. ctx->dd.ssl_ctx = NULL;
  18114. }
  18115. #elif !defined(NO_SSL)
  18116. /* Deallocate SSL context */
  18117. if (ctx->dd.ssl_ctx != NULL) {
  18118. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  18119. int callback_ret =
  18120. (ctx->callbacks.external_ssl_ctx == NULL)
  18121. ? 0
  18122. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  18123. if (callback_ret == 0) {
  18124. SSL_CTX_free(ctx->dd.ssl_ctx);
  18125. }
  18126. /* else: ignore error and omit SSL_CTX_free in case
  18127. * callback_ret is 1 */
  18128. }
  18129. #endif /* !NO_SSL */
  18130. /* Deallocate worker thread ID array */
  18131. mg_free(ctx->worker_threadids);
  18132. /* Deallocate worker thread ID array */
  18133. mg_free(ctx->worker_connections);
  18134. /* deallocate system name string */
  18135. mg_free(ctx->systemName);
  18136. /* Deallocate context itself */
  18137. mg_free(ctx);
  18138. }
  18139. CIVETWEB_API void
  18140. mg_stop(struct mg_context *ctx)
  18141. {
  18142. pthread_t mt;
  18143. if (!ctx) {
  18144. return;
  18145. }
  18146. /* We don't use a lock here. Calling mg_stop with the same ctx from
  18147. * two threads is not allowed. */
  18148. mt = ctx->masterthreadid;
  18149. if (mt == 0) {
  18150. return;
  18151. }
  18152. ctx->masterthreadid = 0;
  18153. /* Set stop flag, so all threads know they have to exit. */
  18154. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  18155. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  18156. * immediately */
  18157. closesocket(ctx->user_shutdown_notification_socket);
  18158. ctx->user_shutdown_notification_socket =
  18159. -1; /* to avoid calling closesocket() again in free_context() */
  18160. /* Join timer thread */
  18161. #if defined(USE_TIMERS)
  18162. timers_exit(ctx);
  18163. #endif
  18164. /* Wait until everything has stopped. */
  18165. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  18166. (void)mg_sleep(10);
  18167. }
  18168. /* Wait to stop master thread */
  18169. mg_join_thread(mt);
  18170. /* Close remaining Lua states */
  18171. #if defined(USE_LUA)
  18172. lua_ctx_exit(ctx);
  18173. #endif
  18174. /* Free memory */
  18175. free_context(ctx);
  18176. }
  18177. static void
  18178. get_system_name(char **sysName)
  18179. {
  18180. #if defined(_WIN32)
  18181. char name[128];
  18182. DWORD dwVersion = 0;
  18183. DWORD dwMajorVersion = 0;
  18184. DWORD dwMinorVersion = 0;
  18185. DWORD dwBuild = 0;
  18186. BOOL wowRet, isWoW = FALSE;
  18187. #if defined(_MSC_VER)
  18188. #pragma warning(push)
  18189. /* GetVersion was declared deprecated */
  18190. #pragma warning(disable : 4996)
  18191. #endif
  18192. dwVersion = GetVersion();
  18193. #if defined(_MSC_VER)
  18194. #pragma warning(pop)
  18195. #endif
  18196. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18197. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18198. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  18199. (void)dwBuild;
  18200. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  18201. sprintf(name,
  18202. "Windows %u.%u%s",
  18203. (unsigned)dwMajorVersion,
  18204. (unsigned)dwMinorVersion,
  18205. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  18206. *sysName = mg_strdup(name);
  18207. #elif defined(__rtems__)
  18208. *sysName = mg_strdup("RTEMS");
  18209. #elif defined(__ZEPHYR__)
  18210. *sysName = mg_strdup("Zephyr OS");
  18211. #else
  18212. struct utsname name;
  18213. memset(&name, 0, sizeof(name));
  18214. uname(&name);
  18215. *sysName = mg_strdup(name.sysname);
  18216. #endif
  18217. }
  18218. static void
  18219. legacy_init(const char **options)
  18220. {
  18221. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  18222. if (options) {
  18223. const char **run_options = options;
  18224. const char *optname = config_options[LISTENING_PORTS].name;
  18225. /* Try to find the "listening_ports" option */
  18226. while (*run_options) {
  18227. if (!strcmp(*run_options, optname)) {
  18228. ports_option = run_options[1];
  18229. }
  18230. run_options += 2;
  18231. }
  18232. }
  18233. if (is_ssl_port_used(ports_option)) {
  18234. /* Initialize with SSL support */
  18235. mg_init_library(MG_FEATURES_TLS);
  18236. } else {
  18237. /* Initialize without SSL support */
  18238. mg_init_library(MG_FEATURES_DEFAULT);
  18239. }
  18240. }
  18241. /* we'll assume it's only Windows that doesn't have socketpair() available */
  18242. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  18243. #define HAVE_SOCKETPAIR 1
  18244. #endif
  18245. static int
  18246. mg_socketpair(int *sockA, int *sockB)
  18247. {
  18248. int temp[2] = {-1, -1};
  18249. int asock = -1;
  18250. /** Default to unallocated */
  18251. *sockA = -1;
  18252. *sockB = -1;
  18253. #if defined(HAVE_SOCKETPAIR)
  18254. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  18255. if (ret == 0) {
  18256. *sockA = temp[0];
  18257. *sockB = temp[1];
  18258. set_close_on_exec(*sockA, NULL, NULL);
  18259. set_close_on_exec(*sockB, NULL, NULL);
  18260. }
  18261. (void)asock; /* not used */
  18262. return ret;
  18263. #else
  18264. /** No socketpair() call is available, so we'll have to roll our own
  18265. * implementation */
  18266. asock = socket(PF_INET, SOCK_STREAM, 0);
  18267. if (asock >= 0) {
  18268. struct sockaddr_in addr;
  18269. struct sockaddr *pa = (struct sockaddr *)&addr;
  18270. socklen_t addrLen = sizeof(addr);
  18271. memset(&addr, 0, sizeof(addr));
  18272. addr.sin_family = AF_INET;
  18273. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18274. addr.sin_port = 0;
  18275. if ((bind(asock, pa, sizeof(addr)) == 0)
  18276. && (getsockname(asock, pa, &addrLen) == 0)
  18277. && (listen(asock, 1) == 0)) {
  18278. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18279. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18280. temp[1] = accept(asock, pa, &addrLen);
  18281. if (temp[1] >= 0) {
  18282. closesocket(asock);
  18283. *sockA = temp[0];
  18284. *sockB = temp[1];
  18285. set_close_on_exec(*sockA, NULL, NULL);
  18286. set_close_on_exec(*sockB, NULL, NULL);
  18287. return 0; /* success! */
  18288. }
  18289. }
  18290. }
  18291. }
  18292. /* Cleanup */
  18293. if (asock >= 0)
  18294. closesocket(asock);
  18295. if (temp[0] >= 0)
  18296. closesocket(temp[0]);
  18297. if (temp[1] >= 0)
  18298. closesocket(temp[1]);
  18299. return -1; /* fail! */
  18300. #endif
  18301. }
  18302. static int
  18303. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18304. {
  18305. const unsigned int i = ctx->spawned_worker_threads;
  18306. if (i >= ctx->cfg_max_worker_threads) {
  18307. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18308. threads, ever! */
  18309. }
  18310. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18311. #if defined(ALTERNATIVE_QUEUE)
  18312. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18313. #else
  18314. if ((only_if_no_idle_threads)
  18315. && (ctx->idle_worker_thread_count
  18316. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18317. #endif
  18318. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18319. return -2; /* There are idle threads available, so no need to spawn a
  18320. new worker thread now */
  18321. }
  18322. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18323. condition while the thread is starting
  18324. up */
  18325. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18326. ctx->worker_connections[i].phys_ctx = ctx;
  18327. int ret = mg_start_thread_with_id(worker_thread,
  18328. &ctx->worker_connections[i],
  18329. &ctx->worker_threadids[i]);
  18330. if (ret == 0) {
  18331. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18332. the table */
  18333. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18334. } else {
  18335. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18336. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18337. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18338. }
  18339. return ret;
  18340. }
  18341. CIVETWEB_API struct mg_context *
  18342. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18343. {
  18344. struct mg_context *ctx;
  18345. const char *name, *value, *default_value;
  18346. int idx, ok, prespawnthreadcount, workerthreadcount;
  18347. unsigned int i;
  18348. int itmp;
  18349. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18350. const char **options =
  18351. ((init != NULL) ? (init->configuration_options) : (NULL));
  18352. struct mg_workerTLS tls;
  18353. if (error != NULL) {
  18354. error->code = MG_ERROR_DATA_CODE_OK;
  18355. error->code_sub = 0;
  18356. if (error->text_buffer_size > 0) {
  18357. *error->text = 0;
  18358. }
  18359. }
  18360. if (mg_init_library_called == 0) {
  18361. /* Legacy INIT, if mg_start is called without mg_init_library.
  18362. * Note: This will cause a memory leak when unloading the library.
  18363. */
  18364. legacy_init(options);
  18365. }
  18366. if (mg_init_library_called == 0) {
  18367. if (error != NULL) {
  18368. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18369. mg_snprintf(NULL,
  18370. NULL, /* No truncation check for error buffers */
  18371. error->text,
  18372. error->text_buffer_size,
  18373. "%s",
  18374. "Library uninitialized");
  18375. }
  18376. return NULL;
  18377. }
  18378. /* Allocate context and initialize reasonable general case defaults. */
  18379. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18380. if (ctx == NULL) {
  18381. if (error != NULL) {
  18382. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18383. error->code_sub = (unsigned)sizeof(*ctx);
  18384. mg_snprintf(NULL,
  18385. NULL, /* No truncation check for error buffers */
  18386. error->text,
  18387. error->text_buffer_size,
  18388. "%s",
  18389. "Out of memory");
  18390. }
  18391. return NULL;
  18392. }
  18393. /* Random number generator will initialize at the first call */
  18394. ctx->dd.auth_nonce_mask =
  18395. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18396. /* Save started thread index to reuse in other external API calls
  18397. * For the sake of thread synchronization all non-civetweb threads
  18398. * can be considered as single external thread */
  18399. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18400. tls.is_master = -1; /* Thread calling mg_start */
  18401. tls.thread_idx = ctx->starter_thread_idx;
  18402. #if defined(_WIN32)
  18403. tls.pthread_cond_helper_mutex = NULL;
  18404. #endif
  18405. pthread_setspecific(sTlsKey, &tls);
  18406. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18407. #if !defined(ALTERNATIVE_QUEUE)
  18408. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18409. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18410. ctx->sq_blocked = 0;
  18411. #endif
  18412. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18413. #if defined(USE_LUA)
  18414. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18415. #endif
  18416. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18417. * will cause poll() to return immediately in the master-thread, so that
  18418. * mg_stop() can also return immediately.
  18419. */
  18420. ok &= (0
  18421. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18422. &ctx->thread_shutdown_notification_socket));
  18423. if (!ok) {
  18424. unsigned error_id = (unsigned)ERRNO;
  18425. const char *err_msg =
  18426. "Cannot initialize thread synchronization objects";
  18427. /* Fatal error - abort start. However, this situation should never
  18428. * occur in practice. */
  18429. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18430. if (error != NULL) {
  18431. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18432. error->code_sub = error_id;
  18433. mg_snprintf(NULL,
  18434. NULL, /* No truncation check for error buffers */
  18435. error->text,
  18436. error->text_buffer_size,
  18437. "%s",
  18438. err_msg);
  18439. }
  18440. mg_free(ctx);
  18441. pthread_setspecific(sTlsKey, NULL);
  18442. return NULL;
  18443. }
  18444. if ((init != NULL) && (init->callbacks != NULL)) {
  18445. /* Set all callbacks except exit_context. */
  18446. ctx->callbacks = *init->callbacks;
  18447. exit_callback = init->callbacks->exit_context;
  18448. /* The exit callback is activated once the context is successfully
  18449. * created. It should not be called, if an incomplete context object
  18450. * is deleted during a failed initialization. */
  18451. ctx->callbacks.exit_context = 0;
  18452. }
  18453. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18454. ctx->dd.handlers = NULL;
  18455. ctx->dd.next = NULL;
  18456. #if defined(USE_LUA)
  18457. lua_ctx_init(ctx);
  18458. #endif
  18459. /* Store options */
  18460. while (options && (name = *options++) != NULL) {
  18461. idx = get_option_index(name);
  18462. if (idx == -1) {
  18463. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18464. if (error != NULL) {
  18465. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18466. error->code_sub = (unsigned)-1;
  18467. mg_snprintf(NULL,
  18468. NULL, /* No truncation check for error buffers */
  18469. error->text,
  18470. error->text_buffer_size,
  18471. "Invalid configuration option: %s",
  18472. name);
  18473. }
  18474. free_context(ctx);
  18475. pthread_setspecific(sTlsKey, NULL);
  18476. return NULL;
  18477. } else if ((value = *options++) == NULL) {
  18478. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18479. if (error != NULL) {
  18480. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18481. error->code_sub = (unsigned)idx;
  18482. mg_snprintf(NULL,
  18483. NULL, /* No truncation check for error buffers */
  18484. error->text,
  18485. error->text_buffer_size,
  18486. "Invalid configuration option value: %s",
  18487. name);
  18488. }
  18489. free_context(ctx);
  18490. pthread_setspecific(sTlsKey, NULL);
  18491. return NULL;
  18492. }
  18493. if (ctx->dd.config[idx] != NULL) {
  18494. /* A duplicate configuration option is not an error - the last
  18495. * option value will be used. */
  18496. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18497. mg_free(ctx->dd.config[idx]);
  18498. }
  18499. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18500. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18501. }
  18502. /* Set default value if needed */
  18503. for (i = 0; config_options[i].name != NULL; i++) {
  18504. default_value = config_options[i].default_value;
  18505. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18506. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18507. }
  18508. }
  18509. /* Request size option */
  18510. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18511. if (itmp < 1024) {
  18512. mg_cry_ctx_internal(ctx,
  18513. "%s too small",
  18514. config_options[MAX_REQUEST_SIZE].name);
  18515. if (error != NULL) {
  18516. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18517. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18518. mg_snprintf(NULL,
  18519. NULL, /* No truncation check for error buffers */
  18520. error->text,
  18521. error->text_buffer_size,
  18522. "Invalid configuration option value: %s",
  18523. config_options[MAX_REQUEST_SIZE].name);
  18524. }
  18525. free_context(ctx);
  18526. pthread_setspecific(sTlsKey, NULL);
  18527. return NULL;
  18528. }
  18529. ctx->max_request_size = (unsigned)itmp;
  18530. /* Queue length */
  18531. #if !defined(ALTERNATIVE_QUEUE)
  18532. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18533. if (itmp < 1) {
  18534. mg_cry_ctx_internal(ctx,
  18535. "%s too small",
  18536. config_options[CONNECTION_QUEUE_SIZE].name);
  18537. if (error != NULL) {
  18538. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18539. error->code_sub = CONNECTION_QUEUE_SIZE;
  18540. mg_snprintf(NULL,
  18541. NULL, /* No truncation check for error buffers */
  18542. error->text,
  18543. error->text_buffer_size,
  18544. "Invalid configuration option value: %s",
  18545. config_options[CONNECTION_QUEUE_SIZE].name);
  18546. }
  18547. free_context(ctx);
  18548. pthread_setspecific(sTlsKey, NULL);
  18549. return NULL;
  18550. }
  18551. ctx->squeue =
  18552. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18553. if (ctx->squeue == NULL) {
  18554. mg_cry_ctx_internal(ctx,
  18555. "Out of memory: Cannot allocate %s",
  18556. config_options[CONNECTION_QUEUE_SIZE].name);
  18557. if (error != NULL) {
  18558. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18559. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18560. mg_snprintf(NULL,
  18561. NULL, /* No truncation check for error buffers */
  18562. error->text,
  18563. error->text_buffer_size,
  18564. "Out of memory: Cannot allocate %s",
  18565. config_options[CONNECTION_QUEUE_SIZE].name);
  18566. }
  18567. free_context(ctx);
  18568. pthread_setspecific(sTlsKey, NULL);
  18569. return NULL;
  18570. }
  18571. ctx->sq_size = itmp;
  18572. #endif
  18573. /* Worker thread count option */
  18574. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18575. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18576. if ((prespawnthreadcount < 0)
  18577. || (prespawnthreadcount > workerthreadcount)) {
  18578. prespawnthreadcount =
  18579. workerthreadcount; /* can't prespawn more than all of them! */
  18580. }
  18581. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18582. if (workerthreadcount <= 0) {
  18583. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18584. } else {
  18585. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18586. }
  18587. if (error != NULL) {
  18588. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18589. error->code_sub = NUM_THREADS;
  18590. mg_snprintf(NULL,
  18591. NULL, /* No truncation check for error buffers */
  18592. error->text,
  18593. error->text_buffer_size,
  18594. "Invalid configuration option value: %s",
  18595. config_options[NUM_THREADS].name);
  18596. }
  18597. free_context(ctx);
  18598. pthread_setspecific(sTlsKey, NULL);
  18599. return NULL;
  18600. }
  18601. /* Document root */
  18602. #if defined(NO_FILES)
  18603. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18604. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18605. if (error != NULL) {
  18606. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18607. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18608. mg_snprintf(NULL,
  18609. NULL, /* No truncation check for error buffers */
  18610. error->text,
  18611. error->text_buffer_size,
  18612. "Invalid configuration option value: %s",
  18613. config_options[DOCUMENT_ROOT].name);
  18614. }
  18615. free_context(ctx);
  18616. pthread_setspecific(sTlsKey, NULL);
  18617. return NULL;
  18618. }
  18619. #endif
  18620. get_system_name(&ctx->systemName);
  18621. #if defined(USE_LUA)
  18622. /* If a Lua background script has been configured, start it. */
  18623. ctx->lua_bg_log_available = 0;
  18624. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18625. char ebuf[256];
  18626. struct vec opt_vec;
  18627. struct vec eq_vec;
  18628. const char *sparams;
  18629. memset(ebuf, 0, sizeof(ebuf));
  18630. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18631. /* Create a Lua state, load all standard libraries and the mg table */
  18632. lua_State *state = mg_lua_context_script_prepare(
  18633. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18634. if (!state) {
  18635. mg_cry_ctx_internal(ctx,
  18636. "lua_background_script load error: %s",
  18637. ebuf);
  18638. if (error != NULL) {
  18639. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18640. mg_snprintf(NULL,
  18641. NULL, /* No truncation check for error buffers */
  18642. error->text,
  18643. error->text_buffer_size,
  18644. "Error in script %s: %s",
  18645. config_options[LUA_BACKGROUND_SCRIPT].name,
  18646. ebuf);
  18647. }
  18648. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18649. free_context(ctx);
  18650. pthread_setspecific(sTlsKey, NULL);
  18651. return NULL;
  18652. }
  18653. /* Add a table with parameters into mg.params */
  18654. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18655. if (sparams && sparams[0]) {
  18656. lua_getglobal(state, "mg");
  18657. lua_pushstring(state, "params");
  18658. lua_newtable(state);
  18659. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18660. != NULL) {
  18661. reg_llstring(
  18662. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18663. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18664. break;
  18665. }
  18666. lua_rawset(state, -3);
  18667. lua_pop(state, 1);
  18668. }
  18669. /* Call script */
  18670. state = mg_lua_context_script_run(state,
  18671. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18672. ctx,
  18673. ebuf,
  18674. sizeof(ebuf));
  18675. if (!state) {
  18676. mg_cry_ctx_internal(ctx,
  18677. "lua_background_script start error: %s",
  18678. ebuf);
  18679. if (error != NULL) {
  18680. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18681. mg_snprintf(NULL,
  18682. NULL, /* No truncation check for error buffers */
  18683. error->text,
  18684. error->text_buffer_size,
  18685. "Error in script %s: %s",
  18686. config_options[DOCUMENT_ROOT].name,
  18687. ebuf);
  18688. }
  18689. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18690. free_context(ctx);
  18691. pthread_setspecific(sTlsKey, NULL);
  18692. return NULL;
  18693. }
  18694. /* state remains valid */
  18695. ctx->lua_background_state = (void *)state;
  18696. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18697. } else {
  18698. ctx->lua_background_state = 0;
  18699. }
  18700. #endif
  18701. /* Step by step initialization of ctx - depending on build options */
  18702. #if !defined(NO_FILESYSTEMS)
  18703. if (!set_gpass_option(ctx, NULL)) {
  18704. const char *err_msg = "Invalid global password file";
  18705. /* Fatal error - abort start. */
  18706. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18707. if (error != NULL) {
  18708. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18709. mg_snprintf(NULL,
  18710. NULL, /* No truncation check for error buffers */
  18711. error->text,
  18712. error->text_buffer_size,
  18713. "%s",
  18714. err_msg);
  18715. }
  18716. free_context(ctx);
  18717. pthread_setspecific(sTlsKey, NULL);
  18718. return NULL;
  18719. }
  18720. #endif
  18721. #if defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  18722. if (!mg_sslctx_init(ctx, NULL)) {
  18723. const char *err_msg = "Error initializing SSL context";
  18724. /* Fatal error - abort start. */
  18725. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18726. if (error != NULL) {
  18727. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18728. mg_snprintf(NULL,
  18729. NULL, /* No truncation check for error buffers */
  18730. error->text,
  18731. error->text_buffer_size,
  18732. "%s",
  18733. err_msg);
  18734. }
  18735. free_context(ctx);
  18736. pthread_setspecific(sTlsKey, NULL);
  18737. return NULL;
  18738. }
  18739. #elif !defined(NO_SSL)
  18740. if (!init_ssl_ctx(ctx, NULL)) {
  18741. const char *err_msg = "Error initializing SSL context";
  18742. /* Fatal error - abort start. */
  18743. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18744. if (error != NULL) {
  18745. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18746. mg_snprintf(NULL,
  18747. NULL, /* No truncation check for error buffers */
  18748. error->text,
  18749. error->text_buffer_size,
  18750. "%s",
  18751. err_msg);
  18752. }
  18753. free_context(ctx);
  18754. pthread_setspecific(sTlsKey, NULL);
  18755. return NULL;
  18756. }
  18757. #endif
  18758. if (!set_ports_option(ctx)) {
  18759. const char *err_msg = "Failed to setup server ports";
  18760. /* Fatal error - abort start. */
  18761. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18762. if (error != NULL) {
  18763. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18764. mg_snprintf(NULL,
  18765. NULL, /* No truncation check for error buffers */
  18766. error->text,
  18767. error->text_buffer_size,
  18768. "%s",
  18769. err_msg);
  18770. }
  18771. free_context(ctx);
  18772. pthread_setspecific(sTlsKey, NULL);
  18773. return NULL;
  18774. }
  18775. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18776. if (!set_uid_option(ctx)) {
  18777. const char *err_msg = "Failed to run as configured user";
  18778. /* Fatal error - abort start. */
  18779. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18780. if (error != NULL) {
  18781. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18782. mg_snprintf(NULL,
  18783. NULL, /* No truncation check for error buffers */
  18784. error->text,
  18785. error->text_buffer_size,
  18786. "%s",
  18787. err_msg);
  18788. }
  18789. free_context(ctx);
  18790. pthread_setspecific(sTlsKey, NULL);
  18791. return NULL;
  18792. }
  18793. #endif
  18794. if (!set_acl_option(ctx)) {
  18795. const char *err_msg = "Failed to setup access control list";
  18796. /* Fatal error - abort start. */
  18797. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18798. if (error != NULL) {
  18799. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18800. mg_snprintf(NULL,
  18801. NULL, /* No truncation check for error buffers */
  18802. error->text,
  18803. error->text_buffer_size,
  18804. "%s",
  18805. err_msg);
  18806. }
  18807. free_context(ctx);
  18808. pthread_setspecific(sTlsKey, NULL);
  18809. return NULL;
  18810. }
  18811. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18812. ctx->worker_threadids =
  18813. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18814. sizeof(pthread_t),
  18815. ctx);
  18816. if (ctx->worker_threadids == NULL) {
  18817. const char *err_msg = "Not enough memory for worker thread ID array";
  18818. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18819. if (error != NULL) {
  18820. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18821. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18822. * (unsigned)sizeof(pthread_t);
  18823. mg_snprintf(NULL,
  18824. NULL, /* No truncation check for error buffers */
  18825. error->text,
  18826. error->text_buffer_size,
  18827. "%s",
  18828. err_msg);
  18829. }
  18830. free_context(ctx);
  18831. pthread_setspecific(sTlsKey, NULL);
  18832. return NULL;
  18833. }
  18834. ctx->worker_connections =
  18835. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18836. sizeof(struct mg_connection),
  18837. ctx);
  18838. if (ctx->worker_connections == NULL) {
  18839. const char *err_msg =
  18840. "Not enough memory for worker thread connection array";
  18841. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18842. if (error != NULL) {
  18843. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18844. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18845. * (unsigned)sizeof(struct mg_connection);
  18846. mg_snprintf(NULL,
  18847. NULL, /* No truncation check for error buffers */
  18848. error->text,
  18849. error->text_buffer_size,
  18850. "%s",
  18851. err_msg);
  18852. }
  18853. free_context(ctx);
  18854. pthread_setspecific(sTlsKey, NULL);
  18855. return NULL;
  18856. }
  18857. #if defined(ALTERNATIVE_QUEUE)
  18858. ctx->client_wait_events =
  18859. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18860. sizeof(ctx->client_wait_events[0]),
  18861. ctx);
  18862. if (ctx->client_wait_events == NULL) {
  18863. const char *err_msg = "Not enough memory for worker event array";
  18864. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18865. mg_free(ctx->worker_threadids);
  18866. if (error != NULL) {
  18867. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18868. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18869. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18870. mg_snprintf(NULL,
  18871. NULL, /* No truncation check for error buffers */
  18872. error->text,
  18873. error->text_buffer_size,
  18874. "%s",
  18875. err_msg);
  18876. }
  18877. free_context(ctx);
  18878. pthread_setspecific(sTlsKey, NULL);
  18879. return NULL;
  18880. }
  18881. ctx->client_socks =
  18882. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18883. sizeof(ctx->client_socks[0]),
  18884. ctx);
  18885. if (ctx->client_socks == NULL) {
  18886. const char *err_msg = "Not enough memory for worker socket array";
  18887. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18888. mg_free(ctx->client_wait_events);
  18889. mg_free(ctx->worker_threadids);
  18890. if (error != NULL) {
  18891. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18892. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18893. * (unsigned)sizeof(ctx->client_socks[0]);
  18894. mg_snprintf(NULL,
  18895. NULL, /* No truncation check for error buffers */
  18896. error->text,
  18897. error->text_buffer_size,
  18898. "%s",
  18899. err_msg);
  18900. }
  18901. free_context(ctx);
  18902. pthread_setspecific(sTlsKey, NULL);
  18903. return NULL;
  18904. }
  18905. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18906. ctx->client_wait_events[i] = event_create();
  18907. if (ctx->client_wait_events[i] == 0) {
  18908. const char *err_msg = "Error creating worker event %i";
  18909. mg_cry_ctx_internal(ctx, err_msg, i);
  18910. while (i > 0) {
  18911. i--;
  18912. event_destroy(ctx->client_wait_events[i]);
  18913. }
  18914. mg_free(ctx->client_socks);
  18915. mg_free(ctx->client_wait_events);
  18916. mg_free(ctx->worker_threadids);
  18917. if (error != NULL) {
  18918. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18919. error->code_sub = (unsigned)ERRNO;
  18920. mg_snprintf(NULL,
  18921. NULL, /* No truncation check for error buffers */
  18922. error->text,
  18923. error->text_buffer_size,
  18924. err_msg,
  18925. i);
  18926. }
  18927. free_context(ctx);
  18928. pthread_setspecific(sTlsKey, NULL);
  18929. return NULL;
  18930. }
  18931. }
  18932. #endif
  18933. #if defined(USE_TIMERS)
  18934. if (timers_init(ctx) != 0) {
  18935. const char *err_msg = "Error creating timers";
  18936. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18937. if (error != NULL) {
  18938. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18939. error->code_sub = (unsigned)ERRNO;
  18940. mg_snprintf(NULL,
  18941. NULL, /* No truncation check for error buffers */
  18942. error->text,
  18943. error->text_buffer_size,
  18944. "%s",
  18945. err_msg);
  18946. }
  18947. free_context(ctx);
  18948. pthread_setspecific(sTlsKey, NULL);
  18949. return NULL;
  18950. }
  18951. #endif
  18952. /* Context has been created - init user libraries */
  18953. if (ctx->callbacks.init_context) {
  18954. ctx->callbacks.init_context(ctx);
  18955. }
  18956. /* From now, the context is successfully created.
  18957. * When it is destroyed, the exit callback should be called. */
  18958. ctx->callbacks.exit_context = exit_callback;
  18959. ctx->context_type = CONTEXT_SERVER; /* server context */
  18960. /* Start worker threads */
  18961. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18962. /* worker_thread sets up the other fields */
  18963. if (mg_start_worker_thread(ctx, 0) != 0) {
  18964. long error_no = (long)ERRNO;
  18965. /* thread was not created */
  18966. if (ctx->spawned_worker_threads > 0) {
  18967. /* If the second, third, ... thread cannot be created, set a
  18968. * warning, but keep running. */
  18969. mg_cry_ctx_internal(ctx,
  18970. "Cannot start worker thread %i: error %ld",
  18971. ctx->spawned_worker_threads + 1,
  18972. error_no);
  18973. /* If the server initialization should stop here, all
  18974. * threads that have already been created must be stopped
  18975. * first, before any free_context(ctx) call.
  18976. */
  18977. } else {
  18978. /* If the first worker thread cannot be created, stop
  18979. * initialization and free the entire server context. */
  18980. mg_cry_ctx_internal(ctx,
  18981. "Cannot create threads: error %ld",
  18982. error_no);
  18983. if (error != NULL) {
  18984. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18985. error->code_sub = (unsigned)error_no;
  18986. mg_snprintf(
  18987. NULL,
  18988. NULL, /* No truncation check for error buffers */
  18989. error->text,
  18990. error->text_buffer_size,
  18991. "Cannot create first worker thread: error %ld",
  18992. error_no);
  18993. }
  18994. free_context(ctx);
  18995. pthread_setspecific(sTlsKey, NULL);
  18996. return NULL;
  18997. }
  18998. break;
  18999. }
  19000. }
  19001. /* Start master (listening) thread */
  19002. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  19003. pthread_setspecific(sTlsKey, NULL);
  19004. return ctx;
  19005. }
  19006. CIVETWEB_API struct mg_context *
  19007. mg_start(const struct mg_callbacks *callbacks,
  19008. void *user_data,
  19009. const char **options)
  19010. {
  19011. struct mg_init_data init = {0};
  19012. init.callbacks = callbacks;
  19013. init.user_data = user_data;
  19014. init.configuration_options = options;
  19015. return mg_start2(&init, NULL);
  19016. }
  19017. /* Add an additional domain to an already running web server. */
  19018. CIVETWEB_API int
  19019. mg_start_domain2(struct mg_context *ctx,
  19020. const char **options,
  19021. struct mg_error_data *error)
  19022. {
  19023. const char *name;
  19024. const char *value;
  19025. const char *default_value;
  19026. struct mg_domain_context *new_dom;
  19027. struct mg_domain_context *dom;
  19028. int idx, i;
  19029. if (error != NULL) {
  19030. error->code = MG_ERROR_DATA_CODE_OK;
  19031. error->code_sub = 0;
  19032. if (error->text_buffer_size > 0) {
  19033. *error->text = 0;
  19034. }
  19035. }
  19036. if ((ctx == NULL) || (options == NULL)) {
  19037. if (error != NULL) {
  19038. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  19039. mg_snprintf(NULL,
  19040. NULL, /* No truncation check for error buffers */
  19041. error->text,
  19042. error->text_buffer_size,
  19043. "%s",
  19044. "Invalid parameters");
  19045. }
  19046. return -1;
  19047. }
  19048. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  19049. if (error != NULL) {
  19050. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  19051. mg_snprintf(NULL,
  19052. NULL, /* No truncation check for error buffers */
  19053. error->text,
  19054. error->text_buffer_size,
  19055. "%s",
  19056. "Server already stopped");
  19057. }
  19058. return -7;
  19059. }
  19060. new_dom = (struct mg_domain_context *)
  19061. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  19062. if (!new_dom) {
  19063. /* Out of memory */
  19064. if (error != NULL) {
  19065. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  19066. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  19067. mg_snprintf(NULL,
  19068. NULL, /* No truncation check for error buffers */
  19069. error->text,
  19070. error->text_buffer_size,
  19071. "%s",
  19072. "Out or memory");
  19073. }
  19074. return -6;
  19075. }
  19076. /* Store options - TODO: unite duplicate code */
  19077. while (options && (name = *options++) != NULL) {
  19078. idx = get_option_index(name);
  19079. if (idx == -1) {
  19080. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  19081. if (error != NULL) {
  19082. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19083. error->code_sub = (unsigned)-1;
  19084. mg_snprintf(NULL,
  19085. NULL, /* No truncation check for error buffers */
  19086. error->text,
  19087. error->text_buffer_size,
  19088. "Invalid option: %s",
  19089. name);
  19090. }
  19091. mg_free(new_dom);
  19092. return -2;
  19093. } else if ((value = *options++) == NULL) {
  19094. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  19095. if (error != NULL) {
  19096. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  19097. error->code_sub = (unsigned)idx;
  19098. mg_snprintf(NULL,
  19099. NULL, /* No truncation check for error buffers */
  19100. error->text,
  19101. error->text_buffer_size,
  19102. "Invalid option value: %s",
  19103. name);
  19104. }
  19105. mg_free(new_dom);
  19106. return -2;
  19107. }
  19108. if (new_dom->config[idx] != NULL) {
  19109. /* Duplicate option: Later values overwrite earlier ones. */
  19110. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  19111. mg_free(new_dom->config[idx]);
  19112. }
  19113. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  19114. DEBUG_TRACE("[%s] -> [%s]", name, value);
  19115. }
  19116. /* Authentication domain is mandatory */
  19117. /* TODO: Maybe use a new option hostname? */
  19118. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  19119. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  19120. if (error != NULL) {
  19121. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  19122. error->code_sub = AUTHENTICATION_DOMAIN;
  19123. mg_snprintf(NULL,
  19124. NULL, /* No truncation check for error buffers */
  19125. error->text,
  19126. error->text_buffer_size,
  19127. "Mandatory option %s missing",
  19128. config_options[AUTHENTICATION_DOMAIN].name);
  19129. }
  19130. mg_free(new_dom);
  19131. return -4;
  19132. }
  19133. /* Set default value if needed. Take the config value from
  19134. * ctx as a default value. */
  19135. for (i = 0; config_options[i].name != NULL; i++) {
  19136. default_value = ctx->dd.config[i];
  19137. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  19138. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  19139. }
  19140. }
  19141. new_dom->handlers = ctx->dd.handlers;
  19142. new_dom->next = NULL;
  19143. new_dom->nonce_count = 0;
  19144. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  19145. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  19146. new_dom->shared_lua_websockets = NULL;
  19147. #endif
  19148. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(USE_GNUTLS)
  19149. if (!init_ssl_ctx(ctx, new_dom)) {
  19150. /* Init SSL failed */
  19151. if (error != NULL) {
  19152. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  19153. mg_snprintf(NULL,
  19154. NULL, /* No truncation check for error buffers */
  19155. error->text,
  19156. error->text_buffer_size,
  19157. "%s",
  19158. "Initializing SSL context failed");
  19159. }
  19160. mg_free(new_dom);
  19161. return -3;
  19162. }
  19163. #endif
  19164. /* Add element to linked list. */
  19165. mg_lock_context(ctx);
  19166. idx = 0;
  19167. dom = &(ctx->dd);
  19168. for (;;) {
  19169. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  19170. dom->config[AUTHENTICATION_DOMAIN])) {
  19171. /* Domain collision */
  19172. mg_cry_ctx_internal(ctx,
  19173. "domain %s already in use",
  19174. new_dom->config[AUTHENTICATION_DOMAIN]);
  19175. if (error != NULL) {
  19176. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  19177. mg_snprintf(NULL,
  19178. NULL, /* No truncation check for error buffers */
  19179. error->text,
  19180. error->text_buffer_size,
  19181. "Domain %s specified by %s is already in use",
  19182. new_dom->config[AUTHENTICATION_DOMAIN],
  19183. config_options[AUTHENTICATION_DOMAIN].name);
  19184. }
  19185. mg_free(new_dom);
  19186. mg_unlock_context(ctx);
  19187. return -5;
  19188. }
  19189. /* Count number of domains */
  19190. idx++;
  19191. if (dom->next == NULL) {
  19192. dom->next = new_dom;
  19193. break;
  19194. }
  19195. dom = dom->next;
  19196. }
  19197. mg_unlock_context(ctx);
  19198. /* Return domain number */
  19199. return idx;
  19200. }
  19201. CIVETWEB_API int
  19202. mg_start_domain(struct mg_context *ctx, const char **options)
  19203. {
  19204. return mg_start_domain2(ctx, options, NULL);
  19205. }
  19206. /* Feature check API function */
  19207. CIVETWEB_API unsigned
  19208. mg_check_feature(unsigned feature)
  19209. {
  19210. static const unsigned feature_set = 0
  19211. /* Set bits for available features according to API documentation.
  19212. * This bit mask is created at compile time, according to the active
  19213. * preprocessor defines. It is a single const value at runtime. */
  19214. #if !defined(NO_FILES)
  19215. | MG_FEATURES_FILES
  19216. #endif
  19217. #if !defined(NO_SSL) || defined(USE_MBEDTLS) || defined(USE_GNUTLS)
  19218. | MG_FEATURES_SSL
  19219. #endif
  19220. #if !defined(NO_CGI)
  19221. | MG_FEATURES_CGI
  19222. #endif
  19223. #if defined(USE_IPV6)
  19224. | MG_FEATURES_IPV6
  19225. #endif
  19226. #if defined(USE_WEBSOCKET)
  19227. | MG_FEATURES_WEBSOCKET
  19228. #endif
  19229. #if defined(USE_LUA)
  19230. | MG_FEATURES_LUA
  19231. #endif
  19232. #if defined(USE_DUKTAPE)
  19233. | MG_FEATURES_SSJS
  19234. #endif
  19235. #if !defined(NO_CACHING)
  19236. | MG_FEATURES_CACHE
  19237. #endif
  19238. #if defined(USE_SERVER_STATS)
  19239. | MG_FEATURES_STATS
  19240. #endif
  19241. #if defined(USE_ZLIB)
  19242. | MG_FEATURES_COMPRESSION
  19243. #endif
  19244. #if defined(USE_HTTP2)
  19245. | MG_FEATURES_HTTP2
  19246. #endif
  19247. #if defined(USE_X_DOM_SOCKET)
  19248. | MG_FEATURES_X_DOMAIN_SOCKET
  19249. #endif
  19250. /* Set some extra bits not defined in the API documentation.
  19251. * These bits may change without further notice. */
  19252. #if defined(MG_LEGACY_INTERFACE)
  19253. | 0x80000000u
  19254. #endif
  19255. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19256. | 0x40000000u
  19257. #endif
  19258. #if !defined(NO_RESPONSE_BUFFERING)
  19259. | 0x20000000u
  19260. #endif
  19261. #if defined(MEMORY_DEBUGGING)
  19262. | 0x10000000u
  19263. #endif
  19264. ;
  19265. return (feature & feature_set);
  19266. }
  19267. static size_t
  19268. mg_str_append(char **dst, char *end, const char *src)
  19269. {
  19270. size_t len = strlen(src);
  19271. if (*dst != end) {
  19272. /* Append src if enough space, or close dst. */
  19273. if ((size_t)(end - *dst) > len) {
  19274. strcpy(*dst, src);
  19275. *dst += len;
  19276. } else {
  19277. *dst = end;
  19278. }
  19279. }
  19280. return len;
  19281. }
  19282. /* Get system information. It can be printed or stored by the caller.
  19283. * Return the size of available information. */
  19284. CIVETWEB_API int
  19285. mg_get_system_info(char *buffer, int buflen)
  19286. {
  19287. char *end, *append_eoobj = NULL, block[256];
  19288. size_t system_info_length = 0;
  19289. #if defined(_WIN32)
  19290. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19291. #else
  19292. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19293. #endif
  19294. if ((buffer == NULL) || (buflen < 1)) {
  19295. buflen = 0;
  19296. end = buffer;
  19297. } else {
  19298. *buffer = 0;
  19299. end = buffer + buflen;
  19300. }
  19301. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19302. /* has enough space to append eoobj */
  19303. append_eoobj = buffer;
  19304. if (end) {
  19305. end -= sizeof(eoobj) - 1;
  19306. }
  19307. }
  19308. system_info_length += mg_str_append(&buffer, end, "{");
  19309. /* Server version */
  19310. {
  19311. const char *version = mg_version();
  19312. mg_snprintf(NULL,
  19313. NULL,
  19314. block,
  19315. sizeof(block),
  19316. "%s\"version\" : \"%s\"",
  19317. eol,
  19318. version);
  19319. system_info_length += mg_str_append(&buffer, end, block);
  19320. }
  19321. /* System info */
  19322. {
  19323. #if defined(_WIN32)
  19324. DWORD dwVersion = 0;
  19325. DWORD dwMajorVersion = 0;
  19326. DWORD dwMinorVersion = 0;
  19327. SYSTEM_INFO si;
  19328. GetSystemInfo(&si);
  19329. #if defined(_MSC_VER)
  19330. #pragma warning(push)
  19331. /* GetVersion was declared deprecated */
  19332. #pragma warning(disable : 4996)
  19333. #endif
  19334. dwVersion = GetVersion();
  19335. #if defined(_MSC_VER)
  19336. #pragma warning(pop)
  19337. #endif
  19338. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19339. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19340. mg_snprintf(NULL,
  19341. NULL,
  19342. block,
  19343. sizeof(block),
  19344. ",%s\"os\" : \"Windows %u.%u\"",
  19345. eol,
  19346. (unsigned)dwMajorVersion,
  19347. (unsigned)dwMinorVersion);
  19348. system_info_length += mg_str_append(&buffer, end, block);
  19349. mg_snprintf(NULL,
  19350. NULL,
  19351. block,
  19352. sizeof(block),
  19353. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19354. eol,
  19355. (unsigned)si.wProcessorArchitecture,
  19356. (unsigned)si.dwNumberOfProcessors,
  19357. (unsigned)si.dwActiveProcessorMask);
  19358. system_info_length += mg_str_append(&buffer, end, block);
  19359. #elif defined(__rtems__)
  19360. mg_snprintf(NULL,
  19361. NULL,
  19362. block,
  19363. sizeof(block),
  19364. ",%s\"os\" : \"%s %s\"",
  19365. eol,
  19366. "RTEMS",
  19367. rtems_version());
  19368. system_info_length += mg_str_append(&buffer, end, block);
  19369. #elif defined(__ZEPHYR__)
  19370. mg_snprintf(NULL,
  19371. NULL,
  19372. block,
  19373. sizeof(block),
  19374. ",%s\"os\" : \"%s\"",
  19375. eol,
  19376. "Zephyr OS",
  19377. ZEPHYR_VERSION);
  19378. system_info_length += mg_str_append(&buffer, end, block);
  19379. #else
  19380. struct utsname name;
  19381. memset(&name, 0, sizeof(name));
  19382. uname(&name);
  19383. mg_snprintf(NULL,
  19384. NULL,
  19385. block,
  19386. sizeof(block),
  19387. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19388. eol,
  19389. name.sysname,
  19390. name.version,
  19391. name.release,
  19392. name.machine);
  19393. system_info_length += mg_str_append(&buffer, end, block);
  19394. #endif
  19395. }
  19396. /* Features */
  19397. {
  19398. mg_snprintf(NULL,
  19399. NULL,
  19400. block,
  19401. sizeof(block),
  19402. ",%s\"features\" : %lu"
  19403. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19404. eol,
  19405. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19406. eol,
  19407. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19408. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19409. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19410. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19411. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19412. : "",
  19413. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19414. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19415. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19416. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19417. system_info_length += mg_str_append(&buffer, end, block);
  19418. #if defined(USE_LUA)
  19419. mg_snprintf(NULL,
  19420. NULL,
  19421. block,
  19422. sizeof(block),
  19423. ",%s\"lua_version\" : \"%u (%s)\"",
  19424. eol,
  19425. (unsigned)LUA_VERSION_NUM,
  19426. LUA_RELEASE);
  19427. system_info_length += mg_str_append(&buffer, end, block);
  19428. #endif
  19429. #if defined(USE_DUKTAPE)
  19430. mg_snprintf(NULL,
  19431. NULL,
  19432. block,
  19433. sizeof(block),
  19434. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19435. eol,
  19436. (unsigned)DUK_VERSION / 10000,
  19437. ((unsigned)DUK_VERSION / 100) % 100,
  19438. (unsigned)DUK_VERSION % 100);
  19439. system_info_length += mg_str_append(&buffer, end, block);
  19440. #endif
  19441. }
  19442. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19443. {
  19444. #if defined(BUILD_DATE)
  19445. const char *bd = BUILD_DATE;
  19446. #else
  19447. #if defined(GCC_DIAGNOSTIC)
  19448. #if GCC_VERSION >= 40900
  19449. #pragma GCC diagnostic push
  19450. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19451. * does not work in some versions. If "BUILD_DATE" is defined to some
  19452. * string, it is used instead of __DATE__. */
  19453. #pragma GCC diagnostic ignored "-Wdate-time"
  19454. #endif
  19455. #endif
  19456. const char *bd = __DATE__;
  19457. #if defined(GCC_DIAGNOSTIC)
  19458. #if GCC_VERSION >= 40900
  19459. #pragma GCC diagnostic pop
  19460. #endif
  19461. #endif
  19462. #endif
  19463. mg_snprintf(
  19464. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19465. system_info_length += mg_str_append(&buffer, end, block);
  19466. }
  19467. /* Compiler information */
  19468. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19469. {
  19470. #if defined(_MSC_VER)
  19471. mg_snprintf(NULL,
  19472. NULL,
  19473. block,
  19474. sizeof(block),
  19475. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19476. eol,
  19477. (unsigned)_MSC_VER,
  19478. (unsigned)_MSC_FULL_VER);
  19479. system_info_length += mg_str_append(&buffer, end, block);
  19480. #elif defined(__MINGW64__)
  19481. mg_snprintf(NULL,
  19482. NULL,
  19483. block,
  19484. sizeof(block),
  19485. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19486. eol,
  19487. (unsigned)__MINGW64_VERSION_MAJOR,
  19488. (unsigned)__MINGW64_VERSION_MINOR);
  19489. system_info_length += mg_str_append(&buffer, end, block);
  19490. mg_snprintf(NULL,
  19491. NULL,
  19492. block,
  19493. sizeof(block),
  19494. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19495. eol,
  19496. (unsigned)__MINGW32_MAJOR_VERSION,
  19497. (unsigned)__MINGW32_MINOR_VERSION);
  19498. system_info_length += mg_str_append(&buffer, end, block);
  19499. #elif defined(__MINGW32__)
  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(__clang__)
  19510. mg_snprintf(NULL,
  19511. NULL,
  19512. block,
  19513. sizeof(block),
  19514. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19515. eol,
  19516. __clang_major__,
  19517. __clang_minor__,
  19518. __clang_patchlevel__,
  19519. __clang_version__);
  19520. system_info_length += mg_str_append(&buffer, end, block);
  19521. #elif defined(__GNUC__)
  19522. mg_snprintf(NULL,
  19523. NULL,
  19524. block,
  19525. sizeof(block),
  19526. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19527. eol,
  19528. (unsigned)__GNUC__,
  19529. (unsigned)__GNUC_MINOR__,
  19530. (unsigned)__GNUC_PATCHLEVEL__);
  19531. system_info_length += mg_str_append(&buffer, end, block);
  19532. #elif defined(__INTEL_COMPILER)
  19533. mg_snprintf(NULL,
  19534. NULL,
  19535. block,
  19536. sizeof(block),
  19537. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19538. eol,
  19539. (unsigned)__INTEL_COMPILER);
  19540. system_info_length += mg_str_append(&buffer, end, block);
  19541. #elif defined(__BORLANDC__)
  19542. mg_snprintf(NULL,
  19543. NULL,
  19544. block,
  19545. sizeof(block),
  19546. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19547. eol,
  19548. (unsigned)__BORLANDC__);
  19549. system_info_length += mg_str_append(&buffer, end, block);
  19550. #elif defined(__SUNPRO_C)
  19551. mg_snprintf(NULL,
  19552. NULL,
  19553. block,
  19554. sizeof(block),
  19555. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19556. eol,
  19557. (unsigned)__SUNPRO_C);
  19558. system_info_length += mg_str_append(&buffer, end, block);
  19559. #else
  19560. mg_snprintf(NULL,
  19561. NULL,
  19562. block,
  19563. sizeof(block),
  19564. ",%s\"compiler\" : \"other\"",
  19565. eol);
  19566. system_info_length += mg_str_append(&buffer, end, block);
  19567. #endif
  19568. }
  19569. /* Determine 32/64 bit data mode.
  19570. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19571. {
  19572. mg_snprintf(NULL,
  19573. NULL,
  19574. block,
  19575. sizeof(block),
  19576. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19577. "char:%u/%u, "
  19578. "ptr:%u, size:%u, time:%u\"",
  19579. eol,
  19580. (unsigned)sizeof(short),
  19581. (unsigned)sizeof(int),
  19582. (unsigned)sizeof(long),
  19583. (unsigned)sizeof(long long),
  19584. (unsigned)sizeof(float),
  19585. (unsigned)sizeof(double),
  19586. (unsigned)sizeof(long double),
  19587. (unsigned)sizeof(char),
  19588. (unsigned)sizeof(wchar_t),
  19589. (unsigned)sizeof(void *),
  19590. (unsigned)sizeof(size_t),
  19591. (unsigned)sizeof(time_t));
  19592. system_info_length += mg_str_append(&buffer, end, block);
  19593. }
  19594. /* Terminate string */
  19595. if (append_eoobj) {
  19596. strcat(append_eoobj, eoobj);
  19597. }
  19598. system_info_length += sizeof(eoobj) - 1;
  19599. return (int)system_info_length;
  19600. }
  19601. /* Get context information. It can be printed or stored by the caller.
  19602. * Return the size of available information. */
  19603. CIVETWEB_API int
  19604. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19605. {
  19606. #if defined(USE_SERVER_STATS)
  19607. char *end, *append_eoobj = NULL, block[256];
  19608. size_t context_info_length = 0;
  19609. #if defined(_WIN32)
  19610. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19611. #else
  19612. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19613. #endif
  19614. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19615. if ((buffer == NULL) || (buflen < 1)) {
  19616. buflen = 0;
  19617. end = buffer;
  19618. } else {
  19619. *buffer = 0;
  19620. end = buffer + buflen;
  19621. }
  19622. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19623. /* has enough space to append eoobj */
  19624. append_eoobj = buffer;
  19625. end -= sizeof(eoobj) - 1;
  19626. }
  19627. context_info_length += mg_str_append(&buffer, end, "{");
  19628. if (ms) { /* <-- should be always true */
  19629. /* Memory information */
  19630. int blockCount = (int)ms->blockCount;
  19631. int64_t totalMemUsed = ms->totalMemUsed;
  19632. int64_t maxMemUsed = ms->maxMemUsed;
  19633. if (totalMemUsed > maxMemUsed) {
  19634. maxMemUsed = totalMemUsed;
  19635. }
  19636. mg_snprintf(NULL,
  19637. NULL,
  19638. block,
  19639. sizeof(block),
  19640. "%s\"memory\" : {%s"
  19641. "\"blocks\" : %i,%s"
  19642. "\"used\" : %" INT64_FMT ",%s"
  19643. "\"maxUsed\" : %" INT64_FMT "%s"
  19644. "}",
  19645. eol,
  19646. eol,
  19647. blockCount,
  19648. eol,
  19649. totalMemUsed,
  19650. eol,
  19651. maxMemUsed,
  19652. eol);
  19653. context_info_length += mg_str_append(&buffer, end, block);
  19654. }
  19655. if (ctx) {
  19656. /* Declare all variables at begin of the block, to comply
  19657. * with old C standards. */
  19658. char start_time_str[64] = {0};
  19659. char now_str[64] = {0};
  19660. time_t start_time = ctx->start_time;
  19661. time_t now = time(NULL);
  19662. int64_t total_data_read, total_data_written;
  19663. int active_connections = (int)ctx->active_connections;
  19664. int max_active_connections = (int)ctx->max_active_connections;
  19665. int total_connections = (int)ctx->total_connections;
  19666. if (active_connections > max_active_connections) {
  19667. max_active_connections = active_connections;
  19668. }
  19669. if (active_connections > total_connections) {
  19670. total_connections = active_connections;
  19671. }
  19672. /* Connections information */
  19673. mg_snprintf(NULL,
  19674. NULL,
  19675. block,
  19676. sizeof(block),
  19677. ",%s\"connections\" : {%s"
  19678. "\"active\" : %i,%s"
  19679. "\"maxActive\" : %i,%s"
  19680. "\"total\" : %i%s"
  19681. "}",
  19682. eol,
  19683. eol,
  19684. active_connections,
  19685. eol,
  19686. max_active_connections,
  19687. eol,
  19688. total_connections,
  19689. eol);
  19690. context_info_length += mg_str_append(&buffer, end, block);
  19691. /* Queue information */
  19692. #if !defined(ALTERNATIVE_QUEUE)
  19693. mg_snprintf(NULL,
  19694. NULL,
  19695. block,
  19696. sizeof(block),
  19697. ",%s\"queue\" : {%s"
  19698. "\"length\" : %i,%s"
  19699. "\"filled\" : %i,%s"
  19700. "\"maxFilled\" : %i,%s"
  19701. "\"full\" : %s%s"
  19702. "}",
  19703. eol,
  19704. eol,
  19705. ctx->sq_size,
  19706. eol,
  19707. ctx->sq_head - ctx->sq_tail,
  19708. eol,
  19709. ctx->sq_max_fill,
  19710. eol,
  19711. (ctx->sq_blocked ? "true" : "false"),
  19712. eol);
  19713. context_info_length += mg_str_append(&buffer, end, block);
  19714. #endif
  19715. /* Requests information */
  19716. mg_snprintf(NULL,
  19717. NULL,
  19718. block,
  19719. sizeof(block),
  19720. ",%s\"requests\" : {%s"
  19721. "\"total\" : %lu%s"
  19722. "}",
  19723. eol,
  19724. eol,
  19725. (unsigned long)ctx->total_requests,
  19726. eol);
  19727. context_info_length += mg_str_append(&buffer, end, block);
  19728. /* Data information */
  19729. total_data_read =
  19730. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19731. total_data_written =
  19732. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19733. mg_snprintf(NULL,
  19734. NULL,
  19735. block,
  19736. sizeof(block),
  19737. ",%s\"data\" : {%s"
  19738. "\"read\" : %" INT64_FMT ",%s"
  19739. "\"written\" : %" INT64_FMT "%s"
  19740. "}",
  19741. eol,
  19742. eol,
  19743. total_data_read,
  19744. eol,
  19745. total_data_written,
  19746. eol);
  19747. context_info_length += mg_str_append(&buffer, end, block);
  19748. /* Execution time information */
  19749. gmt_time_string(start_time_str,
  19750. sizeof(start_time_str) - 1,
  19751. &start_time);
  19752. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19753. mg_snprintf(NULL,
  19754. NULL,
  19755. block,
  19756. sizeof(block),
  19757. ",%s\"time\" : {%s"
  19758. "\"uptime\" : %.0f,%s"
  19759. "\"start\" : \"%s\",%s"
  19760. "\"now\" : \"%s\"%s"
  19761. "}",
  19762. eol,
  19763. eol,
  19764. difftime(now, start_time),
  19765. eol,
  19766. start_time_str,
  19767. eol,
  19768. now_str,
  19769. eol);
  19770. context_info_length += mg_str_append(&buffer, end, block);
  19771. }
  19772. /* Terminate string */
  19773. if (append_eoobj) {
  19774. strcat(append_eoobj, eoobj);
  19775. }
  19776. context_info_length += sizeof(eoobj) - 1;
  19777. return (int)context_info_length;
  19778. #else
  19779. (void)ctx;
  19780. if ((buffer != NULL) && (buflen > 0)) {
  19781. *buffer = 0;
  19782. }
  19783. return 0;
  19784. #endif
  19785. }
  19786. CIVETWEB_API void
  19787. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19788. {
  19789. /* https://github.com/civetweb/civetweb/issues/727 */
  19790. if (conn != NULL) {
  19791. conn->must_close = 1;
  19792. }
  19793. }
  19794. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19795. /* Get connection information. It can be printed or stored by the caller.
  19796. * Return the size of available information. */
  19797. CIVETWEB_API int
  19798. mg_get_connection_info(const struct mg_context *ctx,
  19799. int idx,
  19800. char *buffer,
  19801. int buflen)
  19802. {
  19803. const struct mg_connection *conn;
  19804. const struct mg_request_info *ri;
  19805. char *end, *append_eoobj = NULL, block[256];
  19806. size_t connection_info_length = 0;
  19807. int state = 0;
  19808. const char *state_str = "unknown";
  19809. #if defined(_WIN32)
  19810. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19811. #else
  19812. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19813. #endif
  19814. if ((buffer == NULL) || (buflen < 1)) {
  19815. buflen = 0;
  19816. end = buffer;
  19817. } else {
  19818. *buffer = 0;
  19819. end = buffer + buflen;
  19820. }
  19821. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19822. /* has enough space to append eoobj */
  19823. append_eoobj = buffer;
  19824. end -= sizeof(eoobj) - 1;
  19825. }
  19826. if ((ctx == NULL) || (idx < 0)) {
  19827. /* Parameter error */
  19828. return 0;
  19829. }
  19830. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19831. /* Out of range */
  19832. return 0;
  19833. }
  19834. /* Take connection [idx]. This connection is not locked in
  19835. * any way, so some other thread might use it. */
  19836. conn = (ctx->worker_connections) + idx;
  19837. /* Initialize output string */
  19838. connection_info_length += mg_str_append(&buffer, end, "{");
  19839. /* Init variables */
  19840. ri = &(conn->request_info);
  19841. #if defined(USE_SERVER_STATS)
  19842. state = conn->conn_state;
  19843. /* State as string */
  19844. switch (state) {
  19845. case 0:
  19846. state_str = "undefined";
  19847. break;
  19848. case 1:
  19849. state_str = "not used";
  19850. break;
  19851. case 2:
  19852. state_str = "init";
  19853. break;
  19854. case 3:
  19855. state_str = "ready";
  19856. break;
  19857. case 4:
  19858. state_str = "processing";
  19859. break;
  19860. case 5:
  19861. state_str = "processed";
  19862. break;
  19863. case 6:
  19864. state_str = "to close";
  19865. break;
  19866. case 7:
  19867. state_str = "closing";
  19868. break;
  19869. case 8:
  19870. state_str = "closed";
  19871. break;
  19872. case 9:
  19873. state_str = "done";
  19874. break;
  19875. }
  19876. #endif
  19877. /* Connection info */
  19878. if ((state >= 3) && (state < 9)) {
  19879. mg_snprintf(NULL,
  19880. NULL,
  19881. block,
  19882. sizeof(block),
  19883. "%s\"connection\" : {%s"
  19884. "\"remote\" : {%s"
  19885. "\"protocol\" : \"%s\",%s"
  19886. "\"addr\" : \"%s\",%s"
  19887. "\"port\" : %u%s"
  19888. "},%s"
  19889. "\"handled_requests\" : %u%s"
  19890. "}",
  19891. eol,
  19892. eol,
  19893. eol,
  19894. get_proto_name(conn),
  19895. eol,
  19896. ri->remote_addr,
  19897. eol,
  19898. ri->remote_port,
  19899. eol,
  19900. eol,
  19901. conn->handled_requests,
  19902. eol);
  19903. connection_info_length += mg_str_append(&buffer, end, block);
  19904. }
  19905. /* Request info */
  19906. if ((state >= 4) && (state < 6)) {
  19907. mg_snprintf(NULL,
  19908. NULL,
  19909. block,
  19910. sizeof(block),
  19911. "%s%s\"request_info\" : {%s"
  19912. "\"method\" : \"%s\",%s"
  19913. "\"uri\" : \"%s\",%s"
  19914. "\"query\" : %s%s%s%s"
  19915. "}",
  19916. (connection_info_length > 1 ? "," : ""),
  19917. eol,
  19918. eol,
  19919. ri->request_method,
  19920. eol,
  19921. ri->request_uri,
  19922. eol,
  19923. ri->query_string ? "\"" : "",
  19924. ri->query_string ? ri->query_string : "null",
  19925. ri->query_string ? "\"" : "",
  19926. eol);
  19927. connection_info_length += mg_str_append(&buffer, end, block);
  19928. }
  19929. /* Execution time information */
  19930. if ((state >= 2) && (state < 9)) {
  19931. char start_time_str[64] = {0};
  19932. char close_time_str[64] = {0};
  19933. time_t start_time = conn->conn_birth_time;
  19934. time_t close_time = 0;
  19935. double time_diff;
  19936. gmt_time_string(start_time_str,
  19937. sizeof(start_time_str) - 1,
  19938. &start_time);
  19939. #if defined(USE_SERVER_STATS)
  19940. close_time = conn->conn_close_time;
  19941. #endif
  19942. if (close_time != 0) {
  19943. time_diff = difftime(close_time, start_time);
  19944. gmt_time_string(close_time_str,
  19945. sizeof(close_time_str) - 1,
  19946. &close_time);
  19947. } else {
  19948. time_t now = time(NULL);
  19949. time_diff = difftime(now, start_time);
  19950. close_time_str[0] = 0; /* or use "now" ? */
  19951. }
  19952. mg_snprintf(NULL,
  19953. NULL,
  19954. block,
  19955. sizeof(block),
  19956. "%s%s\"time\" : {%s"
  19957. "\"uptime\" : %.0f,%s"
  19958. "\"start\" : \"%s\",%s"
  19959. "\"closed\" : \"%s\"%s"
  19960. "}",
  19961. (connection_info_length > 1 ? "," : ""),
  19962. eol,
  19963. eol,
  19964. time_diff,
  19965. eol,
  19966. start_time_str,
  19967. eol,
  19968. close_time_str,
  19969. eol);
  19970. connection_info_length += mg_str_append(&buffer, end, block);
  19971. }
  19972. /* Remote user name */
  19973. if ((ri->remote_user) && (state < 9)) {
  19974. mg_snprintf(NULL,
  19975. NULL,
  19976. block,
  19977. sizeof(block),
  19978. "%s%s\"user\" : {%s"
  19979. "\"name\" : \"%s\",%s"
  19980. "}",
  19981. (connection_info_length > 1 ? "," : ""),
  19982. eol,
  19983. eol,
  19984. ri->remote_user,
  19985. eol);
  19986. connection_info_length += mg_str_append(&buffer, end, block);
  19987. }
  19988. /* Data block */
  19989. if (state >= 3) {
  19990. mg_snprintf(NULL,
  19991. NULL,
  19992. block,
  19993. sizeof(block),
  19994. "%s%s\"data\" : {%s"
  19995. "\"read\" : %" INT64_FMT ",%s"
  19996. "\"written\" : %" INT64_FMT "%s"
  19997. "}",
  19998. (connection_info_length > 1 ? "," : ""),
  19999. eol,
  20000. eol,
  20001. conn->consumed_content,
  20002. eol,
  20003. conn->num_bytes_sent,
  20004. eol);
  20005. connection_info_length += mg_str_append(&buffer, end, block);
  20006. }
  20007. /* State */
  20008. mg_snprintf(NULL,
  20009. NULL,
  20010. block,
  20011. sizeof(block),
  20012. "%s%s\"state\" : \"%s\"",
  20013. (connection_info_length > 1 ? "," : ""),
  20014. eol,
  20015. state_str);
  20016. connection_info_length += mg_str_append(&buffer, end, block);
  20017. /* Terminate string */
  20018. if (append_eoobj) {
  20019. strcat(append_eoobj, eoobj);
  20020. }
  20021. connection_info_length += sizeof(eoobj) - 1;
  20022. return (int)connection_info_length;
  20023. }
  20024. #if 0
  20025. /* Get handler information. Not fully implemented. Is it required? */
  20026. CIVETWEB_API int
  20027. mg_get_handler_info(struct mg_context *ctx,
  20028. char *buffer,
  20029. int buflen)
  20030. {
  20031. int handler_info_len = 0;
  20032. struct mg_handler_info *tmp_rh;
  20033. mg_lock_context(ctx);
  20034. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  20035. if (buflen > handler_info_len + tmp_rh->uri_len) {
  20036. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  20037. }
  20038. handler_info_len += tmp_rh->uri_len;
  20039. switch (tmp_rh->handler_type) {
  20040. case REQUEST_HANDLER:
  20041. (void)tmp_rh->handler;
  20042. break;
  20043. case WEBSOCKET_HANDLER:
  20044. (void)tmp_rh->connect_handler;
  20045. (void)tmp_rh->ready_handler;
  20046. (void)tmp_rh->data_handler;
  20047. (void)tmp_rh->close_handler;
  20048. break;
  20049. case AUTH_HANDLER:
  20050. (void)tmp_rh->auth_handler;
  20051. break;
  20052. }
  20053. (void)cbdata;
  20054. }
  20055. mg_unlock_context(ctx);
  20056. return handler_info_len;
  20057. }
  20058. #endif
  20059. #endif
  20060. /* Initialize this library. This function does not need to be thread safe.
  20061. */
  20062. CIVETWEB_API unsigned
  20063. mg_init_library(unsigned features)
  20064. {
  20065. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  20066. unsigned features_inited = features_to_init;
  20067. if (mg_init_library_called <= 0) {
  20068. /* Not initialized yet */
  20069. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  20070. return 0;
  20071. }
  20072. }
  20073. mg_global_lock();
  20074. if (mg_init_library_called <= 0) {
  20075. int i;
  20076. size_t len;
  20077. #if defined(_WIN32)
  20078. int file_mutex_init = 1;
  20079. int wsa = 1;
  20080. #else
  20081. int mutexattr_init = 1;
  20082. #endif
  20083. int failed = 1;
  20084. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  20085. if (key_create == 0) {
  20086. #if defined(_WIN32)
  20087. file_mutex_init =
  20088. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  20089. if (file_mutex_init == 0) {
  20090. /* Start WinSock */
  20091. WSADATA data;
  20092. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  20093. }
  20094. #else
  20095. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  20096. if (mutexattr_init == 0) {
  20097. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  20098. PTHREAD_MUTEX_RECURSIVE);
  20099. }
  20100. #endif
  20101. }
  20102. if (failed) {
  20103. #if defined(_WIN32)
  20104. if (wsa == 0) {
  20105. (void)WSACleanup();
  20106. }
  20107. if (file_mutex_init == 0) {
  20108. (void)pthread_mutex_destroy(&global_log_file_lock);
  20109. }
  20110. #else
  20111. if (mutexattr_init == 0) {
  20112. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20113. }
  20114. #endif
  20115. if (key_create == 0) {
  20116. (void)pthread_key_delete(sTlsKey);
  20117. }
  20118. mg_global_unlock();
  20119. (void)pthread_mutex_destroy(&global_lock_mutex);
  20120. return 0;
  20121. }
  20122. len = 1;
  20123. for (i = 0; http_methods[i].name != NULL; i++) {
  20124. size_t sl = strlen(http_methods[i].name);
  20125. len += sl;
  20126. if (i > 0) {
  20127. len += 2;
  20128. }
  20129. }
  20130. all_methods = (char *)mg_malloc(len);
  20131. if (!all_methods) {
  20132. /* Must never happen */
  20133. mg_global_unlock();
  20134. (void)pthread_mutex_destroy(&global_lock_mutex);
  20135. return 0;
  20136. }
  20137. all_methods[0] = 0;
  20138. for (i = 0; http_methods[i].name != NULL; i++) {
  20139. if (i > 0) {
  20140. strcat(all_methods, ", ");
  20141. strcat(all_methods, http_methods[i].name);
  20142. } else {
  20143. strcpy(all_methods, http_methods[i].name);
  20144. }
  20145. }
  20146. }
  20147. #if defined(USE_LUA)
  20148. lua_init_optional_libraries();
  20149. #endif
  20150. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  20151. || defined(OPENSSL_API_3_0)) \
  20152. && !defined(NO_SSL)
  20153. if (features_to_init & MG_FEATURES_SSL) {
  20154. if (!mg_openssl_initialized) {
  20155. char ebuf[128];
  20156. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  20157. mg_openssl_initialized = 1;
  20158. } else {
  20159. (void)ebuf;
  20160. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  20161. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  20162. }
  20163. } else {
  20164. /* ssl already initialized */
  20165. }
  20166. }
  20167. #endif
  20168. if (mg_init_library_called <= 0) {
  20169. mg_init_library_called = 1;
  20170. } else {
  20171. mg_init_library_called++;
  20172. }
  20173. mg_global_unlock();
  20174. return features_inited;
  20175. }
  20176. /* Un-initialize this library. */
  20177. CIVETWEB_API unsigned
  20178. mg_exit_library(void)
  20179. {
  20180. if (mg_init_library_called <= 0) {
  20181. return 0;
  20182. }
  20183. mg_global_lock();
  20184. mg_init_library_called--;
  20185. if (mg_init_library_called == 0) {
  20186. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  20187. if (mg_openssl_initialized) {
  20188. uninitialize_openssl();
  20189. mg_openssl_initialized = 0;
  20190. }
  20191. #endif
  20192. #if defined(_WIN32)
  20193. (void)WSACleanup();
  20194. (void)pthread_mutex_destroy(&global_log_file_lock);
  20195. #else
  20196. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  20197. #endif
  20198. (void)pthread_key_delete(sTlsKey);
  20199. #if defined(USE_LUA)
  20200. lua_exit_optional_libraries();
  20201. #endif
  20202. mg_free(all_methods);
  20203. all_methods = NULL;
  20204. mg_global_unlock();
  20205. (void)pthread_mutex_destroy(&global_lock_mutex);
  20206. return 1;
  20207. }
  20208. mg_global_unlock();
  20209. return 1;
  20210. }
  20211. /* End of civetweb.c */