civetweb.c 603 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608
  1. /* Copyright (c) 2013-2023 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__ZEPHYR__)
  170. #include <ctype.h>
  171. #include <fcntl.h>
  172. #include <netdb.h>
  173. #include <poll.h>
  174. #include <pthread.h>
  175. #include <stdio.h>
  176. #include <stdlib.h>
  177. #include <string.h>
  178. #include <sys/socket.h>
  179. #include <time.h>
  180. #include <zephyr/kernel.h>
  181. /* Max worker threads is the max of pthreads minus the main application thread
  182. * and minus the main civetweb thread, thus -2
  183. */
  184. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  186. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  187. #else
  188. #define ZEPHYR_STACK_SIZE (1024 * 16)
  189. #endif
  190. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  191. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  192. MAX_WORKER_THREADS,
  193. ZEPHYR_STACK_SIZE);
  194. static int zephyr_worker_stack_index;
  195. #endif
  196. #if !defined(CIVETWEB_HEADER_INCLUDED)
  197. /* Include the header file here, so the CivetWeb interface is defined for the
  198. * entire implementation, including the following forward definitions. */
  199. #include "civetweb.h"
  200. #endif
  201. #if !defined(DEBUG_TRACE)
  202. #if defined(DEBUG)
  203. static void DEBUG_TRACE_FUNC(const char *func,
  204. unsigned line,
  205. PRINTF_FORMAT_STRING(const char *fmt),
  206. ...) PRINTF_ARGS(3, 4);
  207. #define DEBUG_TRACE(fmt, ...) \
  208. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  209. #define NEED_DEBUG_TRACE_FUNC
  210. #if !defined(DEBUG_TRACE_STREAM)
  211. #define DEBUG_TRACE_STREAM stdout
  212. #endif
  213. #else
  214. #define DEBUG_TRACE(fmt, ...) \
  215. do { \
  216. } while (0)
  217. #endif /* DEBUG */
  218. #endif /* DEBUG_TRACE */
  219. #if !defined(DEBUG_ASSERT)
  220. #if defined(DEBUG)
  221. #include <stdlib.h>
  222. #define DEBUG_ASSERT(cond) \
  223. do { \
  224. if (!(cond)) { \
  225. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  226. exit(2); /* Exit with error */ \
  227. } \
  228. } while (0)
  229. #else
  230. #define DEBUG_ASSERT(cond)
  231. #endif /* DEBUG */
  232. #endif
  233. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  234. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  237. __attribute__((no_instrument_function));
  238. void
  239. __cyg_profile_func_enter(void *this_fn, void *call_site)
  240. {
  241. if ((void *)this_fn != (void *)printf) {
  242. printf("E %p %p\n", this_fn, call_site);
  243. }
  244. }
  245. void
  246. __cyg_profile_func_exit(void *this_fn, void *call_site)
  247. {
  248. if ((void *)this_fn != (void *)printf) {
  249. printf("X %p %p\n", this_fn, call_site);
  250. }
  251. }
  252. #endif
  253. #if !defined(IGNORE_UNUSED_RESULT)
  254. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  255. #endif
  256. #if defined(__GNUC__) || defined(__MINGW32__)
  257. /* GCC unused function attribute seems fundamentally broken.
  258. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  259. * OR UNUSED" for individual functions failed.
  260. * Either the compiler creates an "unused-function" warning if a
  261. * function is not marked with __attribute__((unused)).
  262. * On the other hand, if the function is marked with this attribute,
  263. * but is used, the compiler raises a completely idiotic
  264. * "used-but-marked-unused" warning - and
  265. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  266. * raises error: unknown option after "#pragma GCC diagnostic".
  267. * Disable this warning completely, until the GCC guys sober up
  268. * again.
  269. */
  270. #pragma GCC diagnostic ignored "-Wunused-function"
  271. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  272. #else
  273. #define FUNCTION_MAY_BE_UNUSED
  274. #endif
  275. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  276. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  277. #include <errno.h>
  278. #include <fcntl.h>
  279. #include <signal.h>
  280. #include <stdlib.h>
  281. #include <sys/stat.h>
  282. #include <sys/types.h>
  283. #endif /* !_WIN32_WCE */
  284. #if defined(__clang__)
  285. /* When using -Weverything, clang does not accept it's own headers
  286. * in a release build configuration. Disable what is too much in
  287. * -Weverything. */
  288. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  289. #endif
  290. #if defined(__GNUC__) || defined(__MINGW32__)
  291. /* Who on earth came to the conclusion, using __DATE__ should rise
  292. * an "expansion of date or time macro is not reproducible"
  293. * warning. That's exactly what was intended by using this macro.
  294. * Just disable this nonsense warning. */
  295. /* And disabling them does not work either:
  296. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  297. * #pragma clang diagnostic ignored "-Wdate-time"
  298. * So we just have to disable ALL warnings for some lines
  299. * of code.
  300. * This seems to be a known GCC bug, not resolved since 2012:
  301. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  302. */
  303. #endif
  304. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if defined(_WIN32)
  376. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  377. #else
  378. /* Unix might return different error codes indicating to try again.
  379. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  380. * decades ago, but better check both and let the compiler optimize it. */
  381. #define ERROR_TRY_AGAIN(err) \
  382. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  383. #endif
  384. #if defined(USE_ZLIB)
  385. #include "zconf.h"
  386. #include "zlib.h"
  387. #endif
  388. /********************************************************************/
  389. /* CivetWeb configuration defines */
  390. /********************************************************************/
  391. /* Maximum number of threads that can be configured.
  392. * The number of threads actually created depends on the "num_threads"
  393. * configuration parameter, but this is the upper limit. */
  394. #if !defined(MAX_WORKER_THREADS)
  395. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  396. #endif
  397. /* Timeout interval for select/poll calls.
  398. * The timeouts depend on "*_timeout_ms" configuration values, but long
  399. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  400. * This reduces the time required to stop the server. */
  401. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  402. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  403. #endif
  404. /* Do not try to compress files smaller than this limit. */
  405. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  406. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  407. #endif
  408. #if !defined(PASSWORDS_FILE_NAME)
  409. #define PASSWORDS_FILE_NAME ".htpasswd"
  410. #endif
  411. /* Initial buffer size for all CGI environment variables. In case there is
  412. * not enough space, another block is allocated. */
  413. #if !defined(CGI_ENVIRONMENT_SIZE)
  414. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  415. #endif
  416. /* Maximum number of environment variables. */
  417. #if !defined(MAX_CGI_ENVIR_VARS)
  418. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  419. #endif
  420. /* General purpose buffer size. */
  421. #if !defined(MG_BUF_LEN) /* in bytes */
  422. #define MG_BUF_LEN (1024 * 8)
  423. #endif
  424. /********************************************************************/
  425. /* Helper macros */
  426. #if !defined(ARRAY_SIZE)
  427. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  428. #endif
  429. #include <stdint.h>
  430. /* Standard defines */
  431. #if !defined(INT64_MAX)
  432. #define INT64_MAX (9223372036854775807)
  433. #endif
  434. #define SHUTDOWN_RD (0)
  435. #define SHUTDOWN_WR (1)
  436. #define SHUTDOWN_BOTH (2)
  437. mg_static_assert(MAX_WORKER_THREADS >= 1,
  438. "worker threads must be a positive number");
  439. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  440. "size_t data type size check");
  441. #if defined(_WIN32) /* WINDOWS include block */
  442. #include <Windows.h>
  443. #include <malloc.h> /* *alloc( */
  444. #include <stdlib.h> /* *alloc( */
  445. #include <time.h> /* struct timespec */
  446. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  447. #include <ws2tcpip.h>
  448. typedef const char *SOCK_OPT_TYPE;
  449. /* For a detailed description of these *_PATH_MAX defines, see
  450. * https://github.com/civetweb/civetweb/issues/937. */
  451. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  452. * null termination, rounded up to the next 4 bytes boundary */
  453. #define UTF8_PATH_MAX (3 * 260)
  454. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  455. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  456. #define UTF16_PATH_MAX (260)
  457. #if !defined(_IN_PORT_T)
  458. #if !defined(in_port_t)
  459. #define in_port_t u_short
  460. #endif
  461. #endif
  462. #if defined(_WIN32_WCE)
  463. #error "WinCE support has ended"
  464. #endif
  465. #include <direct.h>
  466. #include <io.h>
  467. #include <process.h>
  468. #define MAKEUQUAD(lo, hi) \
  469. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  470. #define RATE_DIFF (10000000) /* 100 nsecs */
  471. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  472. #define SYS2UNIX_TIME(lo, hi) \
  473. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  474. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  475. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  476. * Also use _strtoui64 on modern M$ compilers */
  477. #if defined(_MSC_VER)
  478. #if (_MSC_VER < 1300)
  479. #define STRX(x) #x
  480. #define STR(x) STRX(x)
  481. #define __func__ __FILE__ ":" STR(__LINE__)
  482. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  483. #define strtoll(x, y, z) (_atoi64(x))
  484. #else
  485. #define __func__ __FUNCTION__
  486. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  487. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  488. #endif
  489. #endif /* _MSC_VER */
  490. #define ERRNO ((int)(GetLastError()))
  491. #define NO_SOCKLEN_T
  492. #if defined(_WIN64) || defined(__MINGW64__)
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_3_0)
  495. #define SSL_LIB "libssl-3-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  497. #endif
  498. #if defined(OPENSSL_API_1_1)
  499. #define SSL_LIB "libssl-1_1-x64.dll"
  500. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  501. #endif /* OPENSSL_API_1_1 */
  502. #if defined(OPENSSL_API_1_0)
  503. #define SSL_LIB "ssleay64.dll"
  504. #define CRYPTO_LIB "libeay64.dll"
  505. #endif /* OPENSSL_API_1_0 */
  506. #endif
  507. #else /* defined(_WIN64) || defined(__MINGW64__) */
  508. #if !defined(SSL_LIB)
  509. #if defined(OPENSSL_API_3_0)
  510. #define SSL_LIB "libssl-3.dll"
  511. #define CRYPTO_LIB "libcrypto-3.dll"
  512. #endif
  513. #if defined(OPENSSL_API_1_1)
  514. #define SSL_LIB "libssl-1_1.dll"
  515. #define CRYPTO_LIB "libcrypto-1_1.dll"
  516. #endif /* OPENSSL_API_1_1 */
  517. #if defined(OPENSSL_API_1_0)
  518. #define SSL_LIB "ssleay32.dll"
  519. #define CRYPTO_LIB "libeay32.dll"
  520. #endif /* OPENSSL_API_1_0 */
  521. #endif /* SSL_LIB */
  522. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  523. #define O_NONBLOCK (0)
  524. #if !defined(W_OK)
  525. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  526. #endif
  527. #define _POSIX_
  528. #define INT64_FMT "I64d"
  529. #define UINT64_FMT "I64u"
  530. #define WINCDECL __cdecl
  531. #define vsnprintf_impl _vsnprintf
  532. #define access _access
  533. #define mg_sleep(x) (Sleep(x))
  534. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  535. #if !defined(popen)
  536. #define popen(x, y) (_popen(x, y))
  537. #endif
  538. #if !defined(pclose)
  539. #define pclose(x) (_pclose(x))
  540. #endif
  541. #define close(x) (_close(x))
  542. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  543. #define RTLD_LAZY (0)
  544. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  545. #define fdopen(x, y) (_fdopen((x), (y)))
  546. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  547. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  548. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  549. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  550. #define sleep(x) (Sleep((x)*1000))
  551. #define rmdir(x) (_rmdir(x))
  552. #if defined(_WIN64) || !defined(__MINGW32__)
  553. /* Only MinGW 32 bit is missing this function */
  554. #define timegm(x) (_mkgmtime(x))
  555. #else
  556. time_t timegm(struct tm *tm);
  557. #define NEED_TIMEGM
  558. #endif
  559. #if !defined(fileno)
  560. #define fileno(x) (_fileno(x))
  561. #endif /* !fileno MINGW #defines fileno */
  562. typedef struct {
  563. CRITICAL_SECTION sec; /* Immovable */
  564. } pthread_mutex_t;
  565. typedef DWORD pthread_key_t;
  566. typedef HANDLE pthread_t;
  567. typedef struct {
  568. pthread_mutex_t threadIdSec;
  569. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  570. } pthread_cond_t;
  571. #if !defined(__clockid_t_defined)
  572. typedef DWORD clockid_t;
  573. #endif
  574. #if !defined(CLOCK_MONOTONIC)
  575. #define CLOCK_MONOTONIC (1)
  576. #endif
  577. #if !defined(CLOCK_REALTIME)
  578. #define CLOCK_REALTIME (2)
  579. #endif
  580. #if !defined(CLOCK_THREAD)
  581. #define CLOCK_THREAD (3)
  582. #endif
  583. #if !defined(CLOCK_PROCESS)
  584. #define CLOCK_PROCESS (4)
  585. #endif
  586. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  587. #define _TIMESPEC_DEFINED
  588. #endif
  589. #if !defined(_TIMESPEC_DEFINED)
  590. struct timespec {
  591. time_t tv_sec; /* seconds */
  592. long tv_nsec; /* nanoseconds */
  593. };
  594. #endif
  595. #if !defined(WIN_PTHREADS_TIME_H)
  596. #define MUST_IMPLEMENT_CLOCK_GETTIME
  597. #endif
  598. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  599. #define clock_gettime mg_clock_gettime
  600. static int
  601. clock_gettime(clockid_t clk_id, struct timespec *tp)
  602. {
  603. FILETIME ft;
  604. ULARGE_INTEGER li, li2;
  605. BOOL ok = FALSE;
  606. double d;
  607. static double perfcnt_per_sec = 0.0;
  608. static BOOL initialized = FALSE;
  609. if (!initialized) {
  610. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  611. perfcnt_per_sec = 1.0 / li.QuadPart;
  612. initialized = TRUE;
  613. }
  614. if (tp) {
  615. memset(tp, 0, sizeof(*tp));
  616. if (clk_id == CLOCK_REALTIME) {
  617. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  618. GetSystemTimeAsFileTime(&ft);
  619. li.LowPart = ft.dwLowDateTime;
  620. li.HighPart = ft.dwHighDateTime;
  621. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  622. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  623. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  624. ok = TRUE;
  625. /* END: CLOCK_REALTIME */
  626. } else if (clk_id == CLOCK_MONOTONIC) {
  627. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  628. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  629. d = li.QuadPart * perfcnt_per_sec;
  630. tp->tv_sec = (time_t)d;
  631. d -= (double)tp->tv_sec;
  632. tp->tv_nsec = (long)(d * 1.0E9);
  633. ok = TRUE;
  634. /* END: CLOCK_MONOTONIC */
  635. } else if (clk_id == CLOCK_THREAD) {
  636. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  637. FILETIME t_create, t_exit, t_kernel, t_user;
  638. if (GetThreadTimes(GetCurrentThread(),
  639. &t_create,
  640. &t_exit,
  641. &t_kernel,
  642. &t_user)) {
  643. li.LowPart = t_user.dwLowDateTime;
  644. li.HighPart = t_user.dwHighDateTime;
  645. li2.LowPart = t_kernel.dwLowDateTime;
  646. li2.HighPart = t_kernel.dwHighDateTime;
  647. li.QuadPart += li2.QuadPart;
  648. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  649. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  650. ok = TRUE;
  651. }
  652. /* END: CLOCK_THREAD */
  653. } else if (clk_id == CLOCK_PROCESS) {
  654. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  655. FILETIME t_create, t_exit, t_kernel, t_user;
  656. if (GetProcessTimes(GetCurrentProcess(),
  657. &t_create,
  658. &t_exit,
  659. &t_kernel,
  660. &t_user)) {
  661. li.LowPart = t_user.dwLowDateTime;
  662. li.HighPart = t_user.dwHighDateTime;
  663. li2.LowPart = t_kernel.dwLowDateTime;
  664. li2.HighPart = t_kernel.dwHighDateTime;
  665. li.QuadPart += li2.QuadPart;
  666. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  667. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  668. ok = TRUE;
  669. }
  670. /* END: CLOCK_PROCESS */
  671. } else {
  672. /* BEGIN: unknown clock */
  673. /* ok = FALSE; already set by init */
  674. /* END: unknown clock */
  675. }
  676. }
  677. return ok ? 0 : -1;
  678. }
  679. #endif
  680. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  681. static int pthread_mutex_lock(pthread_mutex_t *);
  682. static int pthread_mutex_unlock(pthread_mutex_t *);
  683. static void path_to_unicode(const struct mg_connection *conn,
  684. const char *path,
  685. wchar_t *wbuf,
  686. size_t wbuf_len);
  687. /* All file operations need to be rewritten to solve #246. */
  688. struct mg_file;
  689. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  690. /* POSIX dirent interface */
  691. struct dirent {
  692. char d_name[UTF8_PATH_MAX];
  693. };
  694. typedef struct DIR {
  695. HANDLE handle;
  696. WIN32_FIND_DATAW info;
  697. struct dirent result;
  698. } DIR;
  699. #if defined(HAVE_POLL)
  700. #define mg_pollfd pollfd
  701. #else
  702. struct mg_pollfd {
  703. SOCKET fd;
  704. short events;
  705. short revents;
  706. };
  707. #endif
  708. /* Mark required libraries */
  709. #if defined(_MSC_VER)
  710. #pragma comment(lib, "Ws2_32.lib")
  711. #endif
  712. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  713. #include <inttypes.h>
  714. /* Linux & co. internally use UTF8 */
  715. #define UTF8_PATH_MAX (PATH_MAX)
  716. typedef const void *SOCK_OPT_TYPE;
  717. #if defined(ANDROID)
  718. typedef unsigned short int in_port_t;
  719. #endif
  720. #if !defined(__ZEPHYR__)
  721. #include <arpa/inet.h>
  722. #include <ctype.h>
  723. #include <dirent.h>
  724. #include <grp.h>
  725. #include <limits.h>
  726. #include <netdb.h>
  727. #include <netinet/in.h>
  728. #include <netinet/tcp.h>
  729. #include <poll.h>
  730. #include <pthread.h>
  731. #include <pwd.h>
  732. #include <stdarg.h>
  733. #include <stddef.h>
  734. #include <stdio.h>
  735. #include <stdlib.h>
  736. #include <string.h>
  737. #include <sys/socket.h>
  738. #include <sys/time.h>
  739. #include <sys/utsname.h>
  740. #include <sys/wait.h>
  741. #include <time.h>
  742. #include <unistd.h>
  743. #if defined(USE_X_DOM_SOCKET)
  744. #include <sys/un.h>
  745. #endif
  746. #endif
  747. #define vsnprintf_impl vsnprintf
  748. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  749. #include <dlfcn.h>
  750. #endif
  751. #if defined(__MACH__) && defined(__APPLE__)
  752. #define SSL_LIB "libssl.dylib"
  753. #define CRYPTO_LIB "libcrypto.dylib"
  754. #else
  755. #if !defined(SSL_LIB)
  756. #define SSL_LIB "libssl.so"
  757. #endif
  758. #if !defined(CRYPTO_LIB)
  759. #define CRYPTO_LIB "libcrypto.so"
  760. #endif
  761. #endif
  762. #if !defined(O_BINARY)
  763. #define O_BINARY (0)
  764. #endif /* O_BINARY */
  765. #define closesocket(a) (close(a))
  766. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  767. #define mg_remove(conn, x) (remove(x))
  768. #define mg_sleep(x) (usleep((x)*1000))
  769. #define mg_opendir(conn, x) (opendir(x))
  770. #define mg_closedir(x) (closedir(x))
  771. #define mg_readdir(x) (readdir(x))
  772. #define ERRNO (errno)
  773. #define INVALID_SOCKET (-1)
  774. #define INT64_FMT PRId64
  775. #define UINT64_FMT PRIu64
  776. typedef int SOCKET;
  777. #define WINCDECL
  778. #if defined(__hpux)
  779. /* HPUX 11 does not have monotonic, fall back to realtime */
  780. #if !defined(CLOCK_MONOTONIC)
  781. #define CLOCK_MONOTONIC CLOCK_REALTIME
  782. #endif
  783. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  784. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  785. * the prototypes use int* rather than socklen_t* which matches the
  786. * actual library expectation. When called with the wrong size arg
  787. * accept() returns a zero client inet addr and check_acl() always
  788. * fails. Since socklen_t is widely used below, just force replace
  789. * their typedef with int. - DTL
  790. */
  791. #define socklen_t int
  792. #endif /* hpux */
  793. #define mg_pollfd pollfd
  794. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  795. /* In case our C library is missing "timegm", provide an implementation */
  796. #if defined(NEED_TIMEGM)
  797. static inline int
  798. is_leap(int y)
  799. {
  800. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  801. }
  802. static inline int
  803. count_leap(int y)
  804. {
  805. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  806. }
  807. time_t
  808. timegm(struct tm *tm)
  809. {
  810. static const unsigned short ydays[] = {
  811. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  812. int year = tm->tm_year + 1900;
  813. int mon = tm->tm_mon;
  814. int mday = tm->tm_mday - 1;
  815. int hour = tm->tm_hour;
  816. int min = tm->tm_min;
  817. int sec = tm->tm_sec;
  818. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  819. || (mday >= ydays[mon + 1] - ydays[mon]
  820. + (mon == 1 && is_leap(year) ? 1 : 0))
  821. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  822. return -1;
  823. time_t res = year - 1970;
  824. res *= 365;
  825. res += mday;
  826. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  827. res += count_leap(year);
  828. res *= 24;
  829. res += hour;
  830. res *= 60;
  831. res += min;
  832. res *= 60;
  833. res += sec;
  834. return res;
  835. }
  836. #endif /* NEED_TIMEGM */
  837. /* va_copy should always be a macro, C99 and C++11 - DTL */
  838. #if !defined(va_copy)
  839. #define va_copy(x, y) ((x) = (y))
  840. #endif
  841. #if defined(_WIN32)
  842. /* Create substitutes for POSIX functions in Win32. */
  843. #if defined(GCC_DIAGNOSTIC)
  844. /* Show no warning in case system functions are not used. */
  845. #pragma GCC diagnostic push
  846. #pragma GCC diagnostic ignored "-Wunused-function"
  847. #endif
  848. static pthread_mutex_t global_log_file_lock;
  849. FUNCTION_MAY_BE_UNUSED
  850. static DWORD
  851. pthread_self(void)
  852. {
  853. return GetCurrentThreadId();
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_create(
  858. pthread_key_t *key,
  859. void (*_ignored)(void *) /* destructor not supported for Windows */
  860. )
  861. {
  862. (void)_ignored;
  863. if ((key != 0)) {
  864. *key = TlsAlloc();
  865. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  866. }
  867. return -2;
  868. }
  869. FUNCTION_MAY_BE_UNUSED
  870. static int
  871. pthread_key_delete(pthread_key_t key)
  872. {
  873. return TlsFree(key) ? 0 : 1;
  874. }
  875. FUNCTION_MAY_BE_UNUSED
  876. static int
  877. pthread_setspecific(pthread_key_t key, void *value)
  878. {
  879. return TlsSetValue(key, value) ? 0 : 1;
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static void *
  883. pthread_getspecific(pthread_key_t key)
  884. {
  885. return TlsGetValue(key);
  886. }
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Enable unused function warning again */
  889. #pragma GCC diagnostic pop
  890. #endif
  891. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  892. #else
  893. static pthread_mutexattr_t pthread_mutex_attr;
  894. #endif /* _WIN32 */
  895. #if defined(GCC_DIAGNOSTIC)
  896. /* Show no warning in case system functions are not used. */
  897. #pragma GCC diagnostic push
  898. #pragma GCC diagnostic ignored "-Wunused-function"
  899. #endif /* defined(GCC_DIAGNOSTIC) */
  900. #if defined(__clang__)
  901. /* Show no warning in case system functions are not used. */
  902. #pragma clang diagnostic push
  903. #pragma clang diagnostic ignored "-Wunused-function"
  904. #endif
  905. static pthread_mutex_t global_lock_mutex;
  906. FUNCTION_MAY_BE_UNUSED
  907. static void
  908. mg_global_lock(void)
  909. {
  910. (void)pthread_mutex_lock(&global_lock_mutex);
  911. }
  912. FUNCTION_MAY_BE_UNUSED
  913. static void
  914. mg_global_unlock(void)
  915. {
  916. (void)pthread_mutex_unlock(&global_lock_mutex);
  917. }
  918. #if defined(_WIN64)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  920. #elif defined(_WIN32)
  921. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  922. #endif
  923. /* Atomic functions working on ptrdiff_t ("signed size_t").
  924. * Operations: Increment, Decrement, Add, Maximum.
  925. * Up to size_t, they do not an atomic "load" operation.
  926. */
  927. FUNCTION_MAY_BE_UNUSED
  928. static ptrdiff_t
  929. mg_atomic_inc(volatile ptrdiff_t *addr)
  930. {
  931. ptrdiff_t ret;
  932. #if defined(_WIN64) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement64(addr);
  934. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  935. #ifdef __cplusplus
  936. /* For C++ the Microsoft Visual Studio compiler can not decide what
  937. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  938. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  939. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  940. ret = InterlockedIncrement((LONG *)addr);
  941. #else
  942. ret = InterlockedIncrement(addr);
  943. #endif
  944. #elif defined(__GNUC__) \
  945. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  946. && !defined(NO_ATOMICS)
  947. ret = __sync_add_and_fetch(addr, 1);
  948. #else
  949. mg_global_lock();
  950. ret = (++(*addr));
  951. mg_global_unlock();
  952. #endif
  953. return ret;
  954. }
  955. FUNCTION_MAY_BE_UNUSED
  956. static ptrdiff_t
  957. mg_atomic_dec(volatile ptrdiff_t *addr)
  958. {
  959. ptrdiff_t ret;
  960. #if defined(_WIN64) && !defined(NO_ATOMICS)
  961. ret = InterlockedDecrement64(addr);
  962. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  963. #ifdef __cplusplus
  964. /* see mg_atomic_inc */
  965. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  966. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  967. ret = InterlockedDecrement((LONG *)addr);
  968. #else
  969. ret = InterlockedDecrement(addr);
  970. #endif
  971. #elif defined(__GNUC__) \
  972. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  973. && !defined(NO_ATOMICS)
  974. ret = __sync_sub_and_fetch(addr, 1);
  975. #else
  976. mg_global_lock();
  977. ret = (--(*addr));
  978. mg_global_unlock();
  979. #endif
  980. return ret;
  981. }
  982. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  983. static ptrdiff_t
  984. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedAdd64(addr, value);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedExchangeAdd(addr, value) + value;
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_add_and_fetch(addr, value);
  995. #else
  996. mg_global_lock();
  997. *addr += value;
  998. ret = (*addr);
  999. mg_global_unlock();
  1000. #endif
  1001. return ret;
  1002. }
  1003. FUNCTION_MAY_BE_UNUSED
  1004. static ptrdiff_t
  1005. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1006. ptrdiff_t oldval,
  1007. ptrdiff_t newval)
  1008. {
  1009. ptrdiff_t ret;
  1010. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1011. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1012. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1013. ret = InterlockedCompareExchange(addr, newval, oldval);
  1014. #elif defined(__GNUC__) \
  1015. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1016. && !defined(NO_ATOMICS)
  1017. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1018. #else
  1019. mg_global_lock();
  1020. ret = *addr;
  1021. if ((ret != newval) && (ret == oldval)) {
  1022. *addr = newval;
  1023. }
  1024. mg_global_unlock();
  1025. #endif
  1026. return ret;
  1027. }
  1028. static void
  1029. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1030. {
  1031. register ptrdiff_t tmp = *addr;
  1032. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1033. while (tmp < value) {
  1034. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1035. }
  1036. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1037. while (tmp < value) {
  1038. tmp = InterlockedCompareExchange(addr, value, tmp);
  1039. }
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. while (tmp < value) {
  1044. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1045. }
  1046. #else
  1047. mg_global_lock();
  1048. if (*addr < value) {
  1049. *addr = value;
  1050. }
  1051. mg_global_unlock();
  1052. #endif
  1053. }
  1054. static int64_t
  1055. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1061. ret = InterlockedExchangeAdd64(addr, value) + value;
  1062. #elif defined(__GNUC__) \
  1063. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1064. && !defined(NO_ATOMICS)
  1065. ret = __sync_add_and_fetch(addr, value);
  1066. #else
  1067. mg_global_lock();
  1068. *addr += value;
  1069. ret = (*addr);
  1070. mg_global_unlock();
  1071. #endif
  1072. return ret;
  1073. }
  1074. #endif
  1075. #if defined(GCC_DIAGNOSTIC)
  1076. /* Show no warning in case system functions are not used. */
  1077. #pragma GCC diagnostic pop
  1078. #endif /* defined(GCC_DIAGNOSTIC) */
  1079. #if defined(__clang__)
  1080. /* Show no warning in case system functions are not used. */
  1081. #pragma clang diagnostic pop
  1082. #endif
  1083. #if defined(USE_SERVER_STATS)
  1084. struct mg_memory_stat {
  1085. volatile ptrdiff_t totalMemUsed;
  1086. volatile ptrdiff_t maxMemUsed;
  1087. volatile ptrdiff_t blockCount;
  1088. };
  1089. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1090. static void *
  1091. mg_malloc_ex(size_t size,
  1092. struct mg_context *ctx,
  1093. const char *file,
  1094. unsigned line)
  1095. {
  1096. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1097. void *memory = 0;
  1098. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1099. #if defined(MEMORY_DEBUGGING)
  1100. char mallocStr[256];
  1101. #else
  1102. (void)file;
  1103. (void)line;
  1104. #endif
  1105. if (data) {
  1106. uintptr_t *tmp = (uintptr_t *)data;
  1107. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1108. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1109. mg_atomic_inc(&mstat->blockCount);
  1110. tmp[0] = size;
  1111. tmp[1] = (uintptr_t)mstat;
  1112. memory = (void *)&tmp[2];
  1113. }
  1114. #if defined(MEMORY_DEBUGGING)
  1115. sprintf(mallocStr,
  1116. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1117. memory,
  1118. (unsigned long)size,
  1119. (unsigned long)mstat->totalMemUsed,
  1120. (unsigned long)mstat->blockCount,
  1121. file,
  1122. line);
  1123. DEBUG_TRACE("%s", mallocStr);
  1124. #endif
  1125. return memory;
  1126. }
  1127. static void *
  1128. mg_calloc_ex(size_t count,
  1129. size_t size,
  1130. struct mg_context *ctx,
  1131. const char *file,
  1132. unsigned line)
  1133. {
  1134. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1135. if (data) {
  1136. memset(data, 0, size * count);
  1137. }
  1138. return data;
  1139. }
  1140. static void
  1141. mg_free_ex(void *memory, const char *file, unsigned line)
  1142. {
  1143. #if defined(MEMORY_DEBUGGING)
  1144. char mallocStr[256];
  1145. #else
  1146. (void)file;
  1147. (void)line;
  1148. #endif
  1149. if (memory) {
  1150. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1151. uintptr_t size = ((uintptr_t *)data)[0];
  1152. struct mg_memory_stat *mstat =
  1153. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1154. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1155. mg_atomic_dec(&mstat->blockCount);
  1156. #if defined(MEMORY_DEBUGGING)
  1157. sprintf(mallocStr,
  1158. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1159. memory,
  1160. (unsigned long)size,
  1161. (unsigned long)mstat->totalMemUsed,
  1162. (unsigned long)mstat->blockCount,
  1163. file,
  1164. line);
  1165. DEBUG_TRACE("%s", mallocStr);
  1166. #endif
  1167. free(data);
  1168. }
  1169. }
  1170. static void *
  1171. mg_realloc_ex(void *memory,
  1172. size_t newsize,
  1173. struct mg_context *ctx,
  1174. const char *file,
  1175. unsigned line)
  1176. {
  1177. void *data;
  1178. void *_realloc;
  1179. uintptr_t oldsize;
  1180. #if defined(MEMORY_DEBUGGING)
  1181. char mallocStr[256];
  1182. #else
  1183. (void)file;
  1184. (void)line;
  1185. #endif
  1186. if (newsize) {
  1187. if (memory) {
  1188. /* Reallocate existing block */
  1189. struct mg_memory_stat *mstat;
  1190. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1191. oldsize = ((uintptr_t *)data)[0];
  1192. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1193. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1194. if (_realloc) {
  1195. data = _realloc;
  1196. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1197. #if defined(MEMORY_DEBUGGING)
  1198. sprintf(mallocStr,
  1199. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1200. memory,
  1201. (unsigned long)oldsize,
  1202. (unsigned long)mstat->totalMemUsed,
  1203. (unsigned long)mstat->blockCount,
  1204. file,
  1205. line);
  1206. DEBUG_TRACE("%s", mallocStr);
  1207. #endif
  1208. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1209. #if defined(MEMORY_DEBUGGING)
  1210. sprintf(mallocStr,
  1211. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1212. memory,
  1213. (unsigned long)newsize,
  1214. (unsigned long)mstat->totalMemUsed,
  1215. (unsigned long)mstat->blockCount,
  1216. file,
  1217. line);
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. *(uintptr_t *)data = newsize;
  1221. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1222. } else {
  1223. #if defined(MEMORY_DEBUGGING)
  1224. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1225. #endif
  1226. return _realloc;
  1227. }
  1228. } else {
  1229. /* Allocate new block */
  1230. data = mg_malloc_ex(newsize, ctx, file, line);
  1231. }
  1232. } else {
  1233. /* Free existing block */
  1234. data = 0;
  1235. mg_free_ex(memory, file, line);
  1236. }
  1237. return data;
  1238. }
  1239. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1240. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1241. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1242. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1243. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1246. #else /* USE_SERVER_STATS */
  1247. static __inline void *
  1248. mg_malloc(size_t a)
  1249. {
  1250. return malloc(a);
  1251. }
  1252. static __inline void *
  1253. mg_calloc(size_t a, size_t b)
  1254. {
  1255. return calloc(a, b);
  1256. }
  1257. static __inline void *
  1258. mg_realloc(void *a, size_t b)
  1259. {
  1260. return realloc(a, b);
  1261. }
  1262. static __inline void
  1263. mg_free(void *a)
  1264. {
  1265. free(a);
  1266. }
  1267. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1268. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1269. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1270. #define mg_free_ctx(a, c) mg_free(a)
  1271. #endif /* USE_SERVER_STATS */
  1272. static void mg_vsnprintf(const struct mg_connection *conn,
  1273. int *truncated,
  1274. char *buf,
  1275. size_t buflen,
  1276. const char *fmt,
  1277. va_list ap);
  1278. static void mg_snprintf(const struct mg_connection *conn,
  1279. int *truncated,
  1280. char *buf,
  1281. size_t buflen,
  1282. PRINTF_FORMAT_STRING(const char *fmt),
  1283. ...) PRINTF_ARGS(5, 6);
  1284. /* This following lines are just meant as a reminder to use the mg-functions
  1285. * for memory management */
  1286. #if defined(malloc)
  1287. #undef malloc
  1288. #endif
  1289. #if defined(calloc)
  1290. #undef calloc
  1291. #endif
  1292. #if defined(realloc)
  1293. #undef realloc
  1294. #endif
  1295. #if defined(free)
  1296. #undef free
  1297. #endif
  1298. #if defined(snprintf)
  1299. #undef snprintf
  1300. #endif
  1301. #if defined(vsnprintf)
  1302. #undef vsnprintf
  1303. #endif
  1304. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1305. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1306. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1307. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1308. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1309. #if defined(_WIN32)
  1310. /* vsnprintf must not be used in any system,
  1311. * but this define only works well for Windows. */
  1312. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1313. #endif
  1314. /* mg_init_library counter */
  1315. static int mg_init_library_called = 0;
  1316. #if !defined(NO_SSL)
  1317. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1318. || defined(OPENSSL_API_3_0)
  1319. static int mg_openssl_initialized = 0;
  1320. #endif
  1321. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1322. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1323. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1324. #endif
  1325. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1326. #error "Multiple OPENSSL_API versions defined"
  1327. #endif
  1328. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1329. #error "Multiple OPENSSL_API versions defined"
  1330. #endif
  1331. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1332. #error "Multiple OPENSSL_API versions defined"
  1333. #endif
  1334. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)) \
  1336. && defined(USE_MBEDTLS)
  1337. #error "Multiple SSL libraries defined"
  1338. #endif
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static volatile ptrdiff_t thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. const char *alpn_proto;
  1354. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1355. char txtbuf[4];
  1356. #endif
  1357. };
  1358. #if defined(GCC_DIAGNOSTIC)
  1359. /* Show no warning in case system functions are not used. */
  1360. #pragma GCC diagnostic push
  1361. #pragma GCC diagnostic ignored "-Wunused-function"
  1362. #endif /* defined(GCC_DIAGNOSTIC) */
  1363. #if defined(__clang__)
  1364. /* Show no warning in case system functions are not used. */
  1365. #pragma clang diagnostic push
  1366. #pragma clang diagnostic ignored "-Wunused-function"
  1367. #endif
  1368. /* Get a unique thread ID as unsigned long, independent from the data type
  1369. * of thread IDs defined by the operating system API.
  1370. * If two calls to mg_current_thread_id return the same value, they calls
  1371. * are done from the same thread. If they return different values, they are
  1372. * done from different threads. (Provided this function is used in the same
  1373. * process context and threads are not repeatedly created and deleted, but
  1374. * CivetWeb does not do that).
  1375. * This function must match the signature required for SSL id callbacks:
  1376. * CRYPTO_set_id_callback
  1377. */
  1378. FUNCTION_MAY_BE_UNUSED
  1379. static unsigned long
  1380. mg_current_thread_id(void)
  1381. {
  1382. #if defined(_WIN32)
  1383. return GetCurrentThreadId();
  1384. #else
  1385. #if defined(__clang__)
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunreachable-code"
  1388. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1389. * or not, so one of the two conditions will be unreachable by construction.
  1390. * Unfortunately the C standard does not define a way to check this at
  1391. * compile time, since the #if preprocessor conditions can not use the
  1392. * sizeof operator as an argument. */
  1393. #endif
  1394. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1395. /* This is the problematic case for CRYPTO_set_id_callback:
  1396. * The OS pthread_t can not be cast to unsigned long. */
  1397. struct mg_workerTLS *tls =
  1398. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1399. if (tls == NULL) {
  1400. /* SSL called from an unknown thread: Create some thread index.
  1401. */
  1402. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1403. tls->is_master = -2; /* -2 means "3rd party thread" */
  1404. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1405. pthread_setspecific(sTlsKey, tls);
  1406. }
  1407. return tls->thread_idx;
  1408. } else {
  1409. /* pthread_t may be any data type, so a simple cast to unsigned long
  1410. * can rise a warning/error, depending on the platform.
  1411. * Here memcpy is used as an anything-to-anything cast. */
  1412. unsigned long ret = 0;
  1413. pthread_t t = pthread_self();
  1414. memcpy(&ret, &t, sizeof(pthread_t));
  1415. return ret;
  1416. }
  1417. #if defined(__clang__)
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #endif
  1421. }
  1422. FUNCTION_MAY_BE_UNUSED
  1423. static uint64_t
  1424. mg_get_current_time_ns(void)
  1425. {
  1426. struct timespec tsnow;
  1427. clock_gettime(CLOCK_REALTIME, &tsnow);
  1428. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1429. }
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic pop
  1433. #endif /* defined(GCC_DIAGNOSTIC) */
  1434. #if defined(__clang__)
  1435. /* Show no warning in case system functions are not used. */
  1436. #pragma clang diagnostic pop
  1437. #endif
  1438. #if defined(NEED_DEBUG_TRACE_FUNC)
  1439. static void
  1440. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1441. {
  1442. va_list args;
  1443. struct timespec tsnow;
  1444. /* Get some operating system independent thread id */
  1445. unsigned long thread_id = mg_current_thread_id();
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. flockfile(DEBUG_TRACE_STREAM);
  1448. fprintf(DEBUG_TRACE_STREAM,
  1449. "*** %lu.%09lu %lu %s:%u: ",
  1450. (unsigned long)tsnow.tv_sec,
  1451. (unsigned long)tsnow.tv_nsec,
  1452. thread_id,
  1453. func,
  1454. line);
  1455. va_start(args, fmt);
  1456. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1457. va_end(args);
  1458. putc('\n', DEBUG_TRACE_STREAM);
  1459. fflush(DEBUG_TRACE_STREAM);
  1460. funlockfile(DEBUG_TRACE_STREAM);
  1461. }
  1462. #endif /* NEED_DEBUG_TRACE_FUNC */
  1463. #define MD5_STATIC static
  1464. #include "md5.inl"
  1465. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1466. #if defined(NO_SOCKLEN_T)
  1467. typedef int socklen_t;
  1468. #endif /* NO_SOCKLEN_T */
  1469. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1470. #if !defined(MSG_NOSIGNAL)
  1471. #define MSG_NOSIGNAL (0)
  1472. #endif
  1473. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1474. #if defined(USE_MBEDTLS)
  1475. /* mbedTLS */
  1476. #include "mod_mbedtls.inl"
  1477. #elif defined(NO_SSL)
  1478. /* no SSL */
  1479. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1480. typedef struct SSL_CTX SSL_CTX;
  1481. #elif defined(NO_SSL_DL)
  1482. /* OpenSSL without dynamic loading */
  1483. #include <openssl/bn.h>
  1484. #include <openssl/conf.h>
  1485. #include <openssl/crypto.h>
  1486. #include <openssl/dh.h>
  1487. #include <openssl/engine.h>
  1488. #include <openssl/err.h>
  1489. #include <openssl/opensslv.h>
  1490. #include <openssl/pem.h>
  1491. #include <openssl/ssl.h>
  1492. #include <openssl/tls1.h>
  1493. #include <openssl/x509.h>
  1494. #if defined(WOLFSSL_VERSION)
  1495. /* Additional defines for WolfSSL, see
  1496. * https://github.com/civetweb/civetweb/issues/583 */
  1497. #include "wolfssl_extras.inl"
  1498. #endif
  1499. #if defined(OPENSSL_IS_BORINGSSL)
  1500. /* From boringssl/src/include/openssl/mem.h:
  1501. *
  1502. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1503. * However, that was written in a time before Valgrind and ASAN. Since we now
  1504. * have those tools, the OpenSSL allocation functions are simply macros around
  1505. * the standard memory functions.
  1506. *
  1507. * #define OPENSSL_free free */
  1508. #define free free
  1509. // disable for boringssl
  1510. #define CONF_modules_unload(a) ((void)0)
  1511. #define ENGINE_cleanup() ((void)0)
  1512. #endif
  1513. /* If OpenSSL headers are included, automatically select the API version */
  1514. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1515. #if !defined(OPENSSL_API_3_0)
  1516. #define OPENSSL_API_3_0
  1517. #endif
  1518. #define OPENSSL_REMOVE_THREAD_STATE()
  1519. #else
  1520. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1521. #if !defined(OPENSSL_API_1_1)
  1522. #define OPENSSL_API_1_1
  1523. #endif
  1524. #define OPENSSL_REMOVE_THREAD_STATE()
  1525. #else
  1526. #if !defined(OPENSSL_API_1_0)
  1527. #define OPENSSL_API_1_0
  1528. #endif
  1529. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1530. #endif
  1531. #endif
  1532. #else
  1533. /* SSL loaded dynamically from DLL / shared object */
  1534. /* Add all prototypes here, to be independent from OpenSSL source
  1535. * installation. */
  1536. #include "openssl_dl.inl"
  1537. #endif /* Various SSL bindings */
  1538. #if !defined(NO_CACHING)
  1539. static const char month_names[][4] = {"Jan",
  1540. "Feb",
  1541. "Mar",
  1542. "Apr",
  1543. "May",
  1544. "Jun",
  1545. "Jul",
  1546. "Aug",
  1547. "Sep",
  1548. "Oct",
  1549. "Nov",
  1550. "Dec"};
  1551. #endif /* !NO_CACHING */
  1552. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1553. * the union u. */
  1554. union usa {
  1555. struct sockaddr sa;
  1556. struct sockaddr_in sin;
  1557. #if defined(USE_IPV6)
  1558. struct sockaddr_in6 sin6;
  1559. #endif
  1560. #if defined(USE_X_DOM_SOCKET)
  1561. struct sockaddr_un sun;
  1562. #endif
  1563. };
  1564. #if defined(USE_X_DOM_SOCKET)
  1565. static unsigned short
  1566. USA_IN_PORT_UNSAFE(union usa *s)
  1567. {
  1568. if (s->sa.sa_family == AF_INET)
  1569. return s->sin.sin_port;
  1570. #if defined(USE_IPV6)
  1571. if (s->sa.sa_family == AF_INET6)
  1572. return s->sin6.sin6_port;
  1573. #endif
  1574. return 0;
  1575. }
  1576. #endif
  1577. #if defined(USE_IPV6)
  1578. #define USA_IN_PORT_UNSAFE(s) \
  1579. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1580. #else
  1581. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1582. #endif
  1583. /* Describes a string (chunk of memory). */
  1584. struct vec {
  1585. const char *ptr;
  1586. size_t len;
  1587. };
  1588. struct mg_file_stat {
  1589. /* File properties filled by mg_stat: */
  1590. uint64_t size;
  1591. time_t last_modified;
  1592. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1593. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1594. * case we need a "Content-Eencoding: gzip" header */
  1595. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1596. };
  1597. struct mg_file_access {
  1598. /* File properties filled by mg_fopen: */
  1599. FILE *fp;
  1600. };
  1601. struct mg_file {
  1602. struct mg_file_stat stat;
  1603. struct mg_file_access access;
  1604. };
  1605. #define STRUCT_FILE_INITIALIZER \
  1606. { \
  1607. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1608. { \
  1609. (FILE *)NULL \
  1610. } \
  1611. }
  1612. /* Describes listening socket, or socket which was accept()-ed by the master
  1613. * thread and queued for future handling by the worker thread. */
  1614. struct socket {
  1615. SOCKET sock; /* Listening socket */
  1616. union usa lsa; /* Local socket address */
  1617. union usa rsa; /* Remote socket address */
  1618. unsigned char is_ssl; /* Is port SSL-ed */
  1619. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1620. * port */
  1621. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1622. };
  1623. /* Enum const for all options must be in sync with
  1624. * static struct mg_option config_options[]
  1625. * This is tested in the unit test (test/private.c)
  1626. * "Private Config Options"
  1627. */
  1628. enum {
  1629. /* Once for each server */
  1630. LISTENING_PORTS,
  1631. NUM_THREADS,
  1632. PRESPAWN_THREADS,
  1633. RUN_AS_USER,
  1634. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1635. * socket option typedef TCP_NODELAY. */
  1636. MAX_REQUEST_SIZE,
  1637. LINGER_TIMEOUT,
  1638. CONNECTION_QUEUE_SIZE,
  1639. LISTEN_BACKLOG_SIZE,
  1640. #if defined(__linux__)
  1641. ALLOW_SENDFILE_CALL,
  1642. #endif
  1643. #if defined(_WIN32)
  1644. CASE_SENSITIVE_FILES,
  1645. #endif
  1646. THROTTLE,
  1647. ENABLE_KEEP_ALIVE,
  1648. REQUEST_TIMEOUT,
  1649. KEEP_ALIVE_TIMEOUT,
  1650. #if defined(USE_WEBSOCKET)
  1651. WEBSOCKET_TIMEOUT,
  1652. ENABLE_WEBSOCKET_PING_PONG,
  1653. #endif
  1654. DECODE_URL,
  1655. DECODE_QUERY_STRING,
  1656. #if defined(USE_LUA)
  1657. LUA_BACKGROUND_SCRIPT,
  1658. LUA_BACKGROUND_SCRIPT_PARAMS,
  1659. #endif
  1660. #if defined(USE_HTTP2)
  1661. ENABLE_HTTP2,
  1662. #endif
  1663. /* Once for each domain */
  1664. DOCUMENT_ROOT,
  1665. FALLBACK_DOCUMENT_ROOT,
  1666. ACCESS_LOG_FILE,
  1667. ERROR_LOG_FILE,
  1668. CGI_EXTENSIONS,
  1669. CGI_ENVIRONMENT,
  1670. CGI_INTERPRETER,
  1671. CGI_INTERPRETER_ARGS,
  1672. #if defined(USE_TIMERS)
  1673. CGI_TIMEOUT,
  1674. #endif
  1675. CGI_BUFFERING,
  1676. CGI2_EXTENSIONS,
  1677. CGI2_ENVIRONMENT,
  1678. CGI2_INTERPRETER,
  1679. CGI2_INTERPRETER_ARGS,
  1680. #if defined(USE_TIMERS)
  1681. CGI2_TIMEOUT,
  1682. #endif
  1683. CGI2_BUFFERING,
  1684. #if defined(USE_4_CGI)
  1685. CGI3_EXTENSIONS,
  1686. CGI3_ENVIRONMENT,
  1687. CGI3_INTERPRETER,
  1688. CGI3_INTERPRETER_ARGS,
  1689. #if defined(USE_TIMERS)
  1690. CGI3_TIMEOUT,
  1691. #endif
  1692. CGI3_BUFFERING,
  1693. CGI4_EXTENSIONS,
  1694. CGI4_ENVIRONMENT,
  1695. CGI4_INTERPRETER,
  1696. CGI4_INTERPRETER_ARGS,
  1697. #if defined(USE_TIMERS)
  1698. CGI4_TIMEOUT,
  1699. #endif
  1700. CGI4_BUFFERING,
  1701. #endif
  1702. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1703. PROTECT_URI,
  1704. AUTHENTICATION_DOMAIN,
  1705. ENABLE_AUTH_DOMAIN_CHECK,
  1706. SSI_EXTENSIONS,
  1707. ENABLE_DIRECTORY_LISTING,
  1708. ENABLE_WEBDAV,
  1709. GLOBAL_PASSWORDS_FILE,
  1710. INDEX_FILES,
  1711. ACCESS_CONTROL_LIST,
  1712. EXTRA_MIME_TYPES,
  1713. SSL_CERTIFICATE,
  1714. SSL_CERTIFICATE_CHAIN,
  1715. URL_REWRITE_PATTERN,
  1716. HIDE_FILES,
  1717. SSL_DO_VERIFY_PEER,
  1718. SSL_CACHE_TIMEOUT,
  1719. SSL_CA_PATH,
  1720. SSL_CA_FILE,
  1721. SSL_VERIFY_DEPTH,
  1722. SSL_DEFAULT_VERIFY_PATHS,
  1723. SSL_CIPHER_LIST,
  1724. SSL_PROTOCOL_VERSION,
  1725. SSL_SHORT_TRUST,
  1726. #if defined(USE_LUA)
  1727. LUA_PRELOAD_FILE,
  1728. LUA_SCRIPT_EXTENSIONS,
  1729. LUA_SERVER_PAGE_EXTENSIONS,
  1730. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1731. LUA_DEBUG_PARAMS,
  1732. #endif
  1733. #endif
  1734. #if defined(USE_DUKTAPE)
  1735. DUKTAPE_SCRIPT_EXTENSIONS,
  1736. #endif
  1737. #if defined(USE_WEBSOCKET)
  1738. WEBSOCKET_ROOT,
  1739. FALLBACK_WEBSOCKET_ROOT,
  1740. #endif
  1741. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1742. LUA_WEBSOCKET_EXTENSIONS,
  1743. #endif
  1744. ACCESS_CONTROL_ALLOW_ORIGIN,
  1745. ACCESS_CONTROL_ALLOW_METHODS,
  1746. ACCESS_CONTROL_ALLOW_HEADERS,
  1747. ERROR_PAGES,
  1748. #if !defined(NO_CACHING)
  1749. STATIC_FILE_MAX_AGE,
  1750. STATIC_FILE_CACHE_CONTROL,
  1751. #endif
  1752. #if !defined(NO_SSL)
  1753. STRICT_HTTPS_MAX_AGE,
  1754. #endif
  1755. ADDITIONAL_HEADER,
  1756. ALLOW_INDEX_SCRIPT_SUB_RES,
  1757. NUM_OPTIONS
  1758. };
  1759. /* Config option name, config types, default value.
  1760. * Must be in the same order as the enum const above.
  1761. */
  1762. static const struct mg_option config_options[] = {
  1763. /* Once for each server */
  1764. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1765. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1766. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1767. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1768. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1769. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1770. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1771. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1772. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1773. #if defined(__linux__)
  1774. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1775. #endif
  1776. #if defined(_WIN32)
  1777. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1778. #endif
  1779. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1780. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1781. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1782. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1783. #if defined(USE_WEBSOCKET)
  1784. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1785. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1786. #endif
  1787. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1788. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1789. #if defined(USE_LUA)
  1790. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1791. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1792. #endif
  1793. #if defined(USE_HTTP2)
  1794. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1795. #endif
  1796. /* Once for each domain */
  1797. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1798. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1799. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1800. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1801. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1802. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1803. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1804. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1805. #if defined(USE_TIMERS)
  1806. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1807. #endif
  1808. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1809. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1810. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1811. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1812. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1813. #if defined(USE_TIMERS)
  1814. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1815. #endif
  1816. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1817. #if defined(USE_4_CGI)
  1818. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1819. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1820. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1821. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1822. #if defined(USE_TIMERS)
  1823. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1824. #endif
  1825. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1826. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1827. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1828. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1829. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1830. #if defined(USE_TIMERS)
  1831. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1832. #endif
  1833. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1834. #endif
  1835. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1836. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1837. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1838. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1839. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1840. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1841. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1842. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1843. {"index_files",
  1844. MG_CONFIG_TYPE_STRING_LIST,
  1845. #if defined(USE_LUA)
  1846. "index.xhtml,index.html,index.htm,"
  1847. "index.lp,index.lsp,index.lua,index.cgi,"
  1848. "index.shtml,index.php"},
  1849. #else
  1850. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1851. #endif
  1852. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1853. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1854. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1855. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1856. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1858. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1859. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1860. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1861. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1862. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1863. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1864. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1865. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1866. * as a minimum in 2020 */
  1867. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1868. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1869. #if defined(USE_LUA)
  1870. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1871. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1872. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1873. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1874. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1875. #endif
  1876. #endif
  1877. #if defined(USE_DUKTAPE)
  1878. /* The support for duktape is still in alpha version state.
  1879. * The name of this config option might change. */
  1880. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1881. #endif
  1882. #if defined(USE_WEBSOCKET)
  1883. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1884. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1885. #endif
  1886. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1887. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1888. #endif
  1889. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1890. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1891. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1892. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1893. #if !defined(NO_CACHING)
  1894. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1895. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1896. #endif
  1897. #if !defined(NO_SSL)
  1898. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1899. #endif
  1900. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1901. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1902. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1903. /* Check if the config_options and the corresponding enum have compatible
  1904. * sizes. */
  1905. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1906. == (NUM_OPTIONS + 1),
  1907. "config_options and enum not sync");
  1908. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1909. struct mg_handler_info {
  1910. /* Name/Pattern of the URI. */
  1911. char *uri;
  1912. size_t uri_len;
  1913. /* handler type */
  1914. int handler_type;
  1915. /* Handler for http/https or requests. */
  1916. mg_request_handler handler;
  1917. unsigned int refcount;
  1918. int removing;
  1919. /* Handler for ws/wss (websocket) requests. */
  1920. mg_websocket_connect_handler connect_handler;
  1921. mg_websocket_ready_handler ready_handler;
  1922. mg_websocket_data_handler data_handler;
  1923. mg_websocket_close_handler close_handler;
  1924. /* accepted subprotocols for ws/wss requests. */
  1925. struct mg_websocket_subprotocols *subprotocols;
  1926. /* Handler for authorization requests */
  1927. mg_authorization_handler auth_handler;
  1928. /* User supplied argument for the handler function. */
  1929. void *cbdata;
  1930. /* next handler in a linked list */
  1931. struct mg_handler_info *next;
  1932. };
  1933. enum {
  1934. CONTEXT_INVALID,
  1935. CONTEXT_SERVER,
  1936. CONTEXT_HTTP_CLIENT,
  1937. CONTEXT_WS_CLIENT
  1938. };
  1939. struct mg_domain_context {
  1940. SSL_CTX *ssl_ctx; /* SSL context */
  1941. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1942. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1943. int64_t ssl_cert_last_mtime;
  1944. /* Server nonce */
  1945. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1946. unsigned long nonce_count; /* Used nonces, used for authentication */
  1947. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1948. /* linked list of shared lua websockets */
  1949. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1950. #endif
  1951. /* Linked list of domains */
  1952. struct mg_domain_context *next;
  1953. };
  1954. /* Stop flag can be "volatile" or require a lock.
  1955. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1956. * states a read operation for int is always atomic. */
  1957. #if defined(STOP_FLAG_NEEDS_LOCK)
  1958. typedef ptrdiff_t volatile stop_flag_t;
  1959. static int
  1960. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1961. {
  1962. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1963. return (sf == 0);
  1964. }
  1965. static int
  1966. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1967. {
  1968. stop_flag_t sf = mg_atomic_add(f, 0);
  1969. return (sf == 2);
  1970. }
  1971. static void
  1972. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1973. {
  1974. stop_flag_t sf = 0;
  1975. do {
  1976. sf = mg_atomic_compare_and_swap(f, *f, v);
  1977. } while (sf != v);
  1978. }
  1979. #else /* STOP_FLAG_NEEDS_LOCK */
  1980. typedef int volatile stop_flag_t;
  1981. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1982. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1983. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1984. #endif /* STOP_FLAG_NEEDS_LOCK */
  1985. #if !defined(NUM_WEBDAV_LOCKS)
  1986. #define NUM_WEBDAV_LOCKS 10
  1987. #endif
  1988. #if !defined(LOCK_DURATION_S)
  1989. #define LOCK_DURATION_S 60
  1990. #endif
  1991. struct twebdav_lock {
  1992. uint64_t locktime;
  1993. char token[33];
  1994. char path[UTF8_PATH_MAX * 2];
  1995. char user[UTF8_PATH_MAX * 2];
  1996. };
  1997. struct mg_context {
  1998. /* Part 1 - Physical context:
  1999. * This holds threads, ports, timeouts, ...
  2000. * set for the entire server, independent from the
  2001. * addressed hostname.
  2002. */
  2003. /* Connection related */
  2004. int context_type; /* See CONTEXT_* above */
  2005. struct socket *listening_sockets;
  2006. struct mg_pollfd *listening_socket_fds;
  2007. unsigned int num_listening_sockets;
  2008. struct mg_connection *worker_connections; /* The connection struct, pre-
  2009. * allocated for each worker */
  2010. #if defined(USE_SERVER_STATS)
  2011. volatile ptrdiff_t active_connections;
  2012. volatile ptrdiff_t max_active_connections;
  2013. volatile ptrdiff_t total_connections;
  2014. volatile ptrdiff_t total_requests;
  2015. volatile int64_t total_data_read;
  2016. volatile int64_t total_data_written;
  2017. #endif
  2018. /* Thread related */
  2019. stop_flag_t stop_flag; /* Should we stop event loop */
  2020. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2021. pthread_t masterthreadid; /* The master thread ID */
  2022. unsigned int
  2023. cfg_max_worker_threads; /* How many worker-threads we are allowed to create, total */
  2024. unsigned int
  2025. spawned_worker_threads; /* How many worker-threads currently exist (modified by master thread) */
  2026. unsigned int
  2027. idle_worker_thread_count; /* How many worker-threads are currently sitting around with nothing to do */
  2028. /* Access to this value MUST be synchronized by thread_mutex */
  2029. pthread_t *worker_threadids; /* The worker thread IDs */
  2030. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2031. /* Connection to thread dispatching */
  2032. #if defined(ALTERNATIVE_QUEUE)
  2033. struct socket *client_socks;
  2034. void **client_wait_events;
  2035. #else
  2036. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2037. worker thread */
  2038. volatile int sq_head; /* Head of the socket queue */
  2039. volatile int sq_tail; /* Tail of the socket queue */
  2040. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2041. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2042. volatile int sq_blocked; /* Status information: sq is full */
  2043. int sq_size; /* No of elements in socket queue */
  2044. #if defined(USE_SERVER_STATS)
  2045. int sq_max_fill;
  2046. #endif /* USE_SERVER_STATS */
  2047. #endif /* ALTERNATIVE_QUEUE */
  2048. /* Memory related */
  2049. unsigned int max_request_size; /* The max request size */
  2050. #if defined(USE_SERVER_STATS)
  2051. struct mg_memory_stat ctx_memory;
  2052. #endif
  2053. /* WebDAV lock structures */
  2054. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2055. /* Operating system related */
  2056. char *systemName; /* What operating system is running */
  2057. time_t start_time; /* Server start time, used for authentication
  2058. * and for diagnstics. */
  2059. #if defined(USE_TIMERS)
  2060. struct ttimers *timers;
  2061. #endif
  2062. /* Lua specific: Background operations and shared websockets */
  2063. #if defined(USE_LUA)
  2064. void *lua_background_state; /* lua_State (here as void *) */
  2065. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2066. int lua_bg_log_available; /* Use Lua background state for access log */
  2067. #endif
  2068. /* Server nonce */
  2069. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2070. * ssl_cert_last_mtime, nonce_count, and
  2071. * next (linked list) */
  2072. /* Server callbacks */
  2073. struct mg_callbacks callbacks; /* User-defined callback function */
  2074. void *user_data; /* User-defined data */
  2075. /* Part 2 - Logical domain:
  2076. * This holds hostname, TLS certificate, document root, ...
  2077. * set for a domain hosted at the server.
  2078. * There may be multiple domains hosted at one physical server.
  2079. * The default domain "dd" is the first element of a list of
  2080. * domains.
  2081. */
  2082. struct mg_domain_context dd; /* default domain */
  2083. };
  2084. #if defined(USE_SERVER_STATS)
  2085. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2086. static struct mg_memory_stat *
  2087. get_memory_stat(struct mg_context *ctx)
  2088. {
  2089. if (ctx) {
  2090. return &(ctx->ctx_memory);
  2091. }
  2092. return &mg_common_memory;
  2093. }
  2094. #endif
  2095. enum {
  2096. CONNECTION_TYPE_INVALID = 0,
  2097. CONNECTION_TYPE_REQUEST = 1,
  2098. CONNECTION_TYPE_RESPONSE = 2
  2099. };
  2100. enum {
  2101. PROTOCOL_TYPE_HTTP1 = 0,
  2102. PROTOCOL_TYPE_WEBSOCKET = 1,
  2103. PROTOCOL_TYPE_HTTP2 = 2
  2104. };
  2105. #if defined(USE_HTTP2)
  2106. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2107. #define HTTP2_DYN_TABLE_SIZE (256)
  2108. #endif
  2109. struct mg_http2_connection {
  2110. uint32_t stream_id;
  2111. uint32_t dyn_table_size;
  2112. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2113. };
  2114. #endif
  2115. struct mg_connection {
  2116. int connection_type; /* see CONNECTION_TYPE_* above */
  2117. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2118. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2119. fully sent */
  2120. #if defined(USE_HTTP2)
  2121. struct mg_http2_connection http2;
  2122. #endif
  2123. struct mg_request_info request_info;
  2124. struct mg_response_info response_info;
  2125. struct mg_context *phys_ctx;
  2126. struct mg_domain_context *dom_ctx;
  2127. #if defined(USE_SERVER_STATS)
  2128. int conn_state; /* 0 = undef, numerical value may change in different
  2129. * versions. For the current definition, see
  2130. * mg_get_connection_info_impl */
  2131. #endif
  2132. SSL *ssl; /* SSL descriptor */
  2133. struct socket client; /* Connected client */
  2134. time_t conn_birth_time; /* Time (wall clock) when connection was
  2135. * established */
  2136. #if defined(USE_SERVER_STATS)
  2137. time_t conn_close_time; /* Time (wall clock) when connection was
  2138. * closed (or 0 if still open) */
  2139. double processing_time; /* Processing time for one request. */
  2140. #endif
  2141. struct timespec req_time; /* Time (since system start) when the request
  2142. * was received */
  2143. int64_t num_bytes_sent; /* Total bytes sent to client */
  2144. int64_t content_len; /* How many bytes of content can be read
  2145. * !is_chunked: Content-Length header value
  2146. * or -1 (until connection closed,
  2147. * not allowed for a request)
  2148. * is_chunked: >= 0, appended gradually
  2149. */
  2150. int64_t consumed_content; /* How many bytes of content have been read */
  2151. int is_chunked; /* Transfer-Encoding is chunked:
  2152. * 0 = not chunked,
  2153. * 1 = chunked, not yet, or some data read,
  2154. * 2 = chunked, has error,
  2155. * 3 = chunked, all data read except trailer,
  2156. * 4 = chunked, all data read
  2157. */
  2158. char *buf; /* Buffer for received data */
  2159. char *path_info; /* PATH_INFO part of the URL */
  2160. int must_close; /* 1 if connection must be closed */
  2161. int accept_gzip; /* 1 if gzip encoding is accepted */
  2162. int in_error_handler; /* 1 if in handler for user defined error
  2163. * pages */
  2164. #if defined(USE_WEBSOCKET)
  2165. int in_websocket_handling; /* 1 if in read_websocket */
  2166. #endif
  2167. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2168. && defined(MG_EXPERIMENTAL_INTERFACES)
  2169. /* Parameters for websocket data compression according to rfc7692 */
  2170. int websocket_deflate_server_max_windows_bits;
  2171. int websocket_deflate_client_max_windows_bits;
  2172. int websocket_deflate_server_no_context_takeover;
  2173. int websocket_deflate_client_no_context_takeover;
  2174. int websocket_deflate_initialized;
  2175. int websocket_deflate_flush;
  2176. z_stream websocket_deflate_state;
  2177. z_stream websocket_inflate_state;
  2178. #endif
  2179. int handled_requests; /* Number of requests handled by this connection
  2180. */
  2181. int buf_size; /* Buffer size */
  2182. int request_len; /* Size of the request + headers in a buffer */
  2183. int data_len; /* Total size of data in a buffer */
  2184. int status_code; /* HTTP reply status code, e.g. 200 */
  2185. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2186. * throttle */
  2187. time_t last_throttle_time; /* Last time throttled data was sent */
  2188. int last_throttle_bytes; /* Bytes sent this second */
  2189. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2190. * atomic transmissions for websockets */
  2191. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2192. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2193. #endif
  2194. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2195. * for quick access */
  2196. };
  2197. /* Directory entry */
  2198. struct de {
  2199. char *file_name;
  2200. struct mg_file_stat file;
  2201. };
  2202. #define mg_cry_internal(conn, fmt, ...) \
  2203. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2204. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2205. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2206. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2207. struct mg_context *ctx,
  2208. const char *func,
  2209. unsigned line,
  2210. const char *fmt,
  2211. ...) PRINTF_ARGS(5, 6);
  2212. #if !defined(NO_THREAD_NAME)
  2213. #if defined(_WIN32) && defined(_MSC_VER)
  2214. /* Set the thread name for debugging purposes in Visual Studio
  2215. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2216. */
  2217. #pragma pack(push, 8)
  2218. typedef struct tagTHREADNAME_INFO {
  2219. DWORD dwType; /* Must be 0x1000. */
  2220. LPCSTR szName; /* Pointer to name (in user addr space). */
  2221. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2222. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2223. } THREADNAME_INFO;
  2224. #pragma pack(pop)
  2225. #elif defined(__linux__)
  2226. #include <sys/prctl.h>
  2227. #include <sys/sendfile.h>
  2228. #if defined(ALTERNATIVE_QUEUE)
  2229. #include <sys/eventfd.h>
  2230. #endif /* ALTERNATIVE_QUEUE */
  2231. #if defined(ALTERNATIVE_QUEUE)
  2232. static void *
  2233. event_create(void)
  2234. {
  2235. int evhdl = eventfd(0, EFD_CLOEXEC);
  2236. int *ret;
  2237. if (evhdl == -1) {
  2238. /* Linux uses -1 on error, Windows NULL. */
  2239. /* However, Linux does not return 0 on success either. */
  2240. return 0;
  2241. }
  2242. ret = (int *)mg_malloc(sizeof(int));
  2243. if (ret) {
  2244. *ret = evhdl;
  2245. } else {
  2246. (void)close(evhdl);
  2247. }
  2248. return (void *)ret;
  2249. }
  2250. static int
  2251. event_wait(void *eventhdl)
  2252. {
  2253. uint64_t u;
  2254. int evhdl, s;
  2255. if (!eventhdl) {
  2256. /* error */
  2257. return 0;
  2258. }
  2259. evhdl = *(int *)eventhdl;
  2260. s = (int)read(evhdl, &u, sizeof(u));
  2261. if (s != sizeof(u)) {
  2262. /* error */
  2263. return 0;
  2264. }
  2265. (void)u; /* the value is not required */
  2266. return 1;
  2267. }
  2268. static int
  2269. event_signal(void *eventhdl)
  2270. {
  2271. uint64_t u = 1;
  2272. int evhdl, s;
  2273. if (!eventhdl) {
  2274. /* error */
  2275. return 0;
  2276. }
  2277. evhdl = *(int *)eventhdl;
  2278. s = (int)write(evhdl, &u, sizeof(u));
  2279. if (s != sizeof(u)) {
  2280. /* error */
  2281. return 0;
  2282. }
  2283. return 1;
  2284. }
  2285. static void
  2286. event_destroy(void *eventhdl)
  2287. {
  2288. int evhdl;
  2289. if (!eventhdl) {
  2290. /* error */
  2291. return;
  2292. }
  2293. evhdl = *(int *)eventhdl;
  2294. close(evhdl);
  2295. mg_free(eventhdl);
  2296. }
  2297. #endif
  2298. #endif
  2299. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2300. struct posix_event {
  2301. pthread_mutex_t mutex;
  2302. pthread_cond_t cond;
  2303. int signaled;
  2304. };
  2305. static void *
  2306. event_create(void)
  2307. {
  2308. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2309. if (ret == 0) {
  2310. /* out of memory */
  2311. return 0;
  2312. }
  2313. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2314. /* pthread mutex not available */
  2315. mg_free(ret);
  2316. return 0;
  2317. }
  2318. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2319. /* pthread cond not available */
  2320. pthread_mutex_destroy(&(ret->mutex));
  2321. mg_free(ret);
  2322. return 0;
  2323. }
  2324. ret->signaled = 0;
  2325. return (void *)ret;
  2326. }
  2327. static int
  2328. event_wait(void *eventhdl)
  2329. {
  2330. struct posix_event *ev = (struct posix_event *)eventhdl;
  2331. pthread_mutex_lock(&(ev->mutex));
  2332. while (!ev->signaled) {
  2333. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2334. }
  2335. ev->signaled = 0;
  2336. pthread_mutex_unlock(&(ev->mutex));
  2337. return 1;
  2338. }
  2339. static int
  2340. event_signal(void *eventhdl)
  2341. {
  2342. struct posix_event *ev = (struct posix_event *)eventhdl;
  2343. pthread_mutex_lock(&(ev->mutex));
  2344. pthread_cond_signal(&(ev->cond));
  2345. ev->signaled = 1;
  2346. pthread_mutex_unlock(&(ev->mutex));
  2347. return 1;
  2348. }
  2349. static void
  2350. event_destroy(void *eventhdl)
  2351. {
  2352. struct posix_event *ev = (struct posix_event *)eventhdl;
  2353. pthread_cond_destroy(&(ev->cond));
  2354. pthread_mutex_destroy(&(ev->mutex));
  2355. mg_free(ev);
  2356. }
  2357. #endif
  2358. static void
  2359. mg_set_thread_name(const char *name)
  2360. {
  2361. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2362. mg_snprintf(
  2363. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2364. #if defined(_WIN32)
  2365. #if defined(_MSC_VER)
  2366. /* Windows and Visual Studio Compiler */
  2367. __try {
  2368. THREADNAME_INFO info;
  2369. info.dwType = 0x1000;
  2370. info.szName = threadName;
  2371. info.dwThreadID = ~0U;
  2372. info.dwFlags = 0;
  2373. RaiseException(0x406D1388,
  2374. 0,
  2375. sizeof(info) / sizeof(ULONG_PTR),
  2376. (ULONG_PTR *)&info);
  2377. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2378. }
  2379. #elif defined(__MINGW32__)
  2380. /* No option known to set thread name for MinGW known */
  2381. #endif
  2382. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2383. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2384. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2385. #if defined(__MACH__) && defined(__APPLE__)
  2386. /* OS X only current thread name can be changed */
  2387. (void)pthread_setname_np(threadName);
  2388. #else
  2389. (void)pthread_setname_np(pthread_self(), threadName);
  2390. #endif
  2391. #elif defined(__linux__)
  2392. /* On Linux we can use the prctl function.
  2393. * When building for Linux Standard Base (LSB) use
  2394. * NO_THREAD_NAME. However, thread names are a big
  2395. * help for debugging, so the stadard is to set them.
  2396. */
  2397. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2398. #endif
  2399. }
  2400. #else /* !defined(NO_THREAD_NAME) */
  2401. static void
  2402. mg_set_thread_name(const char *threadName)
  2403. {
  2404. }
  2405. #endif
  2406. CIVETWEB_API const struct mg_option *
  2407. mg_get_valid_options(void)
  2408. {
  2409. return config_options;
  2410. }
  2411. /* Do not open file (unused) */
  2412. #define MG_FOPEN_MODE_NONE (0)
  2413. /* Open file for read only access */
  2414. #define MG_FOPEN_MODE_READ (1)
  2415. /* Open file for writing, create and overwrite */
  2416. #define MG_FOPEN_MODE_WRITE (2)
  2417. /* Open file for writing, create and append */
  2418. #define MG_FOPEN_MODE_APPEND (4)
  2419. static int
  2420. is_file_opened(const struct mg_file_access *fileacc)
  2421. {
  2422. if (!fileacc) {
  2423. return 0;
  2424. }
  2425. return (fileacc->fp != NULL);
  2426. }
  2427. #if !defined(NO_FILESYSTEMS)
  2428. static int mg_stat(const struct mg_connection *conn,
  2429. const char *path,
  2430. struct mg_file_stat *filep);
  2431. /* Reject files with special characters (for Windows) */
  2432. static int
  2433. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2434. {
  2435. const uint8_t *c = (const uint8_t *)path;
  2436. (void)conn; /* not used */
  2437. if ((c == NULL) || (c[0] == 0)) {
  2438. /* Null pointer or empty path --> suspicious */
  2439. return 1;
  2440. }
  2441. #if defined(_WIN32)
  2442. while (*c) {
  2443. if (*c < 32) {
  2444. /* Control character */
  2445. return 1;
  2446. }
  2447. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2448. /* stdin/stdout redirection character */
  2449. return 1;
  2450. }
  2451. if ((*c == '*') || (*c == '?')) {
  2452. /* Wildcard character */
  2453. return 1;
  2454. }
  2455. if (*c == '"') {
  2456. /* Windows quotation */
  2457. return 1;
  2458. }
  2459. c++;
  2460. }
  2461. #endif
  2462. /* Nothing suspicious found */
  2463. return 0;
  2464. }
  2465. /* mg_fopen will open a file either in memory or on the disk.
  2466. * The input parameter path is a string in UTF-8 encoding.
  2467. * The input parameter mode is MG_FOPEN_MODE_*
  2468. * On success, fp will be set in the output struct mg_file.
  2469. * All status members will also be set.
  2470. * The function returns 1 on success, 0 on error. */
  2471. static int
  2472. mg_fopen(const struct mg_connection *conn,
  2473. const char *path,
  2474. int mode,
  2475. struct mg_file *filep)
  2476. {
  2477. int found;
  2478. if (!filep) {
  2479. return 0;
  2480. }
  2481. filep->access.fp = NULL;
  2482. if (mg_path_suspicious(conn, path)) {
  2483. return 0;
  2484. }
  2485. /* filep is initialized in mg_stat: all fields with memset to,
  2486. * some fields like size and modification date with values */
  2487. found = mg_stat(conn, path, &(filep->stat));
  2488. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2489. /* file does not exist and will not be created */
  2490. return 0;
  2491. }
  2492. #if defined(_WIN32)
  2493. {
  2494. wchar_t wbuf[UTF16_PATH_MAX];
  2495. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2496. switch (mode) {
  2497. case MG_FOPEN_MODE_READ:
  2498. filep->access.fp = _wfopen(wbuf, L"rb");
  2499. break;
  2500. case MG_FOPEN_MODE_WRITE:
  2501. filep->access.fp = _wfopen(wbuf, L"wb");
  2502. break;
  2503. case MG_FOPEN_MODE_APPEND:
  2504. filep->access.fp = _wfopen(wbuf, L"ab");
  2505. break;
  2506. }
  2507. }
  2508. #else
  2509. /* Linux et al already use unicode. No need to convert. */
  2510. switch (mode) {
  2511. case MG_FOPEN_MODE_READ:
  2512. filep->access.fp = fopen(path, "r");
  2513. break;
  2514. case MG_FOPEN_MODE_WRITE:
  2515. filep->access.fp = fopen(path, "w");
  2516. break;
  2517. case MG_FOPEN_MODE_APPEND:
  2518. filep->access.fp = fopen(path, "a");
  2519. break;
  2520. }
  2521. #endif
  2522. if (!found) {
  2523. /* File did not exist before fopen was called.
  2524. * Maybe it has been created now. Get stat info
  2525. * like creation time now. */
  2526. found = mg_stat(conn, path, &(filep->stat));
  2527. (void)found;
  2528. }
  2529. /* return OK if file is opened */
  2530. return (filep->access.fp != NULL);
  2531. }
  2532. /* return 0 on success, just like fclose */
  2533. static int
  2534. mg_fclose(struct mg_file_access *fileacc)
  2535. {
  2536. int ret = -1;
  2537. if (fileacc != NULL) {
  2538. if (fileacc->fp != NULL) {
  2539. ret = fclose(fileacc->fp);
  2540. }
  2541. /* reset all members of fileacc */
  2542. memset(fileacc, 0, sizeof(*fileacc));
  2543. }
  2544. return ret;
  2545. }
  2546. #endif /* NO_FILESYSTEMS */
  2547. static void
  2548. mg_strlcpy(char *dst, const char *src, size_t n)
  2549. {
  2550. for (; *src != '\0' && n > 1; n--) {
  2551. *dst++ = *src++;
  2552. }
  2553. *dst = '\0';
  2554. }
  2555. static int
  2556. lowercase(const char *s)
  2557. {
  2558. return tolower((unsigned char)*s);
  2559. }
  2560. CIVETWEB_API int
  2561. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2562. {
  2563. int diff = 0;
  2564. if (len > 0) {
  2565. do {
  2566. diff = lowercase(s1++) - lowercase(s2++);
  2567. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2568. }
  2569. return diff;
  2570. }
  2571. CIVETWEB_API int
  2572. mg_strcasecmp(const char *s1, const char *s2)
  2573. {
  2574. int diff;
  2575. do {
  2576. diff = lowercase(s1++) - lowercase(s2++);
  2577. } while (diff == 0 && s1[-1] != '\0');
  2578. return diff;
  2579. }
  2580. static char *
  2581. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2582. {
  2583. char *p;
  2584. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2585. * defined */
  2586. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2587. mg_strlcpy(p, ptr, len + 1);
  2588. }
  2589. return p;
  2590. }
  2591. static char *
  2592. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2593. {
  2594. return mg_strndup_ctx(str, strlen(str), ctx);
  2595. }
  2596. static char *
  2597. mg_strdup(const char *str)
  2598. {
  2599. return mg_strndup_ctx(str, strlen(str), NULL);
  2600. }
  2601. static const char *
  2602. mg_strcasestr(const char *big_str, const char *small_str)
  2603. {
  2604. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2605. if (big_len >= small_len) {
  2606. for (i = 0; i <= (big_len - small_len); i++) {
  2607. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2608. return big_str + i;
  2609. }
  2610. }
  2611. }
  2612. return NULL;
  2613. }
  2614. /* Return null terminated string of given maximum length.
  2615. * Report errors if length is exceeded. */
  2616. static void
  2617. mg_vsnprintf(const struct mg_connection *conn,
  2618. int *truncated,
  2619. char *buf,
  2620. size_t buflen,
  2621. const char *fmt,
  2622. va_list ap)
  2623. {
  2624. int n, ok;
  2625. if (buflen == 0) {
  2626. if (truncated) {
  2627. *truncated = 1;
  2628. }
  2629. return;
  2630. }
  2631. #if defined(__clang__)
  2632. #pragma clang diagnostic push
  2633. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2634. /* Using fmt as a non-literal is intended here, since it is mostly called
  2635. * indirectly by mg_snprintf */
  2636. #endif
  2637. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2638. ok = (n >= 0) && ((size_t)n < buflen);
  2639. #if defined(__clang__)
  2640. #pragma clang diagnostic pop
  2641. #endif
  2642. if (ok) {
  2643. if (truncated) {
  2644. *truncated = 0;
  2645. }
  2646. } else {
  2647. if (truncated) {
  2648. *truncated = 1;
  2649. }
  2650. mg_cry_internal(conn,
  2651. "truncating vsnprintf buffer: [%.*s]",
  2652. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2653. buf);
  2654. n = (int)buflen - 1;
  2655. }
  2656. buf[n] = '\0';
  2657. }
  2658. static void
  2659. mg_snprintf(const struct mg_connection *conn,
  2660. int *truncated,
  2661. char *buf,
  2662. size_t buflen,
  2663. const char *fmt,
  2664. ...)
  2665. {
  2666. va_list ap;
  2667. va_start(ap, fmt);
  2668. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2669. va_end(ap);
  2670. }
  2671. static int
  2672. get_option_index(const char *name)
  2673. {
  2674. int i;
  2675. for (i = 0; config_options[i].name != NULL; i++) {
  2676. if (strcmp(config_options[i].name, name) == 0) {
  2677. return i;
  2678. }
  2679. }
  2680. return -1;
  2681. }
  2682. CIVETWEB_API const char *
  2683. mg_get_option(const struct mg_context *ctx, const char *name)
  2684. {
  2685. int i;
  2686. if ((i = get_option_index(name)) == -1) {
  2687. return NULL;
  2688. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2689. return "";
  2690. } else {
  2691. return ctx->dd.config[i];
  2692. }
  2693. }
  2694. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2695. CIVETWEB_API struct mg_context *
  2696. mg_get_context(const struct mg_connection *conn)
  2697. {
  2698. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2699. }
  2700. CIVETWEB_API void *
  2701. mg_get_user_data(const struct mg_context *ctx)
  2702. {
  2703. return (ctx == NULL) ? NULL : ctx->user_data;
  2704. }
  2705. CIVETWEB_API void *
  2706. mg_get_user_context_data(const struct mg_connection *conn)
  2707. {
  2708. return mg_get_user_data(mg_get_context(conn));
  2709. }
  2710. CIVETWEB_API void *
  2711. mg_get_thread_pointer(const struct mg_connection *conn)
  2712. {
  2713. /* both methods should return the same pointer */
  2714. if (conn) {
  2715. /* quick access, in case conn is known */
  2716. return conn->tls_user_ptr;
  2717. } else {
  2718. /* otherwise get pointer from thread local storage (TLS) */
  2719. struct mg_workerTLS *tls =
  2720. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2721. return tls->user_ptr;
  2722. }
  2723. }
  2724. CIVETWEB_API void
  2725. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2726. {
  2727. if (const_conn != NULL) {
  2728. /* Const cast, since "const struct mg_connection *" does not mean
  2729. * the connection object is not modified. Here "const" is used,
  2730. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2731. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2732. conn->request_info.conn_data = data;
  2733. }
  2734. }
  2735. CIVETWEB_API void *
  2736. mg_get_user_connection_data(const struct mg_connection *conn)
  2737. {
  2738. if (conn != NULL) {
  2739. return conn->request_info.conn_data;
  2740. }
  2741. return NULL;
  2742. }
  2743. CIVETWEB_API int
  2744. mg_get_server_ports(const struct mg_context *ctx,
  2745. int size,
  2746. struct mg_server_port *ports)
  2747. {
  2748. int i, cnt = 0;
  2749. if (size <= 0) {
  2750. return -1;
  2751. }
  2752. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2753. if (!ctx) {
  2754. return -1;
  2755. }
  2756. if (!ctx->listening_sockets) {
  2757. return -1;
  2758. }
  2759. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2760. ports[cnt].port =
  2761. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2762. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2763. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2764. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2765. /* IPv4 */
  2766. ports[cnt].protocol = 1;
  2767. cnt++;
  2768. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2769. /* IPv6 */
  2770. ports[cnt].protocol = 3;
  2771. cnt++;
  2772. }
  2773. }
  2774. return cnt;
  2775. }
  2776. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2777. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2778. #endif
  2779. static void
  2780. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2781. {
  2782. buf[0] = '\0';
  2783. if (!usa) {
  2784. return;
  2785. }
  2786. if (usa->sa.sa_family == AF_INET) {
  2787. getnameinfo(&usa->sa,
  2788. sizeof(usa->sin),
  2789. buf,
  2790. (unsigned)len,
  2791. NULL,
  2792. 0,
  2793. NI_NUMERICHOST);
  2794. }
  2795. #if defined(USE_IPV6)
  2796. else if (usa->sa.sa_family == AF_INET6) {
  2797. getnameinfo(&usa->sa,
  2798. sizeof(usa->sin6),
  2799. buf,
  2800. (unsigned)len,
  2801. NULL,
  2802. 0,
  2803. NI_NUMERICHOST);
  2804. }
  2805. #endif
  2806. #if defined(USE_X_DOM_SOCKET)
  2807. else if (usa->sa.sa_family == AF_UNIX) {
  2808. /* TODO: Define a remote address for unix domain sockets.
  2809. * This code will always return "localhost", identical to http+tcp:
  2810. getnameinfo(&usa->sa,
  2811. sizeof(usa->sun),
  2812. buf,
  2813. (unsigned)len,
  2814. NULL,
  2815. 0,
  2816. NI_NUMERICHOST);
  2817. */
  2818. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2819. }
  2820. #endif
  2821. }
  2822. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2823. * included in all responses other than 100, 101, 5xx. */
  2824. static void
  2825. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2826. {
  2827. #if !defined(REENTRANT_TIME)
  2828. struct tm *tm;
  2829. tm = ((t != NULL) ? gmtime(t) : NULL);
  2830. if (tm != NULL) {
  2831. #else
  2832. struct tm _tm;
  2833. struct tm *tm = &_tm;
  2834. if (t != NULL) {
  2835. gmtime_r(t, tm);
  2836. #endif
  2837. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2838. } else {
  2839. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2840. }
  2841. }
  2842. /* difftime for struct timespec. Return value is in seconds. */
  2843. static double
  2844. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2845. {
  2846. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2847. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2848. }
  2849. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2850. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2851. const char *func,
  2852. unsigned line,
  2853. const char *fmt,
  2854. va_list ap);
  2855. #include "external_mg_cry_internal_impl.inl"
  2856. #elif !defined(NO_FILESYSTEMS)
  2857. /* Print error message to the opened error log stream. */
  2858. static void
  2859. mg_cry_internal_impl(const struct mg_connection *conn,
  2860. const char *func,
  2861. unsigned line,
  2862. const char *fmt,
  2863. va_list ap)
  2864. {
  2865. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2866. struct mg_file fi;
  2867. time_t timestamp;
  2868. /* Unused, in the RELEASE build */
  2869. (void)func;
  2870. (void)line;
  2871. #if defined(GCC_DIAGNOSTIC)
  2872. #pragma GCC diagnostic push
  2873. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2874. #endif
  2875. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2876. #if defined(GCC_DIAGNOSTIC)
  2877. #pragma GCC diagnostic pop
  2878. #endif
  2879. buf[sizeof(buf) - 1] = 0;
  2880. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2881. if (!conn) {
  2882. puts(buf);
  2883. return;
  2884. }
  2885. /* Do not lock when getting the callback value, here and below.
  2886. * I suppose this is fine, since function cannot disappear in the
  2887. * same way string option can. */
  2888. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2889. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2890. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2891. if (mg_fopen(conn,
  2892. conn->dom_ctx->config[ERROR_LOG_FILE],
  2893. MG_FOPEN_MODE_APPEND,
  2894. &fi)
  2895. == 0) {
  2896. fi.access.fp = NULL;
  2897. }
  2898. } else {
  2899. fi.access.fp = NULL;
  2900. }
  2901. if (fi.access.fp != NULL) {
  2902. flockfile(fi.access.fp);
  2903. timestamp = time(NULL);
  2904. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2905. fprintf(fi.access.fp,
  2906. "[%010lu] [error] [client %s] ",
  2907. (unsigned long)timestamp,
  2908. src_addr);
  2909. if (conn->request_info.request_method != NULL) {
  2910. fprintf(fi.access.fp,
  2911. "%s %s: ",
  2912. conn->request_info.request_method,
  2913. conn->request_info.request_uri
  2914. ? conn->request_info.request_uri
  2915. : "");
  2916. }
  2917. fprintf(fi.access.fp, "%s", buf);
  2918. fputc('\n', fi.access.fp);
  2919. fflush(fi.access.fp);
  2920. funlockfile(fi.access.fp);
  2921. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2922. * mg_cry here anyway ;-) */
  2923. }
  2924. }
  2925. }
  2926. #else
  2927. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2928. #endif /* Externally provided function */
  2929. /* Construct fake connection structure. Used for logging, if connection
  2930. * is not applicable at the moment of logging. */
  2931. static struct mg_connection *
  2932. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2933. {
  2934. static const struct mg_connection conn_zero = {0};
  2935. *fc = conn_zero;
  2936. fc->phys_ctx = ctx;
  2937. fc->dom_ctx = &(ctx->dd);
  2938. return fc;
  2939. }
  2940. static void
  2941. mg_cry_internal_wrap(const struct mg_connection *conn,
  2942. struct mg_context *ctx,
  2943. const char *func,
  2944. unsigned line,
  2945. const char *fmt,
  2946. ...)
  2947. {
  2948. va_list ap;
  2949. va_start(ap, fmt);
  2950. if (!conn && ctx) {
  2951. struct mg_connection fc;
  2952. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2953. } else {
  2954. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2955. }
  2956. va_end(ap);
  2957. }
  2958. CIVETWEB_API void
  2959. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2960. {
  2961. va_list ap;
  2962. va_start(ap, fmt);
  2963. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2964. va_end(ap);
  2965. }
  2966. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2967. CIVETWEB_API const char *
  2968. mg_version(void)
  2969. {
  2970. return CIVETWEB_VERSION;
  2971. }
  2972. CIVETWEB_API const struct mg_request_info *
  2973. mg_get_request_info(const struct mg_connection *conn)
  2974. {
  2975. if (!conn) {
  2976. return NULL;
  2977. }
  2978. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2979. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2980. char txt[16];
  2981. struct mg_workerTLS *tls =
  2982. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2983. sprintf(txt, "%03i", conn->response_info.status_code);
  2984. if (strlen(txt) == 3) {
  2985. memcpy(tls->txtbuf, txt, 4);
  2986. } else {
  2987. strcpy(tls->txtbuf, "ERR");
  2988. }
  2989. ((struct mg_connection *)conn)->request_info.local_uri =
  2990. tls->txtbuf; /* use thread safe buffer */
  2991. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2992. tls->txtbuf; /* use the same thread safe buffer */
  2993. ((struct mg_connection *)conn)->request_info.request_uri =
  2994. tls->txtbuf; /* use the same thread safe buffer */
  2995. ((struct mg_connection *)conn)->request_info.num_headers =
  2996. conn->response_info.num_headers;
  2997. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2998. conn->response_info.http_headers,
  2999. sizeof(conn->response_info.http_headers));
  3000. } else
  3001. #endif
  3002. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3003. return NULL;
  3004. }
  3005. return &conn->request_info;
  3006. }
  3007. CIVETWEB_API const struct mg_response_info *
  3008. mg_get_response_info(const struct mg_connection *conn)
  3009. {
  3010. if (!conn) {
  3011. return NULL;
  3012. }
  3013. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3014. return NULL;
  3015. }
  3016. return &conn->response_info;
  3017. }
  3018. static const char *
  3019. get_proto_name(const struct mg_connection *conn)
  3020. {
  3021. #if defined(__clang__)
  3022. #pragma clang diagnostic push
  3023. #pragma clang diagnostic ignored "-Wunreachable-code"
  3024. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3025. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3026. * unreachable, but splitting into four different #ifdef clauses here is
  3027. * more complicated.
  3028. */
  3029. #endif
  3030. const struct mg_request_info *ri = &conn->request_info;
  3031. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3032. ? (ri->is_ssl ? "wss" : "ws")
  3033. : (ri->is_ssl ? "https" : "http"));
  3034. return proto;
  3035. #if defined(__clang__)
  3036. #pragma clang diagnostic pop
  3037. #endif
  3038. }
  3039. static int
  3040. mg_construct_local_link(const struct mg_connection *conn,
  3041. char *buf,
  3042. size_t buflen,
  3043. const char *define_proto,
  3044. int define_port,
  3045. const char *define_uri)
  3046. {
  3047. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3048. return -1;
  3049. } else {
  3050. int i, j;
  3051. int truncated = 0;
  3052. const struct mg_request_info *ri = &conn->request_info;
  3053. const char *proto =
  3054. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3055. const char *uri =
  3056. (define_uri != NULL)
  3057. ? define_uri
  3058. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3059. int port = (define_port > 0) ? define_port : ri->server_port;
  3060. int default_port = 80;
  3061. char *uri_encoded;
  3062. size_t uri_encoded_len;
  3063. if (uri == NULL) {
  3064. return -1;
  3065. }
  3066. uri_encoded_len = strlen(uri) * 3 + 1;
  3067. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3068. if (uri_encoded == NULL) {
  3069. return -1;
  3070. }
  3071. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3072. /* Directory separator should be preserved. */
  3073. for (i = j = 0; uri_encoded[i]; j++) {
  3074. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3075. uri_encoded[j] = '/';
  3076. i += 3;
  3077. } else {
  3078. uri_encoded[j] = uri_encoded[i++];
  3079. }
  3080. }
  3081. uri_encoded[j] = '\0';
  3082. #if defined(USE_X_DOM_SOCKET)
  3083. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3084. /* TODO: Define and document a link for UNIX domain sockets. */
  3085. /* There seems to be no official standard for this.
  3086. * Common uses seem to be "httpunix://", "http.unix://" or
  3087. * "http+unix://" as a protocol definition string, followed by
  3088. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3089. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3090. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3091. * "" (completely skipping the server name part). In any case, the
  3092. * last part is the server local path. */
  3093. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3094. mg_snprintf(conn,
  3095. &truncated,
  3096. buf,
  3097. buflen,
  3098. "%s.unix://%s%s",
  3099. proto,
  3100. server_name,
  3101. ri->local_uri);
  3102. default_port = 0;
  3103. mg_free(uri_encoded);
  3104. return 0;
  3105. }
  3106. #endif
  3107. if (define_proto) {
  3108. /* If we got a protocol name, use the default port accordingly. */
  3109. if ((0 == strcmp(define_proto, "https"))
  3110. || (0 == strcmp(define_proto, "wss"))) {
  3111. default_port = 443;
  3112. }
  3113. } else if (ri->is_ssl) {
  3114. /* If we did not get a protocol name, use TLS as default if it is
  3115. * already used. */
  3116. default_port = 443;
  3117. }
  3118. {
  3119. #if defined(USE_IPV6)
  3120. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3121. #endif
  3122. int auth_domain_check_enabled =
  3123. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3124. && (!mg_strcasecmp(
  3125. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3126. const char *server_domain =
  3127. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3128. char portstr[16];
  3129. char server_ip[48];
  3130. if (port != default_port) {
  3131. sprintf(portstr, ":%u", (unsigned)port);
  3132. } else {
  3133. portstr[0] = 0;
  3134. }
  3135. if (!auth_domain_check_enabled || !server_domain) {
  3136. sockaddr_to_string(server_ip,
  3137. sizeof(server_ip),
  3138. &conn->client.lsa);
  3139. server_domain = server_ip;
  3140. }
  3141. mg_snprintf(conn,
  3142. &truncated,
  3143. buf,
  3144. buflen,
  3145. #if defined(USE_IPV6)
  3146. "%s://%s%s%s%s%s",
  3147. proto,
  3148. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3149. server_domain,
  3150. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3151. #else
  3152. "%s://%s%s%s",
  3153. proto,
  3154. server_domain,
  3155. #endif
  3156. portstr,
  3157. uri_encoded);
  3158. mg_free(uri_encoded);
  3159. if (truncated) {
  3160. return -1;
  3161. }
  3162. return 0;
  3163. }
  3164. }
  3165. }
  3166. CIVETWEB_API int
  3167. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3168. {
  3169. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3170. }
  3171. /* Skip the characters until one of the delimiters characters found.
  3172. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3173. * Advance pointer to buffer to the next word. Return found 0-terminated
  3174. * word.
  3175. * Delimiters can be quoted with quotechar. */
  3176. static char *
  3177. skip_quoted(char **buf,
  3178. const char *delimiters,
  3179. const char *whitespace,
  3180. char quotechar)
  3181. {
  3182. char *p, *begin_word, *end_word, *end_whitespace;
  3183. begin_word = *buf;
  3184. end_word = begin_word + strcspn(begin_word, delimiters);
  3185. /* Check for quotechar */
  3186. if (end_word > begin_word) {
  3187. p = end_word - 1;
  3188. while (*p == quotechar) {
  3189. /* While the delimiter is quoted, look for the next delimiter. */
  3190. /* This happens, e.g., in calls from parse_auth_header,
  3191. * if the user name contains a " character. */
  3192. /* If there is anything beyond end_word, copy it. */
  3193. if (*end_word != '\0') {
  3194. size_t end_off = strcspn(end_word + 1, delimiters);
  3195. memmove(p, end_word, end_off + 1);
  3196. p += end_off; /* p must correspond to end_word - 1 */
  3197. end_word += end_off + 1;
  3198. } else {
  3199. *p = '\0';
  3200. break;
  3201. }
  3202. }
  3203. for (p++; p < end_word; p++) {
  3204. *p = '\0';
  3205. }
  3206. }
  3207. if (*end_word == '\0') {
  3208. *buf = end_word;
  3209. } else {
  3210. #if defined(GCC_DIAGNOSTIC)
  3211. /* Disable spurious conversion warning for GCC */
  3212. #pragma GCC diagnostic push
  3213. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3214. #endif /* defined(GCC_DIAGNOSTIC) */
  3215. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3216. #if defined(GCC_DIAGNOSTIC)
  3217. #pragma GCC diagnostic pop
  3218. #endif /* defined(GCC_DIAGNOSTIC) */
  3219. for (p = end_word; p < end_whitespace; p++) {
  3220. *p = '\0';
  3221. }
  3222. *buf = end_whitespace;
  3223. }
  3224. return begin_word;
  3225. }
  3226. /* Return HTTP header value, or NULL if not found. */
  3227. static const char *
  3228. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3229. {
  3230. int i;
  3231. for (i = 0; i < num_hdr; i++) {
  3232. if (!mg_strcasecmp(name, hdr[i].name)) {
  3233. return hdr[i].value;
  3234. }
  3235. }
  3236. return NULL;
  3237. }
  3238. /* Retrieve requested HTTP header multiple values, and return the number of
  3239. * found occurrences */
  3240. static int
  3241. get_req_headers(const struct mg_request_info *ri,
  3242. const char *name,
  3243. const char **output,
  3244. int output_max_size)
  3245. {
  3246. int i;
  3247. int cnt = 0;
  3248. if (ri) {
  3249. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3250. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3251. output[cnt++] = ri->http_headers[i].value;
  3252. }
  3253. }
  3254. }
  3255. return cnt;
  3256. }
  3257. CIVETWEB_API const char *
  3258. mg_get_header(const struct mg_connection *conn, const char *name)
  3259. {
  3260. if (!conn) {
  3261. return NULL;
  3262. }
  3263. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3264. return get_header(conn->request_info.http_headers,
  3265. conn->request_info.num_headers,
  3266. name);
  3267. }
  3268. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3269. return get_header(conn->response_info.http_headers,
  3270. conn->response_info.num_headers,
  3271. name);
  3272. }
  3273. return NULL;
  3274. }
  3275. static const char *
  3276. get_http_version(const struct mg_connection *conn)
  3277. {
  3278. if (!conn) {
  3279. return NULL;
  3280. }
  3281. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3282. return conn->request_info.http_version;
  3283. }
  3284. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3285. return conn->response_info.http_version;
  3286. }
  3287. return NULL;
  3288. }
  3289. /* A helper function for traversing a comma separated list of values.
  3290. * It returns a list pointer shifted to the next value, or NULL if the end
  3291. * of the list found.
  3292. * Value is stored in val vector. If value has form "x=y", then eq_val
  3293. * vector is initialized to point to the "y" part, and val vector length
  3294. * is adjusted to point only to "x". */
  3295. static const char *
  3296. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3297. {
  3298. int end;
  3299. reparse:
  3300. if (val == NULL || list == NULL || *list == '\0') {
  3301. /* End of the list */
  3302. return NULL;
  3303. }
  3304. /* Skip over leading LWS */
  3305. while (*list == ' ' || *list == '\t')
  3306. list++;
  3307. val->ptr = list;
  3308. if ((list = strchr(val->ptr, ',')) != NULL) {
  3309. /* Comma found. Store length and shift the list ptr */
  3310. val->len = ((size_t)(list - val->ptr));
  3311. list++;
  3312. } else {
  3313. /* This value is the last one */
  3314. list = val->ptr + strlen(val->ptr);
  3315. val->len = ((size_t)(list - val->ptr));
  3316. }
  3317. /* Adjust length for trailing LWS */
  3318. end = (int)val->len - 1;
  3319. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3320. end--;
  3321. val->len = (size_t)(end) + (size_t)(1);
  3322. if (val->len == 0) {
  3323. /* Ignore any empty entries. */
  3324. goto reparse;
  3325. }
  3326. if (eq_val != NULL) {
  3327. /* Value has form "x=y", adjust pointers and lengths
  3328. * so that val points to "x", and eq_val points to "y". */
  3329. eq_val->len = 0;
  3330. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3331. if (eq_val->ptr != NULL) {
  3332. eq_val->ptr++; /* Skip over '=' character */
  3333. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3334. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3335. }
  3336. }
  3337. return list;
  3338. }
  3339. /* A helper function for checking if a comma separated list of values
  3340. * contains
  3341. * the given option (case insensitvely).
  3342. * 'header' can be NULL, in which case false is returned. */
  3343. static int
  3344. header_has_option(const char *header, const char *option)
  3345. {
  3346. struct vec opt_vec;
  3347. struct vec eq_vec;
  3348. DEBUG_ASSERT(option != NULL);
  3349. DEBUG_ASSERT(option[0] != '\0');
  3350. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3351. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3352. return 1;
  3353. }
  3354. return 0;
  3355. }
  3356. /* Sorting function implemented in a separate file */
  3357. #include "sort.inl"
  3358. /* Pattern matching has been reimplemented in a new file */
  3359. #include "match.inl"
  3360. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3361. * This function must tolerate situations when connection info is not
  3362. * set up, for example if request parsing failed. */
  3363. static int
  3364. should_keep_alive(const struct mg_connection *conn)
  3365. {
  3366. const char *http_version;
  3367. const char *header;
  3368. /* First satisfy needs of the server */
  3369. if ((conn == NULL) || conn->must_close) {
  3370. /* Close, if civetweb framework needs to close */
  3371. return 0;
  3372. }
  3373. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3374. /* Close, if keep alive is not enabled */
  3375. return 0;
  3376. }
  3377. /* Check explicit wish of the client */
  3378. header = mg_get_header(conn, "Connection");
  3379. if (header) {
  3380. /* If there is a connection header from the client, obey */
  3381. if (header_has_option(header, "keep-alive")) {
  3382. return 1;
  3383. }
  3384. return 0;
  3385. }
  3386. /* Use default of the standard */
  3387. http_version = get_http_version(conn);
  3388. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3389. /* HTTP 1.1 default is keep alive */
  3390. return 1;
  3391. }
  3392. /* HTTP 1.0 (and earlier) default is to close the connection */
  3393. return 0;
  3394. }
  3395. static int
  3396. should_decode_url(const struct mg_connection *conn)
  3397. {
  3398. if (!conn || !conn->dom_ctx) {
  3399. return 0;
  3400. }
  3401. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3402. }
  3403. static int
  3404. should_decode_query_string(const struct mg_connection *conn)
  3405. {
  3406. if (!conn || !conn->dom_ctx) {
  3407. return 0;
  3408. }
  3409. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3410. == 0);
  3411. }
  3412. static const char *
  3413. suggest_connection_header(const struct mg_connection *conn)
  3414. {
  3415. return should_keep_alive(conn) ? "keep-alive" : "close";
  3416. }
  3417. #include "response.inl"
  3418. static void
  3419. send_no_cache_header(struct mg_connection *conn)
  3420. {
  3421. /* Send all current and obsolete cache opt-out directives. */
  3422. mg_response_header_add(conn,
  3423. "Cache-Control",
  3424. "no-cache, no-store, "
  3425. "must-revalidate, private, max-age=0",
  3426. -1);
  3427. mg_response_header_add(conn, "Expires", "0", -1);
  3428. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3429. /* Obsolete, but still send it for HTTP/1.0 */
  3430. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3431. }
  3432. }
  3433. static void
  3434. send_static_cache_header(struct mg_connection *conn)
  3435. {
  3436. #if !defined(NO_CACHING)
  3437. int max_age;
  3438. char val[64];
  3439. const char *cache_control =
  3440. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3441. /* If there is a full cache-control option configured,0 use it */
  3442. if (cache_control != NULL) {
  3443. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3444. return;
  3445. }
  3446. /* Read the server config to check how long a file may be cached.
  3447. * The configuration is in seconds. */
  3448. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3449. if (max_age <= 0) {
  3450. /* 0 means "do not cache". All values <0 are reserved
  3451. * and may be used differently in the future. */
  3452. /* If a file should not be cached, do not only send
  3453. * max-age=0, but also pragmas and Expires headers. */
  3454. send_no_cache_header(conn);
  3455. return;
  3456. }
  3457. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3458. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3459. /* See also https://www.mnot.net/cache_docs/ */
  3460. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3461. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3462. * leap
  3463. * year to 31622400 seconds. For the moment, we just send whatever has
  3464. * been configured, still the behavior for >1 year should be considered
  3465. * as undefined. */
  3466. mg_snprintf(
  3467. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3468. mg_response_header_add(conn, "Cache-Control", val, -1);
  3469. #else /* NO_CACHING */
  3470. send_no_cache_header(conn);
  3471. #endif /* !NO_CACHING */
  3472. }
  3473. static void
  3474. send_additional_header(struct mg_connection *conn)
  3475. {
  3476. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3477. #if !defined(NO_SSL)
  3478. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3479. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3480. if (max_age >= 0) {
  3481. char val[64];
  3482. mg_snprintf(conn,
  3483. NULL,
  3484. val,
  3485. sizeof(val),
  3486. "max-age=%lu",
  3487. (unsigned long)max_age);
  3488. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3489. }
  3490. }
  3491. #endif
  3492. if (header && header[0]) {
  3493. mg_response_header_add_lines(conn, header);
  3494. }
  3495. }
  3496. static void
  3497. send_cors_header(struct mg_connection *conn)
  3498. {
  3499. const char *origin_hdr = mg_get_header(conn, "Origin");
  3500. const char *cors_orig_cfg =
  3501. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3502. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3503. /* Cross-origin resource sharing (CORS), see
  3504. * http://www.html5rocks.com/en/tutorials/cors/,
  3505. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3506. * CORS preflight is not supported for files. */
  3507. mg_response_header_add(conn,
  3508. "Access-Control-Allow-Origin",
  3509. cors_orig_cfg,
  3510. -1);
  3511. }
  3512. }
  3513. #if !defined(NO_FILESYSTEMS)
  3514. static void handle_file_based_request(struct mg_connection *conn,
  3515. const char *path,
  3516. struct mg_file *filep);
  3517. #endif /* NO_FILESYSTEMS */
  3518. CIVETWEB_API const char *
  3519. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3520. {
  3521. /* See IANA HTTP status code assignment:
  3522. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3523. */
  3524. switch (response_code) {
  3525. /* RFC2616 Section 10.1 - Informational 1xx */
  3526. case 100:
  3527. return "Continue"; /* RFC2616 Section 10.1.1 */
  3528. case 101:
  3529. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3530. case 102:
  3531. return "Processing"; /* RFC2518 Section 10.1 */
  3532. /* RFC2616 Section 10.2 - Successful 2xx */
  3533. case 200:
  3534. return "OK"; /* RFC2616 Section 10.2.1 */
  3535. case 201:
  3536. return "Created"; /* RFC2616 Section 10.2.2 */
  3537. case 202:
  3538. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3539. case 203:
  3540. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3541. case 204:
  3542. return "No Content"; /* RFC2616 Section 10.2.5 */
  3543. case 205:
  3544. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3545. case 206:
  3546. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3547. case 207:
  3548. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3549. */
  3550. case 208:
  3551. return "Already Reported"; /* RFC5842 Section 7.1 */
  3552. case 226:
  3553. return "IM used"; /* RFC3229 Section 10.4.1 */
  3554. /* RFC2616 Section 10.3 - Redirection 3xx */
  3555. case 300:
  3556. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3557. case 301:
  3558. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3559. case 302:
  3560. return "Found"; /* RFC2616 Section 10.3.3 */
  3561. case 303:
  3562. return "See Other"; /* RFC2616 Section 10.3.4 */
  3563. case 304:
  3564. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3565. case 305:
  3566. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3567. case 307:
  3568. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3569. case 308:
  3570. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3571. /* RFC2616 Section 10.4 - Client Error 4xx */
  3572. case 400:
  3573. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3574. case 401:
  3575. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3576. case 402:
  3577. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3578. case 403:
  3579. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3580. case 404:
  3581. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3582. case 405:
  3583. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3584. case 406:
  3585. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3586. case 407:
  3587. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3588. case 408:
  3589. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3590. case 409:
  3591. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3592. case 410:
  3593. return "Gone"; /* RFC2616 Section 10.4.11 */
  3594. case 411:
  3595. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3596. case 412:
  3597. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3598. case 413:
  3599. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3600. case 414:
  3601. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3602. case 415:
  3603. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3604. case 416:
  3605. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3606. */
  3607. case 417:
  3608. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3609. case 421:
  3610. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3611. case 422:
  3612. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3613. * Section 11.2 */
  3614. case 423:
  3615. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3616. case 424:
  3617. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3618. * Section 11.4 */
  3619. case 426:
  3620. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3621. case 428:
  3622. return "Precondition Required"; /* RFC 6585, Section 3 */
  3623. case 429:
  3624. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3625. case 431:
  3626. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3627. case 451:
  3628. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3629. * Section 3 */
  3630. /* RFC2616 Section 10.5 - Server Error 5xx */
  3631. case 500:
  3632. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3633. case 501:
  3634. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3635. case 502:
  3636. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3637. case 503:
  3638. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3639. case 504:
  3640. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3641. case 505:
  3642. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3643. case 506:
  3644. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3645. case 507:
  3646. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3647. * Section 11.5 */
  3648. case 508:
  3649. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3650. case 510:
  3651. return "Not Extended"; /* RFC 2774, Section 7 */
  3652. case 511:
  3653. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3654. /* Other status codes, not shown in the IANA HTTP status code
  3655. * assignment.
  3656. * E.g., "de facto" standards due to common use, ... */
  3657. case 418:
  3658. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3659. case 419:
  3660. return "Authentication Timeout"; /* common use */
  3661. case 420:
  3662. return "Enhance Your Calm"; /* common use */
  3663. case 440:
  3664. return "Login Timeout"; /* common use */
  3665. case 509:
  3666. return "Bandwidth Limit Exceeded"; /* common use */
  3667. default:
  3668. /* This error code is unknown. This should not happen. */
  3669. if (conn) {
  3670. mg_cry_internal(conn,
  3671. "Unknown HTTP response code: %u",
  3672. response_code);
  3673. }
  3674. /* Return at least a category according to RFC 2616 Section 10. */
  3675. if (response_code >= 100 && response_code < 200) {
  3676. /* Unknown informational status code */
  3677. return "Information";
  3678. }
  3679. if (response_code >= 200 && response_code < 300) {
  3680. /* Unknown success code */
  3681. return "Success";
  3682. }
  3683. if (response_code >= 300 && response_code < 400) {
  3684. /* Unknown redirection code */
  3685. return "Redirection";
  3686. }
  3687. if (response_code >= 400 && response_code < 500) {
  3688. /* Unknown request error code */
  3689. return "Client Error";
  3690. }
  3691. if (response_code >= 500 && response_code < 600) {
  3692. /* Unknown server error code */
  3693. return "Server Error";
  3694. }
  3695. /* Response code not even within reasonable range */
  3696. return "";
  3697. }
  3698. }
  3699. static int
  3700. mg_send_http_error_impl(struct mg_connection *conn,
  3701. int status,
  3702. const char *fmt,
  3703. va_list args)
  3704. {
  3705. char errmsg_buf[MG_BUF_LEN];
  3706. va_list ap;
  3707. int has_body;
  3708. #if !defined(NO_FILESYSTEMS)
  3709. char path_buf[UTF8_PATH_MAX];
  3710. int len, i, page_handler_found, scope, truncated;
  3711. const char *error_handler = NULL;
  3712. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3713. const char *error_page_file_ext, *tstr;
  3714. #endif /* NO_FILESYSTEMS */
  3715. int handled_by_callback = 0;
  3716. if ((conn == NULL) || (fmt == NULL)) {
  3717. return -2;
  3718. }
  3719. /* Set status (for log) */
  3720. conn->status_code = status;
  3721. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3722. has_body = ((status > 199) && (status != 204) && (status != 304));
  3723. /* Prepare message in buf, if required */
  3724. if (has_body
  3725. || (!conn->in_error_handler
  3726. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3727. /* Store error message in errmsg_buf */
  3728. va_copy(ap, args);
  3729. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3730. va_end(ap);
  3731. /* In a debug build, print all html errors */
  3732. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3733. }
  3734. /* If there is a http_error callback, call it.
  3735. * But don't do it recursively, if callback calls mg_send_http_error again.
  3736. */
  3737. if (!conn->in_error_handler
  3738. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3739. /* Mark in_error_handler to avoid recursion and call user callback. */
  3740. conn->in_error_handler = 1;
  3741. handled_by_callback =
  3742. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3743. == 0);
  3744. conn->in_error_handler = 0;
  3745. }
  3746. if (!handled_by_callback) {
  3747. /* Check for recursion */
  3748. if (conn->in_error_handler) {
  3749. DEBUG_TRACE(
  3750. "Recursion when handling error %u - fall back to default",
  3751. status);
  3752. #if !defined(NO_FILESYSTEMS)
  3753. } else {
  3754. /* Send user defined error pages, if defined */
  3755. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3756. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3757. page_handler_found = 0;
  3758. if (error_handler != NULL) {
  3759. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3760. switch (scope) {
  3761. case 1: /* Handler for specific error, e.g. 404 error */
  3762. mg_snprintf(conn,
  3763. &truncated,
  3764. path_buf,
  3765. sizeof(path_buf) - 32,
  3766. "%serror%03u.",
  3767. error_handler,
  3768. status);
  3769. break;
  3770. case 2: /* Handler for error group, e.g., 5xx error
  3771. * handler
  3772. * for all server errors (500-599) */
  3773. mg_snprintf(conn,
  3774. &truncated,
  3775. path_buf,
  3776. sizeof(path_buf) - 32,
  3777. "%serror%01uxx.",
  3778. error_handler,
  3779. status / 100);
  3780. break;
  3781. default: /* Handler for all errors */
  3782. mg_snprintf(conn,
  3783. &truncated,
  3784. path_buf,
  3785. sizeof(path_buf) - 32,
  3786. "%serror.",
  3787. error_handler);
  3788. break;
  3789. }
  3790. /* String truncation in buf may only occur if
  3791. * error_handler is too long. This string is
  3792. * from the config, not from a client. */
  3793. (void)truncated;
  3794. /* The following code is redundant, but it should avoid
  3795. * false positives in static source code analyzers and
  3796. * vulnerability scanners.
  3797. */
  3798. path_buf[sizeof(path_buf) - 32] = 0;
  3799. len = (int)strlen(path_buf);
  3800. if (len > (int)sizeof(path_buf) - 32) {
  3801. len = (int)sizeof(path_buf) - 32;
  3802. }
  3803. /* Start with the file extension from the configuration. */
  3804. tstr = strchr(error_page_file_ext, '.');
  3805. while (tstr) {
  3806. for (i = 1;
  3807. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3808. i++) {
  3809. /* buffer overrun is not possible here, since
  3810. * (i < 32) && (len < sizeof(path_buf) - 32)
  3811. * ==> (i + len) < sizeof(path_buf) */
  3812. path_buf[len + i - 1] = tstr[i];
  3813. }
  3814. /* buffer overrun is not possible here, since
  3815. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3816. * ==> (i + len) <= sizeof(path_buf) */
  3817. path_buf[len + i - 1] = 0;
  3818. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3819. DEBUG_TRACE("Check error page %s - found",
  3820. path_buf);
  3821. page_handler_found = 1;
  3822. break;
  3823. }
  3824. DEBUG_TRACE("Check error page %s - not found",
  3825. path_buf);
  3826. /* Continue with the next file extension from the
  3827. * configuration (if there is a next one). */
  3828. tstr = strchr(tstr + i, '.');
  3829. }
  3830. }
  3831. }
  3832. if (page_handler_found) {
  3833. conn->in_error_handler = 1;
  3834. handle_file_based_request(conn, path_buf, &error_page_file);
  3835. conn->in_error_handler = 0;
  3836. return 0;
  3837. }
  3838. #endif /* NO_FILESYSTEMS */
  3839. }
  3840. /* No custom error page. Send default error page. */
  3841. conn->must_close = 1;
  3842. mg_response_header_start(conn, status);
  3843. send_no_cache_header(conn);
  3844. send_additional_header(conn);
  3845. send_cors_header(conn);
  3846. if (has_body) {
  3847. mg_response_header_add(conn,
  3848. "Content-Type",
  3849. "text/plain; charset=utf-8",
  3850. -1);
  3851. }
  3852. mg_response_header_send(conn);
  3853. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3854. if (has_body) {
  3855. /* For other errors, send a generic error message. */
  3856. const char *status_text = mg_get_response_code_text(conn, status);
  3857. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3858. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3859. } else {
  3860. /* No body allowed. Close the connection. */
  3861. DEBUG_TRACE("Error %i", status);
  3862. }
  3863. }
  3864. return 0;
  3865. }
  3866. CIVETWEB_API int
  3867. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3868. {
  3869. va_list ap;
  3870. int ret;
  3871. va_start(ap, fmt);
  3872. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3873. va_end(ap);
  3874. return ret;
  3875. }
  3876. CIVETWEB_API int
  3877. mg_send_http_ok(struct mg_connection *conn,
  3878. const char *mime_type,
  3879. long long content_length)
  3880. {
  3881. if ((mime_type == NULL) || (*mime_type == 0)) {
  3882. /* No content type defined: default to text/html */
  3883. mime_type = "text/html";
  3884. }
  3885. mg_response_header_start(conn, 200);
  3886. send_no_cache_header(conn);
  3887. send_additional_header(conn);
  3888. send_cors_header(conn);
  3889. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3890. if (content_length < 0) {
  3891. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3892. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3893. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3894. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3895. }
  3896. } else {
  3897. char len[32];
  3898. int trunc = 0;
  3899. mg_snprintf(conn,
  3900. &trunc,
  3901. len,
  3902. sizeof(len),
  3903. "%" UINT64_FMT,
  3904. (uint64_t)content_length);
  3905. if (!trunc) {
  3906. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3907. * !trunc is always true */
  3908. mg_response_header_add(conn, "Content-Length", len, -1);
  3909. }
  3910. }
  3911. mg_response_header_send(conn);
  3912. return 0;
  3913. }
  3914. CIVETWEB_API int
  3915. mg_send_http_redirect(struct mg_connection *conn,
  3916. const char *target_url,
  3917. int redirect_code)
  3918. {
  3919. /* Send a 30x redirect response.
  3920. *
  3921. * Redirect types (status codes):
  3922. *
  3923. * Status | Perm/Temp | Method | Version
  3924. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3925. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3926. * 303 | temporary | always use GET | HTTP/1.1
  3927. * 307 | temporary | always keep method | HTTP/1.1
  3928. * 308 | permanent | always keep method | HTTP/1.1
  3929. */
  3930. #if defined(MG_SEND_REDIRECT_BODY)
  3931. char redirect_body[MG_BUF_LEN];
  3932. size_t content_len = 0;
  3933. char content_len_text[32];
  3934. #endif
  3935. /* In case redirect_code=0, use 307. */
  3936. if (redirect_code == 0) {
  3937. redirect_code = 307;
  3938. }
  3939. /* In case redirect_code is none of the above, return error. */
  3940. if ((redirect_code != 301) && (redirect_code != 302)
  3941. && (redirect_code != 303) && (redirect_code != 307)
  3942. && (redirect_code != 308)) {
  3943. /* Parameter error */
  3944. return -2;
  3945. }
  3946. /* If target_url is not defined, redirect to "/". */
  3947. if ((target_url == NULL) || (*target_url == 0)) {
  3948. target_url = "/";
  3949. }
  3950. #if defined(MG_SEND_REDIRECT_BODY)
  3951. /* TODO: condition name? */
  3952. /* Prepare a response body with a hyperlink.
  3953. *
  3954. * According to RFC2616 (and RFC1945 before):
  3955. * Unless the request method was HEAD, the entity of the
  3956. * response SHOULD contain a short hypertext note with a hyperlink to
  3957. * the new URI(s).
  3958. *
  3959. * However, this response body is not useful in M2M communication.
  3960. * Probably the original reason in the RFC was, clients not supporting
  3961. * a 30x HTTP redirect could still show the HTML page and let the user
  3962. * press the link. Since current browsers support 30x HTTP, the additional
  3963. * HTML body does not seem to make sense anymore.
  3964. *
  3965. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3966. * but it only notes:
  3967. * The server's response payload usually contains a short
  3968. * hypertext note with a hyperlink to the new URI(s).
  3969. *
  3970. * Deactivated by default. If you need the 30x body, set the define.
  3971. */
  3972. mg_snprintf(
  3973. conn,
  3974. NULL /* ignore truncation */,
  3975. redirect_body,
  3976. sizeof(redirect_body),
  3977. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3978. redirect_text,
  3979. target_url,
  3980. target_url);
  3981. content_len = strlen(reply);
  3982. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3983. #endif
  3984. /* Send all required headers */
  3985. mg_response_header_start(conn, redirect_code);
  3986. mg_response_header_add(conn, "Location", target_url, -1);
  3987. if ((redirect_code == 301) || (redirect_code == 308)) {
  3988. /* Permanent redirect */
  3989. send_static_cache_header(conn);
  3990. } else {
  3991. /* Temporary redirect */
  3992. send_no_cache_header(conn);
  3993. }
  3994. send_additional_header(conn);
  3995. send_cors_header(conn);
  3996. #if defined(MG_SEND_REDIRECT_BODY)
  3997. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3998. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3999. #else
  4000. mg_response_header_add(conn, "Content-Length", "0", 1);
  4001. #endif
  4002. mg_response_header_send(conn);
  4003. #if defined(MG_SEND_REDIRECT_BODY)
  4004. /* Send response body */
  4005. /* ... unless it is a HEAD request */
  4006. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4007. ret = mg_write(conn, redirect_body, content_len);
  4008. }
  4009. #endif
  4010. return 1;
  4011. }
  4012. #if defined(_WIN32)
  4013. /* Create substitutes for POSIX functions in Win32. */
  4014. #if defined(GCC_DIAGNOSTIC)
  4015. /* Show no warning in case system functions are not used. */
  4016. #pragma GCC diagnostic push
  4017. #pragma GCC diagnostic ignored "-Wunused-function"
  4018. #endif
  4019. static int
  4020. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4021. {
  4022. (void)unused;
  4023. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4024. InitializeCriticalSection(&mutex->sec);
  4025. return 0;
  4026. }
  4027. static int
  4028. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4029. {
  4030. DeleteCriticalSection(&mutex->sec);
  4031. return 0;
  4032. }
  4033. static int
  4034. pthread_mutex_lock(pthread_mutex_t *mutex)
  4035. {
  4036. EnterCriticalSection(&mutex->sec);
  4037. return 0;
  4038. }
  4039. static int
  4040. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4041. {
  4042. LeaveCriticalSection(&mutex->sec);
  4043. return 0;
  4044. }
  4045. FUNCTION_MAY_BE_UNUSED
  4046. static int
  4047. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4048. {
  4049. (void)unused;
  4050. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4051. cv->waiting_thread = NULL;
  4052. return 0;
  4053. }
  4054. FUNCTION_MAY_BE_UNUSED
  4055. static int
  4056. pthread_cond_timedwait(pthread_cond_t *cv,
  4057. pthread_mutex_t *mutex,
  4058. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4059. {
  4060. struct mg_workerTLS **ptls,
  4061. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4062. int ok;
  4063. uint64_t nsnow, nswaitabs;
  4064. int64_t nswaitrel;
  4065. DWORD mswaitrel;
  4066. pthread_mutex_lock(&cv->threadIdSec);
  4067. /* Add this thread to cv's waiting list */
  4068. ptls = &cv->waiting_thread;
  4069. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4070. ;
  4071. tls->next_waiting_thread = NULL;
  4072. *ptls = tls;
  4073. pthread_mutex_unlock(&cv->threadIdSec);
  4074. if (abstime) {
  4075. nsnow = mg_get_current_time_ns();
  4076. nswaitabs =
  4077. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4078. nswaitrel = nswaitabs - nsnow;
  4079. if (nswaitrel < 0) {
  4080. nswaitrel = 0;
  4081. }
  4082. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4083. } else {
  4084. mswaitrel = (DWORD)INFINITE;
  4085. }
  4086. pthread_mutex_unlock(mutex);
  4087. ok = (WAIT_OBJECT_0
  4088. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4089. if (!ok) {
  4090. ok = 1;
  4091. pthread_mutex_lock(&cv->threadIdSec);
  4092. ptls = &cv->waiting_thread;
  4093. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4094. if (*ptls == tls) {
  4095. *ptls = tls->next_waiting_thread;
  4096. ok = 0;
  4097. break;
  4098. }
  4099. }
  4100. pthread_mutex_unlock(&cv->threadIdSec);
  4101. if (ok) {
  4102. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4103. (DWORD)INFINITE);
  4104. }
  4105. }
  4106. /* This thread has been removed from cv's waiting list */
  4107. pthread_mutex_lock(mutex);
  4108. return ok ? 0 : -1;
  4109. }
  4110. FUNCTION_MAY_BE_UNUSED
  4111. static int
  4112. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4113. {
  4114. return pthread_cond_timedwait(cv, mutex, NULL);
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. pthread_cond_signal(pthread_cond_t *cv)
  4119. {
  4120. HANDLE wkup = NULL;
  4121. BOOL ok = FALSE;
  4122. pthread_mutex_lock(&cv->threadIdSec);
  4123. if (cv->waiting_thread) {
  4124. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4125. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4126. ok = SetEvent(wkup);
  4127. DEBUG_ASSERT(ok);
  4128. }
  4129. pthread_mutex_unlock(&cv->threadIdSec);
  4130. return ok ? 0 : 1;
  4131. }
  4132. FUNCTION_MAY_BE_UNUSED
  4133. static int
  4134. pthread_cond_broadcast(pthread_cond_t *cv)
  4135. {
  4136. pthread_mutex_lock(&cv->threadIdSec);
  4137. while (cv->waiting_thread) {
  4138. pthread_cond_signal(cv);
  4139. }
  4140. pthread_mutex_unlock(&cv->threadIdSec);
  4141. return 0;
  4142. }
  4143. FUNCTION_MAY_BE_UNUSED
  4144. static int
  4145. pthread_cond_destroy(pthread_cond_t *cv)
  4146. {
  4147. pthread_mutex_lock(&cv->threadIdSec);
  4148. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4149. pthread_mutex_unlock(&cv->threadIdSec);
  4150. pthread_mutex_destroy(&cv->threadIdSec);
  4151. return 0;
  4152. }
  4153. #if defined(ALTERNATIVE_QUEUE)
  4154. FUNCTION_MAY_BE_UNUSED
  4155. static void *
  4156. event_create(void)
  4157. {
  4158. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4159. }
  4160. FUNCTION_MAY_BE_UNUSED
  4161. static int
  4162. event_wait(void *eventhdl)
  4163. {
  4164. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4165. return (res == WAIT_OBJECT_0);
  4166. }
  4167. FUNCTION_MAY_BE_UNUSED
  4168. static int
  4169. event_signal(void *eventhdl)
  4170. {
  4171. return (int)SetEvent((HANDLE)eventhdl);
  4172. }
  4173. FUNCTION_MAY_BE_UNUSED
  4174. static void
  4175. event_destroy(void *eventhdl)
  4176. {
  4177. CloseHandle((HANDLE)eventhdl);
  4178. }
  4179. #endif
  4180. #if defined(GCC_DIAGNOSTIC)
  4181. /* Enable unused function warning again */
  4182. #pragma GCC diagnostic pop
  4183. #endif
  4184. /* For Windows, change all slashes to backslashes in path names. */
  4185. static void
  4186. change_slashes_to_backslashes(char *path)
  4187. {
  4188. int i;
  4189. for (i = 0; path[i] != '\0'; i++) {
  4190. if (path[i] == '/') {
  4191. path[i] = '\\';
  4192. }
  4193. /* remove double backslash (check i > 0 to preserve UNC paths,
  4194. * like \\server\file.txt) */
  4195. if ((i > 0) && (path[i] == '\\')) {
  4196. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4197. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4198. }
  4199. }
  4200. }
  4201. }
  4202. static int
  4203. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4204. {
  4205. int diff;
  4206. do {
  4207. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4208. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4209. s1++;
  4210. s2++;
  4211. } while ((diff == 0) && (s1[-1] != L'\0'));
  4212. return diff;
  4213. }
  4214. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4215. * wbuf and wbuf_len is a target buffer and its length. */
  4216. static void
  4217. path_to_unicode(const struct mg_connection *conn,
  4218. const char *path,
  4219. wchar_t *wbuf,
  4220. size_t wbuf_len)
  4221. {
  4222. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4223. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4224. DWORD long_len, err;
  4225. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4226. mg_strlcpy(buf, path, sizeof(buf));
  4227. change_slashes_to_backslashes(buf);
  4228. /* Convert to Unicode and back. If doubly-converted string does not
  4229. * match the original, something is fishy, reject. */
  4230. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4231. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4232. WideCharToMultiByte(
  4233. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4234. if (strcmp(buf, buf2) != 0) {
  4235. wbuf[0] = L'\0';
  4236. }
  4237. /* Windows file systems are not case sensitive, but you can still use
  4238. * uppercase and lowercase letters (on all modern file systems).
  4239. * The server can check if the URI uses the same upper/lowercase
  4240. * letters an the file system, effectively making Windows servers
  4241. * case sensitive (like Linux servers are). It is still not possible
  4242. * to use two files with the same name in different cases on Windows
  4243. * (like /a and /A) - this would be possible in Linux.
  4244. * As a default, Windows is not case sensitive, but the case sensitive
  4245. * file name check can be activated by an additional configuration. */
  4246. if (conn) {
  4247. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4248. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4249. "yes")) {
  4250. /* Use case sensitive compare function */
  4251. fcompare = wcscmp;
  4252. }
  4253. }
  4254. (void)conn; /* conn is currently unused */
  4255. /* Only accept a full file path, not a Windows short (8.3) path. */
  4256. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4257. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4258. if (long_len == 0) {
  4259. err = GetLastError();
  4260. if (err == ERROR_FILE_NOT_FOUND) {
  4261. /* File does not exist. This is not always a problem here. */
  4262. return;
  4263. }
  4264. }
  4265. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4266. /* Short name is used. */
  4267. wbuf[0] = L'\0';
  4268. }
  4269. }
  4270. #if !defined(NO_FILESYSTEMS)
  4271. /* Get file information, return 1 if file exists, 0 if not */
  4272. static int
  4273. mg_stat(const struct mg_connection *conn,
  4274. const char *path,
  4275. struct mg_file_stat *filep)
  4276. {
  4277. wchar_t wbuf[UTF16_PATH_MAX];
  4278. WIN32_FILE_ATTRIBUTE_DATA info;
  4279. time_t creation_time;
  4280. size_t len;
  4281. if (!filep) {
  4282. return 0;
  4283. }
  4284. memset(filep, 0, sizeof(*filep));
  4285. if (mg_path_suspicious(conn, path)) {
  4286. return 0;
  4287. }
  4288. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4289. /* Windows happily opens files with some garbage at the end of file name.
  4290. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4291. * "a.cgi", despite one would expect an error back. */
  4292. len = strlen(path);
  4293. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4294. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4295. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4296. filep->last_modified =
  4297. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4298. info.ftLastWriteTime.dwHighDateTime);
  4299. /* On Windows, the file creation time can be higher than the
  4300. * modification time, e.g. when a file is copied.
  4301. * Since the Last-Modified timestamp is used for caching
  4302. * it should be based on the most recent timestamp. */
  4303. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4304. info.ftCreationTime.dwHighDateTime);
  4305. if (creation_time > filep->last_modified) {
  4306. filep->last_modified = creation_time;
  4307. }
  4308. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4309. return 1;
  4310. }
  4311. return 0;
  4312. }
  4313. #endif
  4314. static int
  4315. mg_remove(const struct mg_connection *conn, const char *path)
  4316. {
  4317. wchar_t wbuf[UTF16_PATH_MAX];
  4318. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4319. return DeleteFileW(wbuf) ? 0 : -1;
  4320. }
  4321. static int
  4322. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4323. {
  4324. wchar_t wbuf[UTF16_PATH_MAX];
  4325. (void)mode;
  4326. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4327. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4328. }
  4329. /* Create substitutes for POSIX functions in Win32. */
  4330. #if defined(GCC_DIAGNOSTIC)
  4331. /* Show no warning in case system functions are not used. */
  4332. #pragma GCC diagnostic push
  4333. #pragma GCC diagnostic ignored "-Wunused-function"
  4334. #endif
  4335. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4336. FUNCTION_MAY_BE_UNUSED
  4337. static DIR *
  4338. mg_opendir(const struct mg_connection *conn, const char *name)
  4339. {
  4340. DIR *dir = NULL;
  4341. wchar_t wpath[UTF16_PATH_MAX];
  4342. DWORD attrs;
  4343. if (name == NULL) {
  4344. SetLastError(ERROR_BAD_ARGUMENTS);
  4345. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4346. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4347. } else {
  4348. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4349. attrs = GetFileAttributesW(wpath);
  4350. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4351. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4352. (void)wcscat(wpath, L"\\*");
  4353. dir->handle = FindFirstFileW(wpath, &dir->info);
  4354. dir->result.d_name[0] = '\0';
  4355. } else {
  4356. mg_free(dir);
  4357. dir = NULL;
  4358. }
  4359. }
  4360. return dir;
  4361. }
  4362. FUNCTION_MAY_BE_UNUSED
  4363. static int
  4364. mg_closedir(DIR *dir)
  4365. {
  4366. int result = 0;
  4367. if (dir != NULL) {
  4368. if (dir->handle != INVALID_HANDLE_VALUE)
  4369. result = FindClose(dir->handle) ? 0 : -1;
  4370. mg_free(dir);
  4371. } else {
  4372. result = -1;
  4373. SetLastError(ERROR_BAD_ARGUMENTS);
  4374. }
  4375. return result;
  4376. }
  4377. FUNCTION_MAY_BE_UNUSED
  4378. static struct dirent *
  4379. mg_readdir(DIR *dir)
  4380. {
  4381. struct dirent *result = 0;
  4382. if (dir) {
  4383. if (dir->handle != INVALID_HANDLE_VALUE) {
  4384. result = &dir->result;
  4385. (void)WideCharToMultiByte(CP_UTF8,
  4386. 0,
  4387. dir->info.cFileName,
  4388. -1,
  4389. result->d_name,
  4390. sizeof(result->d_name),
  4391. NULL,
  4392. NULL);
  4393. if (!FindNextFileW(dir->handle, &dir->info)) {
  4394. (void)FindClose(dir->handle);
  4395. dir->handle = INVALID_HANDLE_VALUE;
  4396. }
  4397. } else {
  4398. SetLastError(ERROR_FILE_NOT_FOUND);
  4399. }
  4400. } else {
  4401. SetLastError(ERROR_BAD_ARGUMENTS);
  4402. }
  4403. return result;
  4404. }
  4405. #if !defined(HAVE_POLL)
  4406. #undef POLLIN
  4407. #undef POLLPRI
  4408. #undef POLLOUT
  4409. #undef POLLERR
  4410. #define POLLIN (1) /* Data ready - read will not block. */
  4411. #define POLLPRI (2) /* Priority data ready. */
  4412. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4413. #define POLLERR (8) /* Error event */
  4414. FUNCTION_MAY_BE_UNUSED
  4415. static int
  4416. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4417. {
  4418. struct timeval tv;
  4419. fd_set rset;
  4420. fd_set wset;
  4421. fd_set eset;
  4422. unsigned int i;
  4423. int result;
  4424. SOCKET maxfd = 0;
  4425. memset(&tv, 0, sizeof(tv));
  4426. tv.tv_sec = milliseconds / 1000;
  4427. tv.tv_usec = (milliseconds % 1000) * 1000;
  4428. FD_ZERO(&rset);
  4429. FD_ZERO(&wset);
  4430. FD_ZERO(&eset);
  4431. for (i = 0; i < n; i++) {
  4432. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4433. if (pfd[i].events & POLLIN) {
  4434. FD_SET(pfd[i].fd, &rset);
  4435. }
  4436. if (pfd[i].events & POLLOUT) {
  4437. FD_SET(pfd[i].fd, &wset);
  4438. }
  4439. /* Check for errors for any FD in the set */
  4440. FD_SET(pfd[i].fd, &eset);
  4441. }
  4442. pfd[i].revents = 0;
  4443. if (pfd[i].fd > maxfd) {
  4444. maxfd = pfd[i].fd;
  4445. }
  4446. }
  4447. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4448. for (i = 0; i < n; i++) {
  4449. if (FD_ISSET(pfd[i].fd, &rset)) {
  4450. pfd[i].revents |= POLLIN;
  4451. }
  4452. if (FD_ISSET(pfd[i].fd, &wset)) {
  4453. pfd[i].revents |= POLLOUT;
  4454. }
  4455. if (FD_ISSET(pfd[i].fd, &eset)) {
  4456. pfd[i].revents |= POLLERR;
  4457. }
  4458. }
  4459. }
  4460. /* We should subtract the time used in select from remaining
  4461. * "milliseconds", in particular if called from mg_poll with a
  4462. * timeout quantum.
  4463. * Unfortunately, the remaining time is not stored in "tv" in all
  4464. * implementations, so the result in "tv" must be considered undefined.
  4465. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4466. return result;
  4467. }
  4468. #endif /* HAVE_POLL */
  4469. #if defined(GCC_DIAGNOSTIC)
  4470. /* Enable unused function warning again */
  4471. #pragma GCC diagnostic pop
  4472. #endif
  4473. static void
  4474. set_close_on_exec(SOCKET sock,
  4475. const struct mg_connection *conn /* may be null */,
  4476. struct mg_context *ctx /* may be null */)
  4477. {
  4478. (void)conn; /* Unused. */
  4479. (void)ctx;
  4480. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4481. }
  4482. CIVETWEB_API int
  4483. mg_start_thread(mg_thread_func_t f, void *p)
  4484. {
  4485. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4486. /* Compile-time option to control stack size, e.g.
  4487. * -DUSE_STACK_SIZE=16384
  4488. */
  4489. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4490. == ((uintptr_t)(-1L)))
  4491. ? -1
  4492. : 0);
  4493. #else
  4494. return (
  4495. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4496. ? -1
  4497. : 0);
  4498. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4499. }
  4500. /* Start a thread storing the thread context. */
  4501. static int
  4502. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4503. void *p,
  4504. pthread_t *threadidptr)
  4505. {
  4506. uintptr_t uip;
  4507. HANDLE threadhandle;
  4508. int result = -1;
  4509. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4510. threadhandle = (HANDLE)uip;
  4511. if ((uip != 0) && (threadidptr != NULL)) {
  4512. *threadidptr = threadhandle;
  4513. result = 0;
  4514. }
  4515. return result;
  4516. }
  4517. /* Wait for a thread to finish. */
  4518. static int
  4519. mg_join_thread(pthread_t threadid)
  4520. {
  4521. int result;
  4522. DWORD dwevent;
  4523. result = -1;
  4524. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4525. if (dwevent == WAIT_FAILED) {
  4526. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4527. } else {
  4528. if (dwevent == WAIT_OBJECT_0) {
  4529. CloseHandle(threadid);
  4530. result = 0;
  4531. }
  4532. }
  4533. return result;
  4534. }
  4535. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4536. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4537. /* Create substitutes for POSIX functions in Win32. */
  4538. #if defined(GCC_DIAGNOSTIC)
  4539. /* Show no warning in case system functions are not used. */
  4540. #pragma GCC diagnostic push
  4541. #pragma GCC diagnostic ignored "-Wunused-function"
  4542. #endif
  4543. FUNCTION_MAY_BE_UNUSED
  4544. static HANDLE
  4545. dlopen(const char *dll_name, int flags)
  4546. {
  4547. wchar_t wbuf[UTF16_PATH_MAX];
  4548. (void)flags;
  4549. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4550. return LoadLibraryW(wbuf);
  4551. }
  4552. FUNCTION_MAY_BE_UNUSED
  4553. static int
  4554. dlclose(void *handle)
  4555. {
  4556. int result;
  4557. if (FreeLibrary((HMODULE)handle) != 0) {
  4558. result = 0;
  4559. } else {
  4560. result = -1;
  4561. }
  4562. return result;
  4563. }
  4564. #if defined(GCC_DIAGNOSTIC)
  4565. /* Enable unused function warning again */
  4566. #pragma GCC diagnostic pop
  4567. #endif
  4568. #endif
  4569. #if !defined(NO_CGI)
  4570. #define SIGKILL (0)
  4571. static int
  4572. kill(pid_t pid, int sig_num)
  4573. {
  4574. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4575. (void)CloseHandle((HANDLE)pid);
  4576. return 0;
  4577. }
  4578. #if !defined(WNOHANG)
  4579. #define WNOHANG (1)
  4580. #endif
  4581. static pid_t
  4582. waitpid(pid_t pid, int *status, int flags)
  4583. {
  4584. DWORD timeout = INFINITE;
  4585. DWORD waitres;
  4586. (void)status; /* Currently not used by any client here */
  4587. if ((flags | WNOHANG) == WNOHANG) {
  4588. timeout = 0;
  4589. }
  4590. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4591. if (waitres == WAIT_OBJECT_0) {
  4592. return pid;
  4593. }
  4594. if (waitres == WAIT_TIMEOUT) {
  4595. return 0;
  4596. }
  4597. return (pid_t)-1;
  4598. }
  4599. static void
  4600. trim_trailing_whitespaces(char *s)
  4601. {
  4602. char *e = s + strlen(s);
  4603. while ((e > s) && isspace((unsigned char)e[-1])) {
  4604. *(--e) = '\0';
  4605. }
  4606. }
  4607. static pid_t
  4608. spawn_process(struct mg_connection *conn,
  4609. const char *prog,
  4610. char *envblk,
  4611. char *envp[],
  4612. int fdin[2],
  4613. int fdout[2],
  4614. int fderr[2],
  4615. const char *dir,
  4616. int cgi_config_idx)
  4617. {
  4618. HANDLE me;
  4619. char *interp;
  4620. char *interp_arg = 0;
  4621. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4622. int truncated;
  4623. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4624. STARTUPINFOA si;
  4625. PROCESS_INFORMATION pi = {0};
  4626. (void)envp;
  4627. memset(&si, 0, sizeof(si));
  4628. si.cb = sizeof(si);
  4629. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4630. si.wShowWindow = SW_HIDE;
  4631. me = GetCurrentProcess();
  4632. DuplicateHandle(me,
  4633. (HANDLE)_get_osfhandle(fdin[0]),
  4634. me,
  4635. &si.hStdInput,
  4636. 0,
  4637. TRUE,
  4638. DUPLICATE_SAME_ACCESS);
  4639. DuplicateHandle(me,
  4640. (HANDLE)_get_osfhandle(fdout[1]),
  4641. me,
  4642. &si.hStdOutput,
  4643. 0,
  4644. TRUE,
  4645. DUPLICATE_SAME_ACCESS);
  4646. DuplicateHandle(me,
  4647. (HANDLE)_get_osfhandle(fderr[1]),
  4648. me,
  4649. &si.hStdError,
  4650. 0,
  4651. TRUE,
  4652. DUPLICATE_SAME_ACCESS);
  4653. /* Mark handles that should not be inherited. See
  4654. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4655. */
  4656. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4657. HANDLE_FLAG_INHERIT,
  4658. 0);
  4659. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4660. HANDLE_FLAG_INHERIT,
  4661. 0);
  4662. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4663. HANDLE_FLAG_INHERIT,
  4664. 0);
  4665. /* First check, if there is a CGI interpreter configured for all CGI
  4666. * scripts. */
  4667. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4668. if (interp != NULL) {
  4669. /* If there is a configured interpreter, check for additional arguments
  4670. */
  4671. interp_arg =
  4672. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4673. } else {
  4674. /* Otherwise, the interpreter must be stated in the first line of the
  4675. * CGI script file, after a #! (shebang) mark. */
  4676. buf[0] = buf[1] = '\0';
  4677. /* Get the full script path */
  4678. mg_snprintf(
  4679. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4680. if (truncated) {
  4681. pi.hProcess = (pid_t)-1;
  4682. goto spawn_cleanup;
  4683. }
  4684. /* Open the script file, to read the first line */
  4685. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4686. /* Read the first line of the script into the buffer */
  4687. mg_fgets(buf, sizeof(buf), &file);
  4688. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4689. buf[sizeof(buf) - 1] = '\0';
  4690. }
  4691. if ((buf[0] == '#') && (buf[1] == '!')) {
  4692. trim_trailing_whitespaces(buf + 2);
  4693. } else {
  4694. buf[2] = '\0';
  4695. }
  4696. interp = buf + 2;
  4697. }
  4698. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4699. if (interp[0] != '\0') {
  4700. /* This is an interpreted script file. We must call the interpreter. */
  4701. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4702. mg_snprintf(conn,
  4703. &truncated,
  4704. cmdline,
  4705. sizeof(cmdline),
  4706. "\"%s\" %s \"%s\\%s\"",
  4707. interp,
  4708. interp_arg,
  4709. full_dir,
  4710. prog);
  4711. } else {
  4712. mg_snprintf(conn,
  4713. &truncated,
  4714. cmdline,
  4715. sizeof(cmdline),
  4716. "\"%s\" \"%s\\%s\"",
  4717. interp,
  4718. full_dir,
  4719. prog);
  4720. }
  4721. } else {
  4722. /* This is (probably) a compiled program. We call it directly. */
  4723. mg_snprintf(conn,
  4724. &truncated,
  4725. cmdline,
  4726. sizeof(cmdline),
  4727. "\"%s\\%s\"",
  4728. full_dir,
  4729. prog);
  4730. }
  4731. if (truncated) {
  4732. pi.hProcess = (pid_t)-1;
  4733. goto spawn_cleanup;
  4734. }
  4735. DEBUG_TRACE("Running [%s]", cmdline);
  4736. if (CreateProcessA(NULL,
  4737. cmdline,
  4738. NULL,
  4739. NULL,
  4740. TRUE,
  4741. CREATE_NEW_PROCESS_GROUP,
  4742. envblk,
  4743. NULL,
  4744. &si,
  4745. &pi)
  4746. == 0) {
  4747. mg_cry_internal(
  4748. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4749. pi.hProcess = (pid_t)-1;
  4750. /* goto spawn_cleanup; */
  4751. }
  4752. spawn_cleanup:
  4753. (void)CloseHandle(si.hStdOutput);
  4754. (void)CloseHandle(si.hStdError);
  4755. (void)CloseHandle(si.hStdInput);
  4756. if (pi.hThread != NULL) {
  4757. (void)CloseHandle(pi.hThread);
  4758. }
  4759. return (pid_t)pi.hProcess;
  4760. }
  4761. #endif /* !NO_CGI */
  4762. static int
  4763. set_blocking_mode(SOCKET sock)
  4764. {
  4765. unsigned long non_blocking = 0;
  4766. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4767. }
  4768. static int
  4769. set_non_blocking_mode(SOCKET sock)
  4770. {
  4771. unsigned long non_blocking = 1;
  4772. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4773. }
  4774. #else
  4775. #if !defined(NO_FILESYSTEMS)
  4776. static int
  4777. mg_stat(const struct mg_connection *conn,
  4778. const char *path,
  4779. struct mg_file_stat *filep)
  4780. {
  4781. struct stat st;
  4782. if (!filep) {
  4783. return 0;
  4784. }
  4785. memset(filep, 0, sizeof(*filep));
  4786. if (mg_path_suspicious(conn, path)) {
  4787. return 0;
  4788. }
  4789. if (0 == stat(path, &st)) {
  4790. filep->size = (uint64_t)(st.st_size);
  4791. filep->last_modified = st.st_mtime;
  4792. filep->is_directory = S_ISDIR(st.st_mode);
  4793. return 1;
  4794. }
  4795. return 0;
  4796. }
  4797. #endif /* NO_FILESYSTEMS */
  4798. static void
  4799. set_close_on_exec(int fd,
  4800. const struct mg_connection *conn /* may be null */,
  4801. struct mg_context *ctx /* may be null */)
  4802. {
  4803. #if defined(__ZEPHYR__)
  4804. (void)fd;
  4805. (void)conn;
  4806. (void)ctx;
  4807. #else
  4808. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4809. if (conn || ctx) {
  4810. struct mg_connection fc;
  4811. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4812. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4813. __func__,
  4814. strerror(ERRNO));
  4815. }
  4816. }
  4817. #endif
  4818. }
  4819. CIVETWEB_API int
  4820. mg_start_thread(mg_thread_func_t func, void *param)
  4821. {
  4822. pthread_t thread_id;
  4823. pthread_attr_t attr;
  4824. int result;
  4825. (void)pthread_attr_init(&attr);
  4826. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4827. #if defined(__ZEPHYR__)
  4828. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4829. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4830. /* Compile-time option to control stack size,
  4831. * e.g. -DUSE_STACK_SIZE=16384 */
  4832. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4833. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4834. result = pthread_create(&thread_id, &attr, func, param);
  4835. pthread_attr_destroy(&attr);
  4836. return result;
  4837. }
  4838. /* Start a thread storing the thread context. */
  4839. static int
  4840. mg_start_thread_with_id(mg_thread_func_t func,
  4841. void *param,
  4842. pthread_t *threadidptr)
  4843. {
  4844. pthread_t thread_id;
  4845. pthread_attr_t attr;
  4846. int result;
  4847. (void)pthread_attr_init(&attr);
  4848. #if defined(__ZEPHYR__)
  4849. pthread_attr_setstack(&attr,
  4850. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4851. ZEPHYR_STACK_SIZE);
  4852. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4853. /* Compile-time option to control stack size,
  4854. * e.g. -DUSE_STACK_SIZE=16384 */
  4855. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4856. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4857. result = pthread_create(&thread_id, &attr, func, param);
  4858. pthread_attr_destroy(&attr);
  4859. if ((result == 0) && (threadidptr != NULL)) {
  4860. *threadidptr = thread_id;
  4861. }
  4862. return result;
  4863. }
  4864. /* Wait for a thread to finish. */
  4865. static int
  4866. mg_join_thread(pthread_t threadid)
  4867. {
  4868. int result;
  4869. result = pthread_join(threadid, NULL);
  4870. return result;
  4871. }
  4872. #if !defined(NO_CGI)
  4873. static pid_t
  4874. spawn_process(struct mg_connection *conn,
  4875. const char *prog,
  4876. char *envblk,
  4877. char *envp[],
  4878. int fdin[2],
  4879. int fdout[2],
  4880. int fderr[2],
  4881. const char *dir,
  4882. int cgi_config_idx)
  4883. {
  4884. pid_t pid;
  4885. const char *interp;
  4886. (void)envblk;
  4887. if ((pid = fork()) == -1) {
  4888. /* Parent */
  4889. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4890. } else if (pid != 0) {
  4891. /* Make sure children close parent-side descriptors.
  4892. * The caller will close the child-side immediately. */
  4893. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4894. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4895. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4896. } else {
  4897. /* Child */
  4898. if (chdir(dir) != 0) {
  4899. mg_cry_internal(
  4900. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4901. } else if (dup2(fdin[0], 0) == -1) {
  4902. mg_cry_internal(conn,
  4903. "%s: dup2(%d, 0): %s",
  4904. __func__,
  4905. fdin[0],
  4906. strerror(ERRNO));
  4907. } else if (dup2(fdout[1], 1) == -1) {
  4908. mg_cry_internal(conn,
  4909. "%s: dup2(%d, 1): %s",
  4910. __func__,
  4911. fdout[1],
  4912. strerror(ERRNO));
  4913. } else if (dup2(fderr[1], 2) == -1) {
  4914. mg_cry_internal(conn,
  4915. "%s: dup2(%d, 2): %s",
  4916. __func__,
  4917. fderr[1],
  4918. strerror(ERRNO));
  4919. } else {
  4920. struct sigaction sa;
  4921. /* Keep stderr and stdout in two different pipes.
  4922. * Stdout will be sent back to the client,
  4923. * stderr should go into a server error log. */
  4924. (void)close(fdin[0]);
  4925. (void)close(fdout[1]);
  4926. (void)close(fderr[1]);
  4927. /* Close write end fdin and read end fdout and fderr */
  4928. (void)close(fdin[1]);
  4929. (void)close(fdout[0]);
  4930. (void)close(fderr[0]);
  4931. /* After exec, all signal handlers are restored to their default
  4932. * values, with one exception of SIGCHLD. According to
  4933. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4934. * will leave unchanged after exec if it was set to be ignored.
  4935. * Restore it to default action. */
  4936. memset(&sa, 0, sizeof(sa));
  4937. sa.sa_handler = SIG_DFL;
  4938. sigaction(SIGCHLD, &sa, NULL);
  4939. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4940. if (interp == NULL) {
  4941. /* no interpreter configured, call the program directly */
  4942. (void)execle(prog, prog, NULL, envp);
  4943. mg_cry_internal(conn,
  4944. "%s: execle(%s): %s",
  4945. __func__,
  4946. prog,
  4947. strerror(ERRNO));
  4948. } else {
  4949. /* call the configured interpreter */
  4950. const char *interp_args =
  4951. conn->dom_ctx
  4952. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4953. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4954. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4955. } else {
  4956. (void)execle(interp, interp, prog, NULL, envp);
  4957. }
  4958. mg_cry_internal(conn,
  4959. "%s: execle(%s %s): %s",
  4960. __func__,
  4961. interp,
  4962. prog,
  4963. strerror(ERRNO));
  4964. }
  4965. }
  4966. exit(EXIT_FAILURE);
  4967. }
  4968. return pid;
  4969. }
  4970. #endif /* !NO_CGI */
  4971. static int
  4972. set_non_blocking_mode(SOCKET sock)
  4973. {
  4974. int flags = fcntl(sock, F_GETFL, 0);
  4975. if (flags < 0) {
  4976. return -1;
  4977. }
  4978. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4979. return -1;
  4980. }
  4981. return 0;
  4982. }
  4983. static int
  4984. set_blocking_mode(SOCKET sock)
  4985. {
  4986. int flags = fcntl(sock, F_GETFL, 0);
  4987. if (flags < 0) {
  4988. return -1;
  4989. }
  4990. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4991. return -1;
  4992. }
  4993. return 0;
  4994. }
  4995. #endif /* _WIN32 / else */
  4996. /* End of initial operating system specific define block. */
  4997. /* Get a random number (independent of C rand function) */
  4998. static uint64_t
  4999. get_random(void)
  5000. {
  5001. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5002. static uint64_t lcg = 0; /* Linear congruential generator */
  5003. uint64_t now = mg_get_current_time_ns();
  5004. if (lfsr == 0) {
  5005. /* lfsr will be only 0 if has not been initialized,
  5006. * so this code is called only once. */
  5007. lfsr = mg_get_current_time_ns();
  5008. lcg = mg_get_current_time_ns();
  5009. } else {
  5010. /* Get the next step of both random number generators. */
  5011. lfsr = (lfsr >> 1)
  5012. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5013. << 63);
  5014. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5015. }
  5016. /* Combining two pseudo-random number generators and a high resolution
  5017. * part
  5018. * of the current server time will make it hard (impossible?) to guess
  5019. * the
  5020. * next number. */
  5021. return (lfsr ^ lcg ^ now);
  5022. }
  5023. static int
  5024. mg_poll(struct mg_pollfd *pfd,
  5025. unsigned int n,
  5026. int milliseconds,
  5027. const stop_flag_t *stop_flag)
  5028. {
  5029. /* Call poll, but only for a maximum time of a few seconds.
  5030. * This will allow to stop the server after some seconds, instead
  5031. * of having to wait for a long socket timeout. */
  5032. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5033. int check_pollerr = 0;
  5034. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5035. /* If we wait for only one file descriptor, wait on error as well */
  5036. pfd[0].events |= POLLERR;
  5037. check_pollerr = 1;
  5038. }
  5039. do {
  5040. int result;
  5041. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5042. /* Shut down signal */
  5043. return -2;
  5044. }
  5045. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5046. ms_now = milliseconds;
  5047. }
  5048. result = poll(pfd, n, ms_now);
  5049. if (result != 0) {
  5050. int err = ERRNO;
  5051. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5052. /* Poll returned either success (1) or error (-1).
  5053. * Forward both to the caller. */
  5054. if ((check_pollerr)
  5055. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5056. == POLLERR)) {
  5057. /* One and only file descriptor returned error */
  5058. return -1;
  5059. }
  5060. return result;
  5061. }
  5062. }
  5063. /* Poll returned timeout (0). */
  5064. if (milliseconds > 0) {
  5065. milliseconds -= ms_now;
  5066. }
  5067. } while (milliseconds > 0);
  5068. /* timeout: return 0 */
  5069. return 0;
  5070. }
  5071. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5072. * descriptor.
  5073. * Return value:
  5074. * >=0 .. number of bytes successfully written
  5075. * -1 .. timeout
  5076. * -2 .. error
  5077. */
  5078. static int
  5079. push_inner(struct mg_context *ctx,
  5080. FILE *fp,
  5081. SOCKET sock,
  5082. SSL *ssl,
  5083. const char *buf,
  5084. int len,
  5085. double timeout)
  5086. {
  5087. uint64_t start = 0, now = 0, timeout_ns = 0;
  5088. int n, err;
  5089. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5090. #if defined(_WIN32)
  5091. typedef int len_t;
  5092. #else
  5093. typedef size_t len_t;
  5094. #endif
  5095. if (timeout > 0) {
  5096. now = mg_get_current_time_ns();
  5097. start = now;
  5098. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5099. }
  5100. if (ctx == NULL) {
  5101. return -2;
  5102. }
  5103. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5104. if (ssl) {
  5105. return -2;
  5106. }
  5107. #endif
  5108. /* Try to read until it succeeds, fails, times out, or the server
  5109. * shuts down. */
  5110. for (;;) {
  5111. #if defined(USE_MBEDTLS)
  5112. if (ssl != NULL) {
  5113. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5114. if (n <= 0) {
  5115. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5116. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5117. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5118. n = 0;
  5119. } else {
  5120. fprintf(stderr, "SSL write failed, error %d\n", n);
  5121. return -2;
  5122. }
  5123. } else {
  5124. err = 0;
  5125. }
  5126. } else
  5127. #elif !defined(NO_SSL)
  5128. if (ssl != NULL) {
  5129. ERR_clear_error();
  5130. n = SSL_write(ssl, buf, len);
  5131. if (n <= 0) {
  5132. err = SSL_get_error(ssl, n);
  5133. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5134. err = ERRNO;
  5135. } else if ((err == SSL_ERROR_WANT_READ)
  5136. || (err == SSL_ERROR_WANT_WRITE)) {
  5137. n = 0;
  5138. } else {
  5139. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5140. ERR_clear_error();
  5141. return -2;
  5142. }
  5143. ERR_clear_error();
  5144. } else {
  5145. err = 0;
  5146. }
  5147. } else
  5148. #endif
  5149. if (fp != NULL) {
  5150. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5151. if (ferror(fp)) {
  5152. n = -1;
  5153. err = ERRNO;
  5154. } else {
  5155. err = 0;
  5156. }
  5157. } else {
  5158. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5159. err = (n < 0) ? ERRNO : 0;
  5160. if (ERROR_TRY_AGAIN(err)) {
  5161. err = 0;
  5162. n = 0;
  5163. }
  5164. if (n < 0) {
  5165. /* shutdown of the socket at client side */
  5166. return -2;
  5167. }
  5168. }
  5169. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5170. return -2;
  5171. }
  5172. if ((n > 0) || ((n == 0) && (len == 0))) {
  5173. /* some data has been read, or no data was requested */
  5174. return n;
  5175. }
  5176. if (n < 0) {
  5177. /* socket error - check errno */
  5178. DEBUG_TRACE("send() failed, error %d", err);
  5179. /* TODO (mid): error handling depending on the error code.
  5180. * These codes are different between Windows and Linux.
  5181. * Currently there is no problem with failing send calls,
  5182. * if there is a reproducible situation, it should be
  5183. * investigated in detail.
  5184. */
  5185. return -2;
  5186. }
  5187. /* Only in case n=0 (timeout), repeat calling the write function */
  5188. /* If send failed, wait before retry */
  5189. if (fp != NULL) {
  5190. /* For files, just wait a fixed time.
  5191. * Maybe it helps, maybe not. */
  5192. mg_sleep(5);
  5193. } else {
  5194. /* For sockets, wait for the socket using poll */
  5195. struct mg_pollfd pfd[1];
  5196. int pollres;
  5197. pfd[0].fd = sock;
  5198. pfd[0].events = POLLOUT;
  5199. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5200. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5201. return -2;
  5202. }
  5203. if (pollres > 0) {
  5204. continue;
  5205. }
  5206. }
  5207. if (timeout > 0) {
  5208. now = mg_get_current_time_ns();
  5209. if ((now - start) > timeout_ns) {
  5210. /* Timeout */
  5211. break;
  5212. }
  5213. }
  5214. }
  5215. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5216. used */
  5217. return -1;
  5218. }
  5219. static int
  5220. push_all(struct mg_context *ctx,
  5221. FILE *fp,
  5222. SOCKET sock,
  5223. SSL *ssl,
  5224. const char *buf,
  5225. int len)
  5226. {
  5227. double timeout = -1.0;
  5228. int n, nwritten = 0;
  5229. if (ctx == NULL) {
  5230. return -1;
  5231. }
  5232. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5233. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5234. }
  5235. if (timeout <= 0.0) {
  5236. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5237. / 1000.0;
  5238. }
  5239. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5240. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5241. if (n < 0) {
  5242. if (nwritten == 0) {
  5243. nwritten = -1; /* Propagate the error */
  5244. }
  5245. break;
  5246. } else if (n == 0) {
  5247. break; /* No more data to write */
  5248. } else {
  5249. nwritten += n;
  5250. len -= n;
  5251. }
  5252. }
  5253. return nwritten;
  5254. }
  5255. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5256. * Return value:
  5257. * >=0 .. number of bytes successfully read
  5258. * -1 .. timeout
  5259. * -2 .. error
  5260. */
  5261. static int
  5262. pull_inner(FILE *fp,
  5263. struct mg_connection *conn,
  5264. char *buf,
  5265. int len,
  5266. double timeout)
  5267. {
  5268. int nread, err = 0;
  5269. #if defined(_WIN32)
  5270. typedef int len_t;
  5271. #else
  5272. typedef size_t len_t;
  5273. #endif
  5274. /* We need an additional wait loop around this, because in some cases
  5275. * with TLSwe may get data from the socket but not from SSL_read.
  5276. * In this case we need to repeat at least once.
  5277. */
  5278. if (fp != NULL) {
  5279. /* Use read() instead of fread(), because if we're reading from the
  5280. * CGI pipe, fread() may block until IO buffer is filled up. We
  5281. * cannot afford to block and must pass all read bytes immediately
  5282. * to the client. */
  5283. nread = (int)read(fileno(fp), buf, (size_t)len);
  5284. err = (nread < 0) ? ERRNO : 0;
  5285. if ((nread == 0) && (len > 0)) {
  5286. /* Should get data, but got EOL */
  5287. return -2;
  5288. }
  5289. #if defined(USE_MBEDTLS)
  5290. } else if (conn->ssl != NULL) {
  5291. struct mg_pollfd pfd[1];
  5292. int to_read;
  5293. int pollres;
  5294. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5295. if (to_read > 0) {
  5296. /* We already know there is no more data buffered in conn->buf
  5297. * but there is more available in the SSL layer. So don't poll
  5298. * conn->client.sock yet. */
  5299. pollres = 1;
  5300. if (to_read > len)
  5301. to_read = len;
  5302. } else {
  5303. pfd[0].fd = conn->client.sock;
  5304. pfd[0].events = POLLIN;
  5305. to_read = len;
  5306. pollres = mg_poll(pfd,
  5307. 1,
  5308. (int)(timeout * 1000.0),
  5309. &(conn->phys_ctx->stop_flag));
  5310. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5311. return -2;
  5312. }
  5313. }
  5314. if (pollres > 0) {
  5315. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5316. if (nread <= 0) {
  5317. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5318. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5319. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5320. nread = 0;
  5321. } else {
  5322. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5323. return -2;
  5324. }
  5325. } else {
  5326. err = 0;
  5327. }
  5328. } else if (pollres < 0) {
  5329. /* Error */
  5330. return -2;
  5331. } else {
  5332. /* pollres = 0 means timeout */
  5333. nread = 0;
  5334. }
  5335. #elif !defined(NO_SSL)
  5336. } else if (conn->ssl != NULL) {
  5337. int ssl_pending;
  5338. struct mg_pollfd pfd[1];
  5339. int pollres;
  5340. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5341. /* We already know there is no more data buffered in conn->buf
  5342. * but there is more available in the SSL layer. So don't poll
  5343. * conn->client.sock yet. */
  5344. if (ssl_pending > len) {
  5345. ssl_pending = len;
  5346. }
  5347. pollres = 1;
  5348. } else {
  5349. pfd[0].fd = conn->client.sock;
  5350. pfd[0].events = POLLIN;
  5351. pollres = mg_poll(pfd,
  5352. 1,
  5353. (int)(timeout * 1000.0),
  5354. &(conn->phys_ctx->stop_flag));
  5355. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5356. return -2;
  5357. }
  5358. }
  5359. if (pollres > 0) {
  5360. ERR_clear_error();
  5361. nread =
  5362. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5363. if (nread <= 0) {
  5364. err = SSL_get_error(conn->ssl, nread);
  5365. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5366. err = ERRNO;
  5367. } else if ((err == SSL_ERROR_WANT_READ)
  5368. || (err == SSL_ERROR_WANT_WRITE)) {
  5369. nread = 0;
  5370. } else {
  5371. /* All errors should return -2 */
  5372. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5373. ERR_clear_error();
  5374. return -2;
  5375. }
  5376. ERR_clear_error();
  5377. } else {
  5378. err = 0;
  5379. }
  5380. } else if (pollres < 0) {
  5381. /* Error */
  5382. return -2;
  5383. } else {
  5384. /* pollres = 0 means timeout */
  5385. nread = 0;
  5386. }
  5387. #endif
  5388. } else {
  5389. struct mg_pollfd pfd[1];
  5390. int pollres;
  5391. pfd[0].fd = conn->client.sock;
  5392. pfd[0].events = POLLIN;
  5393. pollres = mg_poll(pfd,
  5394. 1,
  5395. (int)(timeout * 1000.0),
  5396. &(conn->phys_ctx->stop_flag));
  5397. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5398. return -2;
  5399. }
  5400. if (pollres > 0) {
  5401. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5402. err = (nread < 0) ? ERRNO : 0;
  5403. if (nread <= 0) {
  5404. /* shutdown of the socket at client side */
  5405. return -2;
  5406. }
  5407. } else if (pollres < 0) {
  5408. /* error calling poll */
  5409. return -2;
  5410. } else {
  5411. /* pollres = 0 means timeout */
  5412. nread = 0;
  5413. }
  5414. }
  5415. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5416. return -2;
  5417. }
  5418. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5419. /* some data has been read, or no data was requested */
  5420. return nread;
  5421. }
  5422. if (nread < 0) {
  5423. /* socket error - check errno */
  5424. #if defined(_WIN32)
  5425. if (err == WSAEWOULDBLOCK) {
  5426. /* TODO (low): check if this is still required */
  5427. /* standard case if called from close_socket_gracefully */
  5428. return -2;
  5429. } else if (err == WSAETIMEDOUT) {
  5430. /* TODO (low): check if this is still required */
  5431. /* timeout is handled by the while loop */
  5432. return 0;
  5433. } else if (err == WSAECONNABORTED) {
  5434. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5435. return -2;
  5436. } else {
  5437. DEBUG_TRACE("recv() failed, error %d", err);
  5438. return -2;
  5439. }
  5440. #else
  5441. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5442. * if the timeout is reached and if the socket was set to non-
  5443. * blocking in close_socket_gracefully, so we can not distinguish
  5444. * here. We have to wait for the timeout in both cases for now.
  5445. */
  5446. if (ERROR_TRY_AGAIN(err)) {
  5447. /* TODO (low): check if this is still required */
  5448. /* EAGAIN/EWOULDBLOCK:
  5449. * standard case if called from close_socket_gracefully
  5450. * => should return -1 */
  5451. /* or timeout occurred
  5452. * => the code must stay in the while loop */
  5453. /* EINTR can be generated on a socket with a timeout set even
  5454. * when SA_RESTART is effective for all relevant signals
  5455. * (see signal(7)).
  5456. * => stay in the while loop */
  5457. } else {
  5458. DEBUG_TRACE("recv() failed, error %d", err);
  5459. return -2;
  5460. }
  5461. #endif
  5462. }
  5463. /* Timeout occurred, but no data available. */
  5464. return -1;
  5465. }
  5466. static int
  5467. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5468. {
  5469. int n, nread = 0;
  5470. double timeout = -1.0;
  5471. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5472. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5473. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5474. }
  5475. if (timeout <= 0.0) {
  5476. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5477. / 1000.0;
  5478. }
  5479. start_time = mg_get_current_time_ns();
  5480. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5481. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5482. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5483. if (n == -2) {
  5484. if (nread == 0) {
  5485. nread = -1; /* Propagate the error */
  5486. }
  5487. break;
  5488. } else if (n == -1) {
  5489. /* timeout */
  5490. if (timeout >= 0.0) {
  5491. now = mg_get_current_time_ns();
  5492. if ((now - start_time) <= timeout_ns) {
  5493. continue;
  5494. }
  5495. }
  5496. break;
  5497. } else if (n == 0) {
  5498. break; /* No more data to read */
  5499. } else {
  5500. nread += n;
  5501. len -= n;
  5502. }
  5503. }
  5504. return nread;
  5505. }
  5506. static void
  5507. discard_unread_request_data(struct mg_connection *conn)
  5508. {
  5509. char buf[MG_BUF_LEN];
  5510. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5511. ;
  5512. }
  5513. static int
  5514. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5515. {
  5516. int64_t content_len, n, buffered_len, nread;
  5517. int64_t len64 =
  5518. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5519. * int, we may not read more
  5520. * bytes */
  5521. const char *body;
  5522. if (conn == NULL) {
  5523. return 0;
  5524. }
  5525. /* If Content-Length is not set for a response with body data,
  5526. * we do not know in advance how much data should be read. */
  5527. content_len = conn->content_len;
  5528. if (content_len < 0) {
  5529. /* The body data is completed when the connection is closed. */
  5530. content_len = INT64_MAX;
  5531. }
  5532. nread = 0;
  5533. if (conn->consumed_content < content_len) {
  5534. /* Adjust number of bytes to read. */
  5535. int64_t left_to_read = content_len - conn->consumed_content;
  5536. if (left_to_read < len64) {
  5537. /* Do not read more than the total content length of the
  5538. * request.
  5539. */
  5540. len64 = left_to_read;
  5541. }
  5542. /* Return buffered data */
  5543. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5544. - conn->consumed_content;
  5545. if (buffered_len > 0) {
  5546. if (len64 < buffered_len) {
  5547. buffered_len = len64;
  5548. }
  5549. body = conn->buf + conn->request_len + conn->consumed_content;
  5550. memcpy(buf, body, (size_t)buffered_len);
  5551. len64 -= buffered_len;
  5552. conn->consumed_content += buffered_len;
  5553. nread += buffered_len;
  5554. buf = (char *)buf + buffered_len;
  5555. }
  5556. /* We have returned all buffered data. Read new data from the remote
  5557. * socket.
  5558. */
  5559. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5560. conn->consumed_content += n;
  5561. nread += n;
  5562. } else {
  5563. nread = ((nread > 0) ? nread : n);
  5564. }
  5565. }
  5566. return (int)nread;
  5567. }
  5568. /* Forward declarations */
  5569. static void handle_request(struct mg_connection *);
  5570. static void log_access(const struct mg_connection *);
  5571. /* Handle request, update statistics and call access log */
  5572. static void
  5573. handle_request_stat_log(struct mg_connection *conn)
  5574. {
  5575. #if defined(USE_SERVER_STATS)
  5576. struct timespec tnow;
  5577. conn->conn_state = 4; /* processing */
  5578. #endif
  5579. handle_request(conn);
  5580. #if defined(USE_SERVER_STATS)
  5581. conn->conn_state = 5; /* processed */
  5582. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5583. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5584. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5585. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5586. conn->num_bytes_sent);
  5587. #endif
  5588. DEBUG_TRACE("%s", "handle_request done");
  5589. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5590. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5591. DEBUG_TRACE("%s", "end_request callback done");
  5592. }
  5593. log_access(conn);
  5594. }
  5595. #if defined(USE_HTTP2)
  5596. #if defined(NO_SSL)
  5597. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5598. #endif
  5599. #define USE_ALPN
  5600. #include "http2.inl"
  5601. /* Not supported with HTTP/2 */
  5602. #define HTTP1_only \
  5603. { \
  5604. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5605. http2_must_use_http1(conn); \
  5606. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5607. return; \
  5608. } \
  5609. }
  5610. #else
  5611. #define HTTP1_only
  5612. #endif
  5613. CIVETWEB_API int
  5614. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5615. {
  5616. if (len > INT_MAX) {
  5617. len = INT_MAX;
  5618. }
  5619. if (conn == NULL) {
  5620. return 0;
  5621. }
  5622. if (conn->is_chunked) {
  5623. size_t all_read = 0;
  5624. while (len > 0) {
  5625. if (conn->is_chunked >= 3) {
  5626. /* No more data left to read */
  5627. return 0;
  5628. }
  5629. if (conn->is_chunked != 1) {
  5630. /* Has error */
  5631. return -1;
  5632. }
  5633. if (conn->consumed_content != conn->content_len) {
  5634. /* copy from the current chunk */
  5635. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5636. if (read_ret < 1) {
  5637. /* read error */
  5638. conn->is_chunked = 2;
  5639. return -1;
  5640. }
  5641. all_read += (size_t)read_ret;
  5642. len -= (size_t)read_ret;
  5643. if (conn->consumed_content == conn->content_len) {
  5644. /* Add data bytes in the current chunk have been read,
  5645. * so we are expecting \r\n now. */
  5646. char x[2];
  5647. conn->content_len += 2;
  5648. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5649. || (x[1] != '\n')) {
  5650. /* Protocol violation */
  5651. conn->is_chunked = 2;
  5652. return -1;
  5653. }
  5654. }
  5655. } else {
  5656. /* fetch a new chunk */
  5657. size_t i;
  5658. char lenbuf[64];
  5659. char *end = NULL;
  5660. unsigned long chunkSize = 0;
  5661. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5662. conn->content_len++;
  5663. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5664. lenbuf[i] = 0;
  5665. }
  5666. if ((i > 0) && (lenbuf[i] == ';')) {
  5667. // chunk extension --> skip chars until next CR
  5668. //
  5669. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5670. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5671. //
  5672. // chunk = chunk-size [ chunk-extension ] CRLF
  5673. // chunk-data CRLF
  5674. // ...
  5675. // chunk-extension= *( ";" chunk-ext-name [ "="
  5676. // chunk-ext-val ] )
  5677. do
  5678. ++conn->content_len;
  5679. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5680. && lenbuf[i] != '\r');
  5681. }
  5682. if ((i > 0) && (lenbuf[i] == '\r')
  5683. && (lenbuf[i - 1] != '\r')) {
  5684. continue;
  5685. }
  5686. if ((i > 1) && (lenbuf[i] == '\n')
  5687. && (lenbuf[i - 1] == '\r')) {
  5688. lenbuf[i + 1] = 0;
  5689. chunkSize = strtoul(lenbuf, &end, 16);
  5690. if (chunkSize == 0) {
  5691. /* regular end of content */
  5692. conn->is_chunked = 3;
  5693. }
  5694. break;
  5695. }
  5696. if (!isxdigit((unsigned char)lenbuf[i])) {
  5697. /* illegal character for chunk length */
  5698. conn->is_chunked = 2;
  5699. return -1;
  5700. }
  5701. }
  5702. if ((end == NULL) || (*end != '\r')) {
  5703. /* chunksize not set correctly */
  5704. conn->is_chunked = 2;
  5705. return -1;
  5706. }
  5707. if (conn->is_chunked == 3) {
  5708. /* try discarding trailer for keep-alive */
  5709. // We found the last chunk (length 0) including the
  5710. // CRLF that terminates that chunk. Now follows a possibly
  5711. // empty trailer and a final CRLF.
  5712. //
  5713. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5714. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5715. //
  5716. // Chunked-Body = *chunk
  5717. // last-chunk
  5718. // trailer
  5719. // CRLF
  5720. // ...
  5721. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5722. // ...
  5723. // trailer = *(entity-header CRLF)
  5724. int crlf_count = 2; // one CRLF already determined
  5725. while (crlf_count < 4 && conn->is_chunked == 3) {
  5726. ++conn->content_len;
  5727. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5728. if ((crlf_count == 0 || crlf_count == 2)) {
  5729. if (lenbuf[0] == '\r')
  5730. ++crlf_count;
  5731. else
  5732. crlf_count = 0;
  5733. } else {
  5734. // previous character was a CR
  5735. // --> next character must be LF
  5736. if (lenbuf[0] == '\n')
  5737. ++crlf_count;
  5738. else
  5739. conn->is_chunked = 2;
  5740. }
  5741. } else
  5742. // premature end of trailer
  5743. conn->is_chunked = 2;
  5744. }
  5745. if (conn->is_chunked == 2)
  5746. return -1;
  5747. else
  5748. conn->is_chunked = 4;
  5749. break;
  5750. }
  5751. /* append a new chunk */
  5752. conn->content_len += (int64_t)chunkSize;
  5753. }
  5754. }
  5755. return (int)all_read;
  5756. }
  5757. return mg_read_inner(conn, buf, len);
  5758. }
  5759. CIVETWEB_API int
  5760. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5761. {
  5762. time_t now;
  5763. int n, total, allowed;
  5764. if (conn == NULL) {
  5765. return 0;
  5766. }
  5767. if (len > INT_MAX) {
  5768. return -1;
  5769. }
  5770. /* Mark connection as "data sent" */
  5771. conn->request_state = 10;
  5772. #if defined(USE_HTTP2)
  5773. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5774. http2_data_frame_head(conn, len, 0);
  5775. }
  5776. #endif
  5777. if (conn->throttle > 0) {
  5778. if ((now = time(NULL)) != conn->last_throttle_time) {
  5779. conn->last_throttle_time = now;
  5780. conn->last_throttle_bytes = 0;
  5781. }
  5782. allowed = conn->throttle - conn->last_throttle_bytes;
  5783. if (allowed > (int)len) {
  5784. allowed = (int)len;
  5785. }
  5786. total = push_all(conn->phys_ctx,
  5787. NULL,
  5788. conn->client.sock,
  5789. conn->ssl,
  5790. (const char *)buf,
  5791. allowed);
  5792. if (total == allowed) {
  5793. buf = (const char *)buf + total;
  5794. conn->last_throttle_bytes += total;
  5795. while ((total < (int)len)
  5796. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5797. allowed = (conn->throttle > ((int)len - total))
  5798. ? (int)len - total
  5799. : conn->throttle;
  5800. n = push_all(conn->phys_ctx,
  5801. NULL,
  5802. conn->client.sock,
  5803. conn->ssl,
  5804. (const char *)buf,
  5805. allowed);
  5806. if (n != allowed) {
  5807. break;
  5808. }
  5809. sleep(1);
  5810. conn->last_throttle_bytes = allowed;
  5811. conn->last_throttle_time = time(NULL);
  5812. buf = (const char *)buf + n;
  5813. total += n;
  5814. }
  5815. }
  5816. } else {
  5817. total = push_all(conn->phys_ctx,
  5818. NULL,
  5819. conn->client.sock,
  5820. conn->ssl,
  5821. (const char *)buf,
  5822. (int)len);
  5823. }
  5824. if (total > 0) {
  5825. conn->num_bytes_sent += total;
  5826. }
  5827. return total;
  5828. }
  5829. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5830. CIVETWEB_API int
  5831. mg_send_chunk(struct mg_connection *conn,
  5832. const char *chunk,
  5833. unsigned int chunk_len)
  5834. {
  5835. char lenbuf[16];
  5836. size_t lenbuf_len;
  5837. int ret;
  5838. int t;
  5839. /* First store the length information in a text buffer. */
  5840. sprintf(lenbuf, "%x\r\n", chunk_len);
  5841. lenbuf_len = strlen(lenbuf);
  5842. /* Then send length information, chunk and terminating \r\n. */
  5843. ret = mg_write(conn, lenbuf, lenbuf_len);
  5844. if (ret != (int)lenbuf_len) {
  5845. return -1;
  5846. }
  5847. t = ret;
  5848. ret = mg_write(conn, chunk, chunk_len);
  5849. if (ret != (int)chunk_len) {
  5850. return -1;
  5851. }
  5852. t += ret;
  5853. ret = mg_write(conn, "\r\n", 2);
  5854. if (ret != 2) {
  5855. return -1;
  5856. }
  5857. t += ret;
  5858. return t;
  5859. }
  5860. #if defined(GCC_DIAGNOSTIC)
  5861. /* This block forwards format strings to printf implementations,
  5862. * so we need to disable the format-nonliteral warning. */
  5863. #pragma GCC diagnostic push
  5864. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5865. #endif
  5866. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5867. static int
  5868. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5869. {
  5870. va_list ap_copy;
  5871. size_t size = MG_BUF_LEN / 4;
  5872. int len = -1;
  5873. *buf = NULL;
  5874. while (len < 0) {
  5875. if (*buf) {
  5876. mg_free(*buf);
  5877. }
  5878. size *= 4;
  5879. *buf = (char *)mg_malloc(size);
  5880. if (!*buf) {
  5881. break;
  5882. }
  5883. va_copy(ap_copy, ap);
  5884. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5885. va_end(ap_copy);
  5886. (*buf)[size - 1] = 0;
  5887. }
  5888. return len;
  5889. }
  5890. /* Print message to buffer. If buffer is large enough to hold the message,
  5891. * return buffer. If buffer is to small, allocate large enough buffer on
  5892. * heap,
  5893. * and return allocated buffer. */
  5894. static int
  5895. alloc_vprintf(char **out_buf,
  5896. char *prealloc_buf,
  5897. size_t prealloc_size,
  5898. const char *fmt,
  5899. va_list ap)
  5900. {
  5901. va_list ap_copy;
  5902. int len;
  5903. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5904. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5905. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5906. * Therefore, we make two passes: on first pass, get required message
  5907. * length.
  5908. * On second pass, actually print the message. */
  5909. va_copy(ap_copy, ap);
  5910. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5911. va_end(ap_copy);
  5912. if (len < 0) {
  5913. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5914. * Switch to alternative code path that uses incremental
  5915. * allocations.
  5916. */
  5917. va_copy(ap_copy, ap);
  5918. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5919. va_end(ap_copy);
  5920. } else if ((size_t)(len) >= prealloc_size) {
  5921. /* The pre-allocated buffer not large enough. */
  5922. /* Allocate a new buffer. */
  5923. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5924. if (!*out_buf) {
  5925. /* Allocation failed. Return -1 as "out of memory" error. */
  5926. return -1;
  5927. }
  5928. /* Buffer allocation successful. Store the string there. */
  5929. va_copy(ap_copy, ap);
  5930. IGNORE_UNUSED_RESULT(
  5931. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5932. va_end(ap_copy);
  5933. } else {
  5934. /* The pre-allocated buffer is large enough.
  5935. * Use it to store the string and return the address. */
  5936. va_copy(ap_copy, ap);
  5937. IGNORE_UNUSED_RESULT(
  5938. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5939. va_end(ap_copy);
  5940. *out_buf = prealloc_buf;
  5941. }
  5942. return len;
  5943. }
  5944. static int
  5945. alloc_printf(char **out_buf, const char *fmt, ...)
  5946. {
  5947. va_list ap;
  5948. int result;
  5949. va_start(ap, fmt);
  5950. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5951. va_end(ap);
  5952. return result;
  5953. }
  5954. #if defined(GCC_DIAGNOSTIC)
  5955. /* Enable format-nonliteral warning again. */
  5956. #pragma GCC diagnostic pop
  5957. #endif
  5958. static int
  5959. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5960. {
  5961. char mem[MG_BUF_LEN];
  5962. char *buf = NULL;
  5963. int len;
  5964. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5965. len = mg_write(conn, buf, (size_t)len);
  5966. }
  5967. if (buf != mem) {
  5968. mg_free(buf);
  5969. }
  5970. return len;
  5971. }
  5972. CIVETWEB_API int
  5973. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5974. {
  5975. va_list ap;
  5976. int result;
  5977. va_start(ap, fmt);
  5978. result = mg_vprintf(conn, fmt, ap);
  5979. va_end(ap);
  5980. return result;
  5981. }
  5982. CIVETWEB_API int
  5983. mg_url_decode(const char *src,
  5984. int src_len,
  5985. char *dst,
  5986. int dst_len,
  5987. int is_form_url_encoded)
  5988. {
  5989. int i, j, a, b;
  5990. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5991. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5992. if ((i < src_len - 2) && (src[i] == '%')
  5993. && isxdigit((unsigned char)src[i + 1])
  5994. && isxdigit((unsigned char)src[i + 2])) {
  5995. a = tolower((unsigned char)src[i + 1]);
  5996. b = tolower((unsigned char)src[i + 2]);
  5997. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5998. i += 2;
  5999. } else if (is_form_url_encoded && (src[i] == '+')) {
  6000. dst[j] = ' ';
  6001. } else {
  6002. dst[j] = src[i];
  6003. }
  6004. }
  6005. dst[j] = '\0'; /* Null-terminate the destination */
  6006. return (i >= src_len) ? j : -1;
  6007. }
  6008. /* form url decoding of an entire string */
  6009. static void
  6010. url_decode_in_place(char *buf)
  6011. {
  6012. int len = (int)strlen(buf);
  6013. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6014. }
  6015. CIVETWEB_API int
  6016. mg_get_var(const char *data,
  6017. size_t data_len,
  6018. const char *name,
  6019. char *dst,
  6020. size_t dst_len)
  6021. {
  6022. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6023. }
  6024. CIVETWEB_API int
  6025. mg_get_var2(const char *data,
  6026. size_t data_len,
  6027. const char *name,
  6028. char *dst,
  6029. size_t dst_len,
  6030. size_t occurrence)
  6031. {
  6032. const char *p, *e, *s;
  6033. size_t name_len;
  6034. int len;
  6035. if ((dst == NULL) || (dst_len == 0)) {
  6036. len = -2;
  6037. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6038. len = -1;
  6039. dst[0] = '\0';
  6040. } else {
  6041. name_len = strlen(name);
  6042. e = data + data_len;
  6043. len = -1;
  6044. dst[0] = '\0';
  6045. /* data is "var1=val1&var2=val2...". Find variable first */
  6046. for (p = data; p + name_len < e; p++) {
  6047. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6048. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6049. /* Point p to variable value */
  6050. p += name_len + 1;
  6051. /* Point s to the end of the value */
  6052. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6053. if (s == NULL) {
  6054. s = e;
  6055. }
  6056. DEBUG_ASSERT(s >= p);
  6057. if (s < p) {
  6058. return -3;
  6059. }
  6060. /* Decode variable into destination buffer */
  6061. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6062. /* Redirect error code from -1 to -2 (destination buffer too
  6063. * small). */
  6064. if (len == -1) {
  6065. len = -2;
  6066. }
  6067. break;
  6068. }
  6069. }
  6070. }
  6071. return len;
  6072. }
  6073. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6074. CIVETWEB_API int
  6075. mg_split_form_urlencoded(char *data,
  6076. struct mg_header *form_fields,
  6077. unsigned num_form_fields)
  6078. {
  6079. char *b;
  6080. int i;
  6081. int num = 0;
  6082. if (data == NULL) {
  6083. /* parameter error */
  6084. return -1;
  6085. }
  6086. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6087. /* determine the number of expected fields */
  6088. if (data[0] == 0) {
  6089. return 0;
  6090. }
  6091. /* count number of & to return the number of key-value-pairs */
  6092. num = 1;
  6093. while (*data) {
  6094. if (*data == '&') {
  6095. num++;
  6096. }
  6097. data++;
  6098. }
  6099. return num;
  6100. }
  6101. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6102. /* parameter error */
  6103. return -1;
  6104. }
  6105. for (i = 0; i < (int)num_form_fields; i++) {
  6106. /* extract key-value pairs from input data */
  6107. while ((*data == ' ') || (*data == '\t')) {
  6108. /* skip initial spaces */
  6109. data++;
  6110. }
  6111. if (*data == 0) {
  6112. /* end of string reached */
  6113. break;
  6114. }
  6115. form_fields[num].name = data;
  6116. /* find & or = */
  6117. b = data;
  6118. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6119. b++;
  6120. }
  6121. if (*b == 0) {
  6122. /* last key without value */
  6123. form_fields[num].value = NULL;
  6124. } else if (*b == '&') {
  6125. /* mid key without value */
  6126. form_fields[num].value = NULL;
  6127. } else {
  6128. /* terminate string */
  6129. *b = 0;
  6130. /* value starts after '=' */
  6131. data = b + 1;
  6132. form_fields[num].value = data;
  6133. }
  6134. /* new field is stored */
  6135. num++;
  6136. /* find a next key */
  6137. b = strchr(data, '&');
  6138. if (b == 0) {
  6139. /* no more data */
  6140. break;
  6141. } else {
  6142. /* terminate value of last field at '&' */
  6143. *b = 0;
  6144. /* next key-value-pairs starts after '&' */
  6145. data = b + 1;
  6146. }
  6147. }
  6148. /* Decode all values */
  6149. for (i = 0; i < num; i++) {
  6150. if (form_fields[i].name) {
  6151. url_decode_in_place((char *)form_fields[i].name);
  6152. }
  6153. if (form_fields[i].value) {
  6154. url_decode_in_place((char *)form_fields[i].value);
  6155. }
  6156. }
  6157. /* return number of fields found */
  6158. return num;
  6159. }
  6160. /* HCP24: some changes to compare whole var_name */
  6161. CIVETWEB_API int
  6162. mg_get_cookie(const char *cookie_header,
  6163. const char *var_name,
  6164. char *dst,
  6165. size_t dst_size)
  6166. {
  6167. const char *s, *p, *end;
  6168. int name_len, len = -1;
  6169. if ((dst == NULL) || (dst_size == 0)) {
  6170. return -2;
  6171. }
  6172. dst[0] = '\0';
  6173. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6174. return -1;
  6175. }
  6176. name_len = (int)strlen(var_name);
  6177. end = s + strlen(s);
  6178. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6179. if (s[name_len] == '=') {
  6180. /* HCP24: now check is it a substring or a full cookie name */
  6181. if ((s == cookie_header) || (s[-1] == ' ')) {
  6182. s += name_len + 1;
  6183. if ((p = strchr(s, ' ')) == NULL) {
  6184. p = end;
  6185. }
  6186. if (p[-1] == ';') {
  6187. p--;
  6188. }
  6189. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6190. s++;
  6191. p--;
  6192. }
  6193. if ((size_t)(p - s) < dst_size) {
  6194. len = (int)(p - s);
  6195. mg_strlcpy(dst, s, (size_t)len + 1);
  6196. } else {
  6197. len = -3;
  6198. }
  6199. break;
  6200. }
  6201. }
  6202. }
  6203. return len;
  6204. }
  6205. CIVETWEB_API int
  6206. mg_base64_encode(const unsigned char *src,
  6207. size_t src_len,
  6208. char *dst,
  6209. size_t *dst_len)
  6210. {
  6211. static const char *b64 =
  6212. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6213. size_t i, j;
  6214. int a, b, c;
  6215. if (dst_len != NULL) {
  6216. /* Expected length including 0 termination: */
  6217. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6218. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6219. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6220. if (*dst_len < expected_len) {
  6221. if (*dst_len > 0) {
  6222. dst[0] = '\0';
  6223. }
  6224. *dst_len = expected_len;
  6225. return 0;
  6226. }
  6227. }
  6228. for (i = j = 0; i < src_len; i += 3) {
  6229. a = src[i];
  6230. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6231. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6232. dst[j++] = b64[a >> 2];
  6233. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6234. if (i + 1 < src_len) {
  6235. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6236. }
  6237. if (i + 2 < src_len) {
  6238. dst[j++] = b64[c & 63];
  6239. }
  6240. }
  6241. while (j % 4 != 0) {
  6242. dst[j++] = '=';
  6243. }
  6244. dst[j++] = '\0';
  6245. if (dst_len != NULL) {
  6246. *dst_len = (size_t)j;
  6247. }
  6248. /* Return -1 for "OK" */
  6249. return -1;
  6250. }
  6251. static unsigned char
  6252. b64reverse(char letter)
  6253. {
  6254. if ((letter >= 'A') && (letter <= 'Z')) {
  6255. return (unsigned char)(letter - 'A');
  6256. }
  6257. if ((letter >= 'a') && (letter <= 'z')) {
  6258. return (unsigned char)(letter - 'a' + 26);
  6259. }
  6260. if ((letter >= '0') && (letter <= '9')) {
  6261. return (unsigned char)(letter - '0' + 52);
  6262. }
  6263. if (letter == '+') {
  6264. return 62;
  6265. }
  6266. if (letter == '/') {
  6267. return 63;
  6268. }
  6269. if (letter == '=') {
  6270. return 255; /* normal end */
  6271. }
  6272. return 254; /* error */
  6273. }
  6274. CIVETWEB_API int
  6275. mg_base64_decode(const char *src,
  6276. size_t src_len,
  6277. unsigned char *dst,
  6278. size_t *dst_len)
  6279. {
  6280. size_t i;
  6281. unsigned char a, b, c, d;
  6282. size_t dst_len_limit = (size_t)-1;
  6283. size_t dst_len_used = 0;
  6284. if (dst_len != NULL) {
  6285. dst_len_limit = *dst_len;
  6286. *dst_len = 0;
  6287. }
  6288. for (i = 0; i < src_len; i += 4) {
  6289. /* Read 4 characters from BASE64 string */
  6290. a = b64reverse(src[i]);
  6291. if (a >= 254) {
  6292. return (int)i;
  6293. }
  6294. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6295. if (b >= 254) {
  6296. return (int)i + 1;
  6297. }
  6298. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6299. if (c == 254) {
  6300. return (int)i + 2;
  6301. }
  6302. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6303. if (d == 254) {
  6304. return (int)i + 3;
  6305. }
  6306. /* Add first (of 3) decoded character */
  6307. if (dst_len_used < dst_len_limit) {
  6308. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6309. + (unsigned char)(b >> 4));
  6310. }
  6311. dst_len_used++;
  6312. if (c != 255) {
  6313. if (dst_len_used < dst_len_limit) {
  6314. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6315. + (unsigned char)(c >> 2));
  6316. }
  6317. dst_len_used++;
  6318. if (d != 255) {
  6319. if (dst_len_used < dst_len_limit) {
  6320. dst[dst_len_used] =
  6321. (unsigned char)((unsigned char)(c << 6) + d);
  6322. }
  6323. dst_len_used++;
  6324. }
  6325. }
  6326. }
  6327. /* Add terminating zero */
  6328. if (dst_len_used < dst_len_limit) {
  6329. dst[dst_len_used] = '\0';
  6330. }
  6331. dst_len_used++;
  6332. if (dst_len != NULL) {
  6333. *dst_len = dst_len_used;
  6334. }
  6335. if (dst_len_used > dst_len_limit) {
  6336. /* Out of memory */
  6337. return 0;
  6338. }
  6339. /* Return -1 for "OK" */
  6340. return -1;
  6341. }
  6342. static int
  6343. is_put_or_delete_method(const struct mg_connection *conn)
  6344. {
  6345. if (conn) {
  6346. const char *s = conn->request_info.request_method;
  6347. if (s != NULL) {
  6348. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6349. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6350. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6351. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6352. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6353. || !strcmp(s, "COPY"));
  6354. }
  6355. }
  6356. return 0;
  6357. }
  6358. static int
  6359. is_civetweb_webdav_method(const struct mg_connection *conn)
  6360. {
  6361. /* Note: Here we only have to identify the WebDav methods that need special
  6362. * handling in the CivetWeb code - not all methods used in WebDav. In
  6363. * particular, methods used on directories (when using Windows Explorer as
  6364. * WebDav client).
  6365. */
  6366. if (conn) {
  6367. const char *s = conn->request_info.request_method;
  6368. if (s != NULL) {
  6369. /* These are the civetweb builtin DAV methods */
  6370. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6371. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6372. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6373. }
  6374. }
  6375. return 0;
  6376. }
  6377. #if !defined(NO_FILES)
  6378. static int
  6379. extention_matches_script(
  6380. struct mg_connection *conn, /* in: request (must be valid) */
  6381. const char *filename /* in: filename (must be valid) */
  6382. )
  6383. {
  6384. #if !defined(NO_CGI)
  6385. int cgi_config_idx, inc, max;
  6386. #endif
  6387. #if defined(USE_LUA)
  6388. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6389. filename)
  6390. > 0) {
  6391. return 1;
  6392. }
  6393. #endif
  6394. #if defined(USE_DUKTAPE)
  6395. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6396. filename)
  6397. > 0) {
  6398. return 1;
  6399. }
  6400. #endif
  6401. #if !defined(NO_CGI)
  6402. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6403. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6404. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6405. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6406. && (match_prefix_strlen(
  6407. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6408. filename)
  6409. > 0)) {
  6410. return 1;
  6411. }
  6412. }
  6413. #endif
  6414. /* filename and conn could be unused, if all preocessor conditions
  6415. * are false (no script language supported). */
  6416. (void)filename;
  6417. (void)conn;
  6418. return 0;
  6419. }
  6420. static int
  6421. extention_matches_template_text(
  6422. struct mg_connection *conn, /* in: request (must be valid) */
  6423. const char *filename /* in: filename (must be valid) */
  6424. )
  6425. {
  6426. #if defined(USE_LUA)
  6427. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6428. filename)
  6429. > 0) {
  6430. return 1;
  6431. }
  6432. #endif
  6433. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6434. > 0) {
  6435. return 1;
  6436. }
  6437. return 0;
  6438. }
  6439. /* For given directory path, substitute it to valid index file.
  6440. * Return 1 if index file has been found, 0 if not found.
  6441. * If the file is found, it's stats is returned in stp. */
  6442. static int
  6443. substitute_index_file(struct mg_connection *conn,
  6444. char *path,
  6445. size_t path_len,
  6446. struct mg_file_stat *filestat)
  6447. {
  6448. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6449. struct vec filename_vec;
  6450. size_t n = strlen(path);
  6451. int found = 0;
  6452. /* The 'path' given to us points to the directory. Remove all trailing
  6453. * directory separator characters from the end of the path, and
  6454. * then append single directory separator character. */
  6455. while ((n > 0) && (path[n - 1] == '/')) {
  6456. n--;
  6457. }
  6458. path[n] = '/';
  6459. /* Traverse index files list. For each entry, append it to the given
  6460. * path and see if the file exists. If it exists, break the loop */
  6461. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6462. /* Ignore too long entries that may overflow path buffer */
  6463. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6464. continue;
  6465. }
  6466. /* Prepare full path to the index file */
  6467. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6468. /* Does it exist? */
  6469. if (mg_stat(conn, path, filestat)) {
  6470. /* Yes it does, break the loop */
  6471. found = 1;
  6472. break;
  6473. }
  6474. }
  6475. /* If no index file exists, restore directory path */
  6476. if (!found) {
  6477. path[n] = '\0';
  6478. }
  6479. return found;
  6480. }
  6481. #endif
  6482. static void
  6483. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6484. char *filename, /* out: filename */
  6485. size_t filename_buf_len, /* in: size of filename buffer */
  6486. struct mg_file_stat *filestat, /* out: file status structure */
  6487. int *is_found, /* out: file found (directly) */
  6488. int *is_script_resource, /* out: handled by a script? */
  6489. int *is_websocket_request, /* out: websocket connection? */
  6490. int *is_put_or_delete_request, /* out: put/delete a file? */
  6491. int *is_webdav_request, /* out: webdav request? */
  6492. int *is_template_text /* out: SSI file or LSP file? */
  6493. )
  6494. {
  6495. char const *accept_encoding;
  6496. #if !defined(NO_FILES)
  6497. const char *uri = conn->request_info.local_uri;
  6498. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT], conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT], NULL};
  6499. int fileExists = 0;
  6500. const char *rewrite;
  6501. struct vec a, b;
  6502. ptrdiff_t match_len;
  6503. char gz_path[UTF8_PATH_MAX];
  6504. int truncated;
  6505. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6506. char *tmp_str;
  6507. size_t tmp_str_len, sep_pos;
  6508. int allow_substitute_script_subresources;
  6509. #endif
  6510. #else
  6511. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6512. #endif
  6513. /* Step 1: Set all initially unknown outputs to zero */
  6514. memset(filestat, 0, sizeof(*filestat));
  6515. *filename = 0;
  6516. *is_found = 0;
  6517. *is_script_resource = 0;
  6518. *is_template_text = 0;
  6519. /* Step 2: Classify the request method */
  6520. /* Step 2a: Check if the request attempts to modify the file system */
  6521. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6522. /* Step 2b: Check if the request uses WebDav method that requires special
  6523. * handling */
  6524. *is_webdav_request = is_civetweb_webdav_method(conn);
  6525. /* Step 3: Check if it is a websocket request, and modify the document
  6526. * root if required */
  6527. #if defined(USE_WEBSOCKET)
  6528. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6529. #if !defined(NO_FILES)
  6530. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6531. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6532. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6533. }
  6534. #endif /* !NO_FILES */
  6535. #else /* USE_WEBSOCKET */
  6536. *is_websocket_request = 0;
  6537. #endif /* USE_WEBSOCKET */
  6538. /* Step 4: Check if gzip encoded response is allowed */
  6539. conn->accept_gzip = 0;
  6540. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6541. if (strstr(accept_encoding, "gzip") != NULL) {
  6542. conn->accept_gzip = 1;
  6543. }
  6544. }
  6545. #if !defined(NO_FILES)
  6546. /* Step 5: If there is no root directory, don't look for files. */
  6547. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6548. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6549. * config is not required. */
  6550. if (roots[0] == NULL) {
  6551. /* all file related outputs have already been set to 0, just return
  6552. */
  6553. return;
  6554. }
  6555. for (int i=0; roots[i] != NULL; i++)
  6556. {
  6557. /* Step 6: Determine the local file path from the root path and the
  6558. * request uri. */
  6559. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6560. * part of the path one byte on the right. */
  6561. truncated = 0;
  6562. mg_snprintf(
  6563. conn, &truncated, filename, filename_buf_len - 1, "%s%s", roots[i], uri);
  6564. if (truncated) {
  6565. goto interpret_cleanup;
  6566. }
  6567. /* Step 7: URI rewriting */
  6568. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6569. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6570. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6571. mg_snprintf(conn,
  6572. &truncated,
  6573. filename,
  6574. filename_buf_len - 1,
  6575. "%.*s%s",
  6576. (int)b.len,
  6577. b.ptr,
  6578. uri + match_len);
  6579. break;
  6580. }
  6581. }
  6582. if (truncated) {
  6583. goto interpret_cleanup;
  6584. }
  6585. /* Step 8: Check if the file exists at the server */
  6586. /* Local file path and name, corresponding to requested URI
  6587. * is now stored in "filename" variable. */
  6588. if (mg_stat(conn, filename, filestat)) {
  6589. fileExists = 1;
  6590. break;
  6591. }
  6592. }
  6593. if (fileExists) {
  6594. int uri_len = (int)strlen(uri);
  6595. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6596. /* 8.1: File exists. */
  6597. *is_found = 1;
  6598. /* 8.2: Check if it is a script type. */
  6599. if (extention_matches_script(conn, filename)) {
  6600. /* The request addresses a CGI resource, Lua script or
  6601. * server-side javascript.
  6602. * The URI corresponds to the script itself (like
  6603. * /path/script.cgi), and there is no additional resource
  6604. * path (like /path/script.cgi/something).
  6605. * Requests that modify (replace or delete) a resource, like
  6606. * PUT and DELETE requests, should replace/delete the script
  6607. * file.
  6608. * Requests that read or write from/to a resource, like GET and
  6609. * POST requests, should call the script and return the
  6610. * generated response. */
  6611. *is_script_resource = (!*is_put_or_delete_request);
  6612. }
  6613. /* 8.3: Check for SSI and LSP files */
  6614. if (extention_matches_template_text(conn, filename)) {
  6615. /* Same as above, but for *.lsp and *.shtml files. */
  6616. /* A "template text" is a file delivered directly to the client,
  6617. * but with some text tags replaced by dynamic content.
  6618. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6619. * (LP, LSP) file. */
  6620. *is_template_text = (!*is_put_or_delete_request);
  6621. }
  6622. /* 8.4: If the request target is a directory, there could be
  6623. * a substitute file (index.html, index.cgi, ...). */
  6624. /* But do not substitute a directory for a WebDav request */
  6625. if (filestat->is_directory && is_uri_end_slash
  6626. && (!*is_webdav_request)) {
  6627. /* Use a local copy here, since substitute_index_file will
  6628. * change the content of the file status */
  6629. struct mg_file_stat tmp_filestat;
  6630. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6631. if (substitute_index_file(
  6632. conn, filename, filename_buf_len, &tmp_filestat)) {
  6633. /* Substitute file found. Copy stat to the output, then
  6634. * check if the file is a script file */
  6635. *filestat = tmp_filestat;
  6636. if (extention_matches_script(conn, filename)) {
  6637. /* Substitute file is a script file */
  6638. *is_script_resource = 1;
  6639. } else if (extention_matches_template_text(conn, filename)) {
  6640. /* Substitute file is a LSP or SSI file */
  6641. *is_template_text = 1;
  6642. } else {
  6643. /* Substitute file is a regular file */
  6644. *is_script_resource = 0;
  6645. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6646. }
  6647. }
  6648. /* If there is no substitute file, the server could return
  6649. * a directory listing in a later step */
  6650. }
  6651. return;
  6652. }
  6653. /* Step 9: Check for zipped files: */
  6654. /* If we can't find the actual file, look for the file
  6655. * with the same name but a .gz extension. If we find it,
  6656. * use that and set the gzipped flag in the file struct
  6657. * to indicate that the response need to have the content-
  6658. * encoding: gzip header.
  6659. * We can only do this if the browser declares support. */
  6660. if (conn->accept_gzip) {
  6661. mg_snprintf(
  6662. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6663. if (truncated) {
  6664. goto interpret_cleanup;
  6665. }
  6666. if (mg_stat(conn, gz_path, filestat)) {
  6667. if (filestat) {
  6668. filestat->is_gzipped = 1;
  6669. *is_found = 1;
  6670. }
  6671. /* Currently gz files can not be scripts. */
  6672. return;
  6673. }
  6674. }
  6675. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6676. /* Step 10: Script resources may handle sub-resources */
  6677. /* Support PATH_INFO for CGI scripts. */
  6678. tmp_str_len = strlen(filename);
  6679. tmp_str =
  6680. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6681. if (!tmp_str) {
  6682. /* Out of memory */
  6683. goto interpret_cleanup;
  6684. }
  6685. memcpy(tmp_str, filename, tmp_str_len + 1);
  6686. /* Check config, if index scripts may have sub-resources */
  6687. allow_substitute_script_subresources =
  6688. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6689. "yes");
  6690. if (*is_webdav_request) {
  6691. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6692. * PROPFIND for their subresources? */
  6693. /* allow_substitute_script_subresources = 0; */
  6694. }
  6695. sep_pos = tmp_str_len;
  6696. while (sep_pos > 0) {
  6697. sep_pos--;
  6698. if (tmp_str[sep_pos] == '/') {
  6699. int is_script = 0, does_exist = 0;
  6700. tmp_str[sep_pos] = 0;
  6701. if (tmp_str[0]) {
  6702. is_script = extention_matches_script(conn, tmp_str);
  6703. does_exist = mg_stat(conn, tmp_str, filestat);
  6704. }
  6705. if (does_exist && is_script) {
  6706. filename[sep_pos] = 0;
  6707. memmove(filename + sep_pos + 2,
  6708. filename + sep_pos + 1,
  6709. strlen(filename + sep_pos + 1) + 1);
  6710. conn->path_info = filename + sep_pos + 1;
  6711. filename[sep_pos + 1] = '/';
  6712. *is_script_resource = 1;
  6713. *is_found = 1;
  6714. break;
  6715. }
  6716. if (allow_substitute_script_subresources) {
  6717. if (substitute_index_file(
  6718. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6719. /* some intermediate directory has an index file */
  6720. if (extention_matches_script(conn, tmp_str)) {
  6721. size_t script_name_len = strlen(tmp_str);
  6722. /* subres_name read before this memory locatio will be
  6723. overwritten */
  6724. char *subres_name = filename + sep_pos;
  6725. size_t subres_name_len = strlen(subres_name);
  6726. DEBUG_TRACE("Substitute script %s serving path %s",
  6727. tmp_str,
  6728. filename);
  6729. /* this index file is a script */
  6730. if ((script_name_len + subres_name_len + 2)
  6731. >= filename_buf_len) {
  6732. mg_free(tmp_str);
  6733. goto interpret_cleanup;
  6734. }
  6735. conn->path_info =
  6736. filename + script_name_len + 1; /* new target */
  6737. memmove(conn->path_info, subres_name, subres_name_len);
  6738. conn->path_info[subres_name_len] = 0;
  6739. memcpy(filename, tmp_str, script_name_len + 1);
  6740. *is_script_resource = 1;
  6741. *is_found = 1;
  6742. break;
  6743. } else {
  6744. DEBUG_TRACE("Substitute file %s serving path %s",
  6745. tmp_str,
  6746. filename);
  6747. /* non-script files will not have sub-resources */
  6748. filename[sep_pos] = 0;
  6749. conn->path_info = 0;
  6750. *is_script_resource = 0;
  6751. *is_found = 0;
  6752. break;
  6753. }
  6754. }
  6755. }
  6756. tmp_str[sep_pos] = '/';
  6757. }
  6758. }
  6759. mg_free(tmp_str);
  6760. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6761. #endif /* !defined(NO_FILES) */
  6762. return;
  6763. #if !defined(NO_FILES)
  6764. /* Reset all outputs */
  6765. interpret_cleanup:
  6766. memset(filestat, 0, sizeof(*filestat));
  6767. *filename = 0;
  6768. *is_found = 0;
  6769. *is_script_resource = 0;
  6770. *is_websocket_request = 0;
  6771. *is_put_or_delete_request = 0;
  6772. #endif /* !defined(NO_FILES) */
  6773. }
  6774. /* Check whether full request is buffered. Return:
  6775. * -1 if request or response is malformed
  6776. * 0 if request or response is not yet fully buffered
  6777. * >0 actual request length, including last \r\n\r\n */
  6778. static int
  6779. get_http_header_len(const char *buf, int buflen)
  6780. {
  6781. int i;
  6782. for (i = 0; i < buflen; i++) {
  6783. /* Do an unsigned comparison in some conditions below */
  6784. const unsigned char c = (unsigned char)buf[i];
  6785. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6786. && !isprint(c)) {
  6787. /* abort scan as soon as one malformed character is found */
  6788. return -1;
  6789. }
  6790. if (i < buflen - 1) {
  6791. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6792. /* Two newline, no carriage return - not standard compliant,
  6793. * but it should be accepted */
  6794. return i + 2;
  6795. }
  6796. }
  6797. if (i < buflen - 3) {
  6798. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6799. && (buf[i + 3] == '\n')) {
  6800. /* Two \r\n - standard compliant */
  6801. return i + 4;
  6802. }
  6803. }
  6804. }
  6805. return 0;
  6806. }
  6807. #if !defined(NO_CACHING)
  6808. /* Convert month to the month number. Return -1 on error, or month number */
  6809. static int
  6810. get_month_index(const char *s)
  6811. {
  6812. size_t i;
  6813. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6814. if (!strcmp(s, month_names[i])) {
  6815. return (int)i;
  6816. }
  6817. }
  6818. return -1;
  6819. }
  6820. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6821. static time_t
  6822. parse_date_string(const char *datetime)
  6823. {
  6824. char month_str[32] = {0};
  6825. int second, minute, hour, day, month, year;
  6826. time_t result = (time_t)0;
  6827. struct tm tm;
  6828. if ((sscanf(datetime,
  6829. "%d/%3s/%d %d:%d:%d",
  6830. &day,
  6831. month_str,
  6832. &year,
  6833. &hour,
  6834. &minute,
  6835. &second)
  6836. == 6)
  6837. || (sscanf(datetime,
  6838. "%d %3s %d %d:%d:%d",
  6839. &day,
  6840. month_str,
  6841. &year,
  6842. &hour,
  6843. &minute,
  6844. &second)
  6845. == 6)
  6846. || (sscanf(datetime,
  6847. "%*3s, %d %3s %d %d:%d:%d",
  6848. &day,
  6849. month_str,
  6850. &year,
  6851. &hour,
  6852. &minute,
  6853. &second)
  6854. == 6)
  6855. || (sscanf(datetime,
  6856. "%d-%3s-%d %d:%d:%d",
  6857. &day,
  6858. month_str,
  6859. &year,
  6860. &hour,
  6861. &minute,
  6862. &second)
  6863. == 6)) {
  6864. month = get_month_index(month_str);
  6865. if ((month >= 0) && (year >= 1970)) {
  6866. memset(&tm, 0, sizeof(tm));
  6867. tm.tm_year = year - 1900;
  6868. tm.tm_mon = month;
  6869. tm.tm_mday = day;
  6870. tm.tm_hour = hour;
  6871. tm.tm_min = minute;
  6872. tm.tm_sec = second;
  6873. result = timegm(&tm);
  6874. }
  6875. }
  6876. return result;
  6877. }
  6878. #endif /* !NO_CACHING */
  6879. /* Pre-process URIs according to RFC + protect against directory disclosure
  6880. * attacks by removing '..', excessive '/' and '\' characters */
  6881. static void
  6882. remove_dot_segments(char *inout)
  6883. {
  6884. /* Windows backend protection
  6885. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6886. * in URI by slash */
  6887. char *out_end = inout;
  6888. char *in = inout;
  6889. if (!in) {
  6890. /* Param error. */
  6891. return;
  6892. }
  6893. while (*in) {
  6894. if (*in == '\\') {
  6895. *in = '/';
  6896. }
  6897. in++;
  6898. }
  6899. /* Algorithm "remove_dot_segments" from
  6900. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6901. /* Step 1:
  6902. * The input buffer is initialized.
  6903. * The output buffer is initialized to the empty string.
  6904. */
  6905. in = inout;
  6906. /* Step 2:
  6907. * While the input buffer is not empty, loop as follows:
  6908. */
  6909. /* Less than out_end of the inout buffer is used as output, so keep
  6910. * condition: out_end <= in */
  6911. while (*in) {
  6912. /* Step 2a:
  6913. * If the input buffer begins with a prefix of "../" or "./",
  6914. * then remove that prefix from the input buffer;
  6915. */
  6916. if (!strncmp(in, "../", 3)) {
  6917. in += 3;
  6918. } else if (!strncmp(in, "./", 2)) {
  6919. in += 2;
  6920. }
  6921. /* otherwise */
  6922. /* Step 2b:
  6923. * if the input buffer begins with a prefix of "/./" or "/.",
  6924. * where "." is a complete path segment, then replace that
  6925. * prefix with "/" in the input buffer;
  6926. */
  6927. else if (!strncmp(in, "/./", 3)) {
  6928. in += 2;
  6929. } else if (!strcmp(in, "/.")) {
  6930. in[1] = 0;
  6931. }
  6932. /* otherwise */
  6933. /* Step 2c:
  6934. * if the input buffer begins with a prefix of "/../" or "/..",
  6935. * where ".." is a complete path segment, then replace that
  6936. * prefix with "/" in the input buffer and remove the last
  6937. * segment and its preceding "/" (if any) from the output
  6938. * buffer;
  6939. */
  6940. else if (!strncmp(in, "/../", 4)) {
  6941. in += 3;
  6942. if (inout != out_end) {
  6943. /* remove last segment */
  6944. do {
  6945. out_end--;
  6946. } while ((inout != out_end) && (*out_end != '/'));
  6947. }
  6948. } else if (!strcmp(in, "/..")) {
  6949. in[1] = 0;
  6950. if (inout != out_end) {
  6951. /* remove last segment */
  6952. do {
  6953. out_end--;
  6954. } while ((inout != out_end) && (*out_end != '/'));
  6955. }
  6956. }
  6957. /* otherwise */
  6958. /* Step 2d:
  6959. * if the input buffer consists only of "." or "..", then remove
  6960. * that from the input buffer;
  6961. */
  6962. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6963. *in = 0;
  6964. }
  6965. /* otherwise */
  6966. /* Step 2e:
  6967. * move the first path segment in the input buffer to the end of
  6968. * the output buffer, including the initial "/" character (if
  6969. * any) and any subsequent characters up to, but not including,
  6970. * the next "/" character or the end of the input buffer.
  6971. */
  6972. else {
  6973. do {
  6974. *out_end = *in;
  6975. out_end++;
  6976. in++;
  6977. } while ((*in != 0) && (*in != '/'));
  6978. }
  6979. }
  6980. /* Step 3:
  6981. * Finally, the output buffer is returned as the result of
  6982. * remove_dot_segments.
  6983. */
  6984. /* Terminate output */
  6985. *out_end = 0;
  6986. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6987. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6988. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6989. * or "//" anymore.
  6990. */
  6991. out_end = in = inout;
  6992. while (*in) {
  6993. if (*in == '.') {
  6994. /* remove . at the end or preceding of / */
  6995. char *in_ahead = in;
  6996. do {
  6997. in_ahead++;
  6998. } while (*in_ahead == '.');
  6999. if (*in_ahead == '/') {
  7000. in = in_ahead;
  7001. if ((out_end != inout) && (out_end[-1] == '/')) {
  7002. /* remove generated // */
  7003. out_end--;
  7004. }
  7005. } else if (*in_ahead == 0) {
  7006. in = in_ahead;
  7007. } else {
  7008. do {
  7009. *out_end++ = '.';
  7010. in++;
  7011. } while (in != in_ahead);
  7012. }
  7013. } else if (*in == '/') {
  7014. /* replace // by / */
  7015. *out_end++ = '/';
  7016. do {
  7017. in++;
  7018. } while (*in == '/');
  7019. } else {
  7020. *out_end++ = *in;
  7021. in++;
  7022. }
  7023. }
  7024. *out_end = 0;
  7025. }
  7026. static const struct {
  7027. const char *extension;
  7028. size_t ext_len;
  7029. const char *mime_type;
  7030. } builtin_mime_types[] = {
  7031. /* IANA registered MIME types
  7032. * (http://www.iana.org/assignments/media-types)
  7033. * application types */
  7034. {".bin", 4, "application/octet-stream"},
  7035. {".deb", 4, "application/octet-stream"},
  7036. {".dmg", 4, "application/octet-stream"},
  7037. {".dll", 4, "application/octet-stream"},
  7038. {".doc", 4, "application/msword"},
  7039. {".eps", 4, "application/postscript"},
  7040. {".exe", 4, "application/octet-stream"},
  7041. {".iso", 4, "application/octet-stream"},
  7042. {".js", 3, "application/javascript"},
  7043. {".json", 5, "application/json"},
  7044. {".msi", 4, "application/octet-stream"},
  7045. {".pdf", 4, "application/pdf"},
  7046. {".ps", 3, "application/postscript"},
  7047. {".rtf", 4, "application/rtf"},
  7048. {".xhtml", 6, "application/xhtml+xml"},
  7049. {".xsl", 4, "application/xml"},
  7050. {".xslt", 5, "application/xml"},
  7051. /* fonts */
  7052. {".ttf", 4, "application/font-sfnt"},
  7053. {".cff", 4, "application/font-sfnt"},
  7054. {".otf", 4, "application/font-sfnt"},
  7055. {".aat", 4, "application/font-sfnt"},
  7056. {".sil", 4, "application/font-sfnt"},
  7057. {".pfr", 4, "application/font-tdpfr"},
  7058. {".woff", 5, "application/font-woff"},
  7059. {".woff2", 6, "application/font-woff2"},
  7060. /* audio */
  7061. {".mp3", 4, "audio/mpeg"},
  7062. {".oga", 4, "audio/ogg"},
  7063. {".ogg", 4, "audio/ogg"},
  7064. /* image */
  7065. {".gif", 4, "image/gif"},
  7066. {".ief", 4, "image/ief"},
  7067. {".jpeg", 5, "image/jpeg"},
  7068. {".jpg", 4, "image/jpeg"},
  7069. {".jpm", 4, "image/jpm"},
  7070. {".jpx", 4, "image/jpx"},
  7071. {".png", 4, "image/png"},
  7072. {".svg", 4, "image/svg+xml"},
  7073. {".tif", 4, "image/tiff"},
  7074. {".tiff", 5, "image/tiff"},
  7075. /* model */
  7076. {".wrl", 4, "model/vrml"},
  7077. /* text */
  7078. {".css", 4, "text/css"},
  7079. {".csv", 4, "text/csv"},
  7080. {".htm", 4, "text/html"},
  7081. {".html", 5, "text/html"},
  7082. {".sgm", 4, "text/sgml"},
  7083. {".shtm", 5, "text/html"},
  7084. {".shtml", 6, "text/html"},
  7085. {".txt", 4, "text/plain"},
  7086. {".xml", 4, "text/xml"},
  7087. /* video */
  7088. {".mov", 4, "video/quicktime"},
  7089. {".mp4", 4, "video/mp4"},
  7090. {".mpeg", 5, "video/mpeg"},
  7091. {".mpg", 4, "video/mpeg"},
  7092. {".ogv", 4, "video/ogg"},
  7093. {".qt", 3, "video/quicktime"},
  7094. /* not registered types
  7095. * (http://reference.sitepoint.com/html/mime-types-full,
  7096. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7097. {".arj", 4, "application/x-arj-compressed"},
  7098. {".gz", 3, "application/x-gunzip"},
  7099. {".rar", 4, "application/x-arj-compressed"},
  7100. {".swf", 4, "application/x-shockwave-flash"},
  7101. {".tar", 4, "application/x-tar"},
  7102. {".tgz", 4, "application/x-tar-gz"},
  7103. {".torrent", 8, "application/x-bittorrent"},
  7104. {".ppt", 4, "application/x-mspowerpoint"},
  7105. {".xls", 4, "application/x-msexcel"},
  7106. {".zip", 4, "application/x-zip-compressed"},
  7107. {".aac",
  7108. 4,
  7109. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7110. {".flac", 5, "audio/flac"},
  7111. {".aif", 4, "audio/x-aif"},
  7112. {".m3u", 4, "audio/x-mpegurl"},
  7113. {".mid", 4, "audio/x-midi"},
  7114. {".ra", 3, "audio/x-pn-realaudio"},
  7115. {".ram", 4, "audio/x-pn-realaudio"},
  7116. {".wav", 4, "audio/x-wav"},
  7117. {".bmp", 4, "image/bmp"},
  7118. {".ico", 4, "image/x-icon"},
  7119. {".pct", 4, "image/x-pct"},
  7120. {".pict", 5, "image/pict"},
  7121. {".rgb", 4, "image/x-rgb"},
  7122. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7123. {".asf", 4, "video/x-ms-asf"},
  7124. {".avi", 4, "video/x-msvideo"},
  7125. {".m4v", 4, "video/x-m4v"},
  7126. {NULL, 0, NULL}};
  7127. CIVETWEB_API const char *
  7128. mg_get_builtin_mime_type(const char *path)
  7129. {
  7130. const char *ext;
  7131. size_t i, path_len;
  7132. path_len = strlen(path);
  7133. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7134. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7135. if ((path_len > builtin_mime_types[i].ext_len)
  7136. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7137. return builtin_mime_types[i].mime_type;
  7138. }
  7139. }
  7140. return "text/plain";
  7141. }
  7142. /* Look at the "path" extension and figure what mime type it has.
  7143. * Store mime type in the vector. */
  7144. static void
  7145. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7146. {
  7147. struct vec ext_vec, mime_vec;
  7148. const char *list, *ext;
  7149. size_t path_len;
  7150. path_len = strlen(path);
  7151. if ((conn == NULL) || (vec == NULL)) {
  7152. if (vec != NULL) {
  7153. memset(vec, '\0', sizeof(struct vec));
  7154. }
  7155. return;
  7156. }
  7157. /* Scan user-defined mime types first, in case user wants to
  7158. * override default mime types. */
  7159. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7160. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7161. /* ext now points to the path suffix */
  7162. ext = path + path_len - ext_vec.len;
  7163. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7164. *vec = mime_vec;
  7165. return;
  7166. }
  7167. }
  7168. vec->ptr = mg_get_builtin_mime_type(path);
  7169. vec->len = strlen(vec->ptr);
  7170. }
  7171. /* Stringify binary data. Output buffer must be twice as big as input,
  7172. * because each byte takes 2 bytes in string representation */
  7173. static void
  7174. bin2str(char *to, const unsigned char *p, size_t len)
  7175. {
  7176. static const char *hex = "0123456789abcdef";
  7177. for (; len--; p++) {
  7178. *to++ = hex[p[0] >> 4];
  7179. *to++ = hex[p[0] & 0x0f];
  7180. }
  7181. *to = '\0';
  7182. }
  7183. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7184. */
  7185. CIVETWEB_API char *
  7186. mg_md5(char buf[33], ...)
  7187. {
  7188. md5_byte_t hash[16];
  7189. const char *p;
  7190. va_list ap;
  7191. md5_state_t ctx;
  7192. md5_init(&ctx);
  7193. va_start(ap, buf);
  7194. while ((p = va_arg(ap, const char *)) != NULL) {
  7195. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7196. }
  7197. va_end(ap);
  7198. md5_finish(&ctx, hash);
  7199. bin2str(buf, hash, sizeof(hash));
  7200. return buf;
  7201. }
  7202. /* Check the user's password, return 1 if OK */
  7203. static int
  7204. check_password_digest(const char *method,
  7205. const char *ha1,
  7206. const char *uri,
  7207. const char *nonce,
  7208. const char *nc,
  7209. const char *cnonce,
  7210. const char *qop,
  7211. const char *response)
  7212. {
  7213. char ha2[32 + 1], expected_response[32 + 1];
  7214. /* Some of the parameters may be NULL */
  7215. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7216. || (qop == NULL) || (response == NULL)) {
  7217. return 0;
  7218. }
  7219. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7220. if (strlen(response) != 32) {
  7221. return 0;
  7222. }
  7223. mg_md5(ha2, method, ":", uri, NULL);
  7224. mg_md5(expected_response,
  7225. ha1,
  7226. ":",
  7227. nonce,
  7228. ":",
  7229. nc,
  7230. ":",
  7231. cnonce,
  7232. ":",
  7233. qop,
  7234. ":",
  7235. ha2,
  7236. NULL);
  7237. return mg_strcasecmp(response, expected_response) == 0;
  7238. }
  7239. #if !defined(NO_FILESYSTEMS)
  7240. /* Use the global passwords file, if specified by auth_gpass option,
  7241. * or search for .htpasswd in the requested directory. */
  7242. static void
  7243. open_auth_file(struct mg_connection *conn,
  7244. const char *path,
  7245. struct mg_file *filep)
  7246. {
  7247. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7248. char name[UTF8_PATH_MAX];
  7249. const char *p, *e,
  7250. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7251. int truncated;
  7252. if (gpass != NULL) {
  7253. /* Use global passwords file */
  7254. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7255. #if defined(DEBUG)
  7256. /* Use mg_cry_internal here, since gpass has been
  7257. * configured. */
  7258. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7259. #endif
  7260. }
  7261. /* Important: using local struct mg_file to test path for
  7262. * is_directory flag. If filep is used, mg_stat() makes it
  7263. * appear as if auth file was opened.
  7264. * TODO(mid): Check if this is still required after rewriting
  7265. * mg_stat */
  7266. } else if (mg_stat(conn, path, &filep->stat)
  7267. && filep->stat.is_directory) {
  7268. mg_snprintf(conn,
  7269. &truncated,
  7270. name,
  7271. sizeof(name),
  7272. "%s/%s",
  7273. path,
  7274. PASSWORDS_FILE_NAME);
  7275. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7276. #if defined(DEBUG)
  7277. /* Don't use mg_cry_internal here, but only a trace, since
  7278. * this is a typical case. It will occur for every directory
  7279. * without a password file. */
  7280. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7281. #endif
  7282. }
  7283. } else {
  7284. /* Try to find .htpasswd in requested directory. */
  7285. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7286. if (e[0] == '/') {
  7287. break;
  7288. }
  7289. }
  7290. mg_snprintf(conn,
  7291. &truncated,
  7292. name,
  7293. sizeof(name),
  7294. "%.*s/%s",
  7295. (int)(e - p),
  7296. p,
  7297. PASSWORDS_FILE_NAME);
  7298. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7299. #if defined(DEBUG)
  7300. /* Don't use mg_cry_internal here, but only a trace, since
  7301. * this is a typical case. It will occur for every directory
  7302. * without a password file. */
  7303. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7304. #endif
  7305. }
  7306. }
  7307. }
  7308. }
  7309. #endif /* NO_FILESYSTEMS */
  7310. /* Parsed Authorization header */
  7311. struct ah {
  7312. char *user;
  7313. int type; /* 1 = basic, 2 = digest */
  7314. char *plain_password; /* Basic only */
  7315. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7316. };
  7317. /* Return 1 on success. Always initializes the ah structure. */
  7318. static int
  7319. parse_auth_header(struct mg_connection *conn,
  7320. char *buf,
  7321. size_t buf_size,
  7322. struct ah *ah)
  7323. {
  7324. char *name, *value, *s;
  7325. const char *auth_header;
  7326. uint64_t nonce;
  7327. if (!ah || !conn) {
  7328. return 0;
  7329. }
  7330. (void)memset(ah, 0, sizeof(*ah));
  7331. auth_header = mg_get_header(conn, "Authorization");
  7332. if (auth_header == NULL) {
  7333. /* No Authorization header at all */
  7334. return 0;
  7335. }
  7336. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7337. /* Basic Auth (we never asked for this, but some client may send it) */
  7338. char *split;
  7339. const char *userpw_b64 = auth_header + 6;
  7340. size_t userpw_b64_len = strlen(userpw_b64);
  7341. size_t buf_len_r = buf_size;
  7342. if (mg_base64_decode(
  7343. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7344. != -1) {
  7345. return 0; /* decode error */
  7346. }
  7347. split = strchr(buf, ':');
  7348. if (!split) {
  7349. return 0; /* Format error */
  7350. }
  7351. /* Separate string at ':' */
  7352. *split = 0;
  7353. /* User name is before ':', Password is after ':' */
  7354. ah->user = buf;
  7355. ah->type = 1;
  7356. ah->plain_password = split + 1;
  7357. return 1;
  7358. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7359. /* Digest Auth ... implemented below */
  7360. ah->type = 2;
  7361. } else {
  7362. /* Unknown or invalid Auth method */
  7363. return 0;
  7364. }
  7365. /* Make modifiable copy of the auth header */
  7366. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7367. s = buf;
  7368. /* Parse authorization header */
  7369. for (;;) {
  7370. /* Gobble initial spaces */
  7371. while (isspace((unsigned char)*s)) {
  7372. s++;
  7373. }
  7374. name = skip_quoted(&s, "=", " ", 0);
  7375. /* Value is either quote-delimited, or ends at first comma or space.
  7376. */
  7377. if (s[0] == '\"') {
  7378. s++;
  7379. value = skip_quoted(&s, "\"", " ", '\\');
  7380. if (s[0] == ',') {
  7381. s++;
  7382. }
  7383. } else {
  7384. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7385. * uses spaces */
  7386. }
  7387. if (*name == '\0') {
  7388. break;
  7389. }
  7390. if (!strcmp(name, "username")) {
  7391. ah->user = value;
  7392. } else if (!strcmp(name, "cnonce")) {
  7393. ah->cnonce = value;
  7394. } else if (!strcmp(name, "response")) {
  7395. ah->response = value;
  7396. } else if (!strcmp(name, "uri")) {
  7397. ah->uri = value;
  7398. } else if (!strcmp(name, "qop")) {
  7399. ah->qop = value;
  7400. } else if (!strcmp(name, "nc")) {
  7401. ah->nc = value;
  7402. } else if (!strcmp(name, "nonce")) {
  7403. ah->nonce = value;
  7404. }
  7405. }
  7406. #if !defined(NO_NONCE_CHECK)
  7407. /* Read the nonce from the response. */
  7408. if (ah->nonce == NULL) {
  7409. return 0;
  7410. }
  7411. s = NULL;
  7412. nonce = strtoull(ah->nonce, &s, 10);
  7413. if ((s == NULL) || (*s != 0)) {
  7414. return 0;
  7415. }
  7416. /* Convert the nonce from the client to a number. */
  7417. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7418. /* The converted number corresponds to the time the nounce has been
  7419. * created. This should not be earlier than the server start. */
  7420. /* Server side nonce check is valuable in all situations but one:
  7421. * if the server restarts frequently, but the client should not see
  7422. * that, so the server should accept nonces from previous starts. */
  7423. /* However, the reasonable default is to not accept a nonce from a
  7424. * previous start, so if anyone changed the access rights between
  7425. * two restarts, a new login is required. */
  7426. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7427. /* nonce is from a previous start of the server and no longer valid
  7428. * (replay attack?) */
  7429. return 0;
  7430. }
  7431. /* Check if the nonce is too high, so it has not (yet) been used by the
  7432. * server. */
  7433. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7434. + conn->dom_ctx->nonce_count)) {
  7435. return 0;
  7436. }
  7437. #else
  7438. (void)nonce;
  7439. #endif
  7440. return (ah->user != NULL);
  7441. }
  7442. static const char *
  7443. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7444. {
  7445. if (!filep) {
  7446. return NULL;
  7447. }
  7448. if (filep->access.fp != NULL) {
  7449. return fgets(buf, (int)size, filep->access.fp);
  7450. } else {
  7451. return NULL;
  7452. }
  7453. }
  7454. /* Define the initial recursion depth for procesesing htpasswd files that
  7455. * include other htpasswd
  7456. * (or even the same) files. It is not difficult to provide a file or files
  7457. * s.t. they force civetweb
  7458. * to infinitely recurse and then crash.
  7459. */
  7460. #define INITIAL_DEPTH 9
  7461. #if INITIAL_DEPTH <= 0
  7462. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7463. #endif
  7464. #if !defined(NO_FILESYSTEMS)
  7465. struct read_auth_file_struct {
  7466. struct mg_connection *conn;
  7467. struct ah ah;
  7468. const char *domain;
  7469. char buf[256 + 256 + 40];
  7470. const char *f_user;
  7471. const char *f_domain;
  7472. const char *f_ha1;
  7473. };
  7474. static int
  7475. read_auth_file(struct mg_file *filep,
  7476. struct read_auth_file_struct *workdata,
  7477. int depth)
  7478. {
  7479. int is_authorized = 0;
  7480. struct mg_file fp;
  7481. size_t l;
  7482. if (!filep || !workdata || (0 == depth)) {
  7483. return 0;
  7484. }
  7485. /* Loop over passwords file */
  7486. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7487. l = strlen(workdata->buf);
  7488. while (l > 0) {
  7489. if (isspace((unsigned char)workdata->buf[l - 1])
  7490. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7491. l--;
  7492. workdata->buf[l] = 0;
  7493. } else
  7494. break;
  7495. }
  7496. if (l < 1) {
  7497. continue;
  7498. }
  7499. workdata->f_user = workdata->buf;
  7500. if (workdata->f_user[0] == ':') {
  7501. /* user names may not contain a ':' and may not be empty,
  7502. * so lines starting with ':' may be used for a special purpose
  7503. */
  7504. if (workdata->f_user[1] == '#') {
  7505. /* :# is a comment */
  7506. continue;
  7507. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7508. if (mg_fopen(workdata->conn,
  7509. workdata->f_user + 9,
  7510. MG_FOPEN_MODE_READ,
  7511. &fp)) {
  7512. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7513. (void)mg_fclose(
  7514. &fp.access); /* ignore error on read only file */
  7515. /* No need to continue processing files once we have a
  7516. * match, since nothing will reset it back
  7517. * to 0.
  7518. */
  7519. if (is_authorized) {
  7520. return is_authorized;
  7521. }
  7522. } else {
  7523. mg_cry_internal(workdata->conn,
  7524. "%s: cannot open authorization file: %s",
  7525. __func__,
  7526. workdata->buf);
  7527. }
  7528. continue;
  7529. }
  7530. /* everything is invalid for the moment (might change in the
  7531. * future) */
  7532. mg_cry_internal(workdata->conn,
  7533. "%s: syntax error in authorization file: %s",
  7534. __func__,
  7535. workdata->buf);
  7536. continue;
  7537. }
  7538. workdata->f_domain = strchr(workdata->f_user, ':');
  7539. if (workdata->f_domain == NULL) {
  7540. mg_cry_internal(workdata->conn,
  7541. "%s: syntax error in authorization file: %s",
  7542. __func__,
  7543. workdata->buf);
  7544. continue;
  7545. }
  7546. *(char *)(workdata->f_domain) = 0;
  7547. (workdata->f_domain)++;
  7548. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7549. if (workdata->f_ha1 == NULL) {
  7550. mg_cry_internal(workdata->conn,
  7551. "%s: syntax error in authorization file: %s",
  7552. __func__,
  7553. workdata->buf);
  7554. continue;
  7555. }
  7556. *(char *)(workdata->f_ha1) = 0;
  7557. (workdata->f_ha1)++;
  7558. if (!strcmp(workdata->ah.user, workdata->f_user)
  7559. && !strcmp(workdata->domain, workdata->f_domain)) {
  7560. switch (workdata->ah.type) {
  7561. case 1: /* Basic */
  7562. {
  7563. char md5[33];
  7564. mg_md5(md5,
  7565. workdata->f_user,
  7566. ":",
  7567. workdata->domain,
  7568. ":",
  7569. workdata->ah.plain_password,
  7570. NULL);
  7571. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7572. }
  7573. case 2: /* Digest */
  7574. return check_password_digest(
  7575. workdata->conn->request_info.request_method,
  7576. workdata->f_ha1,
  7577. workdata->ah.uri,
  7578. workdata->ah.nonce,
  7579. workdata->ah.nc,
  7580. workdata->ah.cnonce,
  7581. workdata->ah.qop,
  7582. workdata->ah.response);
  7583. default: /* None/Other/Unknown */
  7584. return 0;
  7585. }
  7586. }
  7587. }
  7588. return is_authorized;
  7589. }
  7590. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7591. static int
  7592. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7593. {
  7594. struct read_auth_file_struct workdata;
  7595. char buf[MG_BUF_LEN];
  7596. if (!conn || !conn->dom_ctx) {
  7597. return 0;
  7598. }
  7599. memset(&workdata, 0, sizeof(workdata));
  7600. workdata.conn = conn;
  7601. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7602. return 0;
  7603. }
  7604. /* CGI needs it as REMOTE_USER */
  7605. conn->request_info.remote_user =
  7606. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7607. if (realm) {
  7608. workdata.domain = realm;
  7609. } else {
  7610. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7611. }
  7612. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7613. }
  7614. /* Public function to check http digest authentication header */
  7615. CIVETWEB_API int
  7616. mg_check_digest_access_authentication(struct mg_connection *conn,
  7617. const char *realm,
  7618. const char *filename)
  7619. {
  7620. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7621. int auth;
  7622. if (!conn || !filename) {
  7623. return -1;
  7624. }
  7625. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7626. return -2;
  7627. }
  7628. auth = authorize(conn, &file, realm);
  7629. mg_fclose(&file.access);
  7630. return auth;
  7631. }
  7632. #endif /* NO_FILESYSTEMS */
  7633. /* Return 1 if request is authorised, 0 otherwise. */
  7634. static int
  7635. check_authorization(struct mg_connection *conn, const char *path)
  7636. {
  7637. #if !defined(NO_FILESYSTEMS)
  7638. char fname[UTF8_PATH_MAX];
  7639. struct vec uri_vec, filename_vec;
  7640. const char *list;
  7641. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7642. int authorized = 1, truncated;
  7643. if (!conn || !conn->dom_ctx) {
  7644. return 0;
  7645. }
  7646. list = conn->dom_ctx->config[PROTECT_URI];
  7647. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7648. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7649. mg_snprintf(conn,
  7650. &truncated,
  7651. fname,
  7652. sizeof(fname),
  7653. "%.*s",
  7654. (int)filename_vec.len,
  7655. filename_vec.ptr);
  7656. if (truncated
  7657. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7658. mg_cry_internal(conn,
  7659. "%s: cannot open %s: %s",
  7660. __func__,
  7661. fname,
  7662. strerror(errno));
  7663. }
  7664. break;
  7665. }
  7666. }
  7667. if (!is_file_opened(&file.access)) {
  7668. open_auth_file(conn, path, &file);
  7669. }
  7670. if (is_file_opened(&file.access)) {
  7671. authorized = authorize(conn, &file, NULL);
  7672. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7673. }
  7674. return authorized;
  7675. #else
  7676. (void)conn;
  7677. (void)path;
  7678. return 1;
  7679. #endif /* NO_FILESYSTEMS */
  7680. }
  7681. /* Internal function. Assumes conn is valid */
  7682. static void
  7683. send_authorization_request(struct mg_connection *conn, const char *realm)
  7684. {
  7685. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7686. int trunc = 0;
  7687. char buf[128];
  7688. if (!realm) {
  7689. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7690. }
  7691. mg_lock_context(conn->phys_ctx);
  7692. nonce += conn->dom_ctx->nonce_count;
  7693. ++conn->dom_ctx->nonce_count;
  7694. mg_unlock_context(conn->phys_ctx);
  7695. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7696. conn->must_close = 1;
  7697. /* Create 401 response */
  7698. mg_response_header_start(conn, 401);
  7699. send_no_cache_header(conn);
  7700. send_additional_header(conn);
  7701. mg_response_header_add(conn, "Content-Length", "0", -1);
  7702. /* Content for "WWW-Authenticate" header */
  7703. mg_snprintf(conn,
  7704. &trunc,
  7705. buf,
  7706. sizeof(buf),
  7707. "Digest qop=\"auth\", realm=\"%s\", "
  7708. "nonce=\"%" UINT64_FMT "\"",
  7709. realm,
  7710. nonce);
  7711. if (!trunc) {
  7712. /* !trunc should always be true */
  7713. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7714. }
  7715. /* Send all headers */
  7716. mg_response_header_send(conn);
  7717. }
  7718. /* Interface function. Parameters are provided by the user, so do
  7719. * at least some basic checks.
  7720. */
  7721. CIVETWEB_API int
  7722. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7723. const char *realm)
  7724. {
  7725. if (conn && conn->dom_ctx) {
  7726. send_authorization_request(conn, realm);
  7727. return 0;
  7728. }
  7729. return -1;
  7730. }
  7731. #if !defined(NO_FILES)
  7732. static int
  7733. is_authorized_for_put(struct mg_connection *conn)
  7734. {
  7735. int ret = 0;
  7736. if (conn) {
  7737. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7738. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7739. if (passfile != NULL
  7740. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7741. ret = authorize(conn, &file, NULL);
  7742. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7743. }
  7744. }
  7745. DEBUG_TRACE("file write authorization: %i", ret);
  7746. return ret;
  7747. }
  7748. #endif
  7749. CIVETWEB_API int
  7750. mg_modify_passwords_file_ha1(const char *fname,
  7751. const char *domain,
  7752. const char *user,
  7753. const char *ha1)
  7754. {
  7755. int found = 0, i, result = 1;
  7756. char line[512], u[256], d[256], h[256];
  7757. struct stat st = {0};
  7758. FILE *fp = NULL;
  7759. char *temp_file = NULL;
  7760. int temp_file_offs = 0;
  7761. /* Regard empty password as no password - remove user record. */
  7762. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7763. ha1 = NULL;
  7764. }
  7765. /* Other arguments must not be empty */
  7766. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7767. return 0;
  7768. }
  7769. /* Using the given file format, user name and domain must not contain
  7770. * the ':' character */
  7771. if (strchr(user, ':') != NULL) {
  7772. return 0;
  7773. }
  7774. if (strchr(domain, ':') != NULL) {
  7775. return 0;
  7776. }
  7777. /* Do not allow control characters like newline in user name and domain.
  7778. * Do not allow excessively long names either. */
  7779. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7780. if (iscntrl((unsigned char)user[i])) {
  7781. return 0;
  7782. }
  7783. }
  7784. if (user[i]) {
  7785. return 0; /* user name too long */
  7786. }
  7787. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7788. if (iscntrl((unsigned char)domain[i])) {
  7789. return 0;
  7790. }
  7791. }
  7792. if (domain[i]) {
  7793. return 0; /* domain name too long */
  7794. }
  7795. /* The maximum length of the path to the password file is limited */
  7796. if (strlen(fname) >= UTF8_PATH_MAX) {
  7797. return 0;
  7798. }
  7799. /* Check if the file exists, and get file size */
  7800. if (0 == stat(fname, &st)) {
  7801. int temp_buf_len;
  7802. if (st.st_size > 10485760) {
  7803. /* Some funster provided a >10 MB text file */
  7804. return 0;
  7805. }
  7806. /* Add enough space for one more line */
  7807. temp_buf_len = (int)st.st_size + 1024;
  7808. /* Allocate memory (instead of using a temporary file) */
  7809. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  7810. if (!temp_file) {
  7811. /* Out of memory */
  7812. return 0;
  7813. }
  7814. /* File exists. Read it into a memory buffer. */
  7815. fp = fopen(fname, "r");
  7816. if (fp == NULL) {
  7817. /* Cannot read file. No permission? */
  7818. mg_free(temp_file);
  7819. return 0;
  7820. }
  7821. /* Read content and store in memory */
  7822. while ((fgets(line, sizeof(line), fp) != NULL)
  7823. && ((temp_file_offs + 600) < temp_buf_len)) {
  7824. /* file format is "user:domain:hash\n" */
  7825. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7826. continue;
  7827. }
  7828. u[255] = 0;
  7829. d[255] = 0;
  7830. h[255] = 0;
  7831. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7832. /* Found the user: change the password hash or drop the user
  7833. */
  7834. if ((ha1 != NULL) && (!found)) {
  7835. i = sprintf(temp_file + temp_file_offs,
  7836. "%s:%s:%s\n",
  7837. user,
  7838. domain,
  7839. ha1);
  7840. if (i < 1) {
  7841. fclose(fp);
  7842. mg_free(temp_file);
  7843. return 0;
  7844. }
  7845. temp_file_offs += i;
  7846. }
  7847. found = 1;
  7848. } else {
  7849. /* Copy existing user, including password hash */
  7850. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7851. if (i < 1) {
  7852. fclose(fp);
  7853. mg_free(temp_file);
  7854. return 0;
  7855. }
  7856. temp_file_offs += i;
  7857. }
  7858. }
  7859. fclose(fp);
  7860. }
  7861. /* Create new file */
  7862. fp = fopen(fname, "w");
  7863. if (!fp) {
  7864. mg_free(temp_file);
  7865. return 0;
  7866. }
  7867. #if !defined(_WIN32)
  7868. /* On Linux & co., restrict file read/write permissions to the owner */
  7869. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7870. result = 0;
  7871. }
  7872. #endif
  7873. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7874. /* Store buffered content of old file */
  7875. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  7876. != (size_t)temp_file_offs) {
  7877. result = 0;
  7878. }
  7879. }
  7880. /* If new user, just add it */
  7881. if ((ha1 != NULL) && (!found)) {
  7882. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7883. result = 0;
  7884. }
  7885. }
  7886. /* All data written */
  7887. if (fclose(fp) != 0) {
  7888. result = 0;
  7889. }
  7890. mg_free(temp_file);
  7891. return result;
  7892. }
  7893. CIVETWEB_API int
  7894. mg_modify_passwords_file(const char *fname,
  7895. const char *domain,
  7896. const char *user,
  7897. const char *pass)
  7898. {
  7899. char ha1buf[33];
  7900. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7901. return 0;
  7902. }
  7903. if ((pass == NULL) || (pass[0] == 0)) {
  7904. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7905. }
  7906. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7907. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7908. }
  7909. static int
  7910. is_valid_port(unsigned long port)
  7911. {
  7912. return (port <= 0xffff);
  7913. }
  7914. static int
  7915. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7916. {
  7917. struct addrinfo hints, *res, *ressave;
  7918. int func_ret = 0;
  7919. int gai_ret;
  7920. memset(&hints, 0, sizeof(struct addrinfo));
  7921. hints.ai_family = af;
  7922. if (!resolve_src) {
  7923. hints.ai_flags = AI_NUMERICHOST;
  7924. }
  7925. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7926. if (gai_ret != 0) {
  7927. /* gai_strerror could be used to convert gai_ret to a string */
  7928. /* POSIX return values: see
  7929. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7930. */
  7931. /* Windows return values: see
  7932. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7933. */
  7934. return 0;
  7935. }
  7936. ressave = res;
  7937. while (res) {
  7938. if ((dstlen >= (size_t)res->ai_addrlen)
  7939. && (res->ai_addr->sa_family == af)) {
  7940. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7941. func_ret = 1;
  7942. }
  7943. res = res->ai_next;
  7944. }
  7945. freeaddrinfo(ressave);
  7946. return func_ret;
  7947. }
  7948. static int
  7949. connect_socket(
  7950. struct mg_context *ctx /* may be NULL */,
  7951. const char *host,
  7952. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7953. int use_ssl, /* 0 or 1 */
  7954. struct mg_error_data *error,
  7955. SOCKET *sock /* output: socket, must not be NULL */,
  7956. union usa *sa /* output: socket address, must not be NULL */
  7957. )
  7958. {
  7959. int ip_ver = 0;
  7960. int conn_ret = -1;
  7961. int sockerr = 0;
  7962. *sock = INVALID_SOCKET;
  7963. memset(sa, 0, sizeof(*sa));
  7964. if (host == NULL) {
  7965. if (error != NULL) {
  7966. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7967. mg_snprintf(NULL,
  7968. NULL, /* No truncation check for ebuf */
  7969. error->text,
  7970. error->text_buffer_size,
  7971. "%s",
  7972. "NULL host");
  7973. }
  7974. return 0;
  7975. }
  7976. #if defined(USE_X_DOM_SOCKET)
  7977. if (port == -99) {
  7978. /* Unix domain socket */
  7979. size_t hostlen = strlen(host);
  7980. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7981. if (error != NULL) {
  7982. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7983. mg_snprintf(NULL,
  7984. NULL, /* No truncation check for ebuf */
  7985. error->text,
  7986. error->text_buffer_size,
  7987. "%s",
  7988. "host length exceeds limit");
  7989. }
  7990. return 0;
  7991. }
  7992. } else
  7993. #endif
  7994. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7995. if (error != NULL) {
  7996. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7997. mg_snprintf(NULL,
  7998. NULL, /* No truncation check for ebuf */
  7999. error->text,
  8000. error->text_buffer_size,
  8001. "%s",
  8002. "invalid port");
  8003. }
  8004. return 0;
  8005. }
  8006. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8007. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8008. if (use_ssl && (TLS_client_method == NULL)) {
  8009. if (error != NULL) {
  8010. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8011. mg_snprintf(NULL,
  8012. NULL, /* No truncation check for ebuf */
  8013. error->text,
  8014. error->text_buffer_size,
  8015. "%s",
  8016. "SSL is not initialized");
  8017. }
  8018. return 0;
  8019. }
  8020. #else
  8021. if (use_ssl && (SSLv23_client_method == NULL)) {
  8022. if (error != 0) {
  8023. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8024. mg_snprintf(NULL,
  8025. NULL, /* No truncation check for ebuf */
  8026. error->text,
  8027. error->text_buffer_size,
  8028. "%s",
  8029. "SSL is not initialized");
  8030. }
  8031. return 0;
  8032. }
  8033. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8034. #else
  8035. (void)use_ssl;
  8036. #endif /* NO SSL */
  8037. #if defined(USE_X_DOM_SOCKET)
  8038. if (port == -99) {
  8039. size_t hostlen = strlen(host);
  8040. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8041. ip_ver = -99;
  8042. sa->sun.sun_family = AF_UNIX;
  8043. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8044. memcpy(sa->sun.sun_path, host, hostlen);
  8045. } else
  8046. #endif
  8047. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8048. sa->sin.sin_port = htons((uint16_t)port);
  8049. ip_ver = 4;
  8050. #if defined(USE_IPV6)
  8051. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8052. sa->sin6.sin6_port = htons((uint16_t)port);
  8053. ip_ver = 6;
  8054. } else if (host[0] == '[') {
  8055. /* While getaddrinfo on Windows will work with [::1],
  8056. * getaddrinfo on Linux only works with ::1 (without []). */
  8057. size_t l = strlen(host + 1);
  8058. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8059. if (h) {
  8060. h[l - 1] = 0;
  8061. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8062. sa->sin6.sin6_port = htons((uint16_t)port);
  8063. ip_ver = 6;
  8064. }
  8065. mg_free(h);
  8066. }
  8067. #endif
  8068. }
  8069. if (ip_ver == 0) {
  8070. if (error != NULL) {
  8071. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8072. mg_snprintf(NULL,
  8073. NULL, /* No truncation check for ebuf */
  8074. error->text,
  8075. error->text_buffer_size,
  8076. "%s",
  8077. "host not found");
  8078. }
  8079. return 0;
  8080. }
  8081. if (ip_ver == 4) {
  8082. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8083. }
  8084. #if defined(USE_IPV6)
  8085. else if (ip_ver == 6) {
  8086. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8087. }
  8088. #endif
  8089. #if defined(USE_X_DOM_SOCKET)
  8090. else if (ip_ver == -99) {
  8091. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8092. }
  8093. #endif
  8094. if (*sock == INVALID_SOCKET) {
  8095. if (error != NULL) {
  8096. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8097. error->code_sub = (unsigned)ERRNO;
  8098. mg_snprintf(NULL,
  8099. NULL, /* No truncation check for ebuf */
  8100. error->text,
  8101. error->text_buffer_size,
  8102. "socket(): %s",
  8103. strerror(ERRNO));
  8104. }
  8105. return 0;
  8106. }
  8107. if (0 != set_non_blocking_mode(*sock)) {
  8108. if (error != NULL) {
  8109. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8110. error->code_sub = (unsigned)ERRNO;
  8111. mg_snprintf(NULL,
  8112. NULL, /* No truncation check for ebuf */
  8113. error->text,
  8114. error->text_buffer_size,
  8115. "Cannot set socket to non-blocking: %s",
  8116. strerror(ERRNO));
  8117. }
  8118. closesocket(*sock);
  8119. *sock = INVALID_SOCKET;
  8120. return 0;
  8121. }
  8122. set_close_on_exec(*sock, NULL, ctx);
  8123. if (ip_ver == 4) {
  8124. /* connected with IPv4 */
  8125. conn_ret = connect(*sock,
  8126. (struct sockaddr *)((void *)&sa->sin),
  8127. sizeof(sa->sin));
  8128. }
  8129. #if defined(USE_IPV6)
  8130. else if (ip_ver == 6) {
  8131. /* connected with IPv6 */
  8132. conn_ret = connect(*sock,
  8133. (struct sockaddr *)((void *)&sa->sin6),
  8134. sizeof(sa->sin6));
  8135. }
  8136. #endif
  8137. #if defined(USE_X_DOM_SOCKET)
  8138. else if (ip_ver == -99) {
  8139. /* connected to domain socket */
  8140. conn_ret = connect(*sock,
  8141. (struct sockaddr *)((void *)&sa->sun),
  8142. sizeof(sa->sun));
  8143. }
  8144. #endif
  8145. if (conn_ret != 0) {
  8146. sockerr = ERRNO;
  8147. }
  8148. #if defined(_WIN32)
  8149. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8150. #else
  8151. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8152. #endif
  8153. /* Data for getsockopt */
  8154. void *psockerr = &sockerr;
  8155. int ret;
  8156. #if defined(_WIN32)
  8157. int len = (int)sizeof(sockerr);
  8158. #else
  8159. socklen_t len = (socklen_t)sizeof(sockerr);
  8160. #endif
  8161. /* Data for poll */
  8162. struct mg_pollfd pfd[1];
  8163. int pollres;
  8164. int ms_wait = 10000; /* 10 second timeout */
  8165. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8166. /* For a non-blocking socket, the connect sequence is:
  8167. * 1) call connect (will not block)
  8168. * 2) wait until the socket is ready for writing (select or poll)
  8169. * 3) check connection state with getsockopt
  8170. */
  8171. pfd[0].fd = *sock;
  8172. pfd[0].events = POLLOUT;
  8173. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8174. if (pollres != 1) {
  8175. /* Not connected */
  8176. if (error != NULL) {
  8177. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8178. mg_snprintf(NULL,
  8179. NULL, /* No truncation check for ebuf */
  8180. error->text,
  8181. error->text_buffer_size,
  8182. "connect(%s:%d): timeout",
  8183. host,
  8184. port);
  8185. }
  8186. closesocket(*sock);
  8187. *sock = INVALID_SOCKET;
  8188. return 0;
  8189. }
  8190. #if defined(_WIN32)
  8191. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8192. #else
  8193. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8194. #endif
  8195. if ((ret == 0) && (sockerr == 0)) {
  8196. conn_ret = 0;
  8197. }
  8198. }
  8199. if (conn_ret != 0) {
  8200. /* Not connected */
  8201. if (error != NULL) {
  8202. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8203. error->code_sub = (unsigned)ERRNO;
  8204. mg_snprintf(NULL,
  8205. NULL, /* No truncation check for ebuf */
  8206. error->text,
  8207. error->text_buffer_size,
  8208. "connect(%s:%d): error %s",
  8209. host,
  8210. port,
  8211. strerror(sockerr));
  8212. }
  8213. closesocket(*sock);
  8214. *sock = INVALID_SOCKET;
  8215. return 0;
  8216. }
  8217. return 1;
  8218. }
  8219. CIVETWEB_API int
  8220. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8221. {
  8222. static const char *dont_escape = "._-$,;~()";
  8223. static const char *hex = "0123456789abcdef";
  8224. char *pos = dst;
  8225. const char *end = dst + dst_len - 1;
  8226. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8227. if (isalnum((unsigned char)*src)
  8228. || (strchr(dont_escape, *src) != NULL)) {
  8229. *pos = *src;
  8230. } else if (pos + 2 < end) {
  8231. pos[0] = '%';
  8232. pos[1] = hex[(unsigned char)*src >> 4];
  8233. pos[2] = hex[(unsigned char)*src & 0xf];
  8234. pos += 2;
  8235. } else {
  8236. break;
  8237. }
  8238. }
  8239. *pos = '\0';
  8240. return (*src == '\0') ? (int)(pos - dst) : -1;
  8241. }
  8242. /* Return 0 on success, non-zero if an error occurs. */
  8243. static int
  8244. print_dir_entry(struct mg_connection *conn, struct de *de)
  8245. {
  8246. size_t namesize, escsize, i;
  8247. char *href, *esc, *p;
  8248. char size[64], mod[64];
  8249. #if defined(REENTRANT_TIME)
  8250. struct tm _tm;
  8251. struct tm *tm = &_tm;
  8252. #else
  8253. struct tm *tm;
  8254. #endif
  8255. /* Estimate worst case size for encoding and escaping */
  8256. namesize = strlen(de->file_name) + 1;
  8257. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8258. href = (char *)mg_malloc(namesize * 3 + escsize);
  8259. if (href == NULL) {
  8260. return -1;
  8261. }
  8262. mg_url_encode(de->file_name, href, namesize * 3);
  8263. esc = NULL;
  8264. if (escsize > 0) {
  8265. /* HTML escaping needed */
  8266. esc = href + namesize * 3;
  8267. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8268. mg_strlcpy(p, de->file_name + i, 2);
  8269. if (*p == '&') {
  8270. strcpy(p, "&amp;");
  8271. } else if (*p == '<') {
  8272. strcpy(p, "&lt;");
  8273. } else if (*p == '>') {
  8274. strcpy(p, "&gt;");
  8275. }
  8276. }
  8277. }
  8278. if (de->file.is_directory) {
  8279. mg_snprintf(conn,
  8280. NULL, /* Buffer is big enough */
  8281. size,
  8282. sizeof(size),
  8283. "%s",
  8284. "[DIRECTORY]");
  8285. } else {
  8286. /* We use (signed) cast below because MSVC 6 compiler cannot
  8287. * convert unsigned __int64 to double. Sigh. */
  8288. if (de->file.size < 1024) {
  8289. mg_snprintf(conn,
  8290. NULL, /* Buffer is big enough */
  8291. size,
  8292. sizeof(size),
  8293. "%d",
  8294. (int)de->file.size);
  8295. } else if (de->file.size < 0x100000) {
  8296. mg_snprintf(conn,
  8297. NULL, /* Buffer is big enough */
  8298. size,
  8299. sizeof(size),
  8300. "%.1fk",
  8301. (double)de->file.size / 1024.0);
  8302. } else if (de->file.size < 0x40000000) {
  8303. mg_snprintf(conn,
  8304. NULL, /* Buffer is big enough */
  8305. size,
  8306. sizeof(size),
  8307. "%.1fM",
  8308. (double)de->file.size / 1048576);
  8309. } else {
  8310. mg_snprintf(conn,
  8311. NULL, /* Buffer is big enough */
  8312. size,
  8313. sizeof(size),
  8314. "%.1fG",
  8315. (double)de->file.size / 1073741824);
  8316. }
  8317. }
  8318. /* Note: mg_snprintf will not cause a buffer overflow above.
  8319. * So, string truncation checks are not required here. */
  8320. #if defined(REENTRANT_TIME)
  8321. localtime_r(&de->file.last_modified, tm);
  8322. #else
  8323. tm = localtime(&de->file.last_modified);
  8324. #endif
  8325. if (tm != NULL) {
  8326. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8327. } else {
  8328. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8329. }
  8330. mg_printf(conn,
  8331. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8332. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8333. href,
  8334. de->file.is_directory ? "/" : "",
  8335. esc ? esc : de->file_name,
  8336. de->file.is_directory ? "/" : "",
  8337. mod,
  8338. size);
  8339. mg_free(href);
  8340. return 0;
  8341. }
  8342. /* This function is called from send_directory() and used for
  8343. * sorting directory entries by size, name, or modification time. */
  8344. static int
  8345. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8346. {
  8347. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8348. if (p1 && p2) {
  8349. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8350. int cmp_result = 0;
  8351. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8352. query_string = "n";
  8353. }
  8354. /* Sort Directories vs Files */
  8355. if (a->file.is_directory && !b->file.is_directory) {
  8356. return -1; /* Always put directories on top */
  8357. } else if (!a->file.is_directory && b->file.is_directory) {
  8358. return 1; /* Always put directories on top */
  8359. }
  8360. /* Sort by size or date */
  8361. if (*query_string == 's') {
  8362. cmp_result = (a->file.size == b->file.size)
  8363. ? 0
  8364. : ((a->file.size > b->file.size) ? 1 : -1);
  8365. } else if (*query_string == 'd') {
  8366. cmp_result =
  8367. (a->file.last_modified == b->file.last_modified)
  8368. ? 0
  8369. : ((a->file.last_modified > b->file.last_modified) ? 1
  8370. : -1);
  8371. }
  8372. /* Sort by name:
  8373. * if (*query_string == 'n') ...
  8374. * but also sort files of same size/date by name as secondary criterion.
  8375. */
  8376. if (cmp_result == 0) {
  8377. cmp_result = strcmp(a->file_name, b->file_name);
  8378. }
  8379. /* For descending order, invert result */
  8380. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8381. }
  8382. return 0;
  8383. }
  8384. static int
  8385. must_hide_file(struct mg_connection *conn, const char *path)
  8386. {
  8387. if (conn && conn->dom_ctx) {
  8388. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8389. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8390. return (match_prefix_strlen(pw_pattern, path) > 0)
  8391. || (match_prefix_strlen(pattern, path) > 0);
  8392. }
  8393. return 0;
  8394. }
  8395. #if !defined(NO_FILESYSTEMS)
  8396. static int
  8397. scan_directory(struct mg_connection *conn,
  8398. const char *dir,
  8399. void *data,
  8400. int (*cb)(struct de *, void *))
  8401. {
  8402. char path[UTF8_PATH_MAX];
  8403. struct dirent *dp;
  8404. DIR *dirp;
  8405. struct de de;
  8406. int truncated;
  8407. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8408. return 0;
  8409. } else {
  8410. while ((dp = mg_readdir(dirp)) != NULL) {
  8411. /* Do not show current dir and hidden files */
  8412. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8413. || must_hide_file(conn, dp->d_name)) {
  8414. continue;
  8415. }
  8416. mg_snprintf(
  8417. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8418. /* If we don't memset stat structure to zero, mtime will have
  8419. * garbage and strftime() will segfault later on in
  8420. * print_dir_entry(). memset is required only if mg_stat()
  8421. * fails. For more details, see
  8422. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8423. memset(&de.file, 0, sizeof(de.file));
  8424. if (truncated) {
  8425. /* If the path is not complete, skip processing. */
  8426. continue;
  8427. }
  8428. if (!mg_stat(conn, path, &de.file)) {
  8429. mg_cry_internal(conn,
  8430. "%s: mg_stat(%s) failed: %s",
  8431. __func__,
  8432. path,
  8433. strerror(ERRNO));
  8434. }
  8435. de.file_name = dp->d_name;
  8436. if (cb(&de, data)) {
  8437. /* stopped */
  8438. break;
  8439. }
  8440. }
  8441. (void)mg_closedir(dirp);
  8442. }
  8443. return 1;
  8444. }
  8445. #endif /* NO_FILESYSTEMS */
  8446. #if !defined(NO_FILES)
  8447. static int
  8448. remove_directory(struct mg_connection *conn, const char *dir)
  8449. {
  8450. char path[UTF8_PATH_MAX];
  8451. struct dirent *dp;
  8452. DIR *dirp;
  8453. struct de de;
  8454. int truncated;
  8455. int ok = 1;
  8456. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8457. return 0;
  8458. } else {
  8459. while ((dp = mg_readdir(dirp)) != NULL) {
  8460. /* Do not show current dir (but show hidden files as they will
  8461. * also be removed) */
  8462. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8463. continue;
  8464. }
  8465. mg_snprintf(
  8466. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8467. /* If we don't memset stat structure to zero, mtime will have
  8468. * garbage and strftime() will segfault later on in
  8469. * print_dir_entry(). memset is required only if mg_stat()
  8470. * fails. For more details, see
  8471. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8472. memset(&de.file, 0, sizeof(de.file));
  8473. if (truncated) {
  8474. /* Do not delete anything shorter */
  8475. ok = 0;
  8476. continue;
  8477. }
  8478. if (!mg_stat(conn, path, &de.file)) {
  8479. mg_cry_internal(conn,
  8480. "%s: mg_stat(%s) failed: %s",
  8481. __func__,
  8482. path,
  8483. strerror(ERRNO));
  8484. ok = 0;
  8485. }
  8486. if (de.file.is_directory) {
  8487. if (remove_directory(conn, path) == 0) {
  8488. ok = 0;
  8489. }
  8490. } else {
  8491. /* This will fail file is the file is in memory */
  8492. if (mg_remove(conn, path) == 0) {
  8493. ok = 0;
  8494. }
  8495. }
  8496. }
  8497. (void)mg_closedir(dirp);
  8498. IGNORE_UNUSED_RESULT(rmdir(dir));
  8499. }
  8500. return ok;
  8501. }
  8502. #endif
  8503. struct dir_scan_data {
  8504. struct de *entries;
  8505. size_t num_entries;
  8506. size_t arr_size;
  8507. };
  8508. #if !defined(NO_FILESYSTEMS)
  8509. static int
  8510. dir_scan_callback(struct de *de, void *data)
  8511. {
  8512. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8513. struct de *entries = dsd->entries;
  8514. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8515. /* Here "entries" is a temporary pointer and can be replaced,
  8516. * "dsd->entries" is the original pointer */
  8517. entries =
  8518. (struct de *)mg_realloc(entries,
  8519. dsd->arr_size * 2 * sizeof(entries[0]));
  8520. if (entries == NULL) {
  8521. /* stop scan */
  8522. return 1;
  8523. }
  8524. dsd->entries = entries;
  8525. dsd->arr_size *= 2;
  8526. }
  8527. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8528. if (entries[dsd->num_entries].file_name == NULL) {
  8529. /* stop scan */
  8530. return 1;
  8531. }
  8532. entries[dsd->num_entries].file = de->file;
  8533. dsd->num_entries++;
  8534. return 0;
  8535. }
  8536. static void
  8537. handle_directory_request(struct mg_connection *conn, const char *dir)
  8538. {
  8539. size_t i;
  8540. int sort_direction;
  8541. struct dir_scan_data data = {NULL, 0, 128};
  8542. char date[64], *esc, *p;
  8543. const char *title;
  8544. time_t curtime = time(NULL);
  8545. if (!conn) {
  8546. return;
  8547. }
  8548. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8549. mg_send_http_error(conn,
  8550. 500,
  8551. "Error: Cannot open directory\nopendir(%s): %s",
  8552. dir,
  8553. strerror(ERRNO));
  8554. return;
  8555. }
  8556. gmt_time_string(date, sizeof(date), &curtime);
  8557. esc = NULL;
  8558. title = conn->request_info.local_uri;
  8559. if (title[strcspn(title, "&<>")]) {
  8560. /* HTML escaping needed */
  8561. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8562. if (esc) {
  8563. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8564. mg_strlcpy(p, title + i, 2);
  8565. if (*p == '&') {
  8566. strcpy(p, "&amp;");
  8567. } else if (*p == '<') {
  8568. strcpy(p, "&lt;");
  8569. } else if (*p == '>') {
  8570. strcpy(p, "&gt;");
  8571. }
  8572. }
  8573. } else {
  8574. title = "";
  8575. }
  8576. }
  8577. sort_direction = ((conn->request_info.query_string != NULL)
  8578. && (conn->request_info.query_string[0] != '\0')
  8579. && (conn->request_info.query_string[1] == 'd'))
  8580. ? 'a'
  8581. : 'd';
  8582. conn->must_close = 1;
  8583. /* Create 200 OK response */
  8584. mg_response_header_start(conn, 200);
  8585. send_static_cache_header(conn);
  8586. send_additional_header(conn);
  8587. mg_response_header_add(conn,
  8588. "Content-Type",
  8589. "text/html; charset=utf-8",
  8590. -1);
  8591. /* Send all headers */
  8592. mg_response_header_send(conn);
  8593. /* Body */
  8594. mg_printf(conn,
  8595. "<!DOCTYPE html>"
  8596. "<html><head><title>Index of %s</title>"
  8597. "<style>th {text-align: left;}</style></head>"
  8598. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8599. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8600. "<th><a href=\"?d%c\">Modified</a></th>"
  8601. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8602. "<tr><td colspan=\"3\"><hr></td></tr>",
  8603. esc ? esc : title,
  8604. esc ? esc : title,
  8605. sort_direction,
  8606. sort_direction,
  8607. sort_direction);
  8608. mg_free(esc);
  8609. /* Print first entry - link to a parent directory */
  8610. mg_printf(conn,
  8611. "<tr><td><a href=\"%s\">%s</a></td>"
  8612. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8613. "..",
  8614. "Parent directory",
  8615. "-",
  8616. "-");
  8617. /* Sort and print directory entries */
  8618. if (data.entries != NULL) {
  8619. mg_sort(data.entries,
  8620. data.num_entries,
  8621. sizeof(data.entries[0]),
  8622. compare_dir_entries,
  8623. (void *)conn->request_info.query_string);
  8624. for (i = 0; i < data.num_entries; i++) {
  8625. print_dir_entry(conn, &data.entries[i]);
  8626. mg_free(data.entries[i].file_name);
  8627. }
  8628. mg_free(data.entries);
  8629. }
  8630. mg_printf(conn, "%s", "</table></pre></body></html>");
  8631. conn->status_code = 200;
  8632. }
  8633. #endif /* NO_FILESYSTEMS */
  8634. /* Send len bytes from the opened file to the client. */
  8635. static void
  8636. send_file_data(struct mg_connection *conn,
  8637. struct mg_file *filep,
  8638. int64_t offset,
  8639. int64_t len,
  8640. int no_buffering)
  8641. {
  8642. char buf[MG_BUF_LEN];
  8643. int to_read, num_read, num_written;
  8644. int64_t size;
  8645. if (!filep || !conn) {
  8646. return;
  8647. }
  8648. /* Sanity check the offset */
  8649. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8650. : (int64_t)(filep->stat.size);
  8651. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8652. if (len > 0 && filep->access.fp != NULL) {
  8653. /* file stored on disk */
  8654. #if defined(__linux__)
  8655. /* sendfile is only available for Linux */
  8656. if ((conn->ssl == 0) && (conn->throttle == 0)
  8657. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8658. "yes"))) {
  8659. off_t sf_offs = (off_t)offset;
  8660. ssize_t sf_sent;
  8661. int sf_file = fileno(filep->access.fp);
  8662. int loop_cnt = 0;
  8663. do {
  8664. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8665. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8666. size_t sf_tosend =
  8667. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8668. sf_sent =
  8669. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8670. if (sf_sent > 0) {
  8671. len -= sf_sent;
  8672. offset += sf_sent;
  8673. } else if (loop_cnt == 0) {
  8674. /* This file can not be sent using sendfile.
  8675. * This might be the case for pseudo-files in the
  8676. * /sys/ and /proc/ file system.
  8677. * Use the regular user mode copy code instead. */
  8678. break;
  8679. } else if (sf_sent == 0) {
  8680. /* No error, but 0 bytes sent. May be EOF? */
  8681. return;
  8682. }
  8683. loop_cnt++;
  8684. } while ((len > 0) && (sf_sent >= 0));
  8685. if (sf_sent > 0) {
  8686. return; /* OK */
  8687. }
  8688. /* sf_sent<0 means error, thus fall back to the classic way */
  8689. /* This is always the case, if sf_file is not a "normal" file,
  8690. * e.g., for sending data from the output of a CGI process. */
  8691. offset = (int64_t)sf_offs;
  8692. }
  8693. #endif
  8694. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8695. mg_cry_internal(conn,
  8696. "%s: fseeko() failed: %s",
  8697. __func__,
  8698. strerror(ERRNO));
  8699. mg_send_http_error(
  8700. conn,
  8701. 500,
  8702. "%s",
  8703. "Error: Unable to access file at requested position.");
  8704. } else {
  8705. while (len > 0) {
  8706. /* Calculate how much to read from the file into the buffer. */
  8707. /* If no_buffering is set, we should not wait until the
  8708. * CGI->Server buffer is filled, but send everything
  8709. * immediately. In theory buffering could be turned off using
  8710. * setbuf(filep->access.fp, NULL);
  8711. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8712. * but in practice this does not work. A "Linux only" solution
  8713. * may be to use select(). The only portable way is to read byte
  8714. * by byte, but this is quite inefficient from a performance
  8715. * point of view. */
  8716. to_read = no_buffering ? 1 : sizeof(buf);
  8717. if ((int64_t)to_read > len) {
  8718. to_read = (int)len;
  8719. }
  8720. /* Read from file, exit the loop on error */
  8721. if ((num_read =
  8722. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8723. <= 0) {
  8724. break;
  8725. }
  8726. /* Send read bytes to the client, exit the loop on error */
  8727. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8728. != num_read) {
  8729. break;
  8730. }
  8731. /* Both read and were successful, adjust counters */
  8732. len -= num_written;
  8733. }
  8734. }
  8735. }
  8736. }
  8737. static int
  8738. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8739. {
  8740. return sscanf(header,
  8741. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8742. a,
  8743. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8744. // to an integer value, but function will not report
  8745. // conversion errors; consider using 'strtol' instead
  8746. }
  8747. static void
  8748. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8749. {
  8750. if ((filestat != NULL) && (buf != NULL)) {
  8751. mg_snprintf(NULL,
  8752. NULL, /* All calls to construct_etag use 64 byte buffer */
  8753. buf,
  8754. buf_len,
  8755. "\"%lx.%" INT64_FMT "\"",
  8756. (unsigned long)filestat->last_modified,
  8757. filestat->size);
  8758. }
  8759. }
  8760. static void
  8761. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8762. {
  8763. if (filep != NULL && filep->fp != NULL) {
  8764. #if defined(_WIN32)
  8765. (void)conn; /* Unused. */
  8766. #else
  8767. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8768. mg_cry_internal(conn,
  8769. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8770. __func__,
  8771. strerror(ERRNO));
  8772. }
  8773. #endif
  8774. }
  8775. }
  8776. #if defined(USE_ZLIB)
  8777. #include "mod_zlib.inl"
  8778. #endif
  8779. #if !defined(NO_FILESYSTEMS)
  8780. static void
  8781. handle_static_file_request(struct mg_connection *conn,
  8782. const char *path,
  8783. struct mg_file *filep,
  8784. const char *mime_type,
  8785. const char *additional_headers)
  8786. {
  8787. char lm[64], etag[64];
  8788. char range[128]; /* large enough, so there will be no overflow */
  8789. const char *range_hdr;
  8790. int64_t cl, r1, r2;
  8791. struct vec mime_vec;
  8792. int n, truncated;
  8793. char gz_path[UTF8_PATH_MAX];
  8794. const char *encoding = 0;
  8795. int is_head_request;
  8796. #if defined(USE_ZLIB)
  8797. /* Compression is allowed, unless there is a reason not to use
  8798. * compression. If the file is already compressed, too small or a
  8799. * "range" request was made, on the fly compression is not possible. */
  8800. int allow_on_the_fly_compression = 1;
  8801. #endif
  8802. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8803. return;
  8804. }
  8805. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8806. if (mime_type == NULL) {
  8807. get_mime_type(conn, path, &mime_vec);
  8808. } else {
  8809. mime_vec.ptr = mime_type;
  8810. mime_vec.len = strlen(mime_type);
  8811. }
  8812. if (filep->stat.size > INT64_MAX) {
  8813. mg_send_http_error(conn,
  8814. 500,
  8815. "Error: File size is too large to send\n%" INT64_FMT,
  8816. filep->stat.size);
  8817. return;
  8818. }
  8819. cl = (int64_t)filep->stat.size;
  8820. conn->status_code = 200;
  8821. range[0] = '\0';
  8822. #if defined(USE_ZLIB)
  8823. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8824. * it's important to rewrite the filename after resolving
  8825. * the mime type from it, to preserve the actual file's type */
  8826. if (!conn->accept_gzip) {
  8827. allow_on_the_fly_compression = 0;
  8828. }
  8829. #endif
  8830. /* Check if there is a range header */
  8831. range_hdr = mg_get_header(conn, "Range");
  8832. /* For gzipped files, add *.gz */
  8833. if (filep->stat.is_gzipped) {
  8834. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8835. if (truncated) {
  8836. mg_send_http_error(conn,
  8837. 500,
  8838. "Error: Path of zipped file too long (%s)",
  8839. path);
  8840. return;
  8841. }
  8842. path = gz_path;
  8843. encoding = "gzip";
  8844. #if defined(USE_ZLIB)
  8845. /* File is already compressed. No "on the fly" compression. */
  8846. allow_on_the_fly_compression = 0;
  8847. #endif
  8848. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8849. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8850. struct mg_file_stat file_stat;
  8851. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8852. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8853. && !file_stat.is_directory) {
  8854. file_stat.is_gzipped = 1;
  8855. filep->stat = file_stat;
  8856. cl = (int64_t)filep->stat.size;
  8857. path = gz_path;
  8858. encoding = "gzip";
  8859. #if defined(USE_ZLIB)
  8860. /* File is already compressed. No "on the fly" compression. */
  8861. allow_on_the_fly_compression = 0;
  8862. #endif
  8863. }
  8864. }
  8865. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8866. mg_send_http_error(conn,
  8867. 500,
  8868. "Error: Cannot open file\nfopen(%s): %s",
  8869. path,
  8870. strerror(ERRNO));
  8871. return;
  8872. }
  8873. fclose_on_exec(&filep->access, conn);
  8874. /* If "Range" request was made: parse header, send only selected part
  8875. * of the file. */
  8876. r1 = r2 = 0;
  8877. if ((range_hdr != NULL)
  8878. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8879. && (r2 >= 0)) {
  8880. /* actually, range requests don't play well with a pre-gzipped
  8881. * file (since the range is specified in the uncompressed space) */
  8882. if (filep->stat.is_gzipped) {
  8883. mg_send_http_error(
  8884. conn,
  8885. 416, /* 416 = Range Not Satisfiable */
  8886. "%s",
  8887. "Error: Range requests in gzipped files are not supported");
  8888. (void)mg_fclose(
  8889. &filep->access); /* ignore error on read only file */
  8890. return;
  8891. }
  8892. conn->status_code = 206;
  8893. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8894. mg_snprintf(conn,
  8895. NULL, /* range buffer is big enough */
  8896. range,
  8897. sizeof(range),
  8898. "bytes "
  8899. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8900. r1,
  8901. r1 + cl - 1,
  8902. filep->stat.size);
  8903. #if defined(USE_ZLIB)
  8904. /* Do not compress ranges. */
  8905. allow_on_the_fly_compression = 0;
  8906. #endif
  8907. }
  8908. /* Do not compress small files. Small files do not benefit from file
  8909. * compression, but there is still some overhead. */
  8910. #if defined(USE_ZLIB)
  8911. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8912. /* File is below the size limit. */
  8913. allow_on_the_fly_compression = 0;
  8914. }
  8915. #endif
  8916. /* Prepare Etag, and Last-Modified headers. */
  8917. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8918. construct_etag(etag, sizeof(etag), &filep->stat);
  8919. /* Create 2xx (200, 206) response */
  8920. mg_response_header_start(conn, conn->status_code);
  8921. send_static_cache_header(conn);
  8922. send_additional_header(conn);
  8923. send_cors_header(conn);
  8924. mg_response_header_add(conn,
  8925. "Content-Type",
  8926. mime_vec.ptr,
  8927. (int)mime_vec.len);
  8928. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8929. mg_response_header_add(conn, "Etag", etag, -1);
  8930. #if defined(USE_ZLIB)
  8931. /* On the fly compression allowed */
  8932. if (allow_on_the_fly_compression) {
  8933. /* For on the fly compression, we don't know the content size in
  8934. * advance, so we have to use chunked encoding */
  8935. encoding = "gzip";
  8936. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8937. /* HTTP/2 is always using "chunks" (frames) */
  8938. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8939. }
  8940. } else
  8941. #endif
  8942. {
  8943. /* Without on-the-fly compression, we know the content-length
  8944. * and we can use ranges (with on-the-fly compression we cannot).
  8945. * So we send these response headers only in this case. */
  8946. char len[32];
  8947. int trunc = 0;
  8948. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8949. if (!trunc) {
  8950. mg_response_header_add(conn, "Content-Length", len, -1);
  8951. }
  8952. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8953. }
  8954. if (encoding) {
  8955. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8956. }
  8957. if (range[0] != 0) {
  8958. mg_response_header_add(conn, "Content-Range", range, -1);
  8959. }
  8960. /* The code above does not add any header starting with X- to make
  8961. * sure no one of the additional_headers is included twice */
  8962. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8963. mg_response_header_add_lines(conn, additional_headers);
  8964. }
  8965. /* Send all headers */
  8966. mg_response_header_send(conn);
  8967. if (!is_head_request) {
  8968. #if defined(USE_ZLIB)
  8969. if (allow_on_the_fly_compression) {
  8970. /* Compress and send */
  8971. send_compressed_data(conn, filep);
  8972. } else
  8973. #endif
  8974. {
  8975. /* Send file directly */
  8976. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8977. }
  8978. }
  8979. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8980. }
  8981. CIVETWEB_API int
  8982. mg_send_file_body(struct mg_connection *conn, const char *path)
  8983. {
  8984. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8985. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8986. return -1;
  8987. }
  8988. fclose_on_exec(&file.access, conn);
  8989. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8990. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8991. return 0; /* >= 0 for OK */
  8992. }
  8993. #endif /* NO_FILESYSTEMS */
  8994. #if !defined(NO_CACHING)
  8995. /* Return True if we should reply 304 Not Modified. */
  8996. static int
  8997. is_not_modified(const struct mg_connection *conn,
  8998. const struct mg_file_stat *filestat)
  8999. {
  9000. char etag[64];
  9001. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9002. const char *inm = mg_get_header(conn, "If-None-Match");
  9003. construct_etag(etag, sizeof(etag), filestat);
  9004. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9005. || ((ims != NULL)
  9006. && (filestat->last_modified <= parse_date_string(ims)));
  9007. }
  9008. static void
  9009. handle_not_modified_static_file_request(struct mg_connection *conn,
  9010. struct mg_file *filep)
  9011. {
  9012. char lm[64], etag[64];
  9013. if ((conn == NULL) || (filep == NULL)) {
  9014. return;
  9015. }
  9016. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9017. construct_etag(etag, sizeof(etag), &filep->stat);
  9018. /* Create 304 "not modified" response */
  9019. mg_response_header_start(conn, 304);
  9020. send_static_cache_header(conn);
  9021. send_additional_header(conn);
  9022. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9023. mg_response_header_add(conn, "Etag", etag, -1);
  9024. /* Send all headers */
  9025. mg_response_header_send(conn);
  9026. }
  9027. #endif
  9028. #if !defined(NO_FILESYSTEMS)
  9029. CIVETWEB_API void
  9030. mg_send_file(struct mg_connection *conn, const char *path)
  9031. {
  9032. mg_send_mime_file2(conn, path, NULL, NULL);
  9033. }
  9034. CIVETWEB_API void
  9035. mg_send_mime_file(struct mg_connection *conn,
  9036. const char *path,
  9037. const char *mime_type)
  9038. {
  9039. mg_send_mime_file2(conn, path, mime_type, NULL);
  9040. }
  9041. CIVETWEB_API void
  9042. mg_send_mime_file2(struct mg_connection *conn,
  9043. const char *path,
  9044. const char *mime_type,
  9045. const char *additional_headers)
  9046. {
  9047. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9048. if (!conn) {
  9049. /* No conn */
  9050. return;
  9051. }
  9052. if (mg_stat(conn, path, &file.stat)) {
  9053. #if !defined(NO_CACHING)
  9054. if (is_not_modified(conn, &file.stat)) {
  9055. /* Send 304 "Not Modified" - this must not send any body data */
  9056. handle_not_modified_static_file_request(conn, &file);
  9057. } else
  9058. #endif /* NO_CACHING */
  9059. if (file.stat.is_directory) {
  9060. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9061. "yes")) {
  9062. handle_directory_request(conn, path);
  9063. } else {
  9064. mg_send_http_error(conn,
  9065. 403,
  9066. "%s",
  9067. "Error: Directory listing denied");
  9068. }
  9069. } else {
  9070. handle_static_file_request(
  9071. conn, path, &file, mime_type, additional_headers);
  9072. }
  9073. } else {
  9074. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9075. }
  9076. }
  9077. /* For a given PUT path, create all intermediate subdirectories.
  9078. * Return 0 if the path itself is a directory.
  9079. * Return 1 if the path leads to a file.
  9080. * Return -1 for if the path is too long.
  9081. * Return -2 if path can not be created.
  9082. */
  9083. static int
  9084. put_dir(struct mg_connection *conn, const char *path)
  9085. {
  9086. char buf[UTF8_PATH_MAX];
  9087. const char *s, *p;
  9088. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9089. size_t len;
  9090. int res = 1;
  9091. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9092. len = (size_t)(p - path);
  9093. if (len >= sizeof(buf)) {
  9094. /* path too long */
  9095. res = -1;
  9096. break;
  9097. }
  9098. memcpy(buf, path, len);
  9099. buf[len] = '\0';
  9100. /* Try to create intermediate directory */
  9101. DEBUG_TRACE("mkdir(%s)", buf);
  9102. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9103. /* path does not exist and can not be created */
  9104. res = -2;
  9105. break;
  9106. }
  9107. /* Is path itself a directory? */
  9108. if (p[1] == '\0') {
  9109. res = 0;
  9110. }
  9111. }
  9112. return res;
  9113. }
  9114. static void
  9115. remove_bad_file(const struct mg_connection *conn, const char *path)
  9116. {
  9117. int r = mg_remove(conn, path);
  9118. if (r != 0) {
  9119. mg_cry_internal(conn,
  9120. "%s: Cannot remove invalid file %s",
  9121. __func__,
  9122. path);
  9123. }
  9124. }
  9125. CIVETWEB_API long long
  9126. mg_store_body(struct mg_connection *conn, const char *path)
  9127. {
  9128. char buf[MG_BUF_LEN];
  9129. long long len = 0;
  9130. int ret, n;
  9131. struct mg_file fi;
  9132. if (conn->consumed_content != 0) {
  9133. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9134. return -11;
  9135. }
  9136. ret = put_dir(conn, path);
  9137. if (ret < 0) {
  9138. /* -1 for path too long,
  9139. * -2 for path can not be created. */
  9140. return ret;
  9141. }
  9142. if (ret != 1) {
  9143. /* Return 0 means, path itself is a directory. */
  9144. return 0;
  9145. }
  9146. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9147. return -12;
  9148. }
  9149. ret = mg_read(conn, buf, sizeof(buf));
  9150. while (ret > 0) {
  9151. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9152. if (n != ret) {
  9153. (void)mg_fclose(
  9154. &fi.access); /* File is bad and will be removed anyway. */
  9155. remove_bad_file(conn, path);
  9156. return -13;
  9157. }
  9158. len += ret;
  9159. ret = mg_read(conn, buf, sizeof(buf));
  9160. }
  9161. /* File is open for writing. If fclose fails, there was probably an
  9162. * error flushing the buffer to disk, so the file on disk might be
  9163. * broken. Delete it and return an error to the caller. */
  9164. if (mg_fclose(&fi.access) != 0) {
  9165. remove_bad_file(conn, path);
  9166. return -14;
  9167. }
  9168. return len;
  9169. }
  9170. #endif /* NO_FILESYSTEMS */
  9171. /* Parse a buffer:
  9172. * Forward the string pointer till the end of a word, then
  9173. * terminate it and forward till the begin of the next word.
  9174. */
  9175. static int
  9176. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9177. {
  9178. /* Forward until a space is found - use isgraph here */
  9179. /* See http://www.cplusplus.com/reference/cctype/ */
  9180. while (isgraph((unsigned char)**ppw)) {
  9181. (*ppw)++;
  9182. }
  9183. /* Check end of word */
  9184. if (eol) {
  9185. /* must be a end of line */
  9186. if ((**ppw != '\r') && (**ppw != '\n')) {
  9187. return -1;
  9188. }
  9189. } else {
  9190. /* must be a end of a word, but not a line */
  9191. if (**ppw != ' ') {
  9192. return -1;
  9193. }
  9194. }
  9195. /* Terminate and forward to the next word */
  9196. do {
  9197. **ppw = 0;
  9198. (*ppw)++;
  9199. } while (isspace((unsigned char)**ppw));
  9200. /* Check after term */
  9201. if (!eol) {
  9202. /* if it's not the end of line, there must be a next word */
  9203. if (!isgraph((unsigned char)**ppw)) {
  9204. return -1;
  9205. }
  9206. }
  9207. /* ok */
  9208. return 1;
  9209. }
  9210. /* Parse HTTP headers from the given buffer, advance buf pointer
  9211. * to the point where parsing stopped.
  9212. * All parameters must be valid pointers (not NULL).
  9213. * Return <0 on error. */
  9214. static int
  9215. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9216. {
  9217. int i;
  9218. int num_headers = 0;
  9219. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9220. char *dp = *buf;
  9221. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9222. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9223. dp++;
  9224. }
  9225. if (dp == *buf) {
  9226. /* End of headers reached. */
  9227. break;
  9228. }
  9229. /* Drop all spaces after header name before : */
  9230. while (*dp == ' ') {
  9231. *dp = 0;
  9232. dp++;
  9233. }
  9234. if (*dp != ':') {
  9235. /* This is not a valid field. */
  9236. return -1;
  9237. }
  9238. /* End of header key (*dp == ':') */
  9239. /* Truncate here and set the key name */
  9240. *dp = 0;
  9241. hdr[i].name = *buf;
  9242. /* Skip all spaces */
  9243. do {
  9244. dp++;
  9245. } while ((*dp == ' ') || (*dp == '\t'));
  9246. /* The rest of the line is the value */
  9247. hdr[i].value = dp;
  9248. /* Find end of line */
  9249. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9250. dp++;
  9251. };
  9252. /* eliminate \r */
  9253. if (*dp == '\r') {
  9254. *dp = 0;
  9255. dp++;
  9256. if (*dp != '\n') {
  9257. /* This is not a valid line. */
  9258. return -1;
  9259. }
  9260. }
  9261. /* here *dp is either 0 or '\n' */
  9262. /* in any case, we have a new header */
  9263. num_headers = i + 1;
  9264. if (*dp) {
  9265. *dp = 0;
  9266. dp++;
  9267. *buf = dp;
  9268. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9269. /* This is the end of the header */
  9270. break;
  9271. }
  9272. } else {
  9273. *buf = dp;
  9274. break;
  9275. }
  9276. }
  9277. return num_headers;
  9278. }
  9279. struct mg_http_method_info {
  9280. const char *name;
  9281. int request_has_body;
  9282. int response_has_body;
  9283. int is_safe;
  9284. int is_idempotent;
  9285. int is_cacheable;
  9286. };
  9287. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9288. static const struct mg_http_method_info http_methods[] = {
  9289. /* HTTP (RFC 2616) */
  9290. {"GET", 0, 1, 1, 1, 1},
  9291. {"POST", 1, 1, 0, 0, 0},
  9292. {"PUT", 1, 0, 0, 1, 0},
  9293. {"DELETE", 0, 0, 0, 1, 0},
  9294. {"HEAD", 0, 0, 1, 1, 1},
  9295. {"OPTIONS", 0, 0, 1, 1, 0},
  9296. {"CONNECT", 1, 1, 0, 0, 0},
  9297. /* TRACE method (RFC 2616) is not supported for security reasons */
  9298. /* PATCH method (RFC 5789) */
  9299. {"PATCH", 1, 0, 0, 0, 0},
  9300. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9301. /* WEBDAV (RFC 2518) */
  9302. {"PROPFIND", 0, 1, 1, 1, 0},
  9303. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9304. * Some PROPFIND results MAY be cached, with care,
  9305. * as there is no cache validation mechanism for
  9306. * most properties. This method is both safe and
  9307. * idempotent (see Section 9.1 of [RFC2616]). */
  9308. {"MKCOL", 0, 0, 0, 1, 0},
  9309. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9310. * When MKCOL is invoked without a request body,
  9311. * the newly created collection SHOULD have no
  9312. * members. A MKCOL request message may contain
  9313. * a message body. The precise behavior of a MKCOL
  9314. * request when the body is present is undefined,
  9315. * ... ==> We do not support MKCOL with body data.
  9316. * This method is idempotent, but not safe (see
  9317. * Section 9.1 of [RFC2616]). Responses to this
  9318. * method MUST NOT be cached. */
  9319. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9320. {"LOCK", 1, 1, 0, 0, 0},
  9321. {"UNLOCK", 1, 0, 0, 0, 0},
  9322. {"PROPPATCH", 1, 1, 0, 0, 0},
  9323. {"COPY", 1, 0, 0, 0, 0},
  9324. {"MOVE", 1, 1, 0, 0, 0},
  9325. /* Unsupported WEBDAV Methods: */
  9326. /* + 11 methods from RFC 3253 */
  9327. /* ORDERPATCH (RFC 3648) */
  9328. /* ACL (RFC 3744) */
  9329. /* SEARCH (RFC 5323) */
  9330. /* + MicroSoft extensions
  9331. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9332. /* REPORT method (RFC 3253) */
  9333. {"REPORT", 1, 1, 1, 1, 1},
  9334. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9335. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9336. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9337. * to be useful for REST in case a "GET request with body" is
  9338. * required. */
  9339. {NULL, 0, 0, 0, 0, 0}
  9340. /* end of list */
  9341. };
  9342. /* All method names */
  9343. static char *all_methods = NULL; /* Built by mg_init_library */
  9344. static const struct mg_http_method_info *
  9345. get_http_method_info(const char *method)
  9346. {
  9347. /* Check if the method is known to the server. The list of all known
  9348. * HTTP methods can be found here at
  9349. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9350. */
  9351. const struct mg_http_method_info *m = http_methods;
  9352. while (m->name) {
  9353. if (!strcmp(m->name, method)) {
  9354. return m;
  9355. }
  9356. m++;
  9357. }
  9358. return NULL;
  9359. }
  9360. static int
  9361. is_valid_http_method(const char *method)
  9362. {
  9363. return (get_http_method_info(method) != NULL);
  9364. }
  9365. /* Parse HTTP request, fill in mg_request_info structure.
  9366. * This function modifies the buffer by NUL-terminating
  9367. * HTTP request components, header names and header values.
  9368. * Parameters:
  9369. * buf (in/out): pointer to the HTTP header to parse and split
  9370. * len (in): length of HTTP header buffer
  9371. * re (out): parsed header as mg_request_info
  9372. * buf and ri must be valid pointers (not NULL), len>0.
  9373. * Returns <0 on error. */
  9374. static int
  9375. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9376. {
  9377. int request_length;
  9378. int init_skip = 0;
  9379. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9380. * remote_port */
  9381. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9382. NULL;
  9383. ri->num_headers = 0;
  9384. /* RFC says that all initial whitespaces should be ignored */
  9385. /* This included all leading \r and \n (isspace) */
  9386. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9387. while ((len > 0) && isspace((unsigned char)*buf)) {
  9388. buf++;
  9389. len--;
  9390. init_skip++;
  9391. }
  9392. if (len == 0) {
  9393. /* Incomplete request */
  9394. return 0;
  9395. }
  9396. /* Control characters are not allowed, including zero */
  9397. if (iscntrl((unsigned char)*buf)) {
  9398. return -1;
  9399. }
  9400. /* Find end of HTTP header */
  9401. request_length = get_http_header_len(buf, len);
  9402. if (request_length <= 0) {
  9403. return request_length;
  9404. }
  9405. buf[request_length - 1] = '\0';
  9406. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9407. return -1;
  9408. }
  9409. /* The first word has to be the HTTP method */
  9410. ri->request_method = buf;
  9411. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9412. return -1;
  9413. }
  9414. /* The second word is the URI */
  9415. ri->request_uri = buf;
  9416. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9417. return -1;
  9418. }
  9419. /* Next would be the HTTP version */
  9420. ri->http_version = buf;
  9421. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9422. return -1;
  9423. }
  9424. /* Check for a valid HTTP version key */
  9425. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9426. /* Invalid request */
  9427. return -1;
  9428. }
  9429. ri->http_version += 5;
  9430. /* Check for a valid http method */
  9431. if (!is_valid_http_method(ri->request_method)) {
  9432. return -1;
  9433. }
  9434. /* Parse all HTTP headers */
  9435. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9436. if (ri->num_headers < 0) {
  9437. /* Error while parsing headers */
  9438. return -1;
  9439. }
  9440. return request_length + init_skip;
  9441. }
  9442. static int
  9443. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9444. {
  9445. int response_length;
  9446. int init_skip = 0;
  9447. char *tmp, *tmp2;
  9448. long l;
  9449. /* Initialize elements. */
  9450. ri->http_version = ri->status_text = NULL;
  9451. ri->num_headers = ri->status_code = 0;
  9452. /* RFC says that all initial whitespaces should be ignored */
  9453. /* This included all leading \r and \n (isspace) */
  9454. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9455. while ((len > 0) && isspace((unsigned char)*buf)) {
  9456. buf++;
  9457. len--;
  9458. init_skip++;
  9459. }
  9460. if (len == 0) {
  9461. /* Incomplete request */
  9462. return 0;
  9463. }
  9464. /* Control characters are not allowed, including zero */
  9465. if (iscntrl((unsigned char)*buf)) {
  9466. return -1;
  9467. }
  9468. /* Find end of HTTP header */
  9469. response_length = get_http_header_len(buf, len);
  9470. if (response_length <= 0) {
  9471. return response_length;
  9472. }
  9473. buf[response_length - 1] = '\0';
  9474. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9475. return -1;
  9476. }
  9477. /* The first word is the HTTP version */
  9478. /* Check for a valid HTTP version key */
  9479. if (strncmp(buf, "HTTP/", 5) != 0) {
  9480. /* Invalid request */
  9481. return -1;
  9482. }
  9483. buf += 5;
  9484. if (!isgraph((unsigned char)buf[0])) {
  9485. /* Invalid request */
  9486. return -1;
  9487. }
  9488. ri->http_version = buf;
  9489. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9490. return -1;
  9491. }
  9492. /* The second word is the status as a number */
  9493. tmp = buf;
  9494. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9495. return -1;
  9496. }
  9497. l = strtol(tmp, &tmp2, 10);
  9498. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9499. /* Everything else but a 3 digit code is invalid */
  9500. return -1;
  9501. }
  9502. ri->status_code = (int)l;
  9503. /* The rest of the line is the status text */
  9504. ri->status_text = buf;
  9505. /* Find end of status text */
  9506. /* isgraph or isspace = isprint */
  9507. while (isprint((unsigned char)*buf)) {
  9508. buf++;
  9509. }
  9510. if ((*buf != '\r') && (*buf != '\n')) {
  9511. return -1;
  9512. }
  9513. /* Terminate string and forward buf to next line */
  9514. do {
  9515. *buf = 0;
  9516. buf++;
  9517. } while (isspace((unsigned char)*buf));
  9518. /* Parse all HTTP headers */
  9519. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9520. if (ri->num_headers < 0) {
  9521. /* Error while parsing headers */
  9522. return -1;
  9523. }
  9524. return response_length + init_skip;
  9525. }
  9526. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9527. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9528. * buffer (which marks the end of HTTP request). Buffer buf may already
  9529. * have some data. The length of the data is stored in nread.
  9530. * Upon every read operation, increase nread by the number of bytes read. */
  9531. static int
  9532. read_message(FILE *fp,
  9533. struct mg_connection *conn,
  9534. char *buf,
  9535. int bufsiz,
  9536. int *nread)
  9537. {
  9538. int request_len, n = 0;
  9539. struct timespec last_action_time;
  9540. double request_timeout;
  9541. if (!conn) {
  9542. return 0;
  9543. }
  9544. memset(&last_action_time, 0, sizeof(last_action_time));
  9545. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9546. /* value of request_timeout is in seconds, config in milliseconds */
  9547. request_timeout =
  9548. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9549. } else {
  9550. request_timeout =
  9551. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9552. / 1000.0;
  9553. }
  9554. if (conn->handled_requests > 0) {
  9555. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9556. request_timeout =
  9557. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9558. / 1000.0;
  9559. }
  9560. }
  9561. request_len = get_http_header_len(buf, *nread);
  9562. while (request_len == 0) {
  9563. /* Full request not yet received */
  9564. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9565. /* Server is to be stopped. */
  9566. return -1;
  9567. }
  9568. if (*nread >= bufsiz) {
  9569. /* Request too long */
  9570. return -2;
  9571. }
  9572. n = pull_inner(
  9573. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9574. if (n == -2) {
  9575. /* Receive error */
  9576. return -1;
  9577. }
  9578. /* update clock after every read request */
  9579. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9580. if (n > 0) {
  9581. *nread += n;
  9582. request_len = get_http_header_len(buf, *nread);
  9583. }
  9584. if ((request_len == 0) && (request_timeout >= 0)) {
  9585. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9586. > request_timeout) {
  9587. /* Timeout */
  9588. return -1;
  9589. }
  9590. }
  9591. }
  9592. return request_len;
  9593. }
  9594. #if !defined(NO_CGI) || !defined(NO_FILES)
  9595. static int
  9596. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9597. {
  9598. const char *expect;
  9599. char buf[MG_BUF_LEN];
  9600. int success = 0;
  9601. if (!conn) {
  9602. return 0;
  9603. }
  9604. expect = mg_get_header(conn, "Expect");
  9605. DEBUG_ASSERT(fp != NULL);
  9606. if (!fp) {
  9607. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9608. return 0;
  9609. }
  9610. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9611. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9612. */
  9613. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9614. } else {
  9615. if (expect != NULL) {
  9616. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9617. conn->status_code = 100;
  9618. } else {
  9619. conn->status_code = 200;
  9620. }
  9621. DEBUG_ASSERT(conn->consumed_content == 0);
  9622. if (conn->consumed_content != 0) {
  9623. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9624. return 0;
  9625. }
  9626. for (;;) {
  9627. int nread = mg_read(conn, buf, sizeof(buf));
  9628. if (nread <= 0) {
  9629. success = (nread == 0);
  9630. break;
  9631. }
  9632. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9633. break;
  9634. }
  9635. }
  9636. /* Each error code path in this function must send an error */
  9637. if (!success) {
  9638. /* NOTE: Maybe some data has already been sent. */
  9639. /* TODO (low): If some data has been sent, a correct error
  9640. * reply can no longer be sent, so just close the connection */
  9641. mg_send_http_error(conn, 500, "%s", "");
  9642. }
  9643. }
  9644. return success;
  9645. }
  9646. #endif
  9647. #if defined(USE_TIMERS)
  9648. #define TIMER_API static
  9649. #include "timer.inl"
  9650. #endif /* USE_TIMERS */
  9651. #if !defined(NO_CGI)
  9652. /* This structure helps to create an environment for the spawned CGI
  9653. * program.
  9654. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9655. * last element must be NULL.
  9656. * However, on Windows there is a requirement that all these
  9657. * VARIABLE=VALUE\0
  9658. * strings must reside in a contiguous buffer. The end of the buffer is
  9659. * marked by two '\0' characters.
  9660. * We satisfy both worlds: we create an envp array (which is vars), all
  9661. * entries are actually pointers inside buf. */
  9662. struct cgi_environment {
  9663. struct mg_connection *conn;
  9664. /* Data block */
  9665. char *buf; /* Environment buffer */
  9666. size_t buflen; /* Space available in buf */
  9667. size_t bufused; /* Space taken in buf */
  9668. /* Index block */
  9669. char **var; /* char **envp */
  9670. size_t varlen; /* Number of variables available in var */
  9671. size_t varused; /* Number of variables stored in var */
  9672. };
  9673. static void addenv(struct cgi_environment *env,
  9674. PRINTF_FORMAT_STRING(const char *fmt),
  9675. ...) PRINTF_ARGS(2, 3);
  9676. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9677. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9678. static void
  9679. addenv(struct cgi_environment *env, const char *fmt, ...)
  9680. {
  9681. size_t i, n, space;
  9682. int truncated = 0;
  9683. char *added;
  9684. va_list ap;
  9685. if ((env->varlen - env->varused) < 2) {
  9686. mg_cry_internal(env->conn,
  9687. "%s: Cannot register CGI variable [%s]",
  9688. __func__,
  9689. fmt);
  9690. return;
  9691. }
  9692. /* Calculate how much space is left in the buffer */
  9693. space = (env->buflen - env->bufused);
  9694. do {
  9695. /* Space for "\0\0" is always needed. */
  9696. if (space <= 2) {
  9697. /* Allocate new buffer */
  9698. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9699. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9700. if (!added) {
  9701. /* Out of memory */
  9702. mg_cry_internal(
  9703. env->conn,
  9704. "%s: Cannot allocate memory for CGI variable [%s]",
  9705. __func__,
  9706. fmt);
  9707. return;
  9708. }
  9709. /* Retarget pointers */
  9710. env->buf = added;
  9711. env->buflen = n;
  9712. for (i = 0, n = 0; i < env->varused; i++) {
  9713. env->var[i] = added + n;
  9714. n += strlen(added + n) + 1;
  9715. }
  9716. space = (env->buflen - env->bufused);
  9717. }
  9718. /* Make a pointer to the free space int the buffer */
  9719. added = env->buf + env->bufused;
  9720. /* Copy VARIABLE=VALUE\0 string into the free space */
  9721. va_start(ap, fmt);
  9722. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9723. va_end(ap);
  9724. /* Do not add truncated strings to the environment */
  9725. if (truncated) {
  9726. /* Reallocate the buffer */
  9727. space = 0;
  9728. }
  9729. } while (truncated);
  9730. /* Calculate number of bytes added to the environment */
  9731. n = strlen(added) + 1;
  9732. env->bufused += n;
  9733. /* Append a pointer to the added string into the envp array */
  9734. env->var[env->varused] = added;
  9735. env->varused++;
  9736. }
  9737. /* Return 0 on success, non-zero if an error occurs. */
  9738. static int
  9739. prepare_cgi_environment(struct mg_connection *conn,
  9740. const char *prog,
  9741. struct cgi_environment *env,
  9742. int cgi_config_idx)
  9743. {
  9744. const char *s;
  9745. struct vec var_vec;
  9746. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9747. int i, truncated, uri_len;
  9748. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9749. return -1;
  9750. }
  9751. env->conn = conn;
  9752. env->buflen = CGI_ENVIRONMENT_SIZE;
  9753. env->bufused = 0;
  9754. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9755. if (env->buf == NULL) {
  9756. mg_cry_internal(conn,
  9757. "%s: Not enough memory for environmental buffer",
  9758. __func__);
  9759. return -1;
  9760. }
  9761. env->varlen = MAX_CGI_ENVIR_VARS;
  9762. env->varused = 0;
  9763. env->var =
  9764. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9765. if (env->var == NULL) {
  9766. mg_cry_internal(conn,
  9767. "%s: Not enough memory for environmental variables",
  9768. __func__);
  9769. mg_free(env->buf);
  9770. return -1;
  9771. }
  9772. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9773. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9774. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9775. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  9776. addenv(env, "FALLBACK_DOCUMENT_ROOT=%s", conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  9777. }
  9778. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9779. /* Prepare the environment block */
  9780. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9781. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9782. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9783. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9784. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9785. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9786. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9787. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9788. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9789. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9790. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9791. /* SCRIPT_NAME */
  9792. uri_len = (int)strlen(conn->request_info.local_uri);
  9793. if (conn->path_info == NULL) {
  9794. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9795. /* URI: /path_to_script/script.cgi */
  9796. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9797. } else {
  9798. /* URI: /path_to_script/ ... using index.cgi */
  9799. const char *index_file = strrchr(prog, '/');
  9800. if (index_file) {
  9801. addenv(env,
  9802. "SCRIPT_NAME=%s%s",
  9803. conn->request_info.local_uri,
  9804. index_file + 1);
  9805. }
  9806. }
  9807. } else {
  9808. /* URI: /path_to_script/script.cgi/path_info */
  9809. addenv(env,
  9810. "SCRIPT_NAME=%.*s",
  9811. uri_len - (int)strlen(conn->path_info),
  9812. conn->request_info.local_uri);
  9813. }
  9814. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9815. if (conn->path_info == NULL) {
  9816. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9817. } else {
  9818. addenv(env,
  9819. "PATH_TRANSLATED=%s%s",
  9820. conn->dom_ctx->config[DOCUMENT_ROOT],
  9821. conn->path_info);
  9822. }
  9823. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9824. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9825. addenv(env, "CONTENT_TYPE=%s", s);
  9826. }
  9827. if (conn->request_info.query_string != NULL) {
  9828. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9829. }
  9830. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9831. addenv(env, "CONTENT_LENGTH=%s", s);
  9832. }
  9833. if ((s = getenv("PATH")) != NULL) {
  9834. addenv(env, "PATH=%s", s);
  9835. }
  9836. if (conn->path_info != NULL) {
  9837. addenv(env, "PATH_INFO=%s", conn->path_info);
  9838. }
  9839. if (conn->status_code > 0) {
  9840. /* CGI error handler should show the status code */
  9841. addenv(env, "STATUS=%d", conn->status_code);
  9842. }
  9843. #if defined(_WIN32)
  9844. if ((s = getenv("COMSPEC")) != NULL) {
  9845. addenv(env, "COMSPEC=%s", s);
  9846. }
  9847. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9848. addenv(env, "SYSTEMROOT=%s", s);
  9849. }
  9850. if ((s = getenv("SystemDrive")) != NULL) {
  9851. addenv(env, "SystemDrive=%s", s);
  9852. }
  9853. if ((s = getenv("ProgramFiles")) != NULL) {
  9854. addenv(env, "ProgramFiles=%s", s);
  9855. }
  9856. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9857. addenv(env, "ProgramFiles(x86)=%s", s);
  9858. }
  9859. #else
  9860. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9861. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9862. }
  9863. #endif /* _WIN32 */
  9864. if ((s = getenv("PERLLIB")) != NULL) {
  9865. addenv(env, "PERLLIB=%s", s);
  9866. }
  9867. if (conn->request_info.remote_user != NULL) {
  9868. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9869. addenv(env, "%s", "AUTH_TYPE=Digest");
  9870. }
  9871. /* Add all headers as HTTP_* variables */
  9872. for (i = 0; i < conn->request_info.num_headers; i++) {
  9873. (void)mg_snprintf(conn,
  9874. &truncated,
  9875. http_var_name,
  9876. sizeof(http_var_name),
  9877. "HTTP_%s",
  9878. conn->request_info.http_headers[i].name);
  9879. if (truncated) {
  9880. mg_cry_internal(conn,
  9881. "%s: HTTP header variable too long [%s]",
  9882. __func__,
  9883. conn->request_info.http_headers[i].name);
  9884. continue;
  9885. }
  9886. /* Convert variable name into uppercase, and change - to _ */
  9887. for (p = http_var_name; *p != '\0'; p++) {
  9888. if (*p == '-') {
  9889. *p = '_';
  9890. }
  9891. *p = (char)toupper((unsigned char)*p);
  9892. }
  9893. addenv(env,
  9894. "%s=%s",
  9895. http_var_name,
  9896. conn->request_info.http_headers[i].value);
  9897. }
  9898. /* Add user-specified variables */
  9899. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9900. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9901. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9902. }
  9903. env->var[env->varused] = NULL;
  9904. env->buf[env->bufused] = '\0';
  9905. return 0;
  9906. }
  9907. /* Data for CGI process control: PID and number of references */
  9908. struct process_control_data {
  9909. pid_t pid;
  9910. ptrdiff_t references;
  9911. };
  9912. static int
  9913. abort_cgi_process(void *data)
  9914. {
  9915. /* Waitpid checks for child status and won't work for a pid that does
  9916. * not identify a child of the current process. Thus, if the pid is
  9917. * reused, we will not affect a different process. */
  9918. struct process_control_data *proc = (struct process_control_data *)data;
  9919. int status = 0;
  9920. ptrdiff_t refs;
  9921. pid_t ret_pid;
  9922. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9923. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9924. /* Stop child process */
  9925. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9926. kill(proc->pid, SIGABRT);
  9927. /* Wait until process is terminated (don't leave zombies) */
  9928. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9929. ;
  9930. } else {
  9931. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9932. }
  9933. /* Dec reference counter */
  9934. refs = mg_atomic_dec(&proc->references);
  9935. if (refs == 0) {
  9936. /* no more references - free data */
  9937. mg_free(data);
  9938. }
  9939. return 0;
  9940. }
  9941. /* Local (static) function assumes all arguments are valid. */
  9942. static void
  9943. handle_cgi_request(struct mg_connection *conn,
  9944. const char *prog,
  9945. int cgi_config_idx)
  9946. {
  9947. char *buf;
  9948. size_t buflen;
  9949. int headers_len, data_len, i, truncated;
  9950. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9951. const char *status, *status_text;
  9952. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9953. struct mg_request_info ri;
  9954. struct cgi_environment blk;
  9955. FILE *in = NULL, *out = NULL, *err = NULL;
  9956. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9957. pid_t pid = (pid_t)-1;
  9958. struct process_control_data *proc = NULL;
  9959. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9960. int no_buffering = 0;
  9961. #if defined(USE_TIMERS)
  9962. double cgi_timeout;
  9963. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9964. /* Get timeout in seconds */
  9965. cgi_timeout =
  9966. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9967. } else {
  9968. cgi_timeout =
  9969. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9970. }
  9971. #endif
  9972. if (cfg_buffering != NULL) {
  9973. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9974. no_buffering = 1;
  9975. }
  9976. }
  9977. buf = NULL;
  9978. buflen = conn->phys_ctx->max_request_size;
  9979. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9980. if (i != 0) {
  9981. blk.buf = NULL;
  9982. blk.var = NULL;
  9983. goto done;
  9984. }
  9985. /* CGI must be executed in its own directory. 'dir' must point to the
  9986. * directory containing executable program, 'p' must point to the
  9987. * executable program name relative to 'dir'. */
  9988. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9989. if (truncated) {
  9990. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9991. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9992. goto done;
  9993. }
  9994. if ((p = strrchr(dir, '/')) != NULL) {
  9995. *p++ = '\0';
  9996. } else {
  9997. dir[0] = '.';
  9998. dir[1] = '\0';
  9999. p = (char *)prog;
  10000. }
  10001. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10002. status = strerror(ERRNO);
  10003. mg_cry_internal(
  10004. conn,
  10005. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10006. prog,
  10007. status);
  10008. mg_send_http_error(conn,
  10009. 500,
  10010. "Error: Cannot create CGI pipe: %s",
  10011. status);
  10012. goto done;
  10013. }
  10014. proc = (struct process_control_data *)
  10015. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10016. if (proc == NULL) {
  10017. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10018. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10019. goto done;
  10020. }
  10021. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10022. pid = spawn_process(
  10023. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10024. if (pid == (pid_t)-1) {
  10025. status = strerror(ERRNO);
  10026. mg_cry_internal(
  10027. conn,
  10028. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10029. prog,
  10030. status);
  10031. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10032. mg_free(proc);
  10033. proc = NULL;
  10034. goto done;
  10035. }
  10036. /* Store data in shared process_control_data */
  10037. proc->pid = pid;
  10038. proc->references = 1;
  10039. #if defined(USE_TIMERS)
  10040. if (cgi_timeout > 0.0) {
  10041. proc->references = 2;
  10042. // Start a timer for CGI
  10043. timer_add(conn->phys_ctx,
  10044. cgi_timeout /* in seconds */,
  10045. 0.0,
  10046. 1,
  10047. abort_cgi_process,
  10048. (void *)proc,
  10049. NULL);
  10050. }
  10051. #endif
  10052. /* Parent closes only one side of the pipes.
  10053. * If we don't mark them as closed, close() attempt before
  10054. * return from this function throws an exception on Windows.
  10055. * Windows does not like when closed descriptor is closed again. */
  10056. (void)close(fdin[0]);
  10057. (void)close(fdout[1]);
  10058. (void)close(fderr[1]);
  10059. fdin[0] = fdout[1] = fderr[1] = -1;
  10060. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10061. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10062. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10063. status = strerror(ERRNO);
  10064. mg_cry_internal(conn,
  10065. "Error: CGI program \"%s\": Can not open fd: %s",
  10066. prog,
  10067. status);
  10068. mg_send_http_error(conn,
  10069. 500,
  10070. "Error: CGI can not open fd\nfdopen: %s",
  10071. status);
  10072. goto done;
  10073. }
  10074. setbuf(in, NULL);
  10075. setbuf(out, NULL);
  10076. setbuf(err, NULL);
  10077. fout.access.fp = out;
  10078. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10079. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10080. conn->content_len);
  10081. /* This is a POST/PUT request, or another request with body data. */
  10082. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10083. /* Error sending the body data */
  10084. mg_cry_internal(
  10085. conn,
  10086. "Error: CGI program \"%s\": Forward body data failed",
  10087. prog);
  10088. goto done;
  10089. }
  10090. }
  10091. /* Close so child gets an EOF. */
  10092. fclose(in);
  10093. in = NULL;
  10094. fdin[1] = -1;
  10095. /* Now read CGI reply into a buffer. We need to set correct
  10096. * status code, thus we need to see all HTTP headers first.
  10097. * Do not send anything back to client, until we buffer in all
  10098. * HTTP headers. */
  10099. data_len = 0;
  10100. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10101. if (buf == NULL) {
  10102. mg_send_http_error(conn,
  10103. 500,
  10104. "Error: Not enough memory for CGI buffer (%u bytes)",
  10105. (unsigned int)buflen);
  10106. mg_cry_internal(
  10107. conn,
  10108. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10109. "bytes)",
  10110. prog,
  10111. (unsigned int)buflen);
  10112. goto done;
  10113. }
  10114. DEBUG_TRACE("CGI: %s", "wait for response");
  10115. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10116. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10117. if (headers_len <= 0) {
  10118. /* Could not parse the CGI response. Check if some error message on
  10119. * stderr. */
  10120. i = pull_all(err, conn, buf, (int)buflen);
  10121. if (i > 0) {
  10122. /* CGI program explicitly sent an error */
  10123. /* Write the error message to the internal log */
  10124. mg_cry_internal(conn,
  10125. "Error: CGI program \"%s\" sent error "
  10126. "message: [%.*s]",
  10127. prog,
  10128. i,
  10129. buf);
  10130. /* Don't send the error message back to the client */
  10131. mg_send_http_error(conn,
  10132. 500,
  10133. "Error: CGI program \"%s\" failed.",
  10134. prog);
  10135. } else {
  10136. /* CGI program did not explicitly send an error, but a broken
  10137. * respon header */
  10138. mg_cry_internal(conn,
  10139. "Error: CGI program sent malformed or too big "
  10140. "(>%u bytes) HTTP headers: [%.*s]",
  10141. (unsigned)buflen,
  10142. data_len,
  10143. buf);
  10144. mg_send_http_error(conn,
  10145. 500,
  10146. "Error: CGI program sent malformed or too big "
  10147. "(>%u bytes) HTTP headers: [%.*s]",
  10148. (unsigned)buflen,
  10149. data_len,
  10150. buf);
  10151. }
  10152. /* in both cases, abort processing CGI */
  10153. goto done;
  10154. }
  10155. pbuf = buf;
  10156. buf[headers_len - 1] = '\0';
  10157. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10158. /* Make up and send the status line */
  10159. status_text = "OK";
  10160. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10161. != NULL) {
  10162. conn->status_code = atoi(status);
  10163. status_text = status;
  10164. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10165. status_text++;
  10166. }
  10167. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10168. != NULL) {
  10169. conn->status_code = 307;
  10170. } else {
  10171. conn->status_code = 200;
  10172. }
  10173. if (!should_keep_alive(conn)) {
  10174. conn->must_close = 1;
  10175. }
  10176. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10177. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10178. /* Send headers */
  10179. for (i = 0; i < ri.num_headers; i++) {
  10180. DEBUG_TRACE("CGI header: %s: %s",
  10181. ri.http_headers[i].name,
  10182. ri.http_headers[i].value);
  10183. mg_printf(conn,
  10184. "%s: %s\r\n",
  10185. ri.http_headers[i].name,
  10186. ri.http_headers[i].value);
  10187. }
  10188. mg_write(conn, "\r\n", 2);
  10189. /* Send chunk of data that may have been read after the headers */
  10190. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10191. /* Read the rest of CGI output and send to the client */
  10192. DEBUG_TRACE("CGI: %s", "forward all data");
  10193. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10194. DEBUG_TRACE("CGI: %s", "all data sent");
  10195. done:
  10196. mg_free(blk.var);
  10197. mg_free(blk.buf);
  10198. if (pid != (pid_t)-1) {
  10199. abort_cgi_process((void *)proc);
  10200. }
  10201. if (fdin[0] != -1) {
  10202. close(fdin[0]);
  10203. }
  10204. if (fdout[1] != -1) {
  10205. close(fdout[1]);
  10206. }
  10207. if (fderr[1] != -1) {
  10208. close(fderr[1]);
  10209. }
  10210. if (in != NULL) {
  10211. fclose(in);
  10212. } else if (fdin[1] != -1) {
  10213. close(fdin[1]);
  10214. }
  10215. if (out != NULL) {
  10216. fclose(out);
  10217. } else if (fdout[0] != -1) {
  10218. close(fdout[0]);
  10219. }
  10220. if (err != NULL) {
  10221. fclose(err);
  10222. } else if (fderr[0] != -1) {
  10223. close(fderr[0]);
  10224. }
  10225. mg_free(buf);
  10226. }
  10227. #endif /* !NO_CGI */
  10228. #if !defined(NO_FILES)
  10229. static void
  10230. dav_mkcol(struct mg_connection *conn, const char *path)
  10231. {
  10232. int rc, body_len;
  10233. struct de de;
  10234. if (conn == NULL) {
  10235. return;
  10236. }
  10237. /* TODO (mid): Check the mg_send_http_error situations in this function
  10238. */
  10239. memset(&de.file, 0, sizeof(de.file));
  10240. if (!mg_stat(conn, path, &de.file)) {
  10241. mg_cry_internal(conn,
  10242. "%s: mg_stat(%s) failed: %s",
  10243. __func__,
  10244. path,
  10245. strerror(ERRNO));
  10246. }
  10247. if (de.file.last_modified) {
  10248. /* TODO (mid): This check does not seem to make any sense ! */
  10249. /* TODO (mid): Add a webdav unit test first, before changing
  10250. * anything here. */
  10251. mg_send_http_error(
  10252. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10253. return;
  10254. }
  10255. body_len = conn->data_len - conn->request_len;
  10256. if (body_len > 0) {
  10257. mg_send_http_error(
  10258. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10259. return;
  10260. }
  10261. rc = mg_mkdir(conn, path, 0755);
  10262. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10263. if (rc == 0) {
  10264. /* Create 201 "Created" response */
  10265. mg_response_header_start(conn, 201);
  10266. send_static_cache_header(conn);
  10267. send_additional_header(conn);
  10268. mg_response_header_add(conn, "Content-Length", "0", -1);
  10269. /* Send all headers - there is no body */
  10270. mg_response_header_send(conn);
  10271. } else {
  10272. int http_status = 500;
  10273. switch (errno) {
  10274. case EEXIST:
  10275. http_status = 405;
  10276. break;
  10277. case EACCES:
  10278. http_status = 403;
  10279. break;
  10280. case ENOENT:
  10281. http_status = 409;
  10282. break;
  10283. }
  10284. mg_send_http_error(conn,
  10285. http_status,
  10286. "Error processing %s: %s",
  10287. path,
  10288. strerror(ERRNO));
  10289. }
  10290. }
  10291. /* Forward decrlaration */
  10292. static int get_uri_type(const char *uri);
  10293. static const char *
  10294. get_rel_url_at_current_server(const char *uri,
  10295. const struct mg_connection *conn);
  10296. static void
  10297. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10298. {
  10299. const char *overwrite_hdr;
  10300. const char *destination_hdr;
  10301. const char *root;
  10302. int rc, dest_uri_type;
  10303. int http_status = 400;
  10304. int do_overwrite = 0;
  10305. int destination_ok = 0;
  10306. char dest_path[UTF8_PATH_MAX];
  10307. struct mg_file_stat ignored;
  10308. if (conn == NULL) {
  10309. return;
  10310. }
  10311. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10312. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10313. destination_hdr = mg_get_header(conn, "Destination");
  10314. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10315. do_overwrite = 1;
  10316. }
  10317. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10318. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10319. return;
  10320. }
  10321. if (root != NULL) {
  10322. char *local_dest = NULL;
  10323. dest_uri_type = get_uri_type(destination_hdr);
  10324. if (dest_uri_type == 2) {
  10325. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10326. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10327. const char *h =
  10328. get_rel_url_at_current_server(destination_hdr, conn);
  10329. if (h) {
  10330. size_t len = strlen(h);
  10331. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10332. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10333. }
  10334. }
  10335. if (local_dest != NULL) {
  10336. remove_dot_segments(local_dest);
  10337. if (local_dest[0] == '/') {
  10338. int trunc_check = 0;
  10339. mg_snprintf(conn,
  10340. &trunc_check,
  10341. dest_path,
  10342. sizeof(dest_path),
  10343. "%s/%s",
  10344. root,
  10345. local_dest);
  10346. if (trunc_check == 0) {
  10347. destination_ok = 1;
  10348. }
  10349. }
  10350. mg_free(local_dest);
  10351. }
  10352. }
  10353. if (!destination_ok) {
  10354. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10355. return;
  10356. }
  10357. /* Check now if this file exists */
  10358. if (mg_stat(conn, dest_path, &ignored)) {
  10359. /* File exists */
  10360. if (do_overwrite) {
  10361. /* Overwrite allowed: delete the file first */
  10362. if (0 != remove(dest_path)) {
  10363. /* No overwrite: return error */
  10364. mg_send_http_error(conn,
  10365. 403,
  10366. "Cannot overwrite file: %s",
  10367. dest_path);
  10368. return;
  10369. }
  10370. } else {
  10371. /* No overwrite: return error */
  10372. mg_send_http_error(conn,
  10373. 412,
  10374. "Destination already exists: %s",
  10375. dest_path);
  10376. return;
  10377. }
  10378. }
  10379. /* Copy / Move / Rename operation. */
  10380. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10381. #if defined(_WIN32)
  10382. {
  10383. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10384. wchar_t wSource[UTF16_PATH_MAX];
  10385. wchar_t wDest[UTF16_PATH_MAX];
  10386. BOOL ok;
  10387. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10388. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10389. if (do_copy) {
  10390. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10391. } else {
  10392. ok = MoveFileExW(wSource,
  10393. wDest,
  10394. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10395. }
  10396. if (ok) {
  10397. rc = 0;
  10398. } else {
  10399. DWORD lastErr = GetLastError();
  10400. if (lastErr == ERROR_ALREADY_EXISTS) {
  10401. mg_send_http_error(conn,
  10402. 412,
  10403. "Destination already exists: %s",
  10404. dest_path);
  10405. return;
  10406. }
  10407. rc = -1;
  10408. http_status = 400;
  10409. }
  10410. }
  10411. #else
  10412. {
  10413. /* Linux uses already UTF-8, we don't need to convert file names. */
  10414. if (do_copy) {
  10415. /* TODO: COPY for Linux. */
  10416. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10417. return;
  10418. }
  10419. rc = rename(path, dest_path);
  10420. if (rc) {
  10421. switch (errno) {
  10422. case EEXIST:
  10423. http_status = 412;
  10424. break;
  10425. case EACCES:
  10426. http_status = 403;
  10427. break;
  10428. case ENOENT:
  10429. http_status = 409;
  10430. break;
  10431. }
  10432. }
  10433. }
  10434. #endif
  10435. if (rc == 0) {
  10436. /* Create 204 "No Content" response */
  10437. mg_response_header_start(conn, 204);
  10438. mg_response_header_add(conn, "Content-Length", "0", -1);
  10439. /* Send all headers - there is no body */
  10440. mg_response_header_send(conn);
  10441. } else {
  10442. mg_send_http_error(conn, http_status, "Operation failed");
  10443. }
  10444. }
  10445. static void
  10446. put_file(struct mg_connection *conn, const char *path)
  10447. {
  10448. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10449. const char *range;
  10450. int64_t r1, r2;
  10451. int rc;
  10452. if (conn == NULL) {
  10453. return;
  10454. }
  10455. DEBUG_TRACE("store %s", path);
  10456. if (mg_stat(conn, path, &file.stat)) {
  10457. /* File already exists */
  10458. conn->status_code = 200;
  10459. if (file.stat.is_directory) {
  10460. /* This is an already existing directory,
  10461. * so there is nothing to do for the server. */
  10462. rc = 0;
  10463. } else {
  10464. /* File exists and is not a directory. */
  10465. /* Can it be replaced? */
  10466. /* Check if the server may write this file */
  10467. if (access(path, W_OK) == 0) {
  10468. /* Access granted */
  10469. rc = 1;
  10470. } else {
  10471. mg_send_http_error(
  10472. conn,
  10473. 403,
  10474. "Error: Put not possible\nReplacing %s is not allowed",
  10475. path);
  10476. return;
  10477. }
  10478. }
  10479. } else {
  10480. /* File should be created */
  10481. conn->status_code = 201;
  10482. rc = put_dir(conn, path);
  10483. }
  10484. if (rc == 0) {
  10485. /* put_dir returns 0 if path is a directory */
  10486. /* Create response */
  10487. mg_response_header_start(conn, conn->status_code);
  10488. send_no_cache_header(conn);
  10489. send_additional_header(conn);
  10490. mg_response_header_add(conn, "Content-Length", "0", -1);
  10491. /* Send all headers - there is no body */
  10492. mg_response_header_send(conn);
  10493. /* Request to create a directory has been fulfilled successfully.
  10494. * No need to put a file. */
  10495. return;
  10496. }
  10497. if (rc == -1) {
  10498. /* put_dir returns -1 if the path is too long */
  10499. mg_send_http_error(conn,
  10500. 414,
  10501. "Error: Path too long\nput_dir(%s): %s",
  10502. path,
  10503. strerror(ERRNO));
  10504. return;
  10505. }
  10506. if (rc == -2) {
  10507. /* put_dir returns -2 if the directory can not be created */
  10508. mg_send_http_error(conn,
  10509. 500,
  10510. "Error: Can not create directory\nput_dir(%s): %s",
  10511. path,
  10512. strerror(ERRNO));
  10513. return;
  10514. }
  10515. /* A file should be created or overwritten. */
  10516. /* Currently CivetWeb does not need read+write access. */
  10517. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10518. || file.access.fp == NULL) {
  10519. (void)mg_fclose(&file.access);
  10520. mg_send_http_error(conn,
  10521. 500,
  10522. "Error: Can not create file\nfopen(%s): %s",
  10523. path,
  10524. strerror(ERRNO));
  10525. return;
  10526. }
  10527. fclose_on_exec(&file.access, conn);
  10528. range = mg_get_header(conn, "Content-Range");
  10529. r1 = r2 = 0;
  10530. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10531. conn->status_code = 206; /* Partial content */
  10532. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10533. mg_send_http_error(conn,
  10534. 500,
  10535. "Error: Internal error processing file %s",
  10536. path);
  10537. return;
  10538. }
  10539. }
  10540. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10541. /* forward_body_data failed.
  10542. * The error code has already been sent to the client,
  10543. * and conn->status_code is already set. */
  10544. (void)mg_fclose(&file.access);
  10545. return;
  10546. }
  10547. if (mg_fclose(&file.access) != 0) {
  10548. /* fclose failed. This might have different reasons, but a likely
  10549. * one is "no space on disk", http 507. */
  10550. conn->status_code = 507;
  10551. }
  10552. /* Create response (status_code has been set before) */
  10553. mg_response_header_start(conn, conn->status_code);
  10554. send_no_cache_header(conn);
  10555. send_additional_header(conn);
  10556. mg_response_header_add(conn, "Content-Length", "0", -1);
  10557. /* Send all headers - there is no body */
  10558. mg_response_header_send(conn);
  10559. }
  10560. static void
  10561. delete_file(struct mg_connection *conn, const char *path)
  10562. {
  10563. struct de de;
  10564. memset(&de.file, 0, sizeof(de.file));
  10565. if (!mg_stat(conn, path, &de.file)) {
  10566. /* mg_stat returns 0 if the file does not exist */
  10567. mg_send_http_error(conn,
  10568. 404,
  10569. "Error: Cannot delete file\nFile %s not found",
  10570. path);
  10571. return;
  10572. }
  10573. DEBUG_TRACE("delete %s", path);
  10574. if (de.file.is_directory) {
  10575. if (remove_directory(conn, path)) {
  10576. /* Delete is successful: Return 204 without content. */
  10577. mg_send_http_error(conn, 204, "%s", "");
  10578. } else {
  10579. /* Delete is not successful: Return 500 (Server error). */
  10580. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10581. }
  10582. return;
  10583. }
  10584. /* This is an existing file (not a directory).
  10585. * Check if write permission is granted. */
  10586. if (access(path, W_OK) != 0) {
  10587. /* File is read only */
  10588. mg_send_http_error(
  10589. conn,
  10590. 403,
  10591. "Error: Delete not possible\nDeleting %s is not allowed",
  10592. path);
  10593. return;
  10594. }
  10595. /* Try to delete it. */
  10596. if (mg_remove(conn, path) == 0) {
  10597. /* Delete was successful: Return 204 without content. */
  10598. mg_response_header_start(conn, 204);
  10599. send_no_cache_header(conn);
  10600. send_additional_header(conn);
  10601. mg_response_header_add(conn, "Content-Length", "0", -1);
  10602. mg_response_header_send(conn);
  10603. } else {
  10604. /* Delete not successful (file locked). */
  10605. mg_send_http_error(conn,
  10606. 423,
  10607. "Error: Cannot delete file\nremove(%s): %s",
  10608. path,
  10609. strerror(ERRNO));
  10610. }
  10611. }
  10612. #endif /* !NO_FILES */
  10613. #if !defined(NO_FILESYSTEMS)
  10614. static void
  10615. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10616. static void
  10617. do_ssi_include(struct mg_connection *conn,
  10618. const char *ssi,
  10619. char *tag,
  10620. int include_level)
  10621. {
  10622. char file_name[MG_BUF_LEN], path[512], *p;
  10623. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10624. size_t len;
  10625. int truncated = 0;
  10626. if (conn == NULL) {
  10627. return;
  10628. }
  10629. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10630. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10631. * always < MG_BUF_LEN. */
  10632. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10633. /* File name is relative to the webserver root */
  10634. file_name[511] = 0;
  10635. (void)mg_snprintf(conn,
  10636. &truncated,
  10637. path,
  10638. sizeof(path),
  10639. "%s/%s",
  10640. conn->dom_ctx->config[DOCUMENT_ROOT],
  10641. file_name);
  10642. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10643. /* File name is relative to the webserver working directory
  10644. * or it is absolute system path */
  10645. file_name[511] = 0;
  10646. (void)
  10647. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10648. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10649. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10650. /* File name is relative to the current document */
  10651. file_name[511] = 0;
  10652. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10653. if (!truncated) {
  10654. if ((p = strrchr(path, '/')) != NULL) {
  10655. p[1] = '\0';
  10656. }
  10657. len = strlen(path);
  10658. (void)mg_snprintf(conn,
  10659. &truncated,
  10660. path + len,
  10661. sizeof(path) - len,
  10662. "%s",
  10663. file_name);
  10664. }
  10665. } else {
  10666. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10667. return;
  10668. }
  10669. if (truncated) {
  10670. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10671. return;
  10672. }
  10673. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10674. mg_cry_internal(conn,
  10675. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10676. tag,
  10677. path,
  10678. strerror(ERRNO));
  10679. } else {
  10680. fclose_on_exec(&file.access, conn);
  10681. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10682. > 0) {
  10683. send_ssi_file(conn, path, &file, include_level + 1);
  10684. } else {
  10685. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10686. }
  10687. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10688. }
  10689. }
  10690. #if !defined(NO_POPEN)
  10691. static void
  10692. do_ssi_exec(struct mg_connection *conn, char *tag)
  10693. {
  10694. char cmd[1024] = "";
  10695. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10696. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10697. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10698. } else {
  10699. cmd[1023] = 0;
  10700. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10701. mg_cry_internal(conn,
  10702. "Cannot SSI #exec: [%s]: %s",
  10703. cmd,
  10704. strerror(ERRNO));
  10705. } else {
  10706. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10707. pclose(file.access.fp);
  10708. }
  10709. }
  10710. }
  10711. #endif /* !NO_POPEN */
  10712. static int
  10713. mg_fgetc(struct mg_file *filep)
  10714. {
  10715. if (filep == NULL) {
  10716. return EOF;
  10717. }
  10718. if (filep->access.fp != NULL) {
  10719. return fgetc(filep->access.fp);
  10720. } else {
  10721. return EOF;
  10722. }
  10723. }
  10724. static void
  10725. send_ssi_file(struct mg_connection *conn,
  10726. const char *path,
  10727. struct mg_file *filep,
  10728. int include_level)
  10729. {
  10730. char buf[MG_BUF_LEN];
  10731. int ch, len, in_tag, in_ssi_tag;
  10732. if (include_level > 10) {
  10733. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10734. return;
  10735. }
  10736. in_tag = in_ssi_tag = len = 0;
  10737. /* Read file, byte by byte, and look for SSI include tags */
  10738. while ((ch = mg_fgetc(filep)) != EOF) {
  10739. if (in_tag) {
  10740. /* We are in a tag, either SSI tag or html tag */
  10741. if (ch == '>') {
  10742. /* Tag is closing */
  10743. buf[len++] = '>';
  10744. if (in_ssi_tag) {
  10745. /* Handle SSI tag */
  10746. buf[len] = 0;
  10747. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10748. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10749. #if !defined(NO_POPEN)
  10750. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10751. do_ssi_exec(conn, buf + 9);
  10752. #endif /* !NO_POPEN */
  10753. } else {
  10754. mg_cry_internal(conn,
  10755. "%s: unknown SSI "
  10756. "command: \"%s\"",
  10757. path,
  10758. buf);
  10759. }
  10760. len = 0;
  10761. in_ssi_tag = in_tag = 0;
  10762. } else {
  10763. /* Not an SSI tag */
  10764. /* Flush buffer */
  10765. (void)mg_write(conn, buf, (size_t)len);
  10766. len = 0;
  10767. in_tag = 0;
  10768. }
  10769. } else {
  10770. /* Tag is still open */
  10771. buf[len++] = (char)(ch & 0xff);
  10772. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10773. /* All SSI tags start with <!--# */
  10774. in_ssi_tag = 1;
  10775. }
  10776. if ((len + 2) > (int)sizeof(buf)) {
  10777. /* Tag to long for buffer */
  10778. mg_cry_internal(conn, "%s: tag is too large", path);
  10779. return;
  10780. }
  10781. }
  10782. } else {
  10783. /* We are not in a tag yet. */
  10784. if (ch == '<') {
  10785. /* Tag is opening */
  10786. in_tag = 1;
  10787. if (len > 0) {
  10788. /* Flush current buffer.
  10789. * Buffer is filled with "len" bytes. */
  10790. (void)mg_write(conn, buf, (size_t)len);
  10791. }
  10792. /* Store the < */
  10793. len = 1;
  10794. buf[0] = '<';
  10795. } else {
  10796. /* No Tag */
  10797. /* Add data to buffer */
  10798. buf[len++] = (char)(ch & 0xff);
  10799. /* Flush if buffer is full */
  10800. if (len == (int)sizeof(buf)) {
  10801. mg_write(conn, buf, (size_t)len);
  10802. len = 0;
  10803. }
  10804. }
  10805. }
  10806. }
  10807. /* Send the rest of buffered data */
  10808. if (len > 0) {
  10809. mg_write(conn, buf, (size_t)len);
  10810. }
  10811. }
  10812. static void
  10813. handle_ssi_file_request(struct mg_connection *conn,
  10814. const char *path,
  10815. struct mg_file *filep)
  10816. {
  10817. char date[64];
  10818. time_t curtime = time(NULL);
  10819. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10820. return;
  10821. }
  10822. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10823. /* File exists (precondition for calling this function),
  10824. * but can not be opened by the server. */
  10825. mg_send_http_error(conn,
  10826. 500,
  10827. "Error: Cannot read file\nfopen(%s): %s",
  10828. path,
  10829. strerror(ERRNO));
  10830. } else {
  10831. /* Set "must_close" for HTTP/1.x, since we do not know the
  10832. * content length */
  10833. conn->must_close = 1;
  10834. gmt_time_string(date, sizeof(date), &curtime);
  10835. fclose_on_exec(&filep->access, conn);
  10836. /* 200 OK response */
  10837. mg_response_header_start(conn, 200);
  10838. send_no_cache_header(conn);
  10839. send_additional_header(conn);
  10840. send_cors_header(conn);
  10841. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10842. mg_response_header_send(conn);
  10843. /* Header sent, now send body */
  10844. send_ssi_file(conn, path, filep, 0);
  10845. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10846. }
  10847. }
  10848. #endif /* NO_FILESYSTEMS */
  10849. #if !defined(NO_FILES)
  10850. static void
  10851. send_options(struct mg_connection *conn)
  10852. {
  10853. if (!conn || !all_methods) {
  10854. return;
  10855. }
  10856. /* We do not set a "Cache-Control" header here, but leave the default.
  10857. * Since browsers do not send an OPTIONS request, we can not test the
  10858. * effect anyway. */
  10859. mg_response_header_start(conn, 200);
  10860. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10861. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10862. /* Use the same as before */
  10863. mg_response_header_add(conn, "Allow", all_methods, -1);
  10864. mg_response_header_add(conn, "DAV", "1", -1);
  10865. } else {
  10866. /* TODO: Check this later for HTTP/2 */
  10867. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10868. }
  10869. send_additional_header(conn);
  10870. mg_response_header_send(conn);
  10871. }
  10872. /* Writes PROPFIND properties for a collection element */
  10873. static int
  10874. print_props(struct mg_connection *conn,
  10875. const char *uri,
  10876. const char *name,
  10877. struct mg_file_stat *filep)
  10878. {
  10879. size_t i;
  10880. char mtime[64];
  10881. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10882. char *link_concat;
  10883. size_t link_concat_len;
  10884. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10885. return 0;
  10886. }
  10887. link_concat_len = strlen(uri) + strlen(name) + 1;
  10888. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10889. if (!link_concat) {
  10890. return 0;
  10891. }
  10892. strcpy(link_concat, uri);
  10893. strcat(link_concat, name);
  10894. /* Get full link used in request */
  10895. mg_construct_local_link(
  10896. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10897. /*
  10898. OutputDebugStringA("print_props:\n uri: ");
  10899. OutputDebugStringA(uri);
  10900. OutputDebugStringA("\n name: ");
  10901. OutputDebugStringA(name);
  10902. OutputDebugStringA("\n link: ");
  10903. OutputDebugStringA(link_buf);
  10904. OutputDebugStringA("\n");
  10905. */
  10906. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10907. mg_printf(conn,
  10908. "<d:response>"
  10909. "<d:href>%s</d:href>"
  10910. "<d:propstat>"
  10911. "<d:prop>"
  10912. "<d:resourcetype>%s</d:resourcetype>"
  10913. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10914. "<d:getlastmodified>%s</d:getlastmodified>"
  10915. "<d:lockdiscovery>",
  10916. link_buf,
  10917. filep->is_directory ? "<d:collection/>" : "",
  10918. filep->size,
  10919. mtime);
  10920. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10921. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10922. if (!strcmp(dav_lock[i].path, link_buf)) {
  10923. mg_printf(conn,
  10924. "<d:activelock>"
  10925. "<d:locktype><d:write/></d:locktype>"
  10926. "<d:lockscope><d:exclusive/></d:lockscope>"
  10927. "<d:depth>0</d:depth>"
  10928. "<d:owner>%s</d:owner>"
  10929. "<d:timeout>Second-%u</d:timeout>"
  10930. "<d:locktoken>"
  10931. "<d:href>%s</d:href>"
  10932. "</d:locktoken>"
  10933. "</d:activelock>\n",
  10934. dav_lock[i].user,
  10935. (unsigned)LOCK_DURATION_S,
  10936. dav_lock[i].token);
  10937. }
  10938. }
  10939. mg_printf(conn,
  10940. "</d:lockdiscovery>"
  10941. "</d:prop>"
  10942. "<d:status>HTTP/1.1 200 OK</d:status>"
  10943. "</d:propstat>"
  10944. "</d:response>\n");
  10945. mg_free(link_concat);
  10946. return 1;
  10947. }
  10948. static int
  10949. print_dav_dir_entry(struct de *de, void *data)
  10950. {
  10951. struct mg_connection *conn = (struct mg_connection *)data;
  10952. if (!de || !conn
  10953. || !print_props(
  10954. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10955. /* stop scan */
  10956. return 1;
  10957. }
  10958. return 0;
  10959. }
  10960. static void
  10961. handle_propfind(struct mg_connection *conn,
  10962. const char *path,
  10963. struct mg_file_stat *filep)
  10964. {
  10965. const char *depth = mg_get_header(conn, "Depth");
  10966. if (!conn || !path || !filep || !conn->dom_ctx) {
  10967. return;
  10968. }
  10969. /* return 207 "Multi-Status" */
  10970. conn->must_close = 1;
  10971. mg_response_header_start(conn, 207);
  10972. send_static_cache_header(conn);
  10973. send_additional_header(conn);
  10974. mg_response_header_add(conn,
  10975. "Content-Type",
  10976. "application/xml; charset=utf-8",
  10977. -1);
  10978. mg_response_header_send(conn);
  10979. /* Content */
  10980. mg_printf(conn,
  10981. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10982. "<d:multistatus xmlns:d='DAV:'>\n");
  10983. /* Print properties for the requested resource itself */
  10984. print_props(conn, conn->request_info.local_uri, "", filep);
  10985. /* If it is a directory, print directory entries too if Depth is not 0
  10986. */
  10987. if (filep->is_directory
  10988. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10989. "yes")
  10990. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10991. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10992. }
  10993. mg_printf(conn, "%s\n", "</d:multistatus>");
  10994. }
  10995. static void
  10996. dav_lock_file(struct mg_connection *conn, const char *path)
  10997. {
  10998. /* internal function - therefore conn is assumed to be valid */
  10999. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11000. uint64_t new_locktime;
  11001. int lock_index = -1;
  11002. int i;
  11003. uint64_t LOCK_DURATION_NS =
  11004. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11005. struct twebdav_lock *dav_lock = NULL;
  11006. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11007. || !conn->phys_ctx) {
  11008. return;
  11009. }
  11010. dav_lock = conn->phys_ctx->webdav_lock;
  11011. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11012. /* const char *refresh = mg_get_header(conn, "If"); */
  11013. /* Link refresh should have an "If" header:
  11014. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11015. * But it seems Windows Explorer does not send them.
  11016. */
  11017. mg_lock_context(conn->phys_ctx);
  11018. new_locktime = mg_get_current_time_ns();
  11019. /* Find a slot for a lock */
  11020. while (lock_index < 0) {
  11021. /* find existing lock */
  11022. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11023. if (!strcmp(dav_lock[i].path, link_buf)) {
  11024. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11025. /* locked by the same user */
  11026. dav_lock[i].locktime = new_locktime;
  11027. lock_index = i;
  11028. break;
  11029. } else {
  11030. /* already locked by someone else */
  11031. if (new_locktime
  11032. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11033. /* Lock expired */
  11034. dav_lock[i].path[0] = 0;
  11035. } else {
  11036. /* Lock still valid */
  11037. mg_unlock_context(conn->phys_ctx);
  11038. mg_send_http_error(conn, 423, "%s", "Already locked");
  11039. return;
  11040. }
  11041. }
  11042. }
  11043. }
  11044. /* create new lock token */
  11045. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11046. if (dav_lock[i].path[0] == 0) {
  11047. char s[32];
  11048. dav_lock[i].locktime = mg_get_current_time_ns();
  11049. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11050. mg_md5(dav_lock[i].token,
  11051. link_buf,
  11052. "\x01",
  11053. s,
  11054. "\x01",
  11055. conn->request_info.remote_user,
  11056. NULL);
  11057. mg_strlcpy(dav_lock[i].path,
  11058. link_buf,
  11059. sizeof(dav_lock[i].path));
  11060. mg_strlcpy(dav_lock[i].user,
  11061. conn->request_info.remote_user,
  11062. sizeof(dav_lock[i].user));
  11063. lock_index = i;
  11064. break;
  11065. }
  11066. }
  11067. if (lock_index < 0) {
  11068. /* too many locks. Find oldest lock */
  11069. uint64_t oldest_locktime = dav_lock[0].locktime;
  11070. lock_index = 0;
  11071. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11072. if (dav_lock[i].locktime < oldest_locktime) {
  11073. oldest_locktime = dav_lock[i].locktime;
  11074. lock_index = i;
  11075. }
  11076. }
  11077. /* invalidate oldest lock */
  11078. dav_lock[lock_index].path[0] = 0;
  11079. }
  11080. }
  11081. mg_unlock_context(conn->phys_ctx);
  11082. /* return 200 "OK" */
  11083. conn->must_close = 1;
  11084. mg_response_header_start(conn, 200);
  11085. send_static_cache_header(conn);
  11086. send_additional_header(conn);
  11087. mg_response_header_add(conn,
  11088. "Content-Type",
  11089. "application/xml; charset=utf-8",
  11090. -1);
  11091. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11092. mg_response_header_send(conn);
  11093. /* Content */
  11094. mg_printf(conn,
  11095. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11096. "<d:prop xmlns:d=\"DAV:\">\n"
  11097. " <d:lockdiscovery>\n"
  11098. " <d:activelock>\n"
  11099. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11100. " <d:locktype><d:write/></d:locktype>\n"
  11101. " <d:owner>\n"
  11102. " <d:href>%s</d:href>\n"
  11103. " </d:owner>\n"
  11104. " <d:timeout>Second-%u</d:timeout>\n"
  11105. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11106. " <d:lockroot>\n"
  11107. " <d:href>%s</d:href>\n"
  11108. " </d:lockroot>\n"
  11109. " </d:activelock>\n"
  11110. " </d:lockdiscovery>\n"
  11111. " </d:prop>\n",
  11112. dav_lock[lock_index].user,
  11113. (LOCK_DURATION_S),
  11114. dav_lock[lock_index].token,
  11115. dav_lock[lock_index].path);
  11116. }
  11117. static void
  11118. dav_unlock_file(struct mg_connection *conn, const char *path)
  11119. {
  11120. /* internal function - therefore conn is assumed to be valid */
  11121. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11122. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11123. int lock_index;
  11124. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11125. return;
  11126. }
  11127. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11128. mg_lock_context(conn->phys_ctx);
  11129. /* find existing lock */
  11130. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11131. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11132. /* Success: return 204 "No Content" */
  11133. mg_unlock_context(conn->phys_ctx);
  11134. conn->must_close = 1;
  11135. mg_response_header_start(conn, 204);
  11136. mg_response_header_send(conn);
  11137. return;
  11138. }
  11139. }
  11140. mg_unlock_context(conn->phys_ctx);
  11141. /* Error: Cannot unlock a resource that is not locked */
  11142. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11143. }
  11144. static void
  11145. dav_proppatch(struct mg_connection *conn, const char *path)
  11146. {
  11147. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11148. if (!conn || !path || !conn->dom_ctx) {
  11149. return;
  11150. }
  11151. /* return 207 "Multi-Status" */
  11152. conn->must_close = 1;
  11153. mg_response_header_start(conn, 207);
  11154. send_static_cache_header(conn);
  11155. send_additional_header(conn);
  11156. mg_response_header_add(conn,
  11157. "Content-Type",
  11158. "application/xml; charset=utf-8",
  11159. -1);
  11160. mg_response_header_send(conn);
  11161. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11162. /* Content */
  11163. mg_printf(conn,
  11164. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11165. "<d:multistatus xmlns:d='DAV:'>\n"
  11166. "<d:response>\n<d:href>%s</d:href>\n",
  11167. link_buf);
  11168. mg_printf(conn,
  11169. "<d:propstat><d:status>HTTP/1.1 403 "
  11170. "Forbidden</d:status></d:propstat>\n");
  11171. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11172. }
  11173. #endif
  11174. CIVETWEB_API void
  11175. mg_lock_connection(struct mg_connection *conn)
  11176. {
  11177. if (conn) {
  11178. (void)pthread_mutex_lock(&conn->mutex);
  11179. }
  11180. }
  11181. CIVETWEB_API void
  11182. mg_unlock_connection(struct mg_connection *conn)
  11183. {
  11184. if (conn) {
  11185. (void)pthread_mutex_unlock(&conn->mutex);
  11186. }
  11187. }
  11188. CIVETWEB_API void
  11189. mg_lock_context(struct mg_context *ctx)
  11190. {
  11191. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11192. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11193. }
  11194. }
  11195. CIVETWEB_API void
  11196. mg_unlock_context(struct mg_context *ctx)
  11197. {
  11198. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11199. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11200. }
  11201. }
  11202. #if defined(USE_LUA)
  11203. #include "mod_lua.inl"
  11204. #endif /* USE_LUA */
  11205. #if defined(USE_DUKTAPE)
  11206. #include "mod_duktape.inl"
  11207. #endif /* USE_DUKTAPE */
  11208. #if defined(USE_WEBSOCKET)
  11209. #if !defined(NO_SSL_DL)
  11210. #if !defined(OPENSSL_API_3_0)
  11211. #define SHA_API static
  11212. #include "sha1.inl"
  11213. #endif
  11214. #endif
  11215. static int
  11216. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11217. {
  11218. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11219. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11220. size_t dst_len = sizeof(b64_sha);
  11221. #if !defined(OPENSSL_API_3_0)
  11222. SHA_CTX sha_ctx;
  11223. #endif
  11224. int truncated;
  11225. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11226. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11227. if (truncated) {
  11228. conn->must_close = 1;
  11229. return 0;
  11230. }
  11231. DEBUG_TRACE("%s", "Send websocket handshake");
  11232. #if defined(OPENSSL_API_3_0)
  11233. EVP_Digest((unsigned char *)buf,
  11234. (uint32_t)strlen(buf),
  11235. (unsigned char *)sha,
  11236. NULL,
  11237. EVP_get_digestbyname("sha1"),
  11238. NULL);
  11239. #else
  11240. SHA1_Init(&sha_ctx);
  11241. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11242. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11243. #endif
  11244. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11245. mg_printf(conn,
  11246. "HTTP/1.1 101 Switching Protocols\r\n"
  11247. "Upgrade: websocket\r\n"
  11248. "Connection: Upgrade\r\n"
  11249. "Sec-WebSocket-Accept: %s\r\n",
  11250. b64_sha);
  11251. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11252. // Send negotiated compression extension parameters
  11253. websocket_deflate_response(conn);
  11254. #endif
  11255. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11256. mg_printf(conn,
  11257. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11258. conn->request_info.acceptedWebSocketSubprotocol);
  11259. } else {
  11260. mg_printf(conn, "%s", "\r\n");
  11261. }
  11262. return 1;
  11263. }
  11264. #if !defined(MG_MAX_UNANSWERED_PING)
  11265. /* Configuration of the maximum number of websocket PINGs that might
  11266. * stay unanswered before the connection is considered broken.
  11267. * Note: The name of this define may still change (until it is
  11268. * defined as a compile parameter in a documentation).
  11269. */
  11270. #define MG_MAX_UNANSWERED_PING (5)
  11271. #endif
  11272. static void
  11273. read_websocket(struct mg_connection *conn,
  11274. mg_websocket_data_handler ws_data_handler,
  11275. void *callback_data)
  11276. {
  11277. /* Pointer to the beginning of the portion of the incoming websocket
  11278. * message queue.
  11279. * The original websocket upgrade request is never removed, so the queue
  11280. * begins after it. */
  11281. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11282. int n, error, exit_by_callback;
  11283. int ret;
  11284. /* body_len is the length of the entire queue in bytes
  11285. * len is the length of the current message
  11286. * data_len is the length of the current message's data payload
  11287. * header_len is the length of the current message's header */
  11288. size_t i, len, mask_len = 0, header_len, body_len;
  11289. uint64_t data_len = 0;
  11290. /* "The masking key is a 32-bit value chosen at random by the client."
  11291. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11292. */
  11293. unsigned char mask[4];
  11294. /* data points to the place where the message is stored when passed to
  11295. * the websocket_data callback. This is either mem on the stack, or a
  11296. * dynamically allocated buffer if it is too large. */
  11297. unsigned char mem[4096];
  11298. unsigned char mop; /* mask flag and opcode */
  11299. /* Variables used for connection monitoring */
  11300. double timeout = -1.0;
  11301. int enable_ping_pong = 0;
  11302. int ping_count = 0;
  11303. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11304. enable_ping_pong =
  11305. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11306. "yes");
  11307. }
  11308. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11309. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11310. }
  11311. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11312. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11313. }
  11314. if (timeout <= 0.0) {
  11315. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11316. }
  11317. /* Enter data processing loop */
  11318. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11319. conn->request_info.remote_addr,
  11320. conn->request_info.remote_port);
  11321. conn->in_websocket_handling = 1;
  11322. mg_set_thread_name("wsock");
  11323. /* Loop continuously, reading messages from the socket, invoking the
  11324. * callback, and waiting repeatedly until an error occurs. */
  11325. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11326. && (!conn->must_close)) {
  11327. header_len = 0;
  11328. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11329. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11330. len = buf[1] & 127;
  11331. mask_len = (buf[1] & 128) ? 4 : 0;
  11332. if ((len < 126) && (body_len >= mask_len)) {
  11333. /* inline 7-bit length field */
  11334. data_len = len;
  11335. header_len = 2 + mask_len;
  11336. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11337. /* 16-bit length field */
  11338. header_len = 4 + mask_len;
  11339. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11340. } else if (body_len >= (10 + mask_len)) {
  11341. /* 64-bit length field */
  11342. uint32_t l1, l2;
  11343. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11344. memcpy(&l2, &buf[6], 4);
  11345. header_len = 10 + mask_len;
  11346. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11347. if (data_len > (uint64_t)0x7FFF0000ul) {
  11348. /* no can do */
  11349. mg_cry_internal(
  11350. conn,
  11351. "%s",
  11352. "websocket out of memory; closing connection");
  11353. break;
  11354. }
  11355. }
  11356. }
  11357. if ((header_len > 0) && (body_len >= header_len)) {
  11358. /* Allocate space to hold websocket payload */
  11359. unsigned char *data = mem;
  11360. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11361. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11362. conn->phys_ctx);
  11363. if (data == NULL) {
  11364. /* Allocation failed, exit the loop and then close the
  11365. * connection */
  11366. mg_cry_internal(
  11367. conn,
  11368. "%s",
  11369. "websocket out of memory; closing connection");
  11370. break;
  11371. }
  11372. }
  11373. /* Copy the mask before we shift the queue and destroy it */
  11374. if (mask_len > 0) {
  11375. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11376. } else {
  11377. memset(mask, 0, sizeof(mask));
  11378. }
  11379. /* Read frame payload from the first message in the queue into
  11380. * data and advance the queue by moving the memory in place. */
  11381. DEBUG_ASSERT(body_len >= header_len);
  11382. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11383. mop = buf[0]; /* current mask and opcode */
  11384. /* Overflow case */
  11385. len = body_len - header_len;
  11386. memcpy(data, buf + header_len, len);
  11387. error = 0;
  11388. while ((uint64_t)len < data_len) {
  11389. n = pull_inner(NULL,
  11390. conn,
  11391. (char *)(data + len),
  11392. (int)(data_len - len),
  11393. timeout);
  11394. if (n <= -2) {
  11395. error = 1;
  11396. break;
  11397. } else if (n > 0) {
  11398. len += (size_t)n;
  11399. } else {
  11400. /* Timeout: should retry */
  11401. /* TODO: retry condition */
  11402. }
  11403. }
  11404. if (error) {
  11405. mg_cry_internal(
  11406. conn,
  11407. "%s",
  11408. "Websocket pull failed; closing connection");
  11409. if (data != mem) {
  11410. mg_free(data);
  11411. }
  11412. break;
  11413. }
  11414. conn->data_len = conn->request_len;
  11415. } else {
  11416. mop = buf[0]; /* current mask and opcode, overwritten by
  11417. * memmove() */
  11418. /* Length of the message being read at the front of the
  11419. * queue. Cast to 31 bit is OK, since we limited
  11420. * data_len before. */
  11421. len = (size_t)data_len + header_len;
  11422. /* Copy the data payload into the data pointer for the
  11423. * callback. Cast to 31 bit is OK, since we
  11424. * limited data_len */
  11425. memcpy(data, buf + header_len, (size_t)data_len);
  11426. /* Move the queue forward len bytes */
  11427. memmove(buf, buf + len, body_len - len);
  11428. /* Mark the queue as advanced */
  11429. conn->data_len -= (int)len;
  11430. }
  11431. /* Apply mask if necessary */
  11432. if (mask_len > 0) {
  11433. for (i = 0; i < (size_t)data_len; i++) {
  11434. data[i] ^= mask[i & 3];
  11435. }
  11436. }
  11437. exit_by_callback = 0;
  11438. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11439. /* filter PONG messages */
  11440. DEBUG_TRACE("PONG from %s:%u",
  11441. conn->request_info.remote_addr,
  11442. conn->request_info.remote_port);
  11443. /* No unanwered PINGs left */
  11444. ping_count = 0;
  11445. } else if (enable_ping_pong
  11446. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11447. /* reply PING messages */
  11448. DEBUG_TRACE("Reply PING from %s:%u",
  11449. conn->request_info.remote_addr,
  11450. conn->request_info.remote_port);
  11451. ret = mg_websocket_write(conn,
  11452. MG_WEBSOCKET_OPCODE_PONG,
  11453. (char *)data,
  11454. (size_t)data_len);
  11455. if (ret <= 0) {
  11456. /* Error: send failed */
  11457. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11458. break;
  11459. }
  11460. } else {
  11461. /* Exit the loop if callback signals to exit (server side),
  11462. * or "connection close" opcode received (client side). */
  11463. if (ws_data_handler != NULL) {
  11464. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11465. if (mop & 0x40) {
  11466. /* Inflate the data received if bit RSV1 is set. */
  11467. if (!conn->websocket_deflate_initialized) {
  11468. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11469. exit_by_callback = 1;
  11470. }
  11471. if (!exit_by_callback) {
  11472. size_t inflate_buf_size_old = 0;
  11473. size_t inflate_buf_size =
  11474. data_len
  11475. * 4; // Initial guess of the inflated message
  11476. // size. We double the memory when needed.
  11477. Bytef *inflated = NULL;
  11478. Bytef *new_mem = NULL;
  11479. conn->websocket_inflate_state.avail_in =
  11480. (uInt)(data_len + 4);
  11481. conn->websocket_inflate_state.next_in = data;
  11482. // Add trailing 0x00 0x00 0xff 0xff bytes
  11483. data[data_len] = '\x00';
  11484. data[data_len + 1] = '\x00';
  11485. data[data_len + 2] = '\xff';
  11486. data[data_len + 3] = '\xff';
  11487. do {
  11488. if (inflate_buf_size_old == 0) {
  11489. new_mem =
  11490. (Bytef *)mg_calloc(inflate_buf_size,
  11491. sizeof(Bytef));
  11492. } else {
  11493. inflate_buf_size *= 2;
  11494. new_mem =
  11495. (Bytef *)mg_realloc(inflated,
  11496. inflate_buf_size);
  11497. }
  11498. if (new_mem == NULL) {
  11499. mg_cry_internal(
  11500. conn,
  11501. "Out of memory: Cannot allocate "
  11502. "inflate buffer of %lu bytes",
  11503. (unsigned long)inflate_buf_size);
  11504. exit_by_callback = 1;
  11505. break;
  11506. }
  11507. inflated = new_mem;
  11508. conn->websocket_inflate_state.avail_out =
  11509. (uInt)(inflate_buf_size
  11510. - inflate_buf_size_old);
  11511. conn->websocket_inflate_state.next_out =
  11512. inflated + inflate_buf_size_old;
  11513. ret = inflate(&conn->websocket_inflate_state,
  11514. Z_SYNC_FLUSH);
  11515. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11516. || ret == Z_MEM_ERROR) {
  11517. mg_cry_internal(
  11518. conn,
  11519. "ZLIB inflate error: %i %s",
  11520. ret,
  11521. (conn->websocket_inflate_state.msg
  11522. ? conn->websocket_inflate_state.msg
  11523. : "<no error message>"));
  11524. exit_by_callback = 1;
  11525. break;
  11526. }
  11527. inflate_buf_size_old = inflate_buf_size;
  11528. } while (conn->websocket_inflate_state.avail_out
  11529. == 0);
  11530. inflate_buf_size -=
  11531. conn->websocket_inflate_state.avail_out;
  11532. if (!ws_data_handler(conn,
  11533. mop,
  11534. (char *)inflated,
  11535. inflate_buf_size,
  11536. callback_data)) {
  11537. exit_by_callback = 1;
  11538. }
  11539. mg_free(inflated);
  11540. }
  11541. } else
  11542. #endif
  11543. if (!ws_data_handler(conn,
  11544. mop,
  11545. (char *)data,
  11546. (size_t)data_len,
  11547. callback_data)) {
  11548. exit_by_callback = 1;
  11549. }
  11550. }
  11551. }
  11552. /* It a buffer has been allocated, free it again */
  11553. if (data != mem) {
  11554. mg_free(data);
  11555. }
  11556. if (exit_by_callback) {
  11557. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11558. conn->request_info.remote_addr,
  11559. conn->request_info.remote_port);
  11560. break;
  11561. }
  11562. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11563. /* Opcode == 8, connection close */
  11564. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11565. conn->request_info.remote_addr,
  11566. conn->request_info.remote_port);
  11567. break;
  11568. }
  11569. /* Not breaking the loop, process next websocket frame. */
  11570. } else {
  11571. /* Read from the socket into the next available location in the
  11572. * message queue. */
  11573. n = pull_inner(NULL,
  11574. conn,
  11575. conn->buf + conn->data_len,
  11576. conn->buf_size - conn->data_len,
  11577. timeout);
  11578. if (n <= -2) {
  11579. /* Error, no bytes read */
  11580. DEBUG_TRACE("PULL from %s:%u failed",
  11581. conn->request_info.remote_addr,
  11582. conn->request_info.remote_port);
  11583. break;
  11584. }
  11585. if (n > 0) {
  11586. conn->data_len += n;
  11587. /* Reset open PING count */
  11588. ping_count = 0;
  11589. } else {
  11590. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11591. && (!conn->must_close)) {
  11592. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11593. /* Stop sending PING */
  11594. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11595. "- closing connection",
  11596. ping_count,
  11597. conn->request_info.remote_addr,
  11598. conn->request_info.remote_port);
  11599. break;
  11600. }
  11601. if (enable_ping_pong) {
  11602. /* Send Websocket PING message */
  11603. DEBUG_TRACE("PING to %s:%u",
  11604. conn->request_info.remote_addr,
  11605. conn->request_info.remote_port);
  11606. ret = mg_websocket_write(conn,
  11607. MG_WEBSOCKET_OPCODE_PING,
  11608. NULL,
  11609. 0);
  11610. if (ret <= 0) {
  11611. /* Error: send failed */
  11612. DEBUG_TRACE("Send PING failed (%i)", ret);
  11613. break;
  11614. }
  11615. ping_count++;
  11616. }
  11617. }
  11618. /* Timeout: should retry */
  11619. /* TODO: get timeout def */
  11620. }
  11621. }
  11622. }
  11623. /* Leave data processing loop */
  11624. mg_set_thread_name("worker");
  11625. conn->in_websocket_handling = 0;
  11626. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11627. conn->request_info.remote_addr,
  11628. conn->request_info.remote_port);
  11629. }
  11630. static int
  11631. mg_websocket_write_exec(struct mg_connection *conn,
  11632. int opcode,
  11633. const char *data,
  11634. size_t dataLen,
  11635. uint32_t masking_key)
  11636. {
  11637. unsigned char header[14];
  11638. size_t headerLen;
  11639. int retval;
  11640. #if defined(GCC_DIAGNOSTIC)
  11641. /* Disable spurious conversion warning for GCC */
  11642. #pragma GCC diagnostic push
  11643. #pragma GCC diagnostic ignored "-Wconversion"
  11644. #endif
  11645. /* Note that POSIX/Winsock's send() is threadsafe
  11646. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11647. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11648. * push(), although that is only a problem if the packet is large or
  11649. * outgoing buffer is full). */
  11650. /* TODO: Check if this lock should be moved to user land.
  11651. * Currently the server sets this lock for websockets, but
  11652. * not for any other connection. It must be set for every
  11653. * conn read/written by more than one thread, no matter if
  11654. * it is a websocket or regular connection. */
  11655. (void)mg_lock_connection(conn);
  11656. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11657. size_t deflated_size = 0;
  11658. Bytef *deflated = 0;
  11659. // Deflate websocket messages over 100kb
  11660. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11661. if (use_deflate) {
  11662. if (!conn->websocket_deflate_initialized) {
  11663. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11664. return 0;
  11665. }
  11666. // Deflating the message
  11667. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11668. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11669. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11670. deflated_size = (size_t)compressBound((uLong)dataLen);
  11671. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11672. if (deflated == NULL) {
  11673. mg_cry_internal(
  11674. conn,
  11675. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11676. (unsigned long)deflated_size);
  11677. mg_unlock_connection(conn);
  11678. return -1;
  11679. }
  11680. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11681. conn->websocket_deflate_state.next_out = deflated;
  11682. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11683. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11684. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11685. } else
  11686. #endif
  11687. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11688. #if defined(GCC_DIAGNOSTIC)
  11689. #pragma GCC diagnostic pop
  11690. #endif
  11691. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11692. if (dataLen < 126) {
  11693. /* inline 7-bit length field */
  11694. header[1] = (unsigned char)dataLen;
  11695. headerLen = 2;
  11696. } else if (dataLen <= 0xFFFF) {
  11697. /* 16-bit length field */
  11698. uint16_t len = htons((uint16_t)dataLen);
  11699. header[1] = 126;
  11700. memcpy(header + 2, &len, 2);
  11701. headerLen = 4;
  11702. } else {
  11703. /* 64-bit length field */
  11704. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11705. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11706. header[1] = 127;
  11707. memcpy(header + 2, &len1, 4);
  11708. memcpy(header + 6, &len2, 4);
  11709. headerLen = 10;
  11710. }
  11711. if (masking_key) {
  11712. /* add mask */
  11713. header[1] |= 0x80;
  11714. memcpy(header + headerLen, &masking_key, 4);
  11715. headerLen += 4;
  11716. }
  11717. retval = mg_write(conn, header, headerLen);
  11718. if (retval != (int)headerLen) {
  11719. /* Did not send complete header */
  11720. retval = -1;
  11721. } else {
  11722. if (dataLen > 0) {
  11723. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11724. if (use_deflate) {
  11725. retval = mg_write(conn, deflated, dataLen);
  11726. mg_free(deflated);
  11727. } else
  11728. #endif
  11729. retval = mg_write(conn, data, dataLen);
  11730. }
  11731. /* if dataLen == 0, the header length (2) is returned */
  11732. }
  11733. /* TODO: Remove this unlock as well, when lock is removed. */
  11734. mg_unlock_connection(conn);
  11735. return retval;
  11736. }
  11737. CIVETWEB_API int
  11738. mg_websocket_write(struct mg_connection *conn,
  11739. int opcode,
  11740. const char *data,
  11741. size_t dataLen)
  11742. {
  11743. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11744. }
  11745. static void
  11746. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11747. {
  11748. size_t i = 0;
  11749. i = 0;
  11750. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11751. /* Convert in 32 bit words, if data is 4 byte aligned */
  11752. while (i < (in_len - 3)) {
  11753. *(uint32_t *)(void *)(out + i) =
  11754. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11755. i += 4;
  11756. }
  11757. }
  11758. if (i != in_len) {
  11759. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11760. while (i < in_len) {
  11761. *(uint8_t *)(void *)(out + i) =
  11762. *(uint8_t *)(void *)(in + i)
  11763. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11764. i++;
  11765. }
  11766. }
  11767. }
  11768. CIVETWEB_API int
  11769. mg_websocket_client_write(struct mg_connection *conn,
  11770. int opcode,
  11771. const char *data,
  11772. size_t dataLen)
  11773. {
  11774. int retval = -1;
  11775. char *masked_data =
  11776. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11777. uint32_t masking_key = 0;
  11778. if (masked_data == NULL) {
  11779. /* Return -1 in an error case */
  11780. mg_cry_internal(conn,
  11781. "%s",
  11782. "Cannot allocate buffer for masked websocket response: "
  11783. "Out of memory");
  11784. return -1;
  11785. }
  11786. do {
  11787. /* Get a masking key - but not 0 */
  11788. masking_key = (uint32_t)get_random();
  11789. } while (masking_key == 0);
  11790. mask_data(data, dataLen, masking_key, masked_data);
  11791. retval = mg_websocket_write_exec(
  11792. conn, opcode, masked_data, dataLen, masking_key);
  11793. mg_free(masked_data);
  11794. return retval;
  11795. }
  11796. static void
  11797. handle_websocket_request(struct mg_connection *conn,
  11798. const char *path,
  11799. int is_callback_resource,
  11800. struct mg_websocket_subprotocols *subprotocols,
  11801. mg_websocket_connect_handler ws_connect_handler,
  11802. mg_websocket_ready_handler ws_ready_handler,
  11803. mg_websocket_data_handler ws_data_handler,
  11804. mg_websocket_close_handler ws_close_handler,
  11805. void *cbData)
  11806. {
  11807. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11808. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11809. ptrdiff_t lua_websock = 0;
  11810. #if !defined(USE_LUA)
  11811. (void)path;
  11812. #endif
  11813. /* Step 1: Check websocket protocol version. */
  11814. /* Step 1.1: Check Sec-WebSocket-Key. */
  11815. if (!websock_key) {
  11816. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11817. * requires a Sec-WebSocket-Key header.
  11818. */
  11819. /* It could be the hixie draft version
  11820. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11821. */
  11822. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11823. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11824. char key3[8];
  11825. if ((key1 != NULL) && (key2 != NULL)) {
  11826. /* This version uses 8 byte body data in a GET request */
  11827. conn->content_len = 8;
  11828. if (8 == mg_read(conn, key3, 8)) {
  11829. /* This is the hixie version */
  11830. mg_send_http_error(conn,
  11831. 426,
  11832. "%s",
  11833. "Protocol upgrade to RFC 6455 required");
  11834. return;
  11835. }
  11836. }
  11837. /* This is an unknown version */
  11838. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11839. return;
  11840. }
  11841. /* Step 1.2: Check websocket protocol version. */
  11842. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11843. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11844. /* Reject wrong versions */
  11845. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11846. return;
  11847. }
  11848. /* Step 1.3: Could check for "Host", but we do not really need this
  11849. * value for anything, so just ignore it. */
  11850. /* Step 2: If a callback is responsible, call it. */
  11851. if (is_callback_resource) {
  11852. /* Step 2.1 check and select subprotocol */
  11853. const char *protocols[64]; // max 64 headers
  11854. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11855. "Sec-WebSocket-Protocol",
  11856. protocols,
  11857. 64);
  11858. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11859. int headerNo, idx;
  11860. size_t len;
  11861. const char *sep, *curSubProtocol,
  11862. *acceptedWebSocketSubprotocol = NULL;
  11863. /* look for matching subprotocol */
  11864. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11865. /* There might be multiple headers ... */
  11866. const char *protocol = protocols[headerNo];
  11867. curSubProtocol = protocol;
  11868. /* ... and in every header there might be a , separated list */
  11869. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11870. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11871. curSubProtocol++;
  11872. sep = strchr(curSubProtocol, ',');
  11873. if (sep) {
  11874. len = (size_t)(sep - curSubProtocol);
  11875. } else {
  11876. len = strlen(curSubProtocol);
  11877. }
  11878. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11879. // COMPARE: curSubProtocol ==
  11880. // subprotocols->subprotocols[idx]
  11881. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11882. && (strncmp(curSubProtocol,
  11883. subprotocols->subprotocols[idx],
  11884. len)
  11885. == 0)) {
  11886. acceptedWebSocketSubprotocol =
  11887. subprotocols->subprotocols[idx];
  11888. break;
  11889. }
  11890. }
  11891. curSubProtocol += len;
  11892. }
  11893. }
  11894. conn->request_info.acceptedWebSocketSubprotocol =
  11895. acceptedWebSocketSubprotocol;
  11896. }
  11897. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11898. websocket_deflate_negotiate(conn);
  11899. #endif
  11900. if ((ws_connect_handler != NULL)
  11901. && (ws_connect_handler(conn, cbData) != 0)) {
  11902. /* C callback has returned non-zero, do not proceed with
  11903. * handshake.
  11904. */
  11905. /* Note that C callbacks are no longer called when Lua is
  11906. * responsible, so C can no longer filter callbacks for Lua. */
  11907. return;
  11908. }
  11909. }
  11910. #if defined(USE_LUA)
  11911. /* Step 3: No callback. Check if Lua is responsible. */
  11912. else {
  11913. /* Step 3.1: Check if Lua is responsible. */
  11914. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11915. lua_websock = match_prefix_strlen(
  11916. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11917. }
  11918. if (lua_websock > 0) {
  11919. /* Step 3.2: Lua is responsible: call it. */
  11920. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11921. if (!conn->lua_websocket_state) {
  11922. /* Lua rejected the new client */
  11923. return;
  11924. }
  11925. }
  11926. }
  11927. #endif
  11928. /* Step 4: Check if there is a responsible websocket handler. */
  11929. if (!is_callback_resource && !lua_websock) {
  11930. /* There is no callback, and Lua is not responsible either. */
  11931. /* Reply with a 404 Not Found. We are still at a standard
  11932. * HTTP request here, before the websocket handshake, so
  11933. * we can still send standard HTTP error replies. */
  11934. mg_send_http_error(conn, 404, "%s", "Not found");
  11935. return;
  11936. }
  11937. /* Step 5: The websocket connection has been accepted */
  11938. if (!send_websocket_handshake(conn, websock_key)) {
  11939. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11940. return;
  11941. }
  11942. /* Step 6: Call the ready handler */
  11943. if (is_callback_resource) {
  11944. if (ws_ready_handler != NULL) {
  11945. ws_ready_handler(conn, cbData);
  11946. }
  11947. #if defined(USE_LUA)
  11948. } else if (lua_websock) {
  11949. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11950. /* the ready handler returned false */
  11951. return;
  11952. }
  11953. #endif
  11954. }
  11955. /* Step 7: Enter the read loop */
  11956. if (is_callback_resource) {
  11957. read_websocket(conn, ws_data_handler, cbData);
  11958. #if defined(USE_LUA)
  11959. } else if (lua_websock) {
  11960. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11961. #endif
  11962. }
  11963. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11964. /* Step 8: Close the deflate & inflate buffers */
  11965. if (conn->websocket_deflate_initialized) {
  11966. deflateEnd(&conn->websocket_deflate_state);
  11967. inflateEnd(&conn->websocket_inflate_state);
  11968. }
  11969. #endif
  11970. /* Step 9: Call the close handler */
  11971. if (ws_close_handler) {
  11972. ws_close_handler(conn, cbData);
  11973. }
  11974. }
  11975. #endif /* !USE_WEBSOCKET */
  11976. /* Is upgrade request:
  11977. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11978. * 1 = upgrade to websocket
  11979. * 2 = upgrade to HTTP/2
  11980. * -1 = upgrade to unknown protocol
  11981. */
  11982. static int
  11983. should_switch_to_protocol(const struct mg_connection *conn)
  11984. {
  11985. const char *connection_headers[8];
  11986. const char *upgrade_to;
  11987. int connection_header_count, i, should_upgrade;
  11988. /* A websocket protocol has the following HTTP headers:
  11989. *
  11990. * Connection: Upgrade
  11991. * Upgrade: Websocket
  11992. *
  11993. * It seems some clients use multiple headers:
  11994. * see https://github.com/civetweb/civetweb/issues/1083
  11995. */
  11996. connection_header_count = get_req_headers(&conn->request_info,
  11997. "Connection",
  11998. connection_headers,
  11999. 8);
  12000. should_upgrade = 0;
  12001. for (i = 0; i < connection_header_count; i++) {
  12002. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12003. should_upgrade = 1;
  12004. }
  12005. }
  12006. if (!should_upgrade) {
  12007. return PROTOCOL_TYPE_HTTP1;
  12008. }
  12009. upgrade_to = mg_get_header(conn, "Upgrade");
  12010. if (upgrade_to == NULL) {
  12011. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12012. return -1;
  12013. }
  12014. /* Upgrade to ... */
  12015. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12016. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12017. * "Sec-WebSocket-Version" are also required.
  12018. * Don't check them here, since even an unsupported websocket protocol
  12019. * request still IS a websocket request (in contrast to a standard HTTP
  12020. * request). It will fail later in handle_websocket_request.
  12021. */
  12022. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12023. }
  12024. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12025. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12026. }
  12027. /* Upgrade to another protocol */
  12028. return -1;
  12029. }
  12030. static int
  12031. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12032. {
  12033. int n;
  12034. unsigned int a, b, c, d, slash;
  12035. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12036. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12037. // integer value, but function will not report conversion
  12038. // errors; consider using 'strtol' instead
  12039. slash = 32;
  12040. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12041. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12042. // an integer value, but function will not report conversion
  12043. // errors; consider using 'strtol' instead
  12044. n = 0;
  12045. }
  12046. }
  12047. if ((n > 0) && ((size_t)n == vec->len)) {
  12048. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12049. /* IPv4 format */
  12050. if (sa->sa.sa_family == AF_INET) {
  12051. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12052. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12053. | ((uint32_t)c << 8) | (uint32_t)d;
  12054. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12055. return (ip & mask) == net;
  12056. }
  12057. return 0;
  12058. }
  12059. }
  12060. #if defined(USE_IPV6)
  12061. else {
  12062. char ad[50];
  12063. const char *p;
  12064. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12065. slash = 128;
  12066. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12067. n = 0;
  12068. }
  12069. }
  12070. if ((n <= 0) && no_strict) {
  12071. /* no square brackets? */
  12072. p = strchr(vec->ptr, '/');
  12073. if (p && (p < (vec->ptr + vec->len))) {
  12074. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12075. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12076. n += (int)(p - vec->ptr);
  12077. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12078. } else {
  12079. n = 0;
  12080. }
  12081. } else if (vec->len < sizeof(ad)) {
  12082. n = (int)vec->len;
  12083. slash = 128;
  12084. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12085. }
  12086. }
  12087. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12088. p = ad;
  12089. c = 0;
  12090. /* zone indexes are unsupported, at least two colons are needed */
  12091. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12092. if (*(p++) == ':') {
  12093. c++;
  12094. }
  12095. }
  12096. if ((*p == '\0') && (c >= 2)) {
  12097. struct sockaddr_in6 sin6;
  12098. unsigned int i;
  12099. /* for strict validation, an actual IPv6 argument is needed */
  12100. if (sa->sa.sa_family != AF_INET6) {
  12101. return 0;
  12102. }
  12103. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12104. /* IPv6 format */
  12105. for (i = 0; i < 16; i++) {
  12106. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12107. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12108. uint8_t mask = 0;
  12109. if (8 * i + 8 < slash) {
  12110. mask = 0xFFu;
  12111. } else if (8 * i < slash) {
  12112. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12113. }
  12114. if ((ip & mask) != net) {
  12115. return 0;
  12116. }
  12117. }
  12118. return 1;
  12119. }
  12120. }
  12121. }
  12122. }
  12123. #else
  12124. (void)no_strict;
  12125. #endif
  12126. /* malformed */
  12127. return -1;
  12128. }
  12129. static int
  12130. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12131. {
  12132. int throttle = 0;
  12133. struct vec vec, val;
  12134. char mult;
  12135. double v;
  12136. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12137. mult = ',';
  12138. if ((val.ptr == NULL)
  12139. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12140. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12141. // to an integer value, but function will not report
  12142. // conversion errors; consider using 'strtol' instead
  12143. || (v < 0)
  12144. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12145. && (mult != ','))) {
  12146. continue;
  12147. }
  12148. v *= (lowercase(&mult) == 'k')
  12149. ? 1024
  12150. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12151. if (vec.len == 1 && vec.ptr[0] == '*') {
  12152. throttle = (int)v;
  12153. } else {
  12154. int matched = parse_match_net(&vec, rsa, 0);
  12155. if (matched >= 0) {
  12156. /* a valid IP subnet */
  12157. if (matched) {
  12158. throttle = (int)v;
  12159. }
  12160. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12161. throttle = (int)v;
  12162. }
  12163. }
  12164. }
  12165. return throttle;
  12166. }
  12167. /* The mg_upload function is superseded by mg_handle_form_request. */
  12168. #include "handle_form.inl"
  12169. static int
  12170. get_first_ssl_listener_index(const struct mg_context *ctx)
  12171. {
  12172. unsigned int i;
  12173. int idx = -1;
  12174. if (ctx) {
  12175. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12176. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12177. }
  12178. }
  12179. return idx;
  12180. }
  12181. /* Return host (without port) */
  12182. static void
  12183. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12184. {
  12185. const char *host_header =
  12186. get_header(ri->http_headers, ri->num_headers, "Host");
  12187. host->ptr = NULL;
  12188. host->len = 0;
  12189. if (host_header != NULL) {
  12190. const char *pos;
  12191. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12192. * is found. */
  12193. if (*host_header == '[') {
  12194. pos = strchr(host_header, ']');
  12195. if (!pos) {
  12196. /* Malformed hostname starts with '[', but no ']' found */
  12197. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12198. return;
  12199. }
  12200. /* terminate after ']' */
  12201. host->ptr = host_header;
  12202. host->len = (size_t)(pos + 1 - host_header);
  12203. } else {
  12204. /* Otherwise, a ':' separates hostname and port number */
  12205. pos = strchr(host_header, ':');
  12206. if (pos != NULL) {
  12207. host->len = (size_t)(pos - host_header);
  12208. } else {
  12209. host->len = strlen(host_header);
  12210. }
  12211. host->ptr = host_header;
  12212. }
  12213. }
  12214. }
  12215. static int
  12216. switch_domain_context(struct mg_connection *conn)
  12217. {
  12218. struct vec host;
  12219. get_host_from_request_info(&host, &conn->request_info);
  12220. if (host.ptr) {
  12221. if (conn->ssl) {
  12222. /* This is a HTTPS connection, maybe we have a hostname
  12223. * from SNI (set in ssl_servername_callback). */
  12224. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12225. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12226. /* We are not using the default domain */
  12227. if ((strlen(sslhost) != host.len)
  12228. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12229. /* Mismatch between SNI domain and HTTP domain */
  12230. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12231. sslhost,
  12232. (int)host.len,
  12233. host.ptr);
  12234. return 0;
  12235. }
  12236. }
  12237. } else {
  12238. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12239. while (dom) {
  12240. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12241. size_t domNameLen = strlen(domName);
  12242. if ((domNameLen == host.len)
  12243. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12244. /* Found matching domain */
  12245. DEBUG_TRACE("HTTP domain %s found",
  12246. dom->config[AUTHENTICATION_DOMAIN]);
  12247. /* TODO: Check if this is a HTTP or HTTPS domain */
  12248. conn->dom_ctx = dom;
  12249. break;
  12250. }
  12251. mg_lock_context(conn->phys_ctx);
  12252. dom = dom->next;
  12253. mg_unlock_context(conn->phys_ctx);
  12254. }
  12255. }
  12256. DEBUG_TRACE("HTTP%s Host: %.*s",
  12257. conn->ssl ? "S" : "",
  12258. (int)host.len,
  12259. host.ptr);
  12260. } else {
  12261. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12262. return 1;
  12263. }
  12264. return 1;
  12265. }
  12266. static void
  12267. redirect_to_https_port(struct mg_connection *conn, int port)
  12268. {
  12269. char target_url[MG_BUF_LEN];
  12270. int truncated = 0;
  12271. const char *expect_proto =
  12272. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12273. /* Use "308 Permanent Redirect" */
  12274. int redirect_code = 308;
  12275. /* In any case, close the current connection */
  12276. conn->must_close = 1;
  12277. /* Send host, port, uri and (if it exists) ?query_string */
  12278. if (mg_construct_local_link(
  12279. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12280. < 0) {
  12281. truncated = 1;
  12282. } else if (conn->request_info.query_string != NULL) {
  12283. size_t slen1 = strlen(target_url);
  12284. size_t slen2 = strlen(conn->request_info.query_string);
  12285. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12286. target_url[slen1] = '?';
  12287. memcpy(target_url + slen1 + 1,
  12288. conn->request_info.query_string,
  12289. slen2);
  12290. target_url[slen1 + slen2 + 1] = 0;
  12291. } else {
  12292. truncated = 1;
  12293. }
  12294. }
  12295. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12296. * is used as buffer size) */
  12297. if (truncated) {
  12298. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12299. return;
  12300. }
  12301. /* Use redirect helper function */
  12302. mg_send_http_redirect(conn, target_url, redirect_code);
  12303. }
  12304. static void
  12305. mg_set_handler_type(struct mg_context *phys_ctx,
  12306. struct mg_domain_context *dom_ctx,
  12307. const char *uri,
  12308. int handler_type,
  12309. int is_delete_request,
  12310. mg_request_handler handler,
  12311. struct mg_websocket_subprotocols *subprotocols,
  12312. mg_websocket_connect_handler connect_handler,
  12313. mg_websocket_ready_handler ready_handler,
  12314. mg_websocket_data_handler data_handler,
  12315. mg_websocket_close_handler close_handler,
  12316. mg_authorization_handler auth_handler,
  12317. void *cbdata)
  12318. {
  12319. struct mg_handler_info *tmp_rh, **lastref;
  12320. size_t urilen = strlen(uri);
  12321. if (handler_type == WEBSOCKET_HANDLER) {
  12322. DEBUG_ASSERT(handler == NULL);
  12323. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12324. || ready_handler != NULL || data_handler != NULL
  12325. || close_handler != NULL);
  12326. DEBUG_ASSERT(auth_handler == NULL);
  12327. if (handler != NULL) {
  12328. return;
  12329. }
  12330. if (!is_delete_request && (connect_handler == NULL)
  12331. && (ready_handler == NULL) && (data_handler == NULL)
  12332. && (close_handler == NULL)) {
  12333. return;
  12334. }
  12335. if (auth_handler != NULL) {
  12336. return;
  12337. }
  12338. } else if (handler_type == REQUEST_HANDLER) {
  12339. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12340. && data_handler == NULL && close_handler == NULL);
  12341. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12342. DEBUG_ASSERT(auth_handler == NULL);
  12343. if ((connect_handler != NULL) || (ready_handler != NULL)
  12344. || (data_handler != NULL) || (close_handler != NULL)) {
  12345. return;
  12346. }
  12347. if (!is_delete_request && (handler == NULL)) {
  12348. return;
  12349. }
  12350. if (auth_handler != NULL) {
  12351. return;
  12352. }
  12353. } else if (handler_type == AUTH_HANDLER) {
  12354. DEBUG_ASSERT(handler == NULL);
  12355. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12356. && data_handler == NULL && close_handler == NULL);
  12357. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12358. if (handler != NULL) {
  12359. return;
  12360. }
  12361. if ((connect_handler != NULL) || (ready_handler != NULL)
  12362. || (data_handler != NULL) || (close_handler != NULL)) {
  12363. return;
  12364. }
  12365. if (!is_delete_request && (auth_handler == NULL)) {
  12366. return;
  12367. }
  12368. } else {
  12369. /* Unknown handler type. */
  12370. return;
  12371. }
  12372. if (!phys_ctx || !dom_ctx) {
  12373. /* no context available */
  12374. return;
  12375. }
  12376. mg_lock_context(phys_ctx);
  12377. /* first try to find an existing handler */
  12378. do {
  12379. lastref = &(dom_ctx->handlers);
  12380. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12381. tmp_rh = tmp_rh->next) {
  12382. if (tmp_rh->handler_type == handler_type
  12383. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12384. if (!is_delete_request) {
  12385. /* update existing handler */
  12386. if (handler_type == REQUEST_HANDLER) {
  12387. /* Wait for end of use before updating */
  12388. if (tmp_rh->refcount) {
  12389. mg_unlock_context(phys_ctx);
  12390. mg_sleep(1);
  12391. mg_lock_context(phys_ctx);
  12392. /* tmp_rh might have been freed, search again. */
  12393. break;
  12394. }
  12395. /* Ok, the handler is no more use -> Update it */
  12396. tmp_rh->handler = handler;
  12397. } else if (handler_type == WEBSOCKET_HANDLER) {
  12398. tmp_rh->subprotocols = subprotocols;
  12399. tmp_rh->connect_handler = connect_handler;
  12400. tmp_rh->ready_handler = ready_handler;
  12401. tmp_rh->data_handler = data_handler;
  12402. tmp_rh->close_handler = close_handler;
  12403. } else { /* AUTH_HANDLER */
  12404. tmp_rh->auth_handler = auth_handler;
  12405. }
  12406. tmp_rh->cbdata = cbdata;
  12407. } else {
  12408. /* remove existing handler */
  12409. if (handler_type == REQUEST_HANDLER) {
  12410. /* Wait for end of use before removing */
  12411. if (tmp_rh->refcount) {
  12412. tmp_rh->removing = 1;
  12413. mg_unlock_context(phys_ctx);
  12414. mg_sleep(1);
  12415. mg_lock_context(phys_ctx);
  12416. /* tmp_rh might have been freed, search again. */
  12417. break;
  12418. }
  12419. /* Ok, the handler is no more used */
  12420. }
  12421. *lastref = tmp_rh->next;
  12422. mg_free(tmp_rh->uri);
  12423. mg_free(tmp_rh);
  12424. }
  12425. mg_unlock_context(phys_ctx);
  12426. return;
  12427. }
  12428. lastref = &(tmp_rh->next);
  12429. }
  12430. } while (tmp_rh != NULL);
  12431. if (is_delete_request) {
  12432. /* no handler to set, this was a remove request to a non-existing
  12433. * handler */
  12434. mg_unlock_context(phys_ctx);
  12435. return;
  12436. }
  12437. tmp_rh =
  12438. (struct mg_handler_info *)mg_calloc_ctx(1,
  12439. sizeof(struct mg_handler_info),
  12440. phys_ctx);
  12441. if (tmp_rh == NULL) {
  12442. mg_unlock_context(phys_ctx);
  12443. mg_cry_ctx_internal(phys_ctx,
  12444. "%s",
  12445. "Cannot create new request handler struct, OOM");
  12446. return;
  12447. }
  12448. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12449. if (!tmp_rh->uri) {
  12450. mg_unlock_context(phys_ctx);
  12451. mg_free(tmp_rh);
  12452. mg_cry_ctx_internal(phys_ctx,
  12453. "%s",
  12454. "Cannot create new request handler struct, OOM");
  12455. return;
  12456. }
  12457. tmp_rh->uri_len = urilen;
  12458. if (handler_type == REQUEST_HANDLER) {
  12459. tmp_rh->refcount = 0;
  12460. tmp_rh->removing = 0;
  12461. tmp_rh->handler = handler;
  12462. } else if (handler_type == WEBSOCKET_HANDLER) {
  12463. tmp_rh->subprotocols = subprotocols;
  12464. tmp_rh->connect_handler = connect_handler;
  12465. tmp_rh->ready_handler = ready_handler;
  12466. tmp_rh->data_handler = data_handler;
  12467. tmp_rh->close_handler = close_handler;
  12468. } else { /* AUTH_HANDLER */
  12469. tmp_rh->auth_handler = auth_handler;
  12470. }
  12471. tmp_rh->cbdata = cbdata;
  12472. tmp_rh->handler_type = handler_type;
  12473. tmp_rh->next = NULL;
  12474. *lastref = tmp_rh;
  12475. mg_unlock_context(phys_ctx);
  12476. }
  12477. CIVETWEB_API void
  12478. mg_set_request_handler(struct mg_context *ctx,
  12479. const char *uri,
  12480. mg_request_handler handler,
  12481. void *cbdata)
  12482. {
  12483. mg_set_handler_type(ctx,
  12484. &(ctx->dd),
  12485. uri,
  12486. REQUEST_HANDLER,
  12487. handler == NULL,
  12488. handler,
  12489. NULL,
  12490. NULL,
  12491. NULL,
  12492. NULL,
  12493. NULL,
  12494. NULL,
  12495. cbdata);
  12496. }
  12497. CIVETWEB_API void
  12498. mg_set_websocket_handler(struct mg_context *ctx,
  12499. const char *uri,
  12500. mg_websocket_connect_handler connect_handler,
  12501. mg_websocket_ready_handler ready_handler,
  12502. mg_websocket_data_handler data_handler,
  12503. mg_websocket_close_handler close_handler,
  12504. void *cbdata)
  12505. {
  12506. mg_set_websocket_handler_with_subprotocols(ctx,
  12507. uri,
  12508. NULL,
  12509. connect_handler,
  12510. ready_handler,
  12511. data_handler,
  12512. close_handler,
  12513. cbdata);
  12514. }
  12515. CIVETWEB_API void
  12516. mg_set_websocket_handler_with_subprotocols(
  12517. struct mg_context *ctx,
  12518. const char *uri,
  12519. struct mg_websocket_subprotocols *subprotocols,
  12520. mg_websocket_connect_handler connect_handler,
  12521. mg_websocket_ready_handler ready_handler,
  12522. mg_websocket_data_handler data_handler,
  12523. mg_websocket_close_handler close_handler,
  12524. void *cbdata)
  12525. {
  12526. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12527. && (data_handler == NULL)
  12528. && (close_handler == NULL);
  12529. mg_set_handler_type(ctx,
  12530. &(ctx->dd),
  12531. uri,
  12532. WEBSOCKET_HANDLER,
  12533. is_delete_request,
  12534. NULL,
  12535. subprotocols,
  12536. connect_handler,
  12537. ready_handler,
  12538. data_handler,
  12539. close_handler,
  12540. NULL,
  12541. cbdata);
  12542. }
  12543. CIVETWEB_API void
  12544. mg_set_auth_handler(struct mg_context *ctx,
  12545. const char *uri,
  12546. mg_authorization_handler handler,
  12547. void *cbdata)
  12548. {
  12549. mg_set_handler_type(ctx,
  12550. &(ctx->dd),
  12551. uri,
  12552. AUTH_HANDLER,
  12553. handler == NULL,
  12554. NULL,
  12555. NULL,
  12556. NULL,
  12557. NULL,
  12558. NULL,
  12559. NULL,
  12560. handler,
  12561. cbdata);
  12562. }
  12563. static int
  12564. get_request_handler(struct mg_connection *conn,
  12565. int handler_type,
  12566. mg_request_handler *handler,
  12567. struct mg_websocket_subprotocols **subprotocols,
  12568. mg_websocket_connect_handler *connect_handler,
  12569. mg_websocket_ready_handler *ready_handler,
  12570. mg_websocket_data_handler *data_handler,
  12571. mg_websocket_close_handler *close_handler,
  12572. mg_authorization_handler *auth_handler,
  12573. void **cbdata,
  12574. struct mg_handler_info **handler_info)
  12575. {
  12576. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12577. if (request_info) {
  12578. const char *uri = request_info->local_uri;
  12579. size_t urilen = strlen(uri);
  12580. struct mg_handler_info *tmp_rh;
  12581. int step, matched;
  12582. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12583. return 0;
  12584. }
  12585. mg_lock_context(conn->phys_ctx);
  12586. for (step = 0; step < 3; step++) {
  12587. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12588. tmp_rh = tmp_rh->next) {
  12589. if (tmp_rh->handler_type != handler_type) {
  12590. continue;
  12591. }
  12592. if (step == 0) {
  12593. /* first try for an exact match */
  12594. matched = (tmp_rh->uri_len == urilen)
  12595. && (strcmp(tmp_rh->uri, uri) == 0);
  12596. } else if (step == 1) {
  12597. /* next try for a partial match, we will accept
  12598. uri/something */
  12599. matched =
  12600. (tmp_rh->uri_len < urilen)
  12601. && (uri[tmp_rh->uri_len] == '/')
  12602. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12603. } else {
  12604. /* finally try for pattern match */
  12605. matched =
  12606. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12607. }
  12608. if (matched) {
  12609. if (handler_type == WEBSOCKET_HANDLER) {
  12610. *subprotocols = tmp_rh->subprotocols;
  12611. *connect_handler = tmp_rh->connect_handler;
  12612. *ready_handler = tmp_rh->ready_handler;
  12613. *data_handler = tmp_rh->data_handler;
  12614. *close_handler = tmp_rh->close_handler;
  12615. } else if (handler_type == REQUEST_HANDLER) {
  12616. if (tmp_rh->removing) {
  12617. /* Treat as none found */
  12618. step = 2;
  12619. break;
  12620. }
  12621. *handler = tmp_rh->handler;
  12622. /* Acquire handler and give it back */
  12623. tmp_rh->refcount++;
  12624. *handler_info = tmp_rh;
  12625. } else { /* AUTH_HANDLER */
  12626. *auth_handler = tmp_rh->auth_handler;
  12627. }
  12628. *cbdata = tmp_rh->cbdata;
  12629. mg_unlock_context(conn->phys_ctx);
  12630. return 1;
  12631. }
  12632. }
  12633. }
  12634. mg_unlock_context(conn->phys_ctx);
  12635. }
  12636. return 0; /* none found */
  12637. }
  12638. /* Check if the script file is in a path, allowed for script files.
  12639. * This can be used if uploading files is possible not only for the server
  12640. * admin, and the upload mechanism does not check the file extension.
  12641. */
  12642. static int
  12643. is_in_script_path(const struct mg_connection *conn, const char *path)
  12644. {
  12645. /* TODO (Feature): Add config value for allowed script path.
  12646. * Default: All allowed. */
  12647. (void)conn;
  12648. (void)path;
  12649. return 1;
  12650. }
  12651. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12652. static int
  12653. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12654. int bits,
  12655. char *data,
  12656. size_t len,
  12657. void *cbdata)
  12658. {
  12659. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12660. if (pcallbacks->websocket_data) {
  12661. return pcallbacks->websocket_data(conn, bits, data, len);
  12662. }
  12663. /* No handler set - assume "OK" */
  12664. return 1;
  12665. }
  12666. static void
  12667. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12668. void *cbdata)
  12669. {
  12670. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12671. if (pcallbacks->connection_close) {
  12672. pcallbacks->connection_close(conn);
  12673. }
  12674. }
  12675. #endif
  12676. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12677. */
  12678. static void
  12679. release_handler_ref(struct mg_connection *conn,
  12680. struct mg_handler_info *handler_info)
  12681. {
  12682. if (handler_info != NULL) {
  12683. /* Use context lock for ref counter */
  12684. mg_lock_context(conn->phys_ctx);
  12685. handler_info->refcount--;
  12686. mg_unlock_context(conn->phys_ctx);
  12687. }
  12688. }
  12689. /* This is the heart of the Civetweb's logic.
  12690. * This function is called when the request is read, parsed and validated,
  12691. * and Civetweb must decide what action to take: serve a file, or
  12692. * a directory, or call embedded function, etcetera. */
  12693. static void
  12694. handle_request(struct mg_connection *conn)
  12695. {
  12696. struct mg_request_info *ri = &conn->request_info;
  12697. char path[UTF8_PATH_MAX];
  12698. int uri_len, ssl_index;
  12699. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12700. is_put_or_delete_request = 0, is_callback_resource = 0,
  12701. is_template_text_file = 0, is_webdav_request = 0;
  12702. int i;
  12703. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12704. mg_request_handler callback_handler = NULL;
  12705. struct mg_handler_info *handler_info = NULL;
  12706. struct mg_websocket_subprotocols *subprotocols;
  12707. mg_websocket_connect_handler ws_connect_handler = NULL;
  12708. mg_websocket_ready_handler ws_ready_handler = NULL;
  12709. mg_websocket_data_handler ws_data_handler = NULL;
  12710. mg_websocket_close_handler ws_close_handler = NULL;
  12711. void *callback_data = NULL;
  12712. mg_authorization_handler auth_handler = NULL;
  12713. void *auth_callback_data = NULL;
  12714. int handler_type;
  12715. time_t curtime = time(NULL);
  12716. char date[64];
  12717. char *tmp;
  12718. path[0] = 0;
  12719. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12720. conn->request_state = 0;
  12721. /* 1. get the request url */
  12722. /* 1.1. split into url and query string */
  12723. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12724. != NULL) {
  12725. *((char *)conn->request_info.query_string++) = '\0';
  12726. }
  12727. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12728. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12729. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12730. if (ssl_index >= 0) {
  12731. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12732. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12733. redirect_to_https_port(conn, port);
  12734. } else {
  12735. /* A http to https forward port has been specified,
  12736. * but no https port to forward to. */
  12737. mg_send_http_error(conn,
  12738. 503,
  12739. "%s",
  12740. "Error: SSL forward not configured properly");
  12741. mg_cry_internal(conn,
  12742. "%s",
  12743. "Can not redirect to SSL, no SSL port available");
  12744. }
  12745. return;
  12746. }
  12747. uri_len = (int)strlen(ri->local_uri);
  12748. /* 1.3. decode url (if config says so) */
  12749. if (should_decode_url(conn)) {
  12750. url_decode_in_place((char *)ri->local_uri);
  12751. }
  12752. /* URL decode the query-string only if explicitly set in the configuration
  12753. */
  12754. if (conn->request_info.query_string) {
  12755. if (should_decode_query_string(conn)) {
  12756. url_decode_in_place((char *)conn->request_info.query_string);
  12757. }
  12758. }
  12759. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12760. * possible. The fact that we cleaned the URI is stored in that the
  12761. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12762. * ri->local_uri_raw still points to memory allocated in
  12763. * worker_thread_run(). ri->local_uri is private to the request so we
  12764. * don't have to use preallocated memory here. */
  12765. tmp = mg_strdup(ri->local_uri_raw);
  12766. if (!tmp) {
  12767. /* Out of memory. We cannot do anything reasonable here. */
  12768. return;
  12769. }
  12770. remove_dot_segments(tmp);
  12771. ri->local_uri = tmp;
  12772. /* step 1. completed, the url is known now */
  12773. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12774. /* 2. if this ip has limited speed, set it for this connection */
  12775. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12776. &conn->client.rsa,
  12777. ri->local_uri);
  12778. /* 3. call a "handle everything" callback, if registered */
  12779. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12780. /* Note that since V1.7 the "begin_request" function is called
  12781. * before an authorization check. If an authorization check is
  12782. * required, use a request_handler instead. */
  12783. i = conn->phys_ctx->callbacks.begin_request(conn);
  12784. if (i > 0) {
  12785. /* callback already processed the request. Store the
  12786. return value as a status code for the access log. */
  12787. conn->status_code = i;
  12788. if (!conn->must_close) {
  12789. discard_unread_request_data(conn);
  12790. }
  12791. DEBUG_TRACE("%s", "begin_request handled request");
  12792. return;
  12793. } else if (i == 0) {
  12794. /* civetweb should process the request */
  12795. } else {
  12796. /* unspecified - may change with the next version */
  12797. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12798. return;
  12799. }
  12800. }
  12801. /* request not yet handled by a handler or redirect, so the request
  12802. * is processed here */
  12803. /* 4. Check for CORS preflight requests and handle them (if configured).
  12804. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12805. */
  12806. if (!strcmp(ri->request_method, "OPTIONS")) {
  12807. /* Send a response to CORS preflights only if
  12808. * access_control_allow_methods is not NULL and not an empty string.
  12809. * In this case, scripts can still handle CORS. */
  12810. const char *cors_meth_cfg =
  12811. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12812. const char *cors_orig_cfg =
  12813. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12814. const char *cors_origin =
  12815. get_header(ri->http_headers, ri->num_headers, "Origin");
  12816. const char *cors_acrm = get_header(ri->http_headers,
  12817. ri->num_headers,
  12818. "Access-Control-Request-Method");
  12819. /* Todo: check if cors_origin is in cors_orig_cfg.
  12820. * Or, let the client check this. */
  12821. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12822. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12823. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12824. /* This is a valid CORS preflight, and the server is configured
  12825. * to handle it automatically. */
  12826. const char *cors_acrh =
  12827. get_header(ri->http_headers,
  12828. ri->num_headers,
  12829. "Access-Control-Request-Headers");
  12830. gmt_time_string(date, sizeof(date), &curtime);
  12831. mg_printf(conn,
  12832. "HTTP/1.1 200 OK\r\n"
  12833. "Date: %s\r\n"
  12834. "Access-Control-Allow-Origin: %s\r\n"
  12835. "Access-Control-Allow-Methods: %s\r\n"
  12836. "Content-Length: 0\r\n"
  12837. "Connection: %s\r\n",
  12838. date,
  12839. cors_orig_cfg,
  12840. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12841. suggest_connection_header(conn));
  12842. if (cors_acrh != NULL) {
  12843. /* CORS request is asking for additional headers */
  12844. const char *cors_hdr_cfg =
  12845. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12846. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12847. /* Allow only if access_control_allow_headers is
  12848. * not NULL and not an empty string. If this
  12849. * configuration is set to *, allow everything.
  12850. * Otherwise this configuration must be a list
  12851. * of allowed HTTP header names. */
  12852. mg_printf(conn,
  12853. "Access-Control-Allow-Headers: %s\r\n",
  12854. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12855. : cors_hdr_cfg));
  12856. }
  12857. }
  12858. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12859. mg_printf(conn, "\r\n");
  12860. DEBUG_TRACE("%s", "OPTIONS done");
  12861. return;
  12862. }
  12863. }
  12864. /* 5. interpret the url to find out how the request must be handled
  12865. */
  12866. /* 5.1. first test, if the request targets the regular http(s)://
  12867. * protocol namespace or the websocket ws(s):// protocol namespace.
  12868. */
  12869. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12870. #if defined(USE_WEBSOCKET)
  12871. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12872. #else
  12873. handler_type = REQUEST_HANDLER;
  12874. #endif /* defined(USE_WEBSOCKET) */
  12875. if (is_websocket_request) {
  12876. HTTP1_only;
  12877. }
  12878. /* 5.2. check if the request will be handled by a callback */
  12879. if (get_request_handler(conn,
  12880. handler_type,
  12881. &callback_handler,
  12882. &subprotocols,
  12883. &ws_connect_handler,
  12884. &ws_ready_handler,
  12885. &ws_data_handler,
  12886. &ws_close_handler,
  12887. NULL,
  12888. &callback_data,
  12889. &handler_info)) {
  12890. /* 5.2.1. A callback will handle this request. All requests
  12891. * handled by a callback have to be considered as requests
  12892. * to a script resource. */
  12893. is_callback_resource = 1;
  12894. is_script_resource = 1;
  12895. is_put_or_delete_request = is_put_or_delete_method(conn);
  12896. /* Never handle a C callback according to File WebDav rules,
  12897. * even if it is a webdav method */
  12898. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12899. } else {
  12900. no_callback_resource:
  12901. /* 5.2.2. No callback is responsible for this request. The URI
  12902. * addresses a file based resource (static content or Lua/cgi
  12903. * scripts in the file system). */
  12904. is_callback_resource = 0;
  12905. interpret_uri(conn,
  12906. path,
  12907. sizeof(path),
  12908. &file.stat,
  12909. &is_found,
  12910. &is_script_resource,
  12911. &is_websocket_request,
  12912. &is_put_or_delete_request,
  12913. &is_webdav_request,
  12914. &is_template_text_file);
  12915. }
  12916. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12917. if (is_webdav_request) {
  12918. /* TODO: Do we need a config option? */
  12919. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12920. if (webdav_enable[0] != 'y') {
  12921. mg_send_http_error(conn,
  12922. 405,
  12923. "%s method not allowed",
  12924. conn->request_info.request_method);
  12925. DEBUG_TRACE("%s", "webdav rejected");
  12926. return;
  12927. }
  12928. }
  12929. /* 6. authorization check */
  12930. /* 6.1. a custom authorization handler is installed */
  12931. if (get_request_handler(conn,
  12932. AUTH_HANDLER,
  12933. NULL,
  12934. NULL,
  12935. NULL,
  12936. NULL,
  12937. NULL,
  12938. NULL,
  12939. &auth_handler,
  12940. &auth_callback_data,
  12941. NULL)) {
  12942. if (!auth_handler(conn, auth_callback_data)) {
  12943. /* Callback handler will not be used anymore. Release it */
  12944. release_handler_ref(conn, handler_info);
  12945. DEBUG_TRACE("%s", "auth handler rejected request");
  12946. return;
  12947. }
  12948. } else if (is_put_or_delete_request && !is_script_resource
  12949. && !is_callback_resource) {
  12950. HTTP1_only;
  12951. /* 6.2. this request is a PUT/DELETE to a real file */
  12952. /* 6.2.1. thus, the server must have real files */
  12953. #if defined(NO_FILES)
  12954. if (1) {
  12955. #else
  12956. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  12957. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  12958. #endif
  12959. /* This code path will not be called for request handlers */
  12960. DEBUG_ASSERT(handler_info == NULL);
  12961. /* This server does not have any real files, thus the
  12962. * PUT/DELETE methods are not valid. */
  12963. mg_send_http_error(conn,
  12964. 405,
  12965. "%s method not allowed",
  12966. conn->request_info.request_method);
  12967. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  12968. return;
  12969. }
  12970. #if !defined(NO_FILES)
  12971. /* 6.2.2. Check if put authorization for static files is
  12972. * available.
  12973. */
  12974. if (!is_authorized_for_put(conn)) {
  12975. send_authorization_request(conn, NULL);
  12976. DEBUG_TRACE("%s", "file write needs authorization");
  12977. return;
  12978. }
  12979. #endif
  12980. } else {
  12981. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12982. * or it is a PUT or DELETE request to a resource that does not
  12983. * correspond to a file. Check authorization. */
  12984. if (!check_authorization(conn, path)) {
  12985. send_authorization_request(conn, NULL);
  12986. /* Callback handler will not be used anymore. Release it */
  12987. release_handler_ref(conn, handler_info);
  12988. DEBUG_TRACE("%s", "access authorization required");
  12989. return;
  12990. }
  12991. }
  12992. /* request is authorized or does not need authorization */
  12993. /* 7. check if there are request handlers for this uri */
  12994. if (is_callback_resource) {
  12995. HTTP1_only;
  12996. if (!is_websocket_request) {
  12997. i = callback_handler(conn, callback_data);
  12998. /* Callback handler will not be used anymore. Release it */
  12999. release_handler_ref(conn, handler_info);
  13000. if (i > 0) {
  13001. /* Do nothing, callback has served the request. Store
  13002. * then return value as status code for the log and discard
  13003. * all data from the client not used by the callback. */
  13004. conn->status_code = i;
  13005. if (!conn->must_close) {
  13006. discard_unread_request_data(conn);
  13007. }
  13008. } else {
  13009. /* The handler did NOT handle the request. */
  13010. /* Some proper reactions would be:
  13011. * a) close the connections without sending anything
  13012. * b) send a 404 not found
  13013. * c) try if there is a file matching the URI
  13014. * It would be possible to do a, b or c in the callback
  13015. * implementation, and return 1 - we cannot do anything
  13016. * here, that is not possible in the callback.
  13017. *
  13018. * TODO: What would be the best reaction here?
  13019. * (Note: The reaction may change, if there is a better
  13020. * idea.)
  13021. */
  13022. /* For the moment, use option c: We look for a proper file,
  13023. * but since a file request is not always a script resource,
  13024. * the authorization check might be different. */
  13025. callback_handler = NULL;
  13026. /* Here we are at a dead end:
  13027. * According to URI matching, a callback should be
  13028. * responsible for handling the request,
  13029. * we called it, but the callback declared itself
  13030. * not responsible.
  13031. * We use a goto here, to get out of this dead end,
  13032. * and continue with the default handling.
  13033. * A goto here is simpler and better to understand
  13034. * than some curious loop. */
  13035. goto no_callback_resource;
  13036. }
  13037. } else {
  13038. #if defined(USE_WEBSOCKET)
  13039. handle_websocket_request(conn,
  13040. path,
  13041. is_callback_resource,
  13042. subprotocols,
  13043. ws_connect_handler,
  13044. ws_ready_handler,
  13045. ws_data_handler,
  13046. ws_close_handler,
  13047. callback_data);
  13048. #endif
  13049. }
  13050. DEBUG_TRACE("%s", "websocket handling done");
  13051. return;
  13052. }
  13053. /* 8. handle websocket requests */
  13054. #if defined(USE_WEBSOCKET)
  13055. if (is_websocket_request) {
  13056. HTTP1_only;
  13057. if (is_script_resource) {
  13058. if (is_in_script_path(conn, path)) {
  13059. /* Websocket Lua script */
  13060. handle_websocket_request(conn,
  13061. path,
  13062. 0 /* Lua Script */,
  13063. NULL,
  13064. NULL,
  13065. NULL,
  13066. NULL,
  13067. NULL,
  13068. conn->phys_ctx->user_data);
  13069. } else {
  13070. /* Script was in an illegal path */
  13071. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13072. }
  13073. } else {
  13074. mg_send_http_error(conn, 404, "%s", "Not found");
  13075. }
  13076. DEBUG_TRACE("%s", "websocket script done");
  13077. return;
  13078. } else
  13079. #endif
  13080. #if defined(NO_FILES)
  13081. /* 9a. In case the server uses only callbacks, this uri is
  13082. * unknown.
  13083. * Then, all request handling ends here. */
  13084. mg_send_http_error(conn, 404, "%s", "Not Found");
  13085. #else
  13086. /* 9b. This request is either for a static file or resource handled
  13087. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13088. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13089. mg_send_http_error(conn, 404, "%s", "Not Found");
  13090. DEBUG_TRACE("%s", "no document root available");
  13091. return;
  13092. }
  13093. /* 10. Request is handled by a script */
  13094. if (is_script_resource) {
  13095. HTTP1_only;
  13096. handle_file_based_request(conn, path, &file);
  13097. DEBUG_TRACE("%s", "script handling done");
  13098. return;
  13099. }
  13100. /* Request was not handled by a callback or script. It will be
  13101. * handled by a server internal method. */
  13102. /* 11. Handle put/delete/mkcol requests */
  13103. if (is_put_or_delete_request) {
  13104. HTTP1_only;
  13105. /* 11.1. PUT method */
  13106. if (!strcmp(ri->request_method, "PUT")) {
  13107. put_file(conn, path);
  13108. DEBUG_TRACE("handling %s request to %s done",
  13109. ri->request_method,
  13110. path);
  13111. return;
  13112. }
  13113. /* 11.2. DELETE method */
  13114. if (!strcmp(ri->request_method, "DELETE")) {
  13115. delete_file(conn, path);
  13116. DEBUG_TRACE("handling %s request to %s done",
  13117. ri->request_method,
  13118. path);
  13119. return;
  13120. }
  13121. /* 11.3. MKCOL method */
  13122. if (!strcmp(ri->request_method, "MKCOL")) {
  13123. dav_mkcol(conn, path);
  13124. DEBUG_TRACE("handling %s request to %s done",
  13125. ri->request_method,
  13126. path);
  13127. return;
  13128. }
  13129. /* 11.4. MOVE method */
  13130. if (!strcmp(ri->request_method, "MOVE")) {
  13131. dav_move_file(conn, path, 0);
  13132. DEBUG_TRACE("handling %s request to %s done",
  13133. ri->request_method,
  13134. path);
  13135. return;
  13136. }
  13137. if (!strcmp(ri->request_method, "COPY")) {
  13138. dav_move_file(conn, path, 1);
  13139. DEBUG_TRACE("handling %s request to %s done",
  13140. ri->request_method,
  13141. path);
  13142. return;
  13143. }
  13144. /* 11.5. LOCK method */
  13145. if (!strcmp(ri->request_method, "LOCK")) {
  13146. dav_lock_file(conn, path);
  13147. DEBUG_TRACE("handling %s request to %s done",
  13148. ri->request_method,
  13149. path);
  13150. return;
  13151. }
  13152. /* 11.6. UNLOCK method */
  13153. if (!strcmp(ri->request_method, "UNLOCK")) {
  13154. dav_unlock_file(conn, path);
  13155. DEBUG_TRACE("handling %s request to %s done",
  13156. ri->request_method,
  13157. path);
  13158. return;
  13159. }
  13160. /* 11.7. PROPPATCH method */
  13161. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13162. dav_proppatch(conn, path);
  13163. DEBUG_TRACE("handling %s request to %s done",
  13164. ri->request_method,
  13165. path);
  13166. return;
  13167. }
  13168. /* 11.8. Other methods, e.g.: PATCH
  13169. * This method is not supported for static resources,
  13170. * only for scripts (Lua, CGI) and callbacks. */
  13171. mg_send_http_error(conn,
  13172. 405,
  13173. "%s method not allowed",
  13174. conn->request_info.request_method);
  13175. DEBUG_TRACE("method %s on %s is not supported",
  13176. ri->request_method,
  13177. path);
  13178. return;
  13179. }
  13180. /* 11. File does not exist, or it was configured that it should be
  13181. * hidden */
  13182. if (!is_found || (must_hide_file(conn, path))) {
  13183. mg_send_http_error(conn, 404, "%s", "Not found");
  13184. DEBUG_TRACE("handling %s request to %s: file not found",
  13185. ri->request_method,
  13186. path);
  13187. return;
  13188. }
  13189. /* 12. Directory uris should end with a slash */
  13190. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13191. && (ri->local_uri[uri_len - 1] != '/')) {
  13192. /* Path + server root */
  13193. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13194. char *new_path;
  13195. if (ri->query_string) {
  13196. buflen += strlen(ri->query_string);
  13197. }
  13198. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13199. if (!new_path) {
  13200. mg_send_http_error(conn, 500, "out or memory");
  13201. } else {
  13202. mg_get_request_link(conn, new_path, buflen - 1);
  13203. strcat(new_path, "/");
  13204. if (ri->query_string) {
  13205. /* Append ? and query string */
  13206. strcat(new_path, "?");
  13207. strcat(new_path, ri->query_string);
  13208. }
  13209. mg_send_http_redirect(conn, new_path, 301);
  13210. mg_free(new_path);
  13211. }
  13212. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13213. ri->request_method,
  13214. path);
  13215. return;
  13216. }
  13217. /* 13. Handle other methods than GET/HEAD */
  13218. /* 13.1. Handle PROPFIND */
  13219. if (!strcmp(ri->request_method, "PROPFIND")) {
  13220. handle_propfind(conn, path, &file.stat);
  13221. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13222. return;
  13223. }
  13224. /* 13.2. Handle OPTIONS for files */
  13225. if (!strcmp(ri->request_method, "OPTIONS")) {
  13226. /* This standard handler is only used for real files.
  13227. * Scripts should support the OPTIONS method themselves, to allow a
  13228. * maximum flexibility.
  13229. * Lua and CGI scripts may fully support CORS this way (including
  13230. * preflights). */
  13231. send_options(conn);
  13232. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13233. return;
  13234. }
  13235. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13236. if ((0 != strcmp(ri->request_method, "GET"))
  13237. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13238. mg_send_http_error(conn,
  13239. 405,
  13240. "%s method not allowed",
  13241. conn->request_info.request_method);
  13242. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13243. return;
  13244. }
  13245. /* 14. directories */
  13246. if (file.stat.is_directory) {
  13247. /* Substitute files have already been handled above. */
  13248. /* Here we can either generate and send a directory listing,
  13249. * or send an "access denied" error. */
  13250. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13251. "yes")) {
  13252. handle_directory_request(conn, path);
  13253. } else {
  13254. mg_send_http_error(conn,
  13255. 403,
  13256. "%s",
  13257. "Error: Directory listing denied");
  13258. }
  13259. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13260. return;
  13261. }
  13262. /* 15. Files with search/replace patterns: LSP and SSI */
  13263. if (is_template_text_file) {
  13264. HTTP1_only;
  13265. handle_file_based_request(conn, path, &file);
  13266. DEBUG_TRACE("handling %s request to %s done (template)",
  13267. ri->request_method,
  13268. path);
  13269. return;
  13270. }
  13271. /* 16. Static file - maybe cached */
  13272. #if !defined(NO_CACHING)
  13273. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13274. /* Send 304 "Not Modified" - this must not send any body data */
  13275. handle_not_modified_static_file_request(conn, &file);
  13276. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13277. ri->request_method,
  13278. path);
  13279. return;
  13280. }
  13281. #endif /* !NO_CACHING */
  13282. /* 17. Static file - not cached */
  13283. handle_static_file_request(conn, path, &file, NULL, NULL);
  13284. DEBUG_TRACE("handling %s request to %s done (static)",
  13285. ri->request_method,
  13286. path);
  13287. #endif /* !defined(NO_FILES) */
  13288. }
  13289. #if !defined(NO_FILESYSTEMS)
  13290. static void
  13291. handle_file_based_request(struct mg_connection *conn,
  13292. const char *path,
  13293. struct mg_file *file)
  13294. {
  13295. #if !defined(NO_CGI)
  13296. int cgi_config_idx, inc, max;
  13297. #endif
  13298. if (!conn || !conn->dom_ctx) {
  13299. return;
  13300. }
  13301. #if defined(USE_LUA)
  13302. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13303. path)
  13304. > 0) {
  13305. if (is_in_script_path(conn, path)) {
  13306. /* Lua server page: an SSI like page containing mostly plain
  13307. * html code plus some tags with server generated contents. */
  13308. handle_lsp_request(conn, path, file, NULL);
  13309. } else {
  13310. /* Script was in an illegal path */
  13311. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13312. }
  13313. return;
  13314. }
  13315. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13316. > 0) {
  13317. if (is_in_script_path(conn, path)) {
  13318. /* Lua in-server module script: a CGI like script used to
  13319. * generate the entire reply. */
  13320. mg_exec_lua_script(conn, path, NULL);
  13321. } else {
  13322. /* Script was in an illegal path */
  13323. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13324. }
  13325. return;
  13326. }
  13327. #endif
  13328. #if defined(USE_DUKTAPE)
  13329. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13330. path)
  13331. > 0) {
  13332. if (is_in_script_path(conn, path)) {
  13333. /* Call duktape to generate the page */
  13334. mg_exec_duktape_script(conn, path);
  13335. } else {
  13336. /* Script was in an illegal path */
  13337. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13338. }
  13339. return;
  13340. }
  13341. #endif
  13342. #if !defined(NO_CGI)
  13343. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13344. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13345. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13346. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13347. if (match_prefix_strlen(
  13348. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13349. path)
  13350. > 0) {
  13351. if (is_in_script_path(conn, path)) {
  13352. /* CGI scripts may support all HTTP methods */
  13353. handle_cgi_request(conn, path, cgi_config_idx);
  13354. } else {
  13355. /* Script was in an illegal path */
  13356. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13357. }
  13358. return;
  13359. }
  13360. }
  13361. }
  13362. #endif /* !NO_CGI */
  13363. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13364. if (is_in_script_path(conn, path)) {
  13365. handle_ssi_file_request(conn, path, file);
  13366. } else {
  13367. /* Script was in an illegal path */
  13368. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13369. }
  13370. return;
  13371. }
  13372. #if !defined(NO_CACHING)
  13373. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13374. /* Send 304 "Not Modified" - this must not send any body data */
  13375. handle_not_modified_static_file_request(conn, file);
  13376. return;
  13377. }
  13378. #endif /* !NO_CACHING */
  13379. handle_static_file_request(conn, path, file, NULL, NULL);
  13380. }
  13381. #endif /* NO_FILESYSTEMS */
  13382. static void
  13383. close_all_listening_sockets(struct mg_context *ctx)
  13384. {
  13385. unsigned int i;
  13386. if (!ctx) {
  13387. return;
  13388. }
  13389. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13390. closesocket(ctx->listening_sockets[i].sock);
  13391. #if defined(USE_X_DOM_SOCKET)
  13392. /* For unix domain sockets, the socket name represents a file that has
  13393. * to be deleted. */
  13394. /* See
  13395. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13396. */
  13397. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13398. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13399. IGNORE_UNUSED_RESULT(
  13400. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13401. }
  13402. #endif
  13403. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13404. }
  13405. mg_free(ctx->listening_sockets);
  13406. ctx->listening_sockets = NULL;
  13407. mg_free(ctx->listening_socket_fds);
  13408. ctx->listening_socket_fds = NULL;
  13409. }
  13410. /* Valid listening port specification is: [ip_address:]port[s]
  13411. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13412. * Examples for IPv6: [::]:80, [::1]:80,
  13413. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13414. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13415. * In order to bind to both, IPv4 and IPv6, you can either add
  13416. * both ports using 8080,[::]:8080, or the short form +8080.
  13417. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13418. * one only accepting IPv4 the other only IPv6. +8080 creates
  13419. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13420. * environment, they might work differently, or might not work
  13421. * at all - it must be tested what options work best in the
  13422. * relevant network environment.
  13423. */
  13424. static int
  13425. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13426. {
  13427. unsigned int a, b, c, d;
  13428. unsigned port;
  13429. unsigned long portUL;
  13430. int ch, len;
  13431. const char *cb;
  13432. char *endptr;
  13433. #if defined(USE_IPV6)
  13434. char buf[100] = {0};
  13435. #endif
  13436. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13437. * Also, all-zeroes in the socket address means binding to all addresses
  13438. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13439. memset(so, 0, sizeof(*so));
  13440. so->lsa.sin.sin_family = AF_INET;
  13441. *ip_version = 0;
  13442. /* Initialize len as invalid. */
  13443. port = 0;
  13444. len = 0;
  13445. /* Test for different ways to format this string */
  13446. if (sscanf(vec->ptr,
  13447. "%u.%u.%u.%u:%u%n",
  13448. &a,
  13449. &b,
  13450. &c,
  13451. &d,
  13452. &port,
  13453. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13454. // to an integer value, but function will not report
  13455. // conversion errors; consider using 'strtol' instead
  13456. == 5) {
  13457. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13458. so->lsa.sin.sin_addr.s_addr =
  13459. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13460. so->lsa.sin.sin_port = htons((uint16_t)port);
  13461. *ip_version = 4;
  13462. #if defined(USE_IPV6)
  13463. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13464. && ((size_t)len <= vec->len)
  13465. && mg_inet_pton(
  13466. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13467. /* IPv6 address, examples: see above */
  13468. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13469. */
  13470. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13471. *ip_version = 6;
  13472. #endif
  13473. } else if ((vec->ptr[0] == '+')
  13474. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13475. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13476. // string to an integer value, but function will not
  13477. // report conversion errors; consider using 'strtol'
  13478. // instead
  13479. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13480. /* Add 1 to len for the + character we skipped before */
  13481. len++;
  13482. #if defined(USE_IPV6)
  13483. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13484. so->lsa.sin6.sin6_family = AF_INET6;
  13485. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13486. *ip_version = 4 + 6;
  13487. #else
  13488. /* Bind to IPv4 only, since IPv6 is not built in. */
  13489. so->lsa.sin.sin_port = htons((uint16_t)port);
  13490. *ip_version = 4;
  13491. #endif
  13492. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13493. && (vec->ptr != endptr)) {
  13494. len = (int)(endptr - vec->ptr);
  13495. port = (uint16_t)portUL;
  13496. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13497. so->lsa.sin.sin_port = htons((uint16_t)port);
  13498. *ip_version = 4;
  13499. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13500. /* String could be a hostname. This check algorithm
  13501. * will only work for RFC 952 compliant hostnames,
  13502. * starting with a letter, containing only letters,
  13503. * digits and hyphen ('-'). Newer specs may allow
  13504. * more, but this is not guaranteed here, since it
  13505. * may interfere with rules for port option lists. */
  13506. /* According to RFC 1035, hostnames are restricted to 255 characters
  13507. * in total (63 between two dots). */
  13508. char hostname[256];
  13509. size_t hostnlen = (size_t)(cb - vec->ptr);
  13510. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13511. /* This would be invalid in any case */
  13512. *ip_version = 0;
  13513. return 0;
  13514. }
  13515. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13516. if (mg_inet_pton(
  13517. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13518. if (sscanf(cb + 1, "%u%n", &port, &len)
  13519. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13520. // string to an integer value, but function will not
  13521. // report conversion errors; consider using 'strtol'
  13522. // instead
  13523. *ip_version = 4;
  13524. so->lsa.sin.sin_port = htons((uint16_t)port);
  13525. len += (int)(hostnlen + 1);
  13526. } else {
  13527. len = 0;
  13528. }
  13529. #if defined(USE_IPV6)
  13530. } else if (mg_inet_pton(AF_INET6,
  13531. hostname,
  13532. &so->lsa.sin6,
  13533. sizeof(so->lsa.sin6),
  13534. 1)) {
  13535. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13536. *ip_version = 6;
  13537. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13538. len += (int)(hostnlen + 1);
  13539. } else {
  13540. len = 0;
  13541. }
  13542. #endif
  13543. } else {
  13544. len = 0;
  13545. }
  13546. #if defined(USE_X_DOM_SOCKET)
  13547. } else if (vec->ptr[0] == 'x') {
  13548. /* unix (linux) domain socket */
  13549. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13550. len = vec->len;
  13551. so->lsa.sun.sun_family = AF_UNIX;
  13552. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13553. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13554. port = 0;
  13555. *ip_version = 99;
  13556. } else {
  13557. /* String too long */
  13558. len = 0;
  13559. }
  13560. #endif
  13561. } else {
  13562. /* Parsing failure. */
  13563. len = 0;
  13564. }
  13565. /* sscanf and the option splitting code ensure the following condition
  13566. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13567. if ((len > 0) && is_valid_port(port)
  13568. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13569. /* Next character after the port number */
  13570. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13571. so->is_ssl = (ch == 's');
  13572. so->ssl_redir = (ch == 'r');
  13573. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13574. return 1;
  13575. }
  13576. }
  13577. /* Reset ip_version to 0 if there is an error */
  13578. *ip_version = 0;
  13579. return 0;
  13580. }
  13581. /* Is there any SSL port in use? */
  13582. static int
  13583. is_ssl_port_used(const char *ports)
  13584. {
  13585. if (ports) {
  13586. /* There are several different allowed syntax variants:
  13587. * - "80" for a single port using every network interface
  13588. * - "localhost:80" for a single port using only localhost
  13589. * - "80,localhost:8080" for two ports, one bound to localhost
  13590. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13591. * to IPv4 localhost, one to IPv6 localhost
  13592. * - "+80" use port 80 for IPv4 and IPv6
  13593. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13594. * for both: IPv4 and IPv4
  13595. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13596. * additionally port 8080 bound to localhost connections
  13597. *
  13598. * If we just look for 's' anywhere in the string, "localhost:80"
  13599. * will be detected as SSL (false positive).
  13600. * Looking for 's' after a digit may cause false positives in
  13601. * "my24service:8080".
  13602. * Looking from 's' backward if there are only ':' and numbers
  13603. * before will not work for "24service:8080" (non SSL, port 8080)
  13604. * or "24s" (SSL, port 24).
  13605. *
  13606. * Remark: Initially hostnames were not allowed to start with a
  13607. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13608. * Section 2.1).
  13609. *
  13610. * To get this correct, the entire string must be parsed as a whole,
  13611. * reading it as a list element for element and parsing with an
  13612. * algorithm equivalent to parse_port_string.
  13613. *
  13614. * In fact, we use local interface names here, not arbitrary
  13615. * hostnames, so in most cases the only name will be "localhost".
  13616. *
  13617. * So, for now, we use this simple algorithm, that may still return
  13618. * a false positive in bizarre cases.
  13619. */
  13620. int i;
  13621. int portslen = (int)strlen(ports);
  13622. char prevIsNumber = 0;
  13623. for (i = 0; i < portslen; i++) {
  13624. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13625. return 1;
  13626. }
  13627. if (ports[i] >= '0' && ports[i] <= '9') {
  13628. prevIsNumber = 1;
  13629. } else {
  13630. prevIsNumber = 0;
  13631. }
  13632. }
  13633. }
  13634. return 0;
  13635. }
  13636. static int
  13637. set_ports_option(struct mg_context *phys_ctx)
  13638. {
  13639. const char *list;
  13640. int on = 1;
  13641. #if defined(USE_IPV6)
  13642. int off = 0;
  13643. #endif
  13644. struct vec vec;
  13645. struct socket so, *ptr;
  13646. struct mg_pollfd *pfd;
  13647. union usa usa;
  13648. socklen_t len;
  13649. int ip_version;
  13650. int portsTotal = 0;
  13651. int portsOk = 0;
  13652. const char *opt_txt;
  13653. long opt_listen_backlog;
  13654. if (!phys_ctx) {
  13655. return 0;
  13656. }
  13657. memset(&so, 0, sizeof(so));
  13658. memset(&usa, 0, sizeof(usa));
  13659. len = sizeof(usa);
  13660. list = phys_ctx->dd.config[LISTENING_PORTS];
  13661. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13662. portsTotal++;
  13663. if (!parse_port_string(&vec, &so, &ip_version)) {
  13664. mg_cry_ctx_internal(
  13665. phys_ctx,
  13666. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13667. (int)vec.len,
  13668. vec.ptr,
  13669. portsTotal,
  13670. "[IP_ADDRESS:]PORT[s|r]");
  13671. continue;
  13672. }
  13673. #if !defined(NO_SSL)
  13674. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13675. mg_cry_ctx_internal(phys_ctx,
  13676. "Cannot add SSL socket (entry %i)",
  13677. portsTotal);
  13678. continue;
  13679. }
  13680. #endif
  13681. /* Create socket. */
  13682. /* For a list of protocol numbers (e.g., TCP==6) see:
  13683. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13684. */
  13685. if ((so.sock =
  13686. socket(so.lsa.sa.sa_family,
  13687. SOCK_STREAM,
  13688. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13689. == INVALID_SOCKET) {
  13690. mg_cry_ctx_internal(phys_ctx,
  13691. "cannot create socket (entry %i)",
  13692. portsTotal);
  13693. continue;
  13694. }
  13695. #if defined(_WIN32)
  13696. /* Windows SO_REUSEADDR lets many procs binds to a
  13697. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13698. * if someone already has the socket -- DTL */
  13699. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13700. * Windows might need a few seconds before
  13701. * the same port can be used again in the
  13702. * same process, so a short Sleep may be
  13703. * required between mg_stop and mg_start.
  13704. */
  13705. if (setsockopt(so.sock,
  13706. SOL_SOCKET,
  13707. SO_EXCLUSIVEADDRUSE,
  13708. (SOCK_OPT_TYPE)&on,
  13709. sizeof(on))
  13710. != 0) {
  13711. /* Set reuse option, but don't abort on errors. */
  13712. mg_cry_ctx_internal(
  13713. phys_ctx,
  13714. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13715. portsTotal);
  13716. }
  13717. #else
  13718. if (setsockopt(so.sock,
  13719. SOL_SOCKET,
  13720. SO_REUSEADDR,
  13721. (SOCK_OPT_TYPE)&on,
  13722. sizeof(on))
  13723. != 0) {
  13724. /* Set reuse option, but don't abort on errors. */
  13725. mg_cry_ctx_internal(
  13726. phys_ctx,
  13727. "cannot set socket option SO_REUSEADDR (entry %i)",
  13728. portsTotal);
  13729. }
  13730. #endif
  13731. #if defined(USE_X_DOM_SOCKET)
  13732. if (ip_version == 99) {
  13733. /* Unix domain socket */
  13734. } else
  13735. #endif
  13736. if (ip_version > 4) {
  13737. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13738. #if defined(USE_IPV6)
  13739. if (ip_version > 6) {
  13740. if (so.lsa.sa.sa_family == AF_INET6
  13741. && setsockopt(so.sock,
  13742. IPPROTO_IPV6,
  13743. IPV6_V6ONLY,
  13744. (void *)&off,
  13745. sizeof(off))
  13746. != 0) {
  13747. /* Set IPv6 only option, but don't abort on errors. */
  13748. mg_cry_ctx_internal(phys_ctx,
  13749. "cannot set socket option "
  13750. "IPV6_V6ONLY=off (entry %i)",
  13751. portsTotal);
  13752. }
  13753. } else {
  13754. if (so.lsa.sa.sa_family == AF_INET6
  13755. && setsockopt(so.sock,
  13756. IPPROTO_IPV6,
  13757. IPV6_V6ONLY,
  13758. (void *)&on,
  13759. sizeof(on))
  13760. != 0) {
  13761. /* Set IPv6 only option, but don't abort on errors. */
  13762. mg_cry_ctx_internal(phys_ctx,
  13763. "cannot set socket option "
  13764. "IPV6_V6ONLY=on (entry %i)",
  13765. portsTotal);
  13766. }
  13767. }
  13768. #else
  13769. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13770. closesocket(so.sock);
  13771. so.sock = INVALID_SOCKET;
  13772. continue;
  13773. #endif
  13774. }
  13775. if (so.lsa.sa.sa_family == AF_INET) {
  13776. len = sizeof(so.lsa.sin);
  13777. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13778. mg_cry_ctx_internal(phys_ctx,
  13779. "cannot bind to %.*s: %d (%s)",
  13780. (int)vec.len,
  13781. vec.ptr,
  13782. (int)ERRNO,
  13783. strerror(errno));
  13784. closesocket(so.sock);
  13785. so.sock = INVALID_SOCKET;
  13786. continue;
  13787. }
  13788. }
  13789. #if defined(USE_IPV6)
  13790. else if (so.lsa.sa.sa_family == AF_INET6) {
  13791. len = sizeof(so.lsa.sin6);
  13792. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13793. mg_cry_ctx_internal(phys_ctx,
  13794. "cannot bind to IPv6 %.*s: %d (%s)",
  13795. (int)vec.len,
  13796. vec.ptr,
  13797. (int)ERRNO,
  13798. strerror(errno));
  13799. closesocket(so.sock);
  13800. so.sock = INVALID_SOCKET;
  13801. continue;
  13802. }
  13803. }
  13804. #endif
  13805. #if defined(USE_X_DOM_SOCKET)
  13806. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13807. len = sizeof(so.lsa.sun);
  13808. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13809. mg_cry_ctx_internal(phys_ctx,
  13810. "cannot bind to unix socket %s: %d (%s)",
  13811. so.lsa.sun.sun_path,
  13812. (int)ERRNO,
  13813. strerror(errno));
  13814. closesocket(so.sock);
  13815. so.sock = INVALID_SOCKET;
  13816. continue;
  13817. }
  13818. }
  13819. #endif
  13820. else {
  13821. mg_cry_ctx_internal(
  13822. phys_ctx,
  13823. "cannot bind: address family not supported (entry %i)",
  13824. portsTotal);
  13825. closesocket(so.sock);
  13826. so.sock = INVALID_SOCKET;
  13827. continue;
  13828. }
  13829. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13830. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13831. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13832. mg_cry_ctx_internal(phys_ctx,
  13833. "%s value \"%s\" is invalid",
  13834. config_options[LISTEN_BACKLOG_SIZE].name,
  13835. opt_txt);
  13836. closesocket(so.sock);
  13837. so.sock = INVALID_SOCKET;
  13838. continue;
  13839. }
  13840. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13841. mg_cry_ctx_internal(phys_ctx,
  13842. "cannot listen to %.*s: %d (%s)",
  13843. (int)vec.len,
  13844. vec.ptr,
  13845. (int)ERRNO,
  13846. strerror(errno));
  13847. closesocket(so.sock);
  13848. so.sock = INVALID_SOCKET;
  13849. continue;
  13850. }
  13851. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13852. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13853. int err = (int)ERRNO;
  13854. mg_cry_ctx_internal(phys_ctx,
  13855. "call to getsockname failed %.*s: %d (%s)",
  13856. (int)vec.len,
  13857. vec.ptr,
  13858. err,
  13859. strerror(errno));
  13860. closesocket(so.sock);
  13861. so.sock = INVALID_SOCKET;
  13862. continue;
  13863. }
  13864. /* Update lsa port in case of random free ports */
  13865. #if defined(USE_IPV6)
  13866. if (so.lsa.sa.sa_family == AF_INET6) {
  13867. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13868. } else
  13869. #endif
  13870. {
  13871. so.lsa.sin.sin_port = usa.sin.sin_port;
  13872. }
  13873. if ((ptr = (struct socket *)
  13874. mg_realloc_ctx(phys_ctx->listening_sockets,
  13875. (phys_ctx->num_listening_sockets + 1)
  13876. * sizeof(phys_ctx->listening_sockets[0]),
  13877. phys_ctx))
  13878. == NULL) {
  13879. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13880. closesocket(so.sock);
  13881. so.sock = INVALID_SOCKET;
  13882. continue;
  13883. }
  13884. if ((pfd = (struct mg_pollfd *)
  13885. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13886. (phys_ctx->num_listening_sockets + 1)
  13887. * sizeof(phys_ctx->listening_socket_fds[0]),
  13888. phys_ctx))
  13889. == NULL) {
  13890. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13891. closesocket(so.sock);
  13892. so.sock = INVALID_SOCKET;
  13893. mg_free(ptr);
  13894. continue;
  13895. }
  13896. set_close_on_exec(so.sock, NULL, phys_ctx);
  13897. phys_ctx->listening_sockets = ptr;
  13898. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13899. phys_ctx->listening_socket_fds = pfd;
  13900. phys_ctx->num_listening_sockets++;
  13901. portsOk++;
  13902. }
  13903. if (portsOk != portsTotal) {
  13904. close_all_listening_sockets(phys_ctx);
  13905. portsOk = 0;
  13906. }
  13907. return portsOk;
  13908. }
  13909. static const char *
  13910. header_val(const struct mg_connection *conn, const char *header)
  13911. {
  13912. const char *header_value;
  13913. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13914. return "-";
  13915. } else {
  13916. return header_value;
  13917. }
  13918. }
  13919. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13920. #include "external_log_access.inl"
  13921. #elif !defined(NO_FILESYSTEMS)
  13922. static void
  13923. log_access(const struct mg_connection *conn)
  13924. {
  13925. const struct mg_request_info *ri;
  13926. struct mg_file fi;
  13927. char date[64], src_addr[IP_ADDR_STR_LEN];
  13928. #if defined(REENTRANT_TIME)
  13929. struct tm _tm;
  13930. struct tm *tm = &_tm;
  13931. #else
  13932. struct tm *tm;
  13933. #endif
  13934. const char *referer;
  13935. const char *user_agent;
  13936. char log_buf[4096];
  13937. if (!conn || !conn->dom_ctx) {
  13938. return;
  13939. }
  13940. /* Set log message to "empty" */
  13941. log_buf[0] = 0;
  13942. #if defined(USE_LUA)
  13943. if (conn->phys_ctx->lua_bg_log_available) {
  13944. int ret;
  13945. struct mg_context *ctx = conn->phys_ctx;
  13946. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13947. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13948. /* call "log()" in Lua */
  13949. lua_getglobal(lstate, "log");
  13950. prepare_lua_request_info_inner(conn, lstate);
  13951. push_lua_response_log_data(conn, lstate);
  13952. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13953. if (ret == 0) {
  13954. int t = lua_type(lstate, -1);
  13955. if (t == LUA_TBOOLEAN) {
  13956. if (lua_toboolean(lstate, -1) == 0) {
  13957. /* log() returned false: do not log */
  13958. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13959. return;
  13960. }
  13961. /* log returned true: continue logging */
  13962. } else if (t == LUA_TSTRING) {
  13963. size_t len;
  13964. const char *txt = lua_tolstring(lstate, -1, &len);
  13965. if ((len == 0) || (*txt == 0)) {
  13966. /* log() returned empty string: do not log */
  13967. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13968. return;
  13969. }
  13970. /* Copy test from Lua into log_buf */
  13971. if (len >= sizeof(log_buf)) {
  13972. len = sizeof(log_buf) - 1;
  13973. }
  13974. memcpy(log_buf, txt, len);
  13975. log_buf[len] = 0;
  13976. }
  13977. } else {
  13978. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13979. }
  13980. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13981. }
  13982. #endif
  13983. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13984. if (mg_fopen(conn,
  13985. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13986. MG_FOPEN_MODE_APPEND,
  13987. &fi)
  13988. == 0) {
  13989. fi.access.fp = NULL;
  13990. }
  13991. } else {
  13992. fi.access.fp = NULL;
  13993. }
  13994. /* Log is written to a file and/or a callback. If both are not set,
  13995. * executing the rest of the function is pointless. */
  13996. if ((fi.access.fp == NULL)
  13997. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13998. return;
  13999. }
  14000. /* If we did not get a log message from Lua, create it here. */
  14001. if (!log_buf[0]) {
  14002. #if defined(REENTRANT_TIME)
  14003. localtime_r(&conn->conn_birth_time, tm);
  14004. #else
  14005. tm = localtime(&conn->conn_birth_time);
  14006. #endif
  14007. if (tm != NULL) {
  14008. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14009. } else {
  14010. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14011. }
  14012. ri = &conn->request_info;
  14013. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14014. referer = header_val(conn, "Referer");
  14015. user_agent = header_val(conn, "User-Agent");
  14016. mg_snprintf(conn,
  14017. NULL, /* Ignore truncation in access log */
  14018. log_buf,
  14019. sizeof(log_buf),
  14020. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14021. " %s %s",
  14022. src_addr,
  14023. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14024. date,
  14025. ri->request_method ? ri->request_method : "-",
  14026. ri->request_uri ? ri->request_uri : "-",
  14027. ri->query_string ? "?" : "",
  14028. ri->query_string ? ri->query_string : "",
  14029. ri->http_version,
  14030. conn->status_code,
  14031. conn->num_bytes_sent,
  14032. referer,
  14033. user_agent);
  14034. }
  14035. /* Here we have a log message in log_buf. Call the callback */
  14036. if (conn->phys_ctx->callbacks.log_access) {
  14037. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14038. /* do not log if callback returns non-zero */
  14039. if (fi.access.fp) {
  14040. mg_fclose(&fi.access);
  14041. }
  14042. return;
  14043. }
  14044. }
  14045. /* Store in file */
  14046. if (fi.access.fp) {
  14047. int ok = 1;
  14048. flockfile(fi.access.fp);
  14049. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14050. ok = 0;
  14051. }
  14052. if (fflush(fi.access.fp) != 0) {
  14053. ok = 0;
  14054. }
  14055. funlockfile(fi.access.fp);
  14056. if (mg_fclose(&fi.access) != 0) {
  14057. ok = 0;
  14058. }
  14059. if (!ok) {
  14060. mg_cry_internal(conn,
  14061. "Error writing log file %s",
  14062. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14063. }
  14064. }
  14065. }
  14066. #else
  14067. #error "Either enable filesystems or provide a custom log_access implementation"
  14068. #endif /* Externally provided function */
  14069. /* Verify given socket address against the ACL.
  14070. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14071. */
  14072. static int
  14073. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14074. {
  14075. int allowed, flag, matched;
  14076. struct vec vec;
  14077. if (phys_ctx) {
  14078. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14079. /* If any ACL is set, deny by default */
  14080. allowed = (list == NULL) ? '+' : '-';
  14081. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14082. flag = vec.ptr[0];
  14083. matched = -1;
  14084. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14085. vec.ptr++;
  14086. vec.len--;
  14087. matched = parse_match_net(&vec, sa, 1);
  14088. }
  14089. if (matched < 0) {
  14090. mg_cry_ctx_internal(phys_ctx,
  14091. "%s: subnet must be [+|-]IP-addr[/x]",
  14092. __func__);
  14093. return -1;
  14094. }
  14095. if (matched) {
  14096. allowed = flag;
  14097. }
  14098. }
  14099. return allowed == '+';
  14100. }
  14101. return -1;
  14102. }
  14103. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14104. static int
  14105. set_uid_option(struct mg_context *phys_ctx)
  14106. {
  14107. int success = 0;
  14108. if (phys_ctx) {
  14109. /* We are currently running as curr_uid. */
  14110. const uid_t curr_uid = getuid();
  14111. /* If set, we want to run as run_as_user. */
  14112. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14113. const struct passwd *to_pw = NULL;
  14114. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14115. /* run_as_user does not exist on the system. We can't proceed
  14116. * further. */
  14117. mg_cry_ctx_internal(phys_ctx,
  14118. "%s: unknown user [%s]",
  14119. __func__,
  14120. run_as_user);
  14121. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14122. /* There was either no request to change user, or we're already
  14123. * running as run_as_user. Nothing else to do.
  14124. */
  14125. success = 1;
  14126. } else {
  14127. /* Valid change request. */
  14128. if (setgid(to_pw->pw_gid) == -1) {
  14129. mg_cry_ctx_internal(phys_ctx,
  14130. "%s: setgid(%s): %s",
  14131. __func__,
  14132. run_as_user,
  14133. strerror(errno));
  14134. } else if (setgroups(0, NULL) == -1) {
  14135. mg_cry_ctx_internal(phys_ctx,
  14136. "%s: setgroups(): %s",
  14137. __func__,
  14138. strerror(errno));
  14139. } else if (setuid(to_pw->pw_uid) == -1) {
  14140. mg_cry_ctx_internal(phys_ctx,
  14141. "%s: setuid(%s): %s",
  14142. __func__,
  14143. run_as_user,
  14144. strerror(errno));
  14145. } else {
  14146. success = 1;
  14147. }
  14148. }
  14149. }
  14150. return success;
  14151. }
  14152. #endif /* !_WIN32 */
  14153. static void
  14154. tls_dtor(void *key)
  14155. {
  14156. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14157. /* key == pthread_getspecific(sTlsKey); */
  14158. if (tls) {
  14159. if (tls->is_master == 2) {
  14160. tls->is_master = -3; /* Mark memory as dead */
  14161. mg_free(tls);
  14162. }
  14163. }
  14164. pthread_setspecific(sTlsKey, NULL);
  14165. }
  14166. #if defined(USE_MBEDTLS)
  14167. /* Check if SSL is required.
  14168. * If so, set up ctx->ssl_ctx pointer. */
  14169. static int
  14170. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14171. {
  14172. if (!phys_ctx) {
  14173. return 0;
  14174. }
  14175. if (!dom_ctx) {
  14176. dom_ctx = &(phys_ctx->dd);
  14177. }
  14178. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14179. /* No SSL port is set. No need to setup SSL. */
  14180. return 1;
  14181. }
  14182. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14183. if (dom_ctx->ssl_ctx == NULL) {
  14184. fprintf(stderr, "ssl_ctx malloc failed\n");
  14185. return 0;
  14186. }
  14187. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14188. == 0
  14189. ? 1
  14190. : 0;
  14191. }
  14192. #elif !defined(NO_SSL)
  14193. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14194. struct mg_domain_context *dom_ctx,
  14195. const char *pem,
  14196. const char *chain);
  14197. static const char *ssl_error(void);
  14198. static int
  14199. refresh_trust(struct mg_connection *conn)
  14200. {
  14201. struct stat cert_buf;
  14202. int64_t t = 0;
  14203. const char *pem;
  14204. const char *chain;
  14205. int should_verify_peer;
  14206. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14207. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14208. * refresh_trust still can not work. */
  14209. return 0;
  14210. }
  14211. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14212. if (chain == NULL) {
  14213. /* pem is not NULL here */
  14214. chain = pem;
  14215. }
  14216. if (*chain == 0) {
  14217. chain = NULL;
  14218. }
  14219. if (stat(pem, &cert_buf) != -1) {
  14220. t = (int64_t)cert_buf.st_mtime;
  14221. }
  14222. mg_lock_context(conn->phys_ctx);
  14223. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14224. conn->dom_ctx->ssl_cert_last_mtime = t;
  14225. should_verify_peer = 0;
  14226. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14227. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14228. == 0) {
  14229. should_verify_peer = 1;
  14230. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14231. "optional")
  14232. == 0) {
  14233. should_verify_peer = 1;
  14234. }
  14235. }
  14236. if (should_verify_peer) {
  14237. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14238. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14239. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14240. ca_file,
  14241. ca_path)
  14242. != 1) {
  14243. mg_unlock_context(conn->phys_ctx);
  14244. mg_cry_ctx_internal(
  14245. conn->phys_ctx,
  14246. "SSL_CTX_load_verify_locations error: %s "
  14247. "ssl_verify_peer requires setting "
  14248. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14249. "present in "
  14250. "the .conf file?",
  14251. ssl_error());
  14252. return 0;
  14253. }
  14254. }
  14255. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14256. mg_unlock_context(conn->phys_ctx);
  14257. return 0;
  14258. }
  14259. }
  14260. mg_unlock_context(conn->phys_ctx);
  14261. return 1;
  14262. }
  14263. #if defined(OPENSSL_API_1_1)
  14264. #else
  14265. static pthread_mutex_t *ssl_mutexes;
  14266. #endif /* OPENSSL_API_1_1 */
  14267. static int
  14268. sslize(struct mg_connection *conn,
  14269. int (*func)(SSL *),
  14270. const struct mg_client_options *client_options)
  14271. {
  14272. int ret, err;
  14273. int short_trust;
  14274. unsigned timeout = 1024;
  14275. unsigned i;
  14276. if (!conn) {
  14277. return 0;
  14278. }
  14279. short_trust =
  14280. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14281. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14282. if (short_trust) {
  14283. int trust_ret = refresh_trust(conn);
  14284. if (!trust_ret) {
  14285. return trust_ret;
  14286. }
  14287. }
  14288. mg_lock_context(conn->phys_ctx);
  14289. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14290. mg_unlock_context(conn->phys_ctx);
  14291. if (conn->ssl == NULL) {
  14292. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14293. OPENSSL_REMOVE_THREAD_STATE();
  14294. return 0;
  14295. }
  14296. SSL_set_app_data(conn->ssl, (char *)conn);
  14297. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14298. if (ret != 1) {
  14299. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14300. SSL_free(conn->ssl);
  14301. conn->ssl = NULL;
  14302. OPENSSL_REMOVE_THREAD_STATE();
  14303. return 0;
  14304. }
  14305. if (client_options) {
  14306. if (client_options->host_name) {
  14307. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14308. }
  14309. }
  14310. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14311. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14312. /* NOTE: The loop below acts as a back-off, so we can end
  14313. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14314. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14315. if (to >= 0) {
  14316. timeout = (unsigned)to;
  14317. }
  14318. }
  14319. /* SSL functions may fail and require to be called again:
  14320. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14321. * Here "func" could be SSL_connect or SSL_accept. */
  14322. for (i = 0; i <= timeout; i += 50) {
  14323. ERR_clear_error();
  14324. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14325. ret = func(conn->ssl);
  14326. if (ret != 1) {
  14327. err = SSL_get_error(conn->ssl, ret);
  14328. if ((err == SSL_ERROR_WANT_CONNECT)
  14329. || (err == SSL_ERROR_WANT_ACCEPT)
  14330. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14331. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14332. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14333. /* Don't wait if the server is going to be stopped. */
  14334. break;
  14335. }
  14336. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14337. /* Simply retry the function call. */
  14338. mg_sleep(50);
  14339. } else {
  14340. /* Need to retry the function call "later".
  14341. * See https://linux.die.net/man/3/ssl_get_error
  14342. * This is typical for non-blocking sockets. */
  14343. struct mg_pollfd pfd;
  14344. int pollres;
  14345. pfd.fd = conn->client.sock;
  14346. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14347. || (err == SSL_ERROR_WANT_WRITE))
  14348. ? POLLOUT
  14349. : POLLIN;
  14350. pollres =
  14351. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14352. if (pollres < 0) {
  14353. /* Break if error occurred (-1)
  14354. * or server shutdown (-2) */
  14355. break;
  14356. }
  14357. }
  14358. } else if (err == SSL_ERROR_SYSCALL) {
  14359. /* This is an IO error. Look at errno. */
  14360. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14361. break;
  14362. } else {
  14363. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14364. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14365. break;
  14366. }
  14367. } else {
  14368. /* success */
  14369. break;
  14370. }
  14371. }
  14372. ERR_clear_error();
  14373. if (ret != 1) {
  14374. SSL_free(conn->ssl);
  14375. conn->ssl = NULL;
  14376. OPENSSL_REMOVE_THREAD_STATE();
  14377. return 0;
  14378. }
  14379. return 1;
  14380. }
  14381. /* Return OpenSSL error message (from CRYPTO lib) */
  14382. static const char *
  14383. ssl_error(void)
  14384. {
  14385. unsigned long err;
  14386. err = ERR_get_error();
  14387. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14388. }
  14389. static int
  14390. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14391. {
  14392. int i;
  14393. const char hexdigit[] = "0123456789abcdef";
  14394. if ((memlen <= 0) || (buflen <= 0)) {
  14395. return 0;
  14396. }
  14397. if (buflen < (3 * memlen)) {
  14398. return 0;
  14399. }
  14400. for (i = 0; i < memlen; i++) {
  14401. if (i > 0) {
  14402. buf[3 * i - 1] = ' ';
  14403. }
  14404. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14405. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14406. }
  14407. buf[3 * memlen - 1] = 0;
  14408. return 1;
  14409. }
  14410. static int
  14411. ssl_get_client_cert_info(const struct mg_connection *conn,
  14412. struct mg_client_cert *client_cert)
  14413. {
  14414. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14415. if (cert) {
  14416. char str_buf[1024];
  14417. unsigned char buf[256];
  14418. char *str_serial = NULL;
  14419. unsigned int ulen;
  14420. int ilen;
  14421. unsigned char *tmp_buf;
  14422. unsigned char *tmp_p;
  14423. /* Handle to algorithm used for fingerprint */
  14424. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14425. /* Get Subject and issuer */
  14426. X509_NAME *subj = X509_get_subject_name(cert);
  14427. X509_NAME *iss = X509_get_issuer_name(cert);
  14428. /* Get serial number */
  14429. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14430. /* Translate serial number to a hex string */
  14431. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14432. if (serial_bn) {
  14433. str_serial = BN_bn2hex(serial_bn);
  14434. BN_free(serial_bn);
  14435. }
  14436. client_cert->serial =
  14437. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14438. /* Translate subject and issuer to a string */
  14439. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14440. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14441. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14442. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14443. /* Calculate SHA1 fingerprint and store as a hex string */
  14444. ulen = 0;
  14445. /* ASN1_digest is deprecated. Do the calculation manually,
  14446. * using EVP_Digest. */
  14447. ilen = i2d_X509(cert, NULL);
  14448. tmp_buf = (ilen > 0)
  14449. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14450. conn->phys_ctx)
  14451. : NULL;
  14452. if (tmp_buf) {
  14453. tmp_p = tmp_buf;
  14454. (void)i2d_X509(cert, &tmp_p);
  14455. if (!EVP_Digest(
  14456. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14457. ulen = 0;
  14458. }
  14459. mg_free(tmp_buf);
  14460. }
  14461. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14462. *str_buf = 0;
  14463. }
  14464. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14465. client_cert->peer_cert = (void *)cert;
  14466. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14467. * see https://linux.die.net/man/3/bn_bn2hex */
  14468. OPENSSL_free(str_serial);
  14469. return 1;
  14470. }
  14471. return 0;
  14472. }
  14473. #if defined(OPENSSL_API_1_1)
  14474. #else
  14475. static void
  14476. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14477. {
  14478. (void)line;
  14479. (void)file;
  14480. if (mode & 1) {
  14481. /* 1 is CRYPTO_LOCK */
  14482. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14483. } else {
  14484. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14485. }
  14486. }
  14487. #endif /* OPENSSL_API_1_1 */
  14488. #if !defined(NO_SSL_DL)
  14489. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14490. static void *
  14491. load_tls_dll(char *ebuf,
  14492. size_t ebuf_len,
  14493. const char *dll_name,
  14494. struct ssl_func *sw,
  14495. int *feature_missing)
  14496. {
  14497. union {
  14498. void *p;
  14499. void (*fp)(void);
  14500. } u;
  14501. void *dll_handle;
  14502. struct ssl_func *fp;
  14503. int ok;
  14504. int truncated = 0;
  14505. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14506. mg_snprintf(NULL,
  14507. NULL, /* No truncation check for ebuf */
  14508. ebuf,
  14509. ebuf_len,
  14510. "%s: cannot load %s",
  14511. __func__,
  14512. dll_name);
  14513. return NULL;
  14514. }
  14515. ok = 1;
  14516. for (fp = sw; fp->name != NULL; fp++) {
  14517. #if defined(_WIN32)
  14518. /* GetProcAddress() returns pointer to function */
  14519. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14520. #else
  14521. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14522. * pointers to function pointers. We need to use a union to make a
  14523. * cast. */
  14524. u.p = dlsym(dll_handle, fp->name);
  14525. #endif /* _WIN32 */
  14526. /* Set pointer (might be NULL) */
  14527. fp->ptr = u.fp;
  14528. if (u.fp == NULL) {
  14529. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14530. if (feature_missing) {
  14531. feature_missing[fp->required]++;
  14532. }
  14533. if (fp->required == TLS_Mandatory) {
  14534. /* Mandatory function is missing */
  14535. if (ok) {
  14536. /* This is the first missing function.
  14537. * Create a new error message. */
  14538. mg_snprintf(NULL,
  14539. &truncated,
  14540. ebuf,
  14541. ebuf_len,
  14542. "%s: %s: cannot find %s",
  14543. __func__,
  14544. dll_name,
  14545. fp->name);
  14546. ok = 0;
  14547. } else {
  14548. /* This is yet anothermissing function.
  14549. * Append existing error message. */
  14550. size_t cur_len = strlen(ebuf);
  14551. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14552. mg_snprintf(NULL,
  14553. &truncated,
  14554. ebuf + cur_len,
  14555. ebuf_len - cur_len - 3,
  14556. ", %s",
  14557. fp->name);
  14558. if (truncated) {
  14559. /* If truncated, add "..." */
  14560. strcat(ebuf, "...");
  14561. }
  14562. }
  14563. }
  14564. }
  14565. }
  14566. }
  14567. if (!ok) {
  14568. (void)dlclose(dll_handle);
  14569. return NULL;
  14570. }
  14571. return dll_handle;
  14572. }
  14573. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14574. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14575. #endif /* NO_SSL_DL */
  14576. #if defined(SSL_ALREADY_INITIALIZED)
  14577. static volatile ptrdiff_t cryptolib_users =
  14578. 1; /* Reference counter for crypto library. */
  14579. #else
  14580. static volatile ptrdiff_t cryptolib_users =
  14581. 0; /* Reference counter for crypto library. */
  14582. #endif
  14583. static int
  14584. initialize_openssl(char *ebuf, size_t ebuf_len)
  14585. {
  14586. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14587. int i, num_locks;
  14588. size_t size;
  14589. #endif
  14590. if (ebuf_len > 0) {
  14591. ebuf[0] = 0;
  14592. }
  14593. #if !defined(NO_SSL_DL)
  14594. if (!cryptolib_dll_handle) {
  14595. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14596. cryptolib_dll_handle = load_tls_dll(
  14597. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14598. if (!cryptolib_dll_handle) {
  14599. mg_snprintf(NULL,
  14600. NULL, /* No truncation check for ebuf */
  14601. ebuf,
  14602. ebuf_len,
  14603. "%s: error loading library %s",
  14604. __func__,
  14605. CRYPTO_LIB);
  14606. DEBUG_TRACE("%s", ebuf);
  14607. return 0;
  14608. }
  14609. }
  14610. #endif /* NO_SSL_DL */
  14611. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14612. return 1;
  14613. }
  14614. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14615. /* Initialize locking callbacks, needed for thread safety.
  14616. * http://www.openssl.org/support/faq.html#PROG1
  14617. */
  14618. num_locks = CRYPTO_num_locks();
  14619. if (num_locks < 0) {
  14620. num_locks = 0;
  14621. }
  14622. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14623. /* allocate mutex array, if required */
  14624. if (num_locks == 0) {
  14625. /* No mutex array required */
  14626. ssl_mutexes = NULL;
  14627. } else {
  14628. /* Mutex array required - allocate it */
  14629. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14630. /* Check OOM */
  14631. if (ssl_mutexes == NULL) {
  14632. mg_snprintf(NULL,
  14633. NULL, /* No truncation check for ebuf */
  14634. ebuf,
  14635. ebuf_len,
  14636. "%s: cannot allocate mutexes: %s",
  14637. __func__,
  14638. ssl_error());
  14639. DEBUG_TRACE("%s", ebuf);
  14640. return 0;
  14641. }
  14642. /* initialize mutex array */
  14643. for (i = 0; i < num_locks; i++) {
  14644. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14645. mg_snprintf(NULL,
  14646. NULL, /* No truncation check for ebuf */
  14647. ebuf,
  14648. ebuf_len,
  14649. "%s: error initializing mutex %i of %i",
  14650. __func__,
  14651. i,
  14652. num_locks);
  14653. DEBUG_TRACE("%s", ebuf);
  14654. mg_free(ssl_mutexes);
  14655. return 0;
  14656. }
  14657. }
  14658. }
  14659. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14660. CRYPTO_set_id_callback(&mg_current_thread_id);
  14661. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14662. #if !defined(NO_SSL_DL)
  14663. if (!ssllib_dll_handle) {
  14664. ssllib_dll_handle =
  14665. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14666. if (!ssllib_dll_handle) {
  14667. #if !defined(OPENSSL_API_1_1)
  14668. mg_free(ssl_mutexes);
  14669. #endif
  14670. DEBUG_TRACE("%s", ebuf);
  14671. return 0;
  14672. }
  14673. }
  14674. #endif /* NO_SSL_DL */
  14675. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14676. && !defined(NO_SSL_DL)
  14677. /* Initialize SSL library */
  14678. OPENSSL_init_ssl(0, NULL);
  14679. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14680. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14681. NULL);
  14682. #else
  14683. /* Initialize SSL library */
  14684. SSL_library_init();
  14685. SSL_load_error_strings();
  14686. #endif
  14687. return 1;
  14688. }
  14689. static int
  14690. ssl_use_pem_file(struct mg_context *phys_ctx,
  14691. struct mg_domain_context *dom_ctx,
  14692. const char *pem,
  14693. const char *chain)
  14694. {
  14695. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14696. mg_cry_ctx_internal(phys_ctx,
  14697. "%s: cannot open certificate file %s: %s",
  14698. __func__,
  14699. pem,
  14700. ssl_error());
  14701. return 0;
  14702. }
  14703. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14704. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14705. mg_cry_ctx_internal(phys_ctx,
  14706. "%s: cannot open private key file %s: %s",
  14707. __func__,
  14708. pem,
  14709. ssl_error());
  14710. return 0;
  14711. }
  14712. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14713. mg_cry_ctx_internal(phys_ctx,
  14714. "%s: certificate and private key do not match: %s",
  14715. __func__,
  14716. pem);
  14717. return 0;
  14718. }
  14719. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14720. * chain files that contain private keys and certificates in
  14721. * SSL_CTX_use_certificate_chain_file.
  14722. * The CivetWeb-Server used pem-Files that contained both information.
  14723. * In order to make wolfSSL work, it is split in two files.
  14724. * One file that contains key and certificate used by the server and
  14725. * an optional chain file for the ssl stack.
  14726. */
  14727. if (chain) {
  14728. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14729. mg_cry_ctx_internal(phys_ctx,
  14730. "%s: cannot use certificate chain file %s: %s",
  14731. __func__,
  14732. chain,
  14733. ssl_error());
  14734. return 0;
  14735. }
  14736. }
  14737. return 1;
  14738. }
  14739. #if defined(OPENSSL_API_1_1)
  14740. static unsigned long
  14741. ssl_get_protocol(int version_id)
  14742. {
  14743. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14744. if (version_id > 0)
  14745. ret |= SSL_OP_NO_SSLv2;
  14746. if (version_id > 1)
  14747. ret |= SSL_OP_NO_SSLv3;
  14748. if (version_id > 2)
  14749. ret |= SSL_OP_NO_TLSv1;
  14750. if (version_id > 3)
  14751. ret |= SSL_OP_NO_TLSv1_1;
  14752. if (version_id > 4)
  14753. ret |= SSL_OP_NO_TLSv1_2;
  14754. #if defined(SSL_OP_NO_TLSv1_3)
  14755. if (version_id > 5)
  14756. ret |= SSL_OP_NO_TLSv1_3;
  14757. #endif
  14758. return ret;
  14759. }
  14760. #else
  14761. static long
  14762. ssl_get_protocol(int version_id)
  14763. {
  14764. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14765. if (version_id > 0)
  14766. ret |= SSL_OP_NO_SSLv2;
  14767. if (version_id > 1)
  14768. ret |= SSL_OP_NO_SSLv3;
  14769. if (version_id > 2)
  14770. ret |= SSL_OP_NO_TLSv1;
  14771. if (version_id > 3)
  14772. ret |= SSL_OP_NO_TLSv1_1;
  14773. if (version_id > 4)
  14774. ret |= SSL_OP_NO_TLSv1_2;
  14775. #if defined(SSL_OP_NO_TLSv1_3)
  14776. if (version_id > 5)
  14777. ret |= SSL_OP_NO_TLSv1_3;
  14778. #endif
  14779. return (long)ret;
  14780. }
  14781. #endif /* OPENSSL_API_1_1 */
  14782. /* SSL callback documentation:
  14783. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14784. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14785. * https://linux.die.net/man/3/ssl_set_info_callback */
  14786. /* Note: There is no "const" for the first argument in the documentation
  14787. * examples, however some (maybe most, but not all) headers of OpenSSL
  14788. * versions / OpenSSL compatibility layers have it. Having a different
  14789. * definition will cause a warning in C and an error in C++. Use "const SSL
  14790. * *", while automatic conversion from "SSL *" works for all compilers,
  14791. * but not other way around */
  14792. static void
  14793. ssl_info_callback(const SSL *ssl, int what, int ret)
  14794. {
  14795. (void)ret;
  14796. if (what & SSL_CB_HANDSHAKE_START) {
  14797. SSL_get_app_data(ssl);
  14798. }
  14799. if (what & SSL_CB_HANDSHAKE_DONE) {
  14800. /* TODO: check for openSSL 1.1 */
  14801. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14802. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14803. }
  14804. }
  14805. static int
  14806. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14807. {
  14808. #if defined(GCC_DIAGNOSTIC)
  14809. #pragma GCC diagnostic push
  14810. #pragma GCC diagnostic ignored "-Wcast-align"
  14811. #endif /* defined(GCC_DIAGNOSTIC) */
  14812. /* We used an aligned pointer in SSL_set_app_data */
  14813. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14814. #if defined(GCC_DIAGNOSTIC)
  14815. #pragma GCC diagnostic pop
  14816. #endif /* defined(GCC_DIAGNOSTIC) */
  14817. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14818. (void)ad;
  14819. (void)arg;
  14820. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14821. DEBUG_ASSERT(0);
  14822. return SSL_TLSEXT_ERR_NOACK;
  14823. }
  14824. conn->dom_ctx = &(conn->phys_ctx->dd);
  14825. /* Old clients (Win XP) will not support SNI. Then, there
  14826. * is no server name available in the request - we can
  14827. * only work with the default certificate.
  14828. * Multiple HTTPS hosts on one IP+port are only possible
  14829. * with a certificate containing all alternative names.
  14830. */
  14831. if ((servername == NULL) || (*servername == 0)) {
  14832. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14833. mg_lock_context(conn->phys_ctx);
  14834. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14835. mg_unlock_context(conn->phys_ctx);
  14836. return SSL_TLSEXT_ERR_NOACK;
  14837. }
  14838. DEBUG_TRACE("TLS connection to host %s", servername);
  14839. while (conn->dom_ctx) {
  14840. if (!mg_strcasecmp(servername,
  14841. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14842. /* Found matching domain */
  14843. DEBUG_TRACE("TLS domain %s found",
  14844. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14845. break;
  14846. }
  14847. mg_lock_context(conn->phys_ctx);
  14848. conn->dom_ctx = conn->dom_ctx->next;
  14849. mg_unlock_context(conn->phys_ctx);
  14850. }
  14851. if (conn->dom_ctx == NULL) {
  14852. /* Default domain */
  14853. DEBUG_TRACE("TLS default domain %s used",
  14854. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14855. conn->dom_ctx = &(conn->phys_ctx->dd);
  14856. }
  14857. mg_lock_context(conn->phys_ctx);
  14858. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14859. mg_unlock_context(conn->phys_ctx);
  14860. return SSL_TLSEXT_ERR_OK;
  14861. }
  14862. #if defined(USE_ALPN)
  14863. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14864. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14865. alpn_proto_list + 3 + 8,
  14866. NULL};
  14867. #if defined(USE_HTTP2)
  14868. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14869. alpn_proto_list + 3,
  14870. alpn_proto_list + 3 + 8,
  14871. NULL};
  14872. #endif
  14873. static int
  14874. alpn_select_cb(SSL *ssl,
  14875. const unsigned char **out,
  14876. unsigned char *outlen,
  14877. const unsigned char *in,
  14878. unsigned int inlen,
  14879. void *arg)
  14880. {
  14881. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14882. unsigned int i, j, enable_http2 = 0;
  14883. const char **alpn_proto_order = alpn_proto_order_http1;
  14884. struct mg_workerTLS *tls =
  14885. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14886. (void)ssl;
  14887. if (tls == NULL) {
  14888. /* Need to store protocol in Thread Local Storage */
  14889. /* If there is no Thread Local Storage, don't use ALPN */
  14890. return SSL_TLSEXT_ERR_NOACK;
  14891. }
  14892. #if defined(USE_HTTP2)
  14893. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14894. if (enable_http2) {
  14895. alpn_proto_order = alpn_proto_order_http2;
  14896. }
  14897. #endif
  14898. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14899. /* check all accepted protocols in this order */
  14900. const char *alpn_proto = alpn_proto_order[j];
  14901. /* search input for matching protocol */
  14902. for (i = 0; i < inlen; i++) {
  14903. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14904. *out = in + i + 1;
  14905. *outlen = in[i];
  14906. tls->alpn_proto = alpn_proto;
  14907. return SSL_TLSEXT_ERR_OK;
  14908. }
  14909. }
  14910. }
  14911. /* Nothing found */
  14912. return SSL_TLSEXT_ERR_NOACK;
  14913. }
  14914. static int
  14915. next_protos_advertised_cb(SSL *ssl,
  14916. const unsigned char **data,
  14917. unsigned int *len,
  14918. void *arg)
  14919. {
  14920. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14921. *data = (const unsigned char *)alpn_proto_list;
  14922. *len = (unsigned int)strlen((const char *)data);
  14923. (void)ssl;
  14924. (void)dom_ctx;
  14925. return SSL_TLSEXT_ERR_OK;
  14926. }
  14927. static int
  14928. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14929. {
  14930. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14931. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14932. (const unsigned char *)alpn_proto_list,
  14933. alpn_len);
  14934. if (ret != 0) {
  14935. mg_cry_ctx_internal(phys_ctx,
  14936. "SSL_CTX_set_alpn_protos error: %s",
  14937. ssl_error());
  14938. }
  14939. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14940. alpn_select_cb,
  14941. (void *)dom_ctx);
  14942. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14943. next_protos_advertised_cb,
  14944. (void *)dom_ctx);
  14945. return ret;
  14946. }
  14947. #endif
  14948. /* Setup SSL CTX as required by CivetWeb */
  14949. static int
  14950. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14951. struct mg_domain_context *dom_ctx,
  14952. const char *pem,
  14953. const char *chain)
  14954. {
  14955. int callback_ret;
  14956. int should_verify_peer;
  14957. int peer_certificate_optional;
  14958. const char *ca_path;
  14959. const char *ca_file;
  14960. int use_default_verify_paths;
  14961. int verify_depth;
  14962. struct timespec now_mt;
  14963. md5_byte_t ssl_context_id[16];
  14964. md5_state_t md5state;
  14965. int protocol_ver;
  14966. int ssl_cache_timeout;
  14967. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14968. && !defined(NO_SSL_DL)
  14969. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14970. mg_cry_ctx_internal(phys_ctx,
  14971. "SSL_CTX_new (server) error: %s",
  14972. ssl_error());
  14973. return 0;
  14974. }
  14975. #else
  14976. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14977. mg_cry_ctx_internal(phys_ctx,
  14978. "SSL_CTX_new (server) error: %s",
  14979. ssl_error());
  14980. return 0;
  14981. }
  14982. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14983. #if defined(SSL_OP_NO_TLSv1_3)
  14984. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14985. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14986. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14987. | SSL_OP_NO_TLSv1_3);
  14988. #else
  14989. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14990. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14991. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14992. #endif
  14993. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14994. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14995. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14996. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14997. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14998. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14999. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15000. #if defined(SSL_OP_NO_RENEGOTIATION)
  15001. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15002. #endif
  15003. #if !defined(NO_SSL_DL)
  15004. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15005. #endif /* NO_SSL_DL */
  15006. /* In SSL documentation examples callback defined without const
  15007. * specifier 'void (*)(SSL *, int, int)' See:
  15008. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15009. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15010. * But in the source code const SSL is used:
  15011. * 'void (*)(const SSL *, int, int)' See:
  15012. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15013. * Problem about wrong documentation described, but not resolved:
  15014. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15015. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15016. * But when compiled with modern C++ compiler, correct const should be
  15017. * provided
  15018. */
  15019. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15020. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15021. ssl_servername_callback);
  15022. /* If a callback has been specified, call it. */
  15023. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15024. ? 0
  15025. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15026. phys_ctx->user_data));
  15027. /* If callback returns 0, civetweb sets up the SSL certificate.
  15028. * If it returns 1, civetweb assumes the callback already did this.
  15029. * If it returns -1, initializing ssl fails. */
  15030. if (callback_ret < 0) {
  15031. mg_cry_ctx_internal(phys_ctx,
  15032. "SSL callback returned error: %i",
  15033. callback_ret);
  15034. return 0;
  15035. }
  15036. if (callback_ret > 0) {
  15037. /* Callback did everything. */
  15038. return 1;
  15039. }
  15040. /* If a domain callback has been specified, call it. */
  15041. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15042. ? 0
  15043. : (phys_ctx->callbacks.init_ssl_domain(
  15044. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15045. dom_ctx->ssl_ctx,
  15046. phys_ctx->user_data));
  15047. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15048. * If it returns 1, civetweb assumes the callback already did this.
  15049. * If it returns -1, initializing ssl fails. */
  15050. if (callback_ret < 0) {
  15051. mg_cry_ctx_internal(phys_ctx,
  15052. "Domain SSL callback returned error: %i",
  15053. callback_ret);
  15054. return 0;
  15055. }
  15056. if (callback_ret > 0) {
  15057. /* Domain callback did everything. */
  15058. return 1;
  15059. }
  15060. /* Use some combination of start time, domain and port as a SSL
  15061. * context ID. This should be unique on the current machine. */
  15062. md5_init(&md5state);
  15063. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15064. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15065. md5_append(&md5state,
  15066. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15067. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15068. md5_append(&md5state,
  15069. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15070. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15071. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15072. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15073. md5_finish(&md5state, ssl_context_id);
  15074. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15075. (unsigned char *)ssl_context_id,
  15076. sizeof(ssl_context_id));
  15077. if (pem != NULL) {
  15078. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15079. return 0;
  15080. }
  15081. }
  15082. /* Should we support client certificates? */
  15083. /* Default is "no". */
  15084. should_verify_peer = 0;
  15085. peer_certificate_optional = 0;
  15086. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15087. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15088. /* Yes, they are mandatory */
  15089. should_verify_peer = 1;
  15090. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15091. "optional")
  15092. == 0) {
  15093. /* Yes, they are optional */
  15094. should_verify_peer = 1;
  15095. peer_certificate_optional = 1;
  15096. }
  15097. }
  15098. use_default_verify_paths =
  15099. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15100. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15101. == 0);
  15102. if (should_verify_peer) {
  15103. ca_path = dom_ctx->config[SSL_CA_PATH];
  15104. ca_file = dom_ctx->config[SSL_CA_FILE];
  15105. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15106. != 1) {
  15107. mg_cry_ctx_internal(phys_ctx,
  15108. "SSL_CTX_load_verify_locations error: %s "
  15109. "ssl_verify_peer requires setting "
  15110. "either ssl_ca_path or ssl_ca_file. "
  15111. "Is any of them present in the "
  15112. ".conf file?",
  15113. ssl_error());
  15114. return 0;
  15115. }
  15116. if (peer_certificate_optional) {
  15117. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15118. } else {
  15119. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15120. SSL_VERIFY_PEER
  15121. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15122. NULL);
  15123. }
  15124. if (use_default_verify_paths
  15125. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15126. mg_cry_ctx_internal(phys_ctx,
  15127. "SSL_CTX_set_default_verify_paths error: %s",
  15128. ssl_error());
  15129. return 0;
  15130. }
  15131. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15132. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15133. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15134. }
  15135. }
  15136. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15137. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15138. dom_ctx->config[SSL_CIPHER_LIST])
  15139. != 1) {
  15140. mg_cry_ctx_internal(phys_ctx,
  15141. "SSL_CTX_set_cipher_list error: %s",
  15142. ssl_error());
  15143. }
  15144. }
  15145. /* SSL session caching */
  15146. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15147. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15148. : 0);
  15149. if (ssl_cache_timeout > 0) {
  15150. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15151. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15152. * default */
  15153. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15154. }
  15155. #if defined(USE_ALPN)
  15156. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15157. #if !defined(NO_SSL_DL)
  15158. if (!tls_feature_missing[TLS_ALPN])
  15159. #endif
  15160. {
  15161. init_alpn(phys_ctx, dom_ctx);
  15162. }
  15163. #endif
  15164. return 1;
  15165. }
  15166. /* Check if SSL is required.
  15167. * If so, dynamically load SSL library
  15168. * and set up ctx->ssl_ctx pointer. */
  15169. static int
  15170. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15171. {
  15172. void *ssl_ctx = 0;
  15173. int callback_ret;
  15174. const char *pem;
  15175. const char *chain;
  15176. char ebuf[128];
  15177. if (!phys_ctx) {
  15178. return 0;
  15179. }
  15180. if (!dom_ctx) {
  15181. dom_ctx = &(phys_ctx->dd);
  15182. }
  15183. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15184. /* No SSL port is set. No need to setup SSL. */
  15185. return 1;
  15186. }
  15187. /* Check for external SSL_CTX */
  15188. callback_ret =
  15189. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15190. ? 0
  15191. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15192. phys_ctx->user_data));
  15193. if (callback_ret < 0) {
  15194. /* Callback exists and returns <0: Initializing failed. */
  15195. mg_cry_ctx_internal(phys_ctx,
  15196. "external_ssl_ctx callback returned error: %i",
  15197. callback_ret);
  15198. return 0;
  15199. } else if (callback_ret > 0) {
  15200. /* Callback exists and returns >0: Initializing complete,
  15201. * civetweb should not modify the SSL context. */
  15202. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15203. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15204. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15205. return 0;
  15206. }
  15207. return 1;
  15208. }
  15209. /* If the callback does not exist or return 0, civetweb must initialize
  15210. * the SSL context. Handle "domain" callback next. */
  15211. /* Check for external domain SSL_CTX callback. */
  15212. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15213. ? 0
  15214. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15215. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15216. &ssl_ctx,
  15217. phys_ctx->user_data));
  15218. if (callback_ret < 0) {
  15219. /* Callback < 0: Error. Abort init. */
  15220. mg_cry_ctx_internal(
  15221. phys_ctx,
  15222. "external_ssl_ctx_domain callback returned error: %i",
  15223. callback_ret);
  15224. return 0;
  15225. } else if (callback_ret > 0) {
  15226. /* Callback > 0: Consider init done. */
  15227. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15228. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15229. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15230. return 0;
  15231. }
  15232. return 1;
  15233. }
  15234. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15235. * 0, CivetWeb should continue initializing SSL */
  15236. /* If PEM file is not specified and the init_ssl callbacks
  15237. * are not specified, setup will fail. */
  15238. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15239. && (phys_ctx->callbacks.init_ssl == NULL)
  15240. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15241. /* No certificate and no init_ssl callbacks:
  15242. * Essential data to set up TLS is missing.
  15243. */
  15244. mg_cry_ctx_internal(phys_ctx,
  15245. "Initializing SSL failed: -%s is not set",
  15246. config_options[SSL_CERTIFICATE].name);
  15247. return 0;
  15248. }
  15249. /* If a certificate chain is configured, use it. */
  15250. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15251. if (chain == NULL) {
  15252. /* Default: certificate chain in PEM file */
  15253. chain = pem;
  15254. }
  15255. if ((chain != NULL) && (*chain == 0)) {
  15256. /* If the chain is an empty string, don't use it. */
  15257. chain = NULL;
  15258. }
  15259. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15260. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15261. return 0;
  15262. }
  15263. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15264. }
  15265. static void
  15266. uninitialize_openssl(void)
  15267. {
  15268. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15269. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15270. /* Shutdown according to
  15271. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15272. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15273. */
  15274. CONF_modules_unload(1);
  15275. #else
  15276. int i;
  15277. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15278. /* Shutdown according to
  15279. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15280. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15281. */
  15282. CRYPTO_set_locking_callback(NULL);
  15283. CRYPTO_set_id_callback(NULL);
  15284. ENGINE_cleanup();
  15285. CONF_modules_unload(1);
  15286. ERR_free_strings();
  15287. EVP_cleanup();
  15288. CRYPTO_cleanup_all_ex_data();
  15289. OPENSSL_REMOVE_THREAD_STATE();
  15290. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15291. pthread_mutex_destroy(&ssl_mutexes[i]);
  15292. }
  15293. mg_free(ssl_mutexes);
  15294. ssl_mutexes = NULL;
  15295. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15296. }
  15297. }
  15298. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15299. #if !defined(NO_FILESYSTEMS)
  15300. static int
  15301. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15302. {
  15303. if (phys_ctx) {
  15304. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15305. const char *path;
  15306. struct mg_connection fc;
  15307. if (!dom_ctx) {
  15308. dom_ctx = &(phys_ctx->dd);
  15309. }
  15310. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15311. if ((path != NULL)
  15312. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15313. mg_cry_ctx_internal(phys_ctx,
  15314. "Cannot open %s: %s",
  15315. path,
  15316. strerror(ERRNO));
  15317. return 0;
  15318. }
  15319. return 1;
  15320. }
  15321. return 0;
  15322. }
  15323. #endif /* NO_FILESYSTEMS */
  15324. static int
  15325. set_acl_option(struct mg_context *phys_ctx)
  15326. {
  15327. union usa sa;
  15328. memset(&sa, 0, sizeof(sa));
  15329. #if defined(USE_IPV6)
  15330. sa.sin6.sin6_family = AF_INET6;
  15331. #else
  15332. sa.sin.sin_family = AF_INET;
  15333. #endif
  15334. return check_acl(phys_ctx, &sa) != -1;
  15335. }
  15336. static void
  15337. reset_per_request_attributes(struct mg_connection *conn)
  15338. {
  15339. if (!conn) {
  15340. return;
  15341. }
  15342. conn->num_bytes_sent = conn->consumed_content = 0;
  15343. conn->path_info = NULL;
  15344. conn->status_code = -1;
  15345. conn->content_len = -1;
  15346. conn->is_chunked = 0;
  15347. conn->must_close = 0;
  15348. conn->request_len = 0;
  15349. conn->request_state = 0;
  15350. conn->throttle = 0;
  15351. conn->accept_gzip = 0;
  15352. conn->response_info.content_length = conn->request_info.content_length = -1;
  15353. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15354. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15355. conn->response_info.status_text = NULL;
  15356. conn->response_info.status_code = 0;
  15357. conn->request_info.remote_user = NULL;
  15358. conn->request_info.request_method = NULL;
  15359. conn->request_info.request_uri = NULL;
  15360. /* Free cleaned local URI (if any) */
  15361. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15362. mg_free((void *)conn->request_info.local_uri);
  15363. conn->request_info.local_uri = NULL;
  15364. }
  15365. conn->request_info.local_uri = NULL;
  15366. #if defined(USE_SERVER_STATS)
  15367. conn->processing_time = 0;
  15368. #endif
  15369. }
  15370. static int
  15371. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15372. {
  15373. if ((so->lsa.sa.sa_family == AF_INET)
  15374. || (so->lsa.sa.sa_family == AF_INET6)) {
  15375. /* Only for TCP sockets */
  15376. if (setsockopt(so->sock,
  15377. IPPROTO_TCP,
  15378. TCP_NODELAY,
  15379. (SOCK_OPT_TYPE)&nodelay_on,
  15380. sizeof(nodelay_on))
  15381. != 0) {
  15382. /* Error */
  15383. return 1;
  15384. }
  15385. }
  15386. /* OK */
  15387. return 0;
  15388. }
  15389. #if !defined(__ZEPHYR__)
  15390. static void
  15391. close_socket_gracefully(struct mg_connection *conn)
  15392. {
  15393. #if defined(_WIN32)
  15394. char buf[MG_BUF_LEN];
  15395. int n;
  15396. #endif
  15397. struct linger linger;
  15398. int error_code = 0;
  15399. int linger_timeout = -2;
  15400. socklen_t opt_len = sizeof(error_code);
  15401. if (!conn) {
  15402. return;
  15403. }
  15404. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15405. * "Note that enabling a nonzero timeout on a nonblocking socket
  15406. * is not recommended.", so set it to blocking now */
  15407. set_blocking_mode(conn->client.sock);
  15408. /* Send FIN to the client */
  15409. shutdown(conn->client.sock, SHUTDOWN_WR);
  15410. #if defined(_WIN32)
  15411. /* Read and discard pending incoming data. If we do not do that and
  15412. * close
  15413. * the socket, the data in the send buffer may be discarded. This
  15414. * behaviour is seen on Windows, when client keeps sending data
  15415. * when server decides to close the connection; then when client
  15416. * does recv() it gets no data back. */
  15417. do {
  15418. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15419. } while (n > 0);
  15420. #endif
  15421. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15422. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15423. }
  15424. /* Set linger option according to configuration */
  15425. if (linger_timeout >= 0) {
  15426. /* Set linger option to avoid socket hanging out after close. This
  15427. * prevent ephemeral port exhaust problem under high QPS. */
  15428. linger.l_onoff = 1;
  15429. #if defined(_MSC_VER)
  15430. #pragma warning(push)
  15431. #pragma warning(disable : 4244)
  15432. #endif
  15433. #if defined(GCC_DIAGNOSTIC)
  15434. #pragma GCC diagnostic push
  15435. #pragma GCC diagnostic ignored "-Wconversion"
  15436. #endif
  15437. /* Data type of linger structure elements may differ,
  15438. * so we don't know what cast we need here.
  15439. * Disable type conversion warnings. */
  15440. linger.l_linger = (linger_timeout + 999) / 1000;
  15441. #if defined(GCC_DIAGNOSTIC)
  15442. #pragma GCC diagnostic pop
  15443. #endif
  15444. #if defined(_MSC_VER)
  15445. #pragma warning(pop)
  15446. #endif
  15447. } else {
  15448. linger.l_onoff = 0;
  15449. linger.l_linger = 0;
  15450. }
  15451. if (linger_timeout < -1) {
  15452. /* Default: don't configure any linger */
  15453. } else if (getsockopt(conn->client.sock,
  15454. SOL_SOCKET,
  15455. SO_ERROR,
  15456. #if defined(_WIN32) /* WinSock uses different data type here */
  15457. (char *)&error_code,
  15458. #else
  15459. &error_code,
  15460. #endif
  15461. &opt_len)
  15462. != 0) {
  15463. /* Cannot determine if socket is already closed. This should
  15464. * not occur and never did in a test. Log an error message
  15465. * and continue. */
  15466. mg_cry_internal(conn,
  15467. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15468. __func__,
  15469. strerror(ERRNO));
  15470. #if defined(_WIN32)
  15471. } else if (error_code == WSAECONNRESET) {
  15472. #else
  15473. } else if (error_code == ECONNRESET) {
  15474. #endif
  15475. /* Socket already closed by client/peer, close socket without linger
  15476. */
  15477. } else {
  15478. /* Set linger timeout */
  15479. if (setsockopt(conn->client.sock,
  15480. SOL_SOCKET,
  15481. SO_LINGER,
  15482. (char *)&linger,
  15483. sizeof(linger))
  15484. != 0) {
  15485. mg_cry_internal(
  15486. conn,
  15487. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15488. __func__,
  15489. linger.l_onoff,
  15490. linger.l_linger,
  15491. strerror(ERRNO));
  15492. }
  15493. }
  15494. /* Now we know that our FIN is ACK-ed, safe to close */
  15495. closesocket(conn->client.sock);
  15496. conn->client.sock = INVALID_SOCKET;
  15497. }
  15498. #endif
  15499. static void
  15500. close_connection(struct mg_connection *conn)
  15501. {
  15502. #if defined(USE_SERVER_STATS)
  15503. conn->conn_state = 6; /* to close */
  15504. #endif
  15505. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15506. if (conn->lua_websocket_state) {
  15507. lua_websocket_close(conn, conn->lua_websocket_state);
  15508. conn->lua_websocket_state = NULL;
  15509. }
  15510. #endif
  15511. mg_lock_connection(conn);
  15512. /* Set close flag, so keep-alive loops will stop */
  15513. conn->must_close = 1;
  15514. /* call the connection_close callback if assigned */
  15515. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15516. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15517. conn->phys_ctx->callbacks.connection_close(conn);
  15518. }
  15519. }
  15520. /* Reset user data, after close callback is called.
  15521. * Do not reuse it. If the user needs a destructor,
  15522. * it must be done in the connection_close callback. */
  15523. mg_set_user_connection_data(conn, NULL);
  15524. #if defined(USE_SERVER_STATS)
  15525. conn->conn_state = 7; /* closing */
  15526. #endif
  15527. #if defined(USE_MBEDTLS)
  15528. if (conn->ssl != NULL) {
  15529. mbed_ssl_close(conn->ssl);
  15530. conn->ssl = NULL;
  15531. }
  15532. #elif !defined(NO_SSL)
  15533. if (conn->ssl != NULL) {
  15534. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15535. */
  15536. SSL_shutdown(conn->ssl);
  15537. SSL_free(conn->ssl);
  15538. OPENSSL_REMOVE_THREAD_STATE();
  15539. conn->ssl = NULL;
  15540. }
  15541. #endif
  15542. if (conn->client.sock != INVALID_SOCKET) {
  15543. #if defined(__ZEPHYR__)
  15544. closesocket(conn->client.sock);
  15545. #else
  15546. close_socket_gracefully(conn);
  15547. #endif
  15548. conn->client.sock = INVALID_SOCKET;
  15549. }
  15550. /* call the connection_closed callback if assigned */
  15551. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15552. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15553. conn->phys_ctx->callbacks.connection_closed(conn);
  15554. }
  15555. }
  15556. mg_unlock_connection(conn);
  15557. #if defined(USE_SERVER_STATS)
  15558. conn->conn_state = 8; /* closed */
  15559. #endif
  15560. }
  15561. CIVETWEB_API void
  15562. mg_close_connection(struct mg_connection *conn)
  15563. {
  15564. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15565. return;
  15566. }
  15567. #if defined(USE_WEBSOCKET)
  15568. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15569. if (conn->in_websocket_handling) {
  15570. /* Set close flag, so the server thread can exit. */
  15571. conn->must_close = 1;
  15572. return;
  15573. }
  15574. }
  15575. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15576. unsigned int i;
  15577. /* client context: loops must end */
  15578. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15579. conn->must_close = 1;
  15580. /* We need to get the client thread out of the select/recv call
  15581. * here. */
  15582. /* Since we use a sleep quantum of some seconds to check for recv
  15583. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15584. /* join worker thread */
  15585. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15586. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15587. }
  15588. }
  15589. #endif /* defined(USE_WEBSOCKET) */
  15590. close_connection(conn);
  15591. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15592. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15593. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15594. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15595. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15596. }
  15597. #endif
  15598. #if defined(USE_WEBSOCKET)
  15599. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15600. mg_free(conn->phys_ctx->worker_threadids);
  15601. (void)pthread_mutex_destroy(&conn->mutex);
  15602. mg_free(conn);
  15603. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15604. (void)pthread_mutex_destroy(&conn->mutex);
  15605. mg_free(conn);
  15606. }
  15607. #else
  15608. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15609. (void)pthread_mutex_destroy(&conn->mutex);
  15610. mg_free(conn);
  15611. }
  15612. #endif /* defined(USE_WEBSOCKET) */
  15613. }
  15614. static struct mg_connection *
  15615. mg_connect_client_impl(const struct mg_client_options *client_options,
  15616. int use_ssl,
  15617. struct mg_init_data *init,
  15618. struct mg_error_data *error)
  15619. {
  15620. struct mg_connection *conn = NULL;
  15621. SOCKET sock;
  15622. union usa sa;
  15623. struct sockaddr *psa;
  15624. socklen_t len;
  15625. unsigned max_req_size =
  15626. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15627. /* Size of structures, aligned to 8 bytes */
  15628. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15629. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15630. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15631. (void)init; /* TODO: Implement required options */
  15632. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15633. if (error != NULL) {
  15634. error->code = MG_ERROR_DATA_CODE_OK;
  15635. error->code_sub = 0;
  15636. if (error->text_buffer_size > 0) {
  15637. error->text[0] = 0;
  15638. }
  15639. }
  15640. if (conn == NULL) {
  15641. if (error != NULL) {
  15642. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15643. error->code_sub = (unsigned)alloc_size;
  15644. mg_snprintf(NULL,
  15645. NULL, /* No truncation check for ebuf */
  15646. error->text,
  15647. error->text_buffer_size,
  15648. "calloc(): %s",
  15649. strerror(ERRNO));
  15650. }
  15651. return NULL;
  15652. }
  15653. #if defined(GCC_DIAGNOSTIC)
  15654. #pragma GCC diagnostic push
  15655. #pragma GCC diagnostic ignored "-Wcast-align"
  15656. #endif /* defined(GCC_DIAGNOSTIC) */
  15657. /* conn_size is aligned to 8 bytes */
  15658. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15659. #if defined(GCC_DIAGNOSTIC)
  15660. #pragma GCC diagnostic pop
  15661. #endif /* defined(GCC_DIAGNOSTIC) */
  15662. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15663. conn->buf_size = (int)max_req_size;
  15664. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15665. conn->dom_ctx = &(conn->phys_ctx->dd);
  15666. if (!connect_socket(conn->phys_ctx,
  15667. client_options->host,
  15668. client_options->port,
  15669. use_ssl,
  15670. error,
  15671. &sock,
  15672. &sa)) {
  15673. /* "error" will be set by connect_socket. */
  15674. /* free all memory and return NULL; */
  15675. mg_free(conn);
  15676. return NULL;
  15677. }
  15678. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15679. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15680. && !defined(NO_SSL_DL)
  15681. if (use_ssl
  15682. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15683. == NULL) {
  15684. if (error != NULL) {
  15685. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15686. mg_snprintf(NULL,
  15687. NULL, /* No truncation check for ebuf */
  15688. error->text,
  15689. error->text_buffer_size,
  15690. "SSL_CTX_new error: %s",
  15691. ssl_error());
  15692. }
  15693. closesocket(sock);
  15694. mg_free(conn);
  15695. return NULL;
  15696. }
  15697. #else
  15698. if (use_ssl
  15699. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15700. == NULL) {
  15701. if (error != NULL) {
  15702. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15703. mg_snprintf(NULL,
  15704. NULL, /* No truncation check for ebuf */
  15705. error->text,
  15706. error->text_buffer_size,
  15707. "SSL_CTX_new error: %s",
  15708. ssl_error());
  15709. }
  15710. closesocket(sock);
  15711. mg_free(conn);
  15712. return NULL;
  15713. }
  15714. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15715. #endif /* NO_SSL */
  15716. #if defined(USE_IPV6)
  15717. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15718. : sizeof(conn->client.rsa.sin6);
  15719. psa = (sa.sa.sa_family == AF_INET)
  15720. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15721. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15722. #else
  15723. len = sizeof(conn->client.rsa.sin);
  15724. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15725. #endif
  15726. conn->client.sock = sock;
  15727. conn->client.lsa = sa;
  15728. if (getsockname(sock, psa, &len) != 0) {
  15729. mg_cry_internal(conn,
  15730. "%s: getsockname() failed: %s",
  15731. __func__,
  15732. strerror(ERRNO));
  15733. }
  15734. conn->client.is_ssl = use_ssl ? 1 : 0;
  15735. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15736. if (error != NULL) {
  15737. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15738. error->code_sub = (unsigned)ERRNO;
  15739. mg_snprintf(NULL,
  15740. NULL, /* No truncation check for ebuf */
  15741. error->text,
  15742. error->text_buffer_size,
  15743. "Can not create mutex");
  15744. }
  15745. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15746. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15747. #endif
  15748. closesocket(sock);
  15749. mg_free(conn);
  15750. return NULL;
  15751. }
  15752. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15753. if (use_ssl) {
  15754. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15755. * SSL_CTX_set_verify call is needed to switch off server
  15756. * certificate checking, which is off by default in OpenSSL and
  15757. * on in yaSSL. */
  15758. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15759. * SSL_VERIFY_PEER, verify_ssl_server); */
  15760. if (client_options->client_cert) {
  15761. if (!ssl_use_pem_file(conn->phys_ctx,
  15762. conn->dom_ctx,
  15763. client_options->client_cert,
  15764. NULL)) {
  15765. if (error != NULL) {
  15766. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15767. mg_snprintf(NULL,
  15768. NULL, /* No truncation check for ebuf */
  15769. error->text,
  15770. error->text_buffer_size,
  15771. "Can not use SSL client certificate");
  15772. }
  15773. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15774. closesocket(sock);
  15775. mg_free(conn);
  15776. return NULL;
  15777. }
  15778. }
  15779. if (client_options->server_cert) {
  15780. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15781. client_options->server_cert,
  15782. NULL)
  15783. != 1) {
  15784. if (error != NULL) {
  15785. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15786. mg_snprintf(NULL,
  15787. NULL, /* No truncation check for ebuf */
  15788. error->text,
  15789. error->text_buffer_size,
  15790. "SSL_CTX_load_verify_locations error: %s",
  15791. ssl_error());
  15792. }
  15793. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15794. closesocket(sock);
  15795. mg_free(conn);
  15796. return NULL;
  15797. }
  15798. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15799. } else {
  15800. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15801. }
  15802. if (!sslize(conn, SSL_connect, client_options)) {
  15803. if (error != NULL) {
  15804. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15805. mg_snprintf(NULL,
  15806. NULL, /* No truncation check for ebuf */
  15807. error->text,
  15808. error->text_buffer_size,
  15809. "SSL connection error");
  15810. }
  15811. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15812. closesocket(sock);
  15813. mg_free(conn);
  15814. return NULL;
  15815. }
  15816. }
  15817. #endif
  15818. return conn;
  15819. }
  15820. CIVETWEB_API struct mg_connection *
  15821. mg_connect_client_secure(const struct mg_client_options *client_options,
  15822. char *error_buffer,
  15823. size_t error_buffer_size)
  15824. {
  15825. struct mg_init_data init;
  15826. struct mg_error_data error;
  15827. memset(&init, 0, sizeof(init));
  15828. memset(&error, 0, sizeof(error));
  15829. error.text_buffer_size = error_buffer_size;
  15830. error.text = error_buffer;
  15831. return mg_connect_client_impl(client_options, 1, &init, &error);
  15832. }
  15833. CIVETWEB_API struct mg_connection *
  15834. mg_connect_client(const char *host,
  15835. int port,
  15836. int use_ssl,
  15837. char *error_buffer,
  15838. size_t error_buffer_size)
  15839. {
  15840. struct mg_client_options opts;
  15841. struct mg_init_data init;
  15842. struct mg_error_data error;
  15843. memset(&init, 0, sizeof(init));
  15844. memset(&error, 0, sizeof(error));
  15845. error.text_buffer_size = error_buffer_size;
  15846. error.text = error_buffer;
  15847. memset(&opts, 0, sizeof(opts));
  15848. opts.host = host;
  15849. opts.port = port;
  15850. if (use_ssl) {
  15851. opts.host_name = host;
  15852. }
  15853. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15854. }
  15855. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15856. CIVETWEB_API struct mg_connection *
  15857. mg_connect_client2(const char *host,
  15858. const char *protocol,
  15859. int port,
  15860. const char *path,
  15861. struct mg_init_data *init,
  15862. struct mg_error_data *error)
  15863. {
  15864. (void)path;
  15865. int is_ssl, is_ws;
  15866. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15867. if (error != NULL) {
  15868. error->code = MG_ERROR_DATA_CODE_OK;
  15869. error->code_sub = 0;
  15870. if (error->text_buffer_size > 0) {
  15871. *error->text = 0;
  15872. }
  15873. }
  15874. if ((host == NULL) || (protocol == NULL)) {
  15875. if (error != NULL) {
  15876. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15877. mg_snprintf(NULL,
  15878. NULL, /* No truncation check for error buffers */
  15879. error->text,
  15880. error->text_buffer_size,
  15881. "%s",
  15882. "Invalid parameters");
  15883. }
  15884. return NULL;
  15885. }
  15886. /* check all known protocols */
  15887. if (!mg_strcasecmp(protocol, "http")) {
  15888. is_ssl = 0;
  15889. is_ws = 0;
  15890. } else if (!mg_strcasecmp(protocol, "https")) {
  15891. is_ssl = 1;
  15892. is_ws = 0;
  15893. #if defined(USE_WEBSOCKET)
  15894. } else if (!mg_strcasecmp(protocol, "ws")) {
  15895. is_ssl = 0;
  15896. is_ws = 1;
  15897. } else if (!mg_strcasecmp(protocol, "wss")) {
  15898. is_ssl = 1;
  15899. is_ws = 1;
  15900. #endif
  15901. } else {
  15902. if (error != NULL) {
  15903. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15904. mg_snprintf(NULL,
  15905. NULL, /* No truncation check for error buffers */
  15906. error->text,
  15907. error->text_buffer_size,
  15908. "Protocol %s not supported",
  15909. protocol);
  15910. }
  15911. return NULL;
  15912. }
  15913. /* TODO: The current implementation here just calls the old
  15914. * implementations, without using any new options. This is just a first
  15915. * step to test the new interfaces. */
  15916. #if defined(USE_WEBSOCKET)
  15917. if (is_ws) {
  15918. /* TODO: implement all options */
  15919. return mg_connect_websocket_client(
  15920. host,
  15921. port,
  15922. is_ssl,
  15923. ((error != NULL) ? error->text : NULL),
  15924. ((error != NULL) ? error->text_buffer_size : 0),
  15925. (path ? path : ""),
  15926. NULL /* TODO: origin */,
  15927. experimental_websocket_client_data_wrapper,
  15928. experimental_websocket_client_close_wrapper,
  15929. (void *)init->callbacks);
  15930. }
  15931. #else
  15932. (void)is_ws;
  15933. #endif
  15934. /* TODO: all additional options */
  15935. struct mg_client_options opts;
  15936. memset(&opts, 0, sizeof(opts));
  15937. opts.host = host;
  15938. opts.port = port;
  15939. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15940. }
  15941. #endif
  15942. static const struct {
  15943. const char *proto;
  15944. size_t proto_len;
  15945. unsigned default_port;
  15946. } abs_uri_protocols[] = {{"http://", 7, 80},
  15947. {"https://", 8, 443},
  15948. {"ws://", 5, 80},
  15949. {"wss://", 6, 443},
  15950. {NULL, 0, 0}};
  15951. /* Check if the uri is valid.
  15952. * return 0 for invalid uri,
  15953. * return 1 for *,
  15954. * return 2 for relative uri,
  15955. * return 3 for absolute uri without port,
  15956. * return 4 for absolute uri with port */
  15957. static int
  15958. get_uri_type(const char *uri)
  15959. {
  15960. int i;
  15961. const char *hostend, *portbegin;
  15962. char *portend;
  15963. unsigned long port;
  15964. /* According to the HTTP standard
  15965. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15966. * URI can be an asterisk (*) or should start with slash (relative uri),
  15967. * or it should start with the protocol (absolute uri). */
  15968. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15969. /* asterisk */
  15970. return 1;
  15971. }
  15972. /* Valid URIs according to RFC 3986
  15973. * (https://www.ietf.org/rfc/rfc3986.txt)
  15974. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15975. * and unreserved characters A-Z a-z 0-9 and -._~
  15976. * and % encoded symbols.
  15977. */
  15978. for (i = 0; uri[i] != 0; i++) {
  15979. if (uri[i] < 33) {
  15980. /* control characters and spaces are invalid */
  15981. return 0;
  15982. }
  15983. /* Allow everything else here (See #894) */
  15984. }
  15985. /* A relative uri starts with a / character */
  15986. if (uri[0] == '/') {
  15987. /* relative uri */
  15988. return 2;
  15989. }
  15990. /* It could be an absolute uri: */
  15991. /* This function only checks if the uri is valid, not if it is
  15992. * addressing the current server. So civetweb can also be used
  15993. * as a proxy server. */
  15994. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15995. if (mg_strncasecmp(uri,
  15996. abs_uri_protocols[i].proto,
  15997. abs_uri_protocols[i].proto_len)
  15998. == 0) {
  15999. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16000. if (!hostend) {
  16001. return 0;
  16002. }
  16003. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16004. if (!portbegin) {
  16005. return 3;
  16006. }
  16007. port = strtoul(portbegin + 1, &portend, 10);
  16008. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16009. return 0;
  16010. }
  16011. return 4;
  16012. }
  16013. }
  16014. return 0;
  16015. }
  16016. /* Return NULL or the relative uri at the current server */
  16017. static const char *
  16018. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16019. {
  16020. const char *server_domain;
  16021. size_t server_domain_len;
  16022. size_t request_domain_len = 0;
  16023. unsigned long port = 0;
  16024. int i, auth_domain_check_enabled;
  16025. const char *hostbegin = NULL;
  16026. const char *hostend = NULL;
  16027. const char *portbegin;
  16028. char *portend;
  16029. auth_domain_check_enabled =
  16030. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16031. /* DNS is case insensitive, so use case insensitive string compare here
  16032. */
  16033. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16034. if (mg_strncasecmp(uri,
  16035. abs_uri_protocols[i].proto,
  16036. abs_uri_protocols[i].proto_len)
  16037. == 0) {
  16038. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16039. hostend = strchr(hostbegin, '/');
  16040. if (!hostend) {
  16041. return 0;
  16042. }
  16043. portbegin = strchr(hostbegin, ':');
  16044. if ((!portbegin) || (portbegin > hostend)) {
  16045. port = abs_uri_protocols[i].default_port;
  16046. request_domain_len = (size_t)(hostend - hostbegin);
  16047. } else {
  16048. port = strtoul(portbegin + 1, &portend, 10);
  16049. if ((portend != hostend) || (port <= 0)
  16050. || !is_valid_port(port)) {
  16051. return 0;
  16052. }
  16053. request_domain_len = (size_t)(portbegin - hostbegin);
  16054. }
  16055. /* protocol found, port set */
  16056. break;
  16057. }
  16058. }
  16059. if (!port) {
  16060. /* port remains 0 if the protocol is not found */
  16061. return 0;
  16062. }
  16063. /* Check if the request is directed to a different server. */
  16064. /* First check if the port is the same. */
  16065. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16066. /* Request is directed to a different port */
  16067. return 0;
  16068. }
  16069. /* Finally check if the server corresponds to the authentication
  16070. * domain of the server (the server domain).
  16071. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16072. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16073. * but do not allow substrings (like
  16074. * http://notmydomain.com/path/file.ext
  16075. * or http://mydomain.com.fake/path/file.ext).
  16076. */
  16077. if (auth_domain_check_enabled) {
  16078. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16079. server_domain_len = strlen(server_domain);
  16080. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16081. return 0;
  16082. }
  16083. if ((request_domain_len == server_domain_len)
  16084. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16085. /* Request is directed to this server - full name match. */
  16086. } else {
  16087. if (request_domain_len < (server_domain_len + 2)) {
  16088. /* Request is directed to another server: The server name
  16089. * is longer than the request name.
  16090. * Drop this case here to avoid overflows in the
  16091. * following checks. */
  16092. return 0;
  16093. }
  16094. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16095. /* Request is directed to another server: It could be a
  16096. * substring
  16097. * like notmyserver.com */
  16098. return 0;
  16099. }
  16100. if (0
  16101. != memcmp(server_domain,
  16102. hostbegin + request_domain_len - server_domain_len,
  16103. server_domain_len)) {
  16104. /* Request is directed to another server:
  16105. * The server name is different. */
  16106. return 0;
  16107. }
  16108. }
  16109. }
  16110. return hostend;
  16111. }
  16112. static int
  16113. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16114. {
  16115. if (ebuf_len > 0) {
  16116. ebuf[0] = '\0';
  16117. }
  16118. *err = 0;
  16119. reset_per_request_attributes(conn);
  16120. if (!conn) {
  16121. mg_snprintf(conn,
  16122. NULL, /* No truncation check for ebuf */
  16123. ebuf,
  16124. ebuf_len,
  16125. "%s",
  16126. "Internal error");
  16127. *err = 500;
  16128. return 0;
  16129. }
  16130. /* Set the time the request was received. This value should be used for
  16131. * timeouts. */
  16132. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16133. conn->request_len =
  16134. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16135. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16136. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16137. mg_snprintf(conn,
  16138. NULL, /* No truncation check for ebuf */
  16139. ebuf,
  16140. ebuf_len,
  16141. "%s",
  16142. "Invalid message size");
  16143. *err = 500;
  16144. return 0;
  16145. }
  16146. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16147. mg_snprintf(conn,
  16148. NULL, /* No truncation check for ebuf */
  16149. ebuf,
  16150. ebuf_len,
  16151. "%s",
  16152. "Message too large");
  16153. *err = 413;
  16154. return 0;
  16155. }
  16156. if (conn->request_len <= 0) {
  16157. if (conn->data_len > 0) {
  16158. mg_snprintf(conn,
  16159. NULL, /* No truncation check for ebuf */
  16160. ebuf,
  16161. ebuf_len,
  16162. "%s",
  16163. "Malformed message");
  16164. *err = 400;
  16165. } else {
  16166. /* Server did not recv anything -> just close the connection */
  16167. conn->must_close = 1;
  16168. mg_snprintf(conn,
  16169. NULL, /* No truncation check for ebuf */
  16170. ebuf,
  16171. ebuf_len,
  16172. "%s",
  16173. "No data received");
  16174. *err = 0;
  16175. }
  16176. return 0;
  16177. }
  16178. return 1;
  16179. }
  16180. static int
  16181. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16182. {
  16183. const char *cl;
  16184. conn->connection_type =
  16185. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16186. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16187. return 0;
  16188. }
  16189. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16190. <= 0) {
  16191. mg_snprintf(conn,
  16192. NULL, /* No truncation check for ebuf */
  16193. ebuf,
  16194. ebuf_len,
  16195. "%s",
  16196. "Bad request");
  16197. *err = 400;
  16198. return 0;
  16199. }
  16200. /* Message is a valid request */
  16201. if (!switch_domain_context(conn)) {
  16202. mg_snprintf(conn,
  16203. NULL, /* No truncation check for ebuf */
  16204. ebuf,
  16205. ebuf_len,
  16206. "%s",
  16207. "Bad request: Host mismatch");
  16208. *err = 400;
  16209. return 0;
  16210. }
  16211. #if USE_ZLIB
  16212. if (((cl = get_header(conn->request_info.http_headers,
  16213. conn->request_info.num_headers,
  16214. "Accept-Encoding"))
  16215. != NULL)
  16216. && strstr(cl, "gzip")) {
  16217. conn->accept_gzip = 1;
  16218. }
  16219. #endif
  16220. if (((cl = get_header(conn->request_info.http_headers,
  16221. conn->request_info.num_headers,
  16222. "Transfer-Encoding"))
  16223. != NULL)
  16224. && mg_strcasecmp(cl, "identity")) {
  16225. if (mg_strcasecmp(cl, "chunked")) {
  16226. mg_snprintf(conn,
  16227. NULL, /* No truncation check for ebuf */
  16228. ebuf,
  16229. ebuf_len,
  16230. "%s",
  16231. "Bad request");
  16232. *err = 400;
  16233. return 0;
  16234. }
  16235. conn->is_chunked = 1;
  16236. conn->content_len = 0; /* not yet read */
  16237. } else if ((cl = get_header(conn->request_info.http_headers,
  16238. conn->request_info.num_headers,
  16239. "Content-Length"))
  16240. != NULL) {
  16241. /* Request has content length set */
  16242. char *endptr = NULL;
  16243. conn->content_len = strtoll(cl, &endptr, 10);
  16244. if ((endptr == cl) || (conn->content_len < 0)) {
  16245. mg_snprintf(conn,
  16246. NULL, /* No truncation check for ebuf */
  16247. ebuf,
  16248. ebuf_len,
  16249. "%s",
  16250. "Bad request");
  16251. *err = 411;
  16252. return 0;
  16253. }
  16254. /* Publish the content length back to the request info. */
  16255. conn->request_info.content_length = conn->content_len;
  16256. } else {
  16257. /* There is no exception, see RFC7230. */
  16258. conn->content_len = 0;
  16259. }
  16260. return 1;
  16261. }
  16262. /* conn is assumed to be valid in this internal function */
  16263. static int
  16264. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16265. {
  16266. const char *cl;
  16267. conn->connection_type =
  16268. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16269. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16270. return 0;
  16271. }
  16272. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16273. <= 0) {
  16274. mg_snprintf(conn,
  16275. NULL, /* No truncation check for ebuf */
  16276. ebuf,
  16277. ebuf_len,
  16278. "%s",
  16279. "Bad response");
  16280. *err = 400;
  16281. return 0;
  16282. }
  16283. /* Message is a valid response */
  16284. if (((cl = get_header(conn->response_info.http_headers,
  16285. conn->response_info.num_headers,
  16286. "Transfer-Encoding"))
  16287. != NULL)
  16288. && mg_strcasecmp(cl, "identity")) {
  16289. if (mg_strcasecmp(cl, "chunked")) {
  16290. mg_snprintf(conn,
  16291. NULL, /* No truncation check for ebuf */
  16292. ebuf,
  16293. ebuf_len,
  16294. "%s",
  16295. "Bad request");
  16296. *err = 400;
  16297. return 0;
  16298. }
  16299. conn->is_chunked = 1;
  16300. conn->content_len = 0; /* not yet read */
  16301. } else if ((cl = get_header(conn->response_info.http_headers,
  16302. conn->response_info.num_headers,
  16303. "Content-Length"))
  16304. != NULL) {
  16305. char *endptr = NULL;
  16306. conn->content_len = strtoll(cl, &endptr, 10);
  16307. if ((endptr == cl) || (conn->content_len < 0)) {
  16308. mg_snprintf(conn,
  16309. NULL, /* No truncation check for ebuf */
  16310. ebuf,
  16311. ebuf_len,
  16312. "%s",
  16313. "Bad request");
  16314. *err = 411;
  16315. return 0;
  16316. }
  16317. /* Publish the content length back to the response info. */
  16318. conn->response_info.content_length = conn->content_len;
  16319. /* TODO: check if it is still used in response_info */
  16320. conn->request_info.content_length = conn->content_len;
  16321. /* TODO: we should also consider HEAD method */
  16322. if (conn->response_info.status_code == 304) {
  16323. conn->content_len = 0;
  16324. }
  16325. } else {
  16326. /* TODO: we should also consider HEAD method */
  16327. if (((conn->response_info.status_code >= 100)
  16328. && (conn->response_info.status_code <= 199))
  16329. || (conn->response_info.status_code == 204)
  16330. || (conn->response_info.status_code == 304)) {
  16331. conn->content_len = 0;
  16332. } else {
  16333. conn->content_len = -1; /* unknown content length */
  16334. }
  16335. }
  16336. return 1;
  16337. }
  16338. CIVETWEB_API int
  16339. mg_get_response(struct mg_connection *conn,
  16340. char *ebuf,
  16341. size_t ebuf_len,
  16342. int timeout)
  16343. {
  16344. int err, ret;
  16345. char txt[32]; /* will not overflow */
  16346. char *save_timeout;
  16347. char *new_timeout;
  16348. if (ebuf_len > 0) {
  16349. ebuf[0] = '\0';
  16350. }
  16351. if (!conn) {
  16352. mg_snprintf(conn,
  16353. NULL, /* No truncation check for ebuf */
  16354. ebuf,
  16355. ebuf_len,
  16356. "%s",
  16357. "Parameter error");
  16358. return -1;
  16359. }
  16360. /* Reset the previous responses */
  16361. conn->data_len = 0;
  16362. /* Implementation of API function for HTTP clients */
  16363. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16364. if (timeout >= 0) {
  16365. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16366. new_timeout = txt;
  16367. } else {
  16368. new_timeout = NULL;
  16369. }
  16370. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16371. ret = get_response(conn, ebuf, ebuf_len, &err);
  16372. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16373. /* TODO: here, the URI is the http response code */
  16374. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16375. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16376. /* TODO (mid): Define proper return values - maybe return length?
  16377. * For the first test use <0 for error and >0 for OK */
  16378. return (ret == 0) ? -1 : +1;
  16379. }
  16380. CIVETWEB_API struct mg_connection *
  16381. mg_download(const char *host,
  16382. int port,
  16383. int use_ssl,
  16384. char *ebuf,
  16385. size_t ebuf_len,
  16386. const char *fmt,
  16387. ...)
  16388. {
  16389. struct mg_connection *conn;
  16390. va_list ap;
  16391. int i;
  16392. int reqerr;
  16393. if (ebuf_len > 0) {
  16394. ebuf[0] = '\0';
  16395. }
  16396. va_start(ap, fmt);
  16397. /* open a connection */
  16398. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16399. if (conn != NULL) {
  16400. i = mg_vprintf(conn, fmt, ap);
  16401. if (i <= 0) {
  16402. mg_snprintf(conn,
  16403. NULL, /* No truncation check for ebuf */
  16404. ebuf,
  16405. ebuf_len,
  16406. "%s",
  16407. "Error sending request");
  16408. } else {
  16409. /* make sure the buffer is clear */
  16410. conn->data_len = 0;
  16411. get_response(conn, ebuf, ebuf_len, &reqerr);
  16412. /* TODO: here, the URI is the http response code */
  16413. conn->request_info.local_uri = conn->request_info.request_uri;
  16414. }
  16415. }
  16416. /* if an error occurred, close the connection */
  16417. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16418. mg_close_connection(conn);
  16419. conn = NULL;
  16420. }
  16421. va_end(ap);
  16422. return conn;
  16423. }
  16424. struct websocket_client_thread_data {
  16425. struct mg_connection *conn;
  16426. mg_websocket_data_handler data_handler;
  16427. mg_websocket_close_handler close_handler;
  16428. void *callback_data;
  16429. };
  16430. #if defined(USE_WEBSOCKET)
  16431. #if defined(_WIN32)
  16432. static unsigned __stdcall websocket_client_thread(void *data)
  16433. #else
  16434. static void *
  16435. websocket_client_thread(void *data)
  16436. #endif
  16437. {
  16438. struct websocket_client_thread_data *cdata =
  16439. (struct websocket_client_thread_data *)data;
  16440. void *user_thread_ptr = NULL;
  16441. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16442. struct sigaction sa;
  16443. /* Ignore SIGPIPE */
  16444. memset(&sa, 0, sizeof(sa));
  16445. sa.sa_handler = SIG_IGN;
  16446. sigaction(SIGPIPE, &sa, NULL);
  16447. #endif
  16448. mg_set_thread_name("ws-clnt");
  16449. if (cdata->conn->phys_ctx) {
  16450. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16451. /* 3 indicates a websocket client thread */
  16452. /* TODO: check if conn->phys_ctx can be set */
  16453. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16454. cdata->conn->phys_ctx, 3);
  16455. }
  16456. }
  16457. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16458. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16459. if (cdata->close_handler != NULL) {
  16460. cdata->close_handler(cdata->conn, cdata->callback_data);
  16461. }
  16462. /* The websocket_client context has only this thread. If it runs out,
  16463. set the stop_flag to 2 (= "stopped"). */
  16464. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16465. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16466. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16467. 3,
  16468. user_thread_ptr);
  16469. }
  16470. mg_free((void *)cdata);
  16471. #if defined(_WIN32)
  16472. return 0;
  16473. #else
  16474. return NULL;
  16475. #endif
  16476. }
  16477. #endif
  16478. static struct mg_connection *
  16479. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16480. int use_ssl,
  16481. char *error_buffer,
  16482. size_t error_buffer_size,
  16483. const char *path,
  16484. const char *origin,
  16485. const char *extensions,
  16486. mg_websocket_data_handler data_func,
  16487. mg_websocket_close_handler close_func,
  16488. void *user_data)
  16489. {
  16490. struct mg_connection *conn = NULL;
  16491. #if defined(USE_WEBSOCKET)
  16492. struct websocket_client_thread_data *thread_data;
  16493. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16494. const char *host = client_options->host;
  16495. int i;
  16496. struct mg_init_data init;
  16497. struct mg_error_data error;
  16498. memset(&init, 0, sizeof(init));
  16499. memset(&error, 0, sizeof(error));
  16500. error.text_buffer_size = error_buffer_size;
  16501. error.text = error_buffer;
  16502. #if defined(__clang__)
  16503. #pragma clang diagnostic push
  16504. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16505. #endif
  16506. /* Establish the client connection and request upgrade */
  16507. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16508. /* Connection object will be null if something goes wrong */
  16509. if (conn == NULL) {
  16510. /* error_buffer should be already filled ... */
  16511. if (!error_buffer[0]) {
  16512. /* ... if not add an error message */
  16513. mg_snprintf(conn,
  16514. NULL, /* No truncation check for ebuf */
  16515. error_buffer,
  16516. error_buffer_size,
  16517. "Unexpected error");
  16518. }
  16519. return NULL;
  16520. }
  16521. if (origin != NULL) {
  16522. if (extensions != NULL) {
  16523. i = mg_printf(conn,
  16524. "GET %s HTTP/1.1\r\n"
  16525. "Host: %s\r\n"
  16526. "Upgrade: websocket\r\n"
  16527. "Connection: Upgrade\r\n"
  16528. "Sec-WebSocket-Key: %s\r\n"
  16529. "Sec-WebSocket-Version: 13\r\n"
  16530. "Sec-WebSocket-Extensions: %s\r\n"
  16531. "Origin: %s\r\n"
  16532. "\r\n",
  16533. path,
  16534. host,
  16535. magic,
  16536. extensions,
  16537. origin);
  16538. } else {
  16539. i = mg_printf(conn,
  16540. "GET %s HTTP/1.1\r\n"
  16541. "Host: %s\r\n"
  16542. "Upgrade: websocket\r\n"
  16543. "Connection: Upgrade\r\n"
  16544. "Sec-WebSocket-Key: %s\r\n"
  16545. "Sec-WebSocket-Version: 13\r\n"
  16546. "Origin: %s\r\n"
  16547. "\r\n",
  16548. path,
  16549. host,
  16550. magic,
  16551. origin);
  16552. }
  16553. } else {
  16554. if (extensions != NULL) {
  16555. i = mg_printf(conn,
  16556. "GET %s HTTP/1.1\r\n"
  16557. "Host: %s\r\n"
  16558. "Upgrade: websocket\r\n"
  16559. "Connection: Upgrade\r\n"
  16560. "Sec-WebSocket-Key: %s\r\n"
  16561. "Sec-WebSocket-Version: 13\r\n"
  16562. "Sec-WebSocket-Extensions: %s\r\n"
  16563. "\r\n",
  16564. path,
  16565. host,
  16566. magic,
  16567. extensions);
  16568. } else {
  16569. i = mg_printf(conn,
  16570. "GET %s HTTP/1.1\r\n"
  16571. "Host: %s\r\n"
  16572. "Upgrade: websocket\r\n"
  16573. "Connection: Upgrade\r\n"
  16574. "Sec-WebSocket-Key: %s\r\n"
  16575. "Sec-WebSocket-Version: 13\r\n"
  16576. "\r\n",
  16577. path,
  16578. host,
  16579. magic);
  16580. }
  16581. }
  16582. if (i <= 0) {
  16583. mg_snprintf(conn,
  16584. NULL, /* No truncation check for ebuf */
  16585. error_buffer,
  16586. error_buffer_size,
  16587. "%s",
  16588. "Error sending request");
  16589. mg_close_connection(conn);
  16590. return NULL;
  16591. }
  16592. conn->data_len = 0;
  16593. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16594. mg_close_connection(conn);
  16595. return NULL;
  16596. }
  16597. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16598. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16599. #if defined(__clang__)
  16600. #pragma clang diagnostic pop
  16601. #endif
  16602. if (conn->response_info.status_code != 101) {
  16603. /* We sent an "upgrade" request. For a correct websocket
  16604. * protocol handshake, we expect a "101 Continue" response.
  16605. * Otherwise it is a protocol violation. Maybe the HTTP
  16606. * Server does not know websockets. */
  16607. if (!*error_buffer) {
  16608. /* set an error, if not yet set */
  16609. mg_snprintf(conn,
  16610. NULL, /* No truncation check for ebuf */
  16611. error_buffer,
  16612. error_buffer_size,
  16613. "Unexpected server reply");
  16614. }
  16615. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16616. mg_close_connection(conn);
  16617. return NULL;
  16618. }
  16619. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16620. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16621. if (!thread_data) {
  16622. DEBUG_TRACE("%s\r\n", "Out of memory");
  16623. mg_close_connection(conn);
  16624. return NULL;
  16625. }
  16626. thread_data->conn = conn;
  16627. thread_data->data_handler = data_func;
  16628. thread_data->close_handler = close_func;
  16629. thread_data->callback_data = user_data;
  16630. conn->phys_ctx->worker_threadids =
  16631. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16632. if (!conn->phys_ctx->worker_threadids) {
  16633. DEBUG_TRACE("%s\r\n", "Out of memory");
  16634. mg_free(thread_data);
  16635. mg_close_connection(conn);
  16636. return NULL;
  16637. }
  16638. /* Now upgrade to ws/wss client context */
  16639. conn->phys_ctx->user_data = user_data;
  16640. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16641. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16642. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16643. /* Start a thread to read the websocket client connection
  16644. * This thread will automatically stop when mg_disconnect is
  16645. * called on the client connection */
  16646. if (mg_start_thread_with_id(websocket_client_thread,
  16647. thread_data,
  16648. conn->phys_ctx->worker_threadids)
  16649. != 0) {
  16650. conn->phys_ctx->spawned_worker_threads = 0;
  16651. mg_free(thread_data);
  16652. mg_close_connection(conn);
  16653. conn = NULL;
  16654. DEBUG_TRACE("%s",
  16655. "Websocket client connect thread could not be started\r\n");
  16656. }
  16657. #else
  16658. /* Appease "unused parameter" warnings */
  16659. (void)client_options;
  16660. (void)use_ssl;
  16661. (void)error_buffer;
  16662. (void)error_buffer_size;
  16663. (void)path;
  16664. (void)origin;
  16665. (void)extensions;
  16666. (void)user_data;
  16667. (void)data_func;
  16668. (void)close_func;
  16669. #endif
  16670. return conn;
  16671. }
  16672. CIVETWEB_API struct mg_connection *
  16673. mg_connect_websocket_client(const char *host,
  16674. int port,
  16675. int use_ssl,
  16676. char *error_buffer,
  16677. size_t error_buffer_size,
  16678. const char *path,
  16679. const char *origin,
  16680. mg_websocket_data_handler data_func,
  16681. mg_websocket_close_handler close_func,
  16682. void *user_data)
  16683. {
  16684. struct mg_client_options client_options;
  16685. memset(&client_options, 0, sizeof(client_options));
  16686. client_options.host = host;
  16687. client_options.port = port;
  16688. return mg_connect_websocket_client_impl(&client_options,
  16689. use_ssl,
  16690. error_buffer,
  16691. error_buffer_size,
  16692. path,
  16693. origin,
  16694. NULL,
  16695. data_func,
  16696. close_func,
  16697. user_data);
  16698. }
  16699. CIVETWEB_API struct mg_connection *
  16700. mg_connect_websocket_client_secure(
  16701. const struct mg_client_options *client_options,
  16702. char *error_buffer,
  16703. size_t error_buffer_size,
  16704. const char *path,
  16705. const char *origin,
  16706. mg_websocket_data_handler data_func,
  16707. mg_websocket_close_handler close_func,
  16708. void *user_data)
  16709. {
  16710. if (!client_options) {
  16711. return NULL;
  16712. }
  16713. return mg_connect_websocket_client_impl(client_options,
  16714. 1,
  16715. error_buffer,
  16716. error_buffer_size,
  16717. path,
  16718. origin,
  16719. NULL,
  16720. data_func,
  16721. close_func,
  16722. user_data);
  16723. }
  16724. CIVETWEB_API struct mg_connection *
  16725. mg_connect_websocket_client_extensions(const char *host,
  16726. int port,
  16727. int use_ssl,
  16728. char *error_buffer,
  16729. size_t error_buffer_size,
  16730. const char *path,
  16731. const char *origin,
  16732. const char *extensions,
  16733. mg_websocket_data_handler data_func,
  16734. mg_websocket_close_handler close_func,
  16735. void *user_data)
  16736. {
  16737. struct mg_client_options client_options;
  16738. memset(&client_options, 0, sizeof(client_options));
  16739. client_options.host = host;
  16740. client_options.port = port;
  16741. return mg_connect_websocket_client_impl(&client_options,
  16742. use_ssl,
  16743. error_buffer,
  16744. error_buffer_size,
  16745. path,
  16746. origin,
  16747. extensions,
  16748. data_func,
  16749. close_func,
  16750. user_data);
  16751. }
  16752. CIVETWEB_API struct mg_connection *
  16753. mg_connect_websocket_client_secure_extensions(
  16754. const struct mg_client_options *client_options,
  16755. char *error_buffer,
  16756. size_t error_buffer_size,
  16757. const char *path,
  16758. const char *origin,
  16759. const char *extensions,
  16760. mg_websocket_data_handler data_func,
  16761. mg_websocket_close_handler close_func,
  16762. void *user_data)
  16763. {
  16764. if (!client_options) {
  16765. return NULL;
  16766. }
  16767. return mg_connect_websocket_client_impl(client_options,
  16768. 1,
  16769. error_buffer,
  16770. error_buffer_size,
  16771. path,
  16772. origin,
  16773. extensions,
  16774. data_func,
  16775. close_func,
  16776. user_data);
  16777. }
  16778. /* Prepare connection data structure */
  16779. static void
  16780. init_connection(struct mg_connection *conn)
  16781. {
  16782. /* Is keep alive allowed by the server */
  16783. int keep_alive_enabled =
  16784. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16785. if (!keep_alive_enabled) {
  16786. conn->must_close = 1;
  16787. }
  16788. /* Important: on new connection, reset the receiving buffer. Credit
  16789. * goes to crule42. */
  16790. conn->data_len = 0;
  16791. conn->handled_requests = 0;
  16792. conn->connection_type = CONNECTION_TYPE_INVALID;
  16793. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16794. mg_set_user_connection_data(conn, NULL);
  16795. #if defined(USE_SERVER_STATS)
  16796. conn->conn_state = 2; /* init */
  16797. #endif
  16798. /* call the init_connection callback if assigned */
  16799. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16800. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16801. void *conn_data = NULL;
  16802. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16803. mg_set_user_connection_data(conn, conn_data);
  16804. }
  16805. }
  16806. }
  16807. /* Process a connection - may handle multiple requests
  16808. * using the same connection.
  16809. * Must be called with a valid connection (conn and
  16810. * conn->phys_ctx must be valid).
  16811. */
  16812. static void
  16813. process_new_connection(struct mg_connection *conn)
  16814. {
  16815. struct mg_request_info *ri = &conn->request_info;
  16816. int keep_alive, discard_len;
  16817. char ebuf[100];
  16818. const char *hostend;
  16819. int reqerr, uri_type;
  16820. #if defined(USE_SERVER_STATS)
  16821. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16822. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16823. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16824. #endif
  16825. DEBUG_TRACE("Start processing connection from %s",
  16826. conn->request_info.remote_addr);
  16827. /* Loop over multiple requests sent using the same connection
  16828. * (while "keep alive"). */
  16829. do {
  16830. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16831. conn->handled_requests + 1);
  16832. #if defined(USE_SERVER_STATS)
  16833. conn->conn_state = 3; /* ready */
  16834. #endif
  16835. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16836. /* The request sent by the client could not be understood by
  16837. * the server, or it was incomplete or a timeout. Send an
  16838. * error message and close the connection. */
  16839. if (reqerr > 0) {
  16840. DEBUG_ASSERT(ebuf[0] != '\0');
  16841. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16842. }
  16843. } else if (strcmp(ri->http_version, "1.0")
  16844. && strcmp(ri->http_version, "1.1")) {
  16845. /* HTTP/2 is not allowed here */
  16846. mg_snprintf(conn,
  16847. NULL, /* No truncation check for ebuf */
  16848. ebuf,
  16849. sizeof(ebuf),
  16850. "Bad HTTP version: [%s]",
  16851. ri->http_version);
  16852. mg_send_http_error(conn, 505, "%s", ebuf);
  16853. }
  16854. if (ebuf[0] == '\0') {
  16855. uri_type = get_uri_type(conn->request_info.request_uri);
  16856. switch (uri_type) {
  16857. case 1:
  16858. /* Asterisk */
  16859. conn->request_info.local_uri_raw = 0;
  16860. /* TODO: Deal with '*'. */
  16861. break;
  16862. case 2:
  16863. /* relative uri */
  16864. conn->request_info.local_uri_raw =
  16865. conn->request_info.request_uri;
  16866. break;
  16867. case 3:
  16868. case 4:
  16869. /* absolute uri (with/without port) */
  16870. hostend = get_rel_url_at_current_server(
  16871. conn->request_info.request_uri, conn);
  16872. if (hostend) {
  16873. conn->request_info.local_uri_raw = hostend;
  16874. } else {
  16875. conn->request_info.local_uri_raw = NULL;
  16876. }
  16877. break;
  16878. default:
  16879. mg_snprintf(conn,
  16880. NULL, /* No truncation check for ebuf */
  16881. ebuf,
  16882. sizeof(ebuf),
  16883. "Invalid URI");
  16884. mg_send_http_error(conn, 400, "%s", ebuf);
  16885. conn->request_info.local_uri_raw = NULL;
  16886. break;
  16887. }
  16888. conn->request_info.local_uri =
  16889. (char *)conn->request_info.local_uri_raw;
  16890. }
  16891. if (ebuf[0] != '\0') {
  16892. conn->protocol_type = -1;
  16893. } else {
  16894. /* HTTP/1 allows protocol upgrade */
  16895. conn->protocol_type = should_switch_to_protocol(conn);
  16896. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16897. /* This will occur, if a HTTP/1.1 request should be upgraded
  16898. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16899. * Since most (all?) major browsers only support HTTP/2 using
  16900. * ALPN, this is hard to test and very low priority.
  16901. * Deactivate it (at least for now).
  16902. */
  16903. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16904. }
  16905. }
  16906. DEBUG_TRACE("http: %s, error: %s",
  16907. (ri->http_version ? ri->http_version : "none"),
  16908. (ebuf[0] ? ebuf : "none"));
  16909. if (ebuf[0] == '\0') {
  16910. if (conn->request_info.local_uri) {
  16911. /* handle request to local server */
  16912. handle_request_stat_log(conn);
  16913. } else {
  16914. /* TODO: handle non-local request (PROXY) */
  16915. conn->must_close = 1;
  16916. }
  16917. } else {
  16918. conn->must_close = 1;
  16919. }
  16920. /* Response complete. Free header buffer */
  16921. free_buffered_response_header_list(conn);
  16922. if (ri->remote_user != NULL) {
  16923. mg_free((void *)ri->remote_user);
  16924. /* Important! When having connections with and without auth
  16925. * would cause double free and then crash */
  16926. ri->remote_user = NULL;
  16927. }
  16928. /* NOTE(lsm): order is important here. should_keep_alive() call
  16929. * is using parsed request, which will be invalid after
  16930. * memmove's below.
  16931. * Therefore, memorize should_keep_alive() result now for later
  16932. * use in loop exit condition. */
  16933. /* Enable it only if this request is completely discardable. */
  16934. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16935. && should_keep_alive(conn) && (conn->content_len >= 0)
  16936. && (conn->request_len > 0)
  16937. && ((conn->is_chunked == 4)
  16938. || (!conn->is_chunked
  16939. && ((conn->consumed_content == conn->content_len)
  16940. || ((conn->request_len + conn->content_len)
  16941. <= conn->data_len))))
  16942. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16943. if (keep_alive) {
  16944. /* Discard all buffered data for this request */
  16945. discard_len =
  16946. ((conn->request_len + conn->content_len) < conn->data_len)
  16947. ? (int)(conn->request_len + conn->content_len)
  16948. : conn->data_len;
  16949. conn->data_len -= discard_len;
  16950. if (conn->data_len > 0) {
  16951. DEBUG_TRACE("discard_len = %d", discard_len);
  16952. memmove(conn->buf,
  16953. conn->buf + discard_len,
  16954. (size_t)conn->data_len);
  16955. }
  16956. }
  16957. DEBUG_ASSERT(conn->data_len >= 0);
  16958. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16959. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16960. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16961. (long int)conn->data_len,
  16962. (long int)conn->buf_size);
  16963. break;
  16964. }
  16965. conn->handled_requests++;
  16966. } while (keep_alive);
  16967. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16968. conn->request_info.remote_addr,
  16969. difftime(time(NULL), conn->conn_birth_time));
  16970. close_connection(conn);
  16971. #if defined(USE_SERVER_STATS)
  16972. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16973. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16974. #endif
  16975. }
  16976. static int mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads); /* forward declaration */
  16977. #if defined(ALTERNATIVE_QUEUE)
  16978. static void
  16979. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16980. {
  16981. unsigned int i;
  16982. (void)mg_start_worker_thread(ctx, 1); /* will start a worker-thread only if there aren't currently any idle worker-threads */
  16983. while (!ctx->stop_flag) {
  16984. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  16985. /* find a free worker slot and signal it */
  16986. if (ctx->client_socks[i].in_use == 2) {
  16987. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16988. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16989. ctx->client_socks[i] = *sp;
  16990. ctx->client_socks[i].in_use = 1;
  16991. /* socket has been moved to the consumer */
  16992. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16993. (void)event_signal(ctx->client_wait_events[i]);
  16994. return;
  16995. }
  16996. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16997. }
  16998. }
  16999. /* queue is full */
  17000. mg_sleep(1);
  17001. }
  17002. /* must consume */
  17003. set_blocking_mode(sp->sock);
  17004. closesocket(sp->sock);
  17005. }
  17006. static int
  17007. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index, int counter_was_preincremented)
  17008. {
  17009. DEBUG_TRACE("%s", "going idle");
  17010. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17011. if (counter_was_preincremented == 0) { /* first call only: the master-thread pre-incremented this before he spawned us */
  17012. ctx->idle_worker_thread_count++;
  17013. }
  17014. ctx->client_socks[thread_index].in_use = 2;
  17015. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17016. event_wait(ctx->client_wait_events[thread_index]);
  17017. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17018. *sp = ctx->client_socks[thread_index];
  17019. if (ctx->stop_flag) {
  17020. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17021. if (sp->in_use == 1) {
  17022. /* must consume */
  17023. set_blocking_mode(sp->sock);
  17024. closesocket(sp->sock);
  17025. }
  17026. return 0;
  17027. }
  17028. ctx->idle_worker_thread_count--;
  17029. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17030. if (sp->in_use == 1) {
  17031. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17032. return 1;
  17033. }
  17034. /* must not reach here */
  17035. DEBUG_ASSERT(0);
  17036. return 0;
  17037. }
  17038. #else /* ALTERNATIVE_QUEUE */
  17039. /* Worker threads take accepted socket from the queue */
  17040. static int
  17041. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index, int counter_was_preincremented)
  17042. {
  17043. (void)thread_index;
  17044. DEBUG_TRACE("%s", "going idle");
  17045. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17046. if (counter_was_preincremented == 0) { /* first call only: the master-thread pre-incremented this before he spawned us */
  17047. ctx->idle_worker_thread_count++;
  17048. }
  17049. /* If the queue is empty, wait. We're idle at this point. */
  17050. while ((ctx->sq_head == ctx->sq_tail)
  17051. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17052. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17053. }
  17054. /* If we're stopping, sq_head may be equal to sq_tail. */
  17055. if (ctx->sq_head > ctx->sq_tail) {
  17056. /* Copy socket from the queue and increment tail */
  17057. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17058. ctx->sq_tail++;
  17059. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17060. /* Wrap pointers if needed */
  17061. while (ctx->sq_tail > ctx->sq_size) {
  17062. ctx->sq_tail -= ctx->sq_size;
  17063. ctx->sq_head -= ctx->sq_size;
  17064. }
  17065. }
  17066. (void)pthread_cond_signal(&ctx->sq_empty);
  17067. ctx->idle_worker_thread_count--;
  17068. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17069. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17070. }
  17071. /* Master thread adds accepted socket to a queue */
  17072. static void
  17073. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17074. {
  17075. int queue_filled;
  17076. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17077. queue_filled = ctx->sq_head - ctx->sq_tail;
  17078. /* If the queue is full, wait */
  17079. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17080. && (queue_filled >= ctx->sq_size)) {
  17081. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17082. #if defined(USE_SERVER_STATS)
  17083. if (queue_filled > ctx->sq_max_fill) {
  17084. ctx->sq_max_fill = queue_filled;
  17085. }
  17086. #endif
  17087. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17088. ctx->sq_blocked = 0; /* Not blocked now */
  17089. queue_filled = ctx->sq_head - ctx->sq_tail;
  17090. }
  17091. if (queue_filled < ctx->sq_size) {
  17092. /* Copy socket to the queue and increment head */
  17093. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17094. ctx->sq_head++;
  17095. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17096. }
  17097. queue_filled = ctx->sq_head - ctx->sq_tail;
  17098. #if defined(USE_SERVER_STATS)
  17099. if (queue_filled > ctx->sq_max_fill) {
  17100. ctx->sq_max_fill = queue_filled;
  17101. }
  17102. #endif
  17103. (void)pthread_cond_signal(&ctx->sq_full);
  17104. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17105. (void)mg_start_worker_thread(ctx, 1); /* will start a worker-thread only if there aren't currently any idle worker-threads */
  17106. }
  17107. #endif /* ALTERNATIVE_QUEUE */
  17108. static void
  17109. worker_thread_run(struct mg_connection *conn)
  17110. {
  17111. struct mg_context *ctx = conn->phys_ctx;
  17112. int thread_index;
  17113. struct mg_workerTLS tls;
  17114. int first_call_to_consume_socket = 1;
  17115. mg_set_thread_name("worker");
  17116. tls.is_master = 0;
  17117. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17118. #if defined(_WIN32)
  17119. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17120. #endif
  17121. /* Initialize thread local storage before calling any callback */
  17122. pthread_setspecific(sTlsKey, &tls);
  17123. /* Check if there is a user callback */
  17124. if (ctx->callbacks.init_thread) {
  17125. /* call init_thread for a worker thread (type 1), and store the
  17126. * return value */
  17127. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17128. } else {
  17129. /* No callback: set user pointer to NULL */
  17130. tls.user_ptr = NULL;
  17131. }
  17132. /* Connection structure has been pre-allocated */
  17133. thread_index = (int)(conn - ctx->worker_connections);
  17134. if ((thread_index < 0)
  17135. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17136. mg_cry_ctx_internal(ctx,
  17137. "Internal error: Invalid worker index %i",
  17138. thread_index);
  17139. return;
  17140. }
  17141. /* Request buffers are not pre-allocated. They are private to the
  17142. * request and do not contain any state information that might be
  17143. * of interest to anyone observing a server status. */
  17144. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17145. if (conn->buf == NULL) {
  17146. mg_cry_ctx_internal(
  17147. ctx,
  17148. "Out of memory: Cannot allocate buffer for worker %i",
  17149. thread_index);
  17150. return;
  17151. }
  17152. conn->buf_size = (int)ctx->max_request_size;
  17153. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17154. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17155. conn->request_info.user_data = ctx->user_data;
  17156. /* Allocate a mutex for this connection to allow communication both
  17157. * within the request handler and from elsewhere in the application
  17158. */
  17159. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17160. mg_free(conn->buf);
  17161. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17162. return;
  17163. }
  17164. #if defined(USE_SERVER_STATS)
  17165. conn->conn_state = 1; /* not consumed */
  17166. #endif
  17167. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17168. * signal sq_empty condvar to wake up the master waiting in
  17169. * produce_socket() */
  17170. while (consume_socket(ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17171. first_call_to_consume_socket = 0;
  17172. /* New connections must start with new protocol negotiation */
  17173. tls.alpn_proto = NULL;
  17174. #if defined(USE_SERVER_STATS)
  17175. conn->conn_close_time = 0;
  17176. #endif
  17177. conn->conn_birth_time = time(NULL);
  17178. /* Fill in IP, port info early so even if SSL setup below fails,
  17179. * error handler would have the corresponding info.
  17180. * Thanks to Johannes Winkelmann for the patch.
  17181. */
  17182. conn->request_info.remote_port =
  17183. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17184. conn->request_info.server_port =
  17185. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17186. sockaddr_to_string(conn->request_info.remote_addr,
  17187. sizeof(conn->request_info.remote_addr),
  17188. &conn->client.rsa);
  17189. DEBUG_TRACE("Incoming %sconnection from %s",
  17190. (conn->client.is_ssl ? "SSL " : ""),
  17191. conn->request_info.remote_addr);
  17192. conn->request_info.is_ssl = conn->client.is_ssl;
  17193. if (conn->client.is_ssl) {
  17194. #if defined(USE_MBEDTLS)
  17195. /* HTTPS connection */
  17196. if (mbed_ssl_accept(&(conn->ssl),
  17197. conn->dom_ctx->ssl_ctx,
  17198. (int *)&(conn->client.sock),
  17199. conn->phys_ctx)
  17200. == 0) {
  17201. /* conn->dom_ctx is set in get_request */
  17202. /* process HTTPS connection */
  17203. init_connection(conn);
  17204. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17205. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17206. process_new_connection(conn);
  17207. } else {
  17208. /* make sure the connection is cleaned up on SSL failure */
  17209. close_connection(conn);
  17210. }
  17211. #elif !defined(NO_SSL)
  17212. /* HTTPS connection */
  17213. if (sslize(conn, SSL_accept, NULL)) {
  17214. /* conn->dom_ctx is set in get_request */
  17215. /* Get SSL client certificate information (if set) */
  17216. struct mg_client_cert client_cert;
  17217. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17218. conn->request_info.client_cert = &client_cert;
  17219. }
  17220. /* process HTTPS connection */
  17221. #if defined(USE_HTTP2)
  17222. if ((tls.alpn_proto != NULL)
  17223. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17224. /* process HTTPS/2 connection */
  17225. init_connection(conn);
  17226. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17227. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17228. conn->content_len =
  17229. -1; /* content length is not predefined */
  17230. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17231. process_new_http2_connection(conn);
  17232. } else
  17233. #endif
  17234. {
  17235. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17236. init_connection(conn);
  17237. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17238. /* Start with HTTP, WS will be an "upgrade" request later */
  17239. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17240. process_new_connection(conn);
  17241. }
  17242. /* Free client certificate info */
  17243. if (conn->request_info.client_cert) {
  17244. mg_free((void *)(conn->request_info.client_cert->subject));
  17245. mg_free((void *)(conn->request_info.client_cert->issuer));
  17246. mg_free((void *)(conn->request_info.client_cert->serial));
  17247. mg_free((void *)(conn->request_info.client_cert->finger));
  17248. /* Free certificate memory */
  17249. X509_free(
  17250. (X509 *)conn->request_info.client_cert->peer_cert);
  17251. conn->request_info.client_cert->peer_cert = 0;
  17252. conn->request_info.client_cert->subject = 0;
  17253. conn->request_info.client_cert->issuer = 0;
  17254. conn->request_info.client_cert->serial = 0;
  17255. conn->request_info.client_cert->finger = 0;
  17256. conn->request_info.client_cert = 0;
  17257. }
  17258. } else {
  17259. /* make sure the connection is cleaned up on SSL failure */
  17260. close_connection(conn);
  17261. }
  17262. #endif
  17263. } else {
  17264. /* process HTTP connection */
  17265. init_connection(conn);
  17266. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17267. /* Start with HTTP, WS will be an "upgrade" request later */
  17268. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17269. process_new_connection(conn);
  17270. }
  17271. DEBUG_TRACE("%s", "Connection closed");
  17272. #if defined(USE_SERVER_STATS)
  17273. conn->conn_close_time = time(NULL);
  17274. #endif
  17275. }
  17276. /* Call exit thread user callback */
  17277. if (ctx->callbacks.exit_thread) {
  17278. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17279. }
  17280. /* delete thread local storage objects */
  17281. pthread_setspecific(sTlsKey, NULL);
  17282. #if defined(_WIN32)
  17283. CloseHandle(tls.pthread_cond_helper_mutex);
  17284. #endif
  17285. pthread_mutex_destroy(&conn->mutex);
  17286. /* Free the request buffer. */
  17287. conn->buf_size = 0;
  17288. mg_free(conn->buf);
  17289. conn->buf = NULL;
  17290. /* Free cleaned URI (if any) */
  17291. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17292. mg_free((void *)conn->request_info.local_uri);
  17293. conn->request_info.local_uri = NULL;
  17294. }
  17295. #if defined(USE_SERVER_STATS)
  17296. conn->conn_state = 9; /* done */
  17297. #endif
  17298. DEBUG_TRACE("%s", "exiting");
  17299. }
  17300. /* Threads have different return types on Windows and Unix. */
  17301. #if defined(_WIN32)
  17302. static unsigned __stdcall worker_thread(void *thread_func_param)
  17303. {
  17304. worker_thread_run((struct mg_connection *)thread_func_param);
  17305. return 0;
  17306. }
  17307. #else
  17308. static void *
  17309. worker_thread(void *thread_func_param)
  17310. {
  17311. #if !defined(__ZEPHYR__)
  17312. struct sigaction sa;
  17313. /* Ignore SIGPIPE */
  17314. memset(&sa, 0, sizeof(sa));
  17315. sa.sa_handler = SIG_IGN;
  17316. sigaction(SIGPIPE, &sa, NULL);
  17317. #endif
  17318. worker_thread_run((struct mg_connection *)thread_func_param);
  17319. return NULL;
  17320. }
  17321. #endif /* _WIN32 */
  17322. /* This is an internal function, thus all arguments are expected to be
  17323. * valid - a NULL check is not required. */
  17324. static void
  17325. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17326. {
  17327. struct socket so;
  17328. char src_addr[IP_ADDR_STR_LEN];
  17329. socklen_t len = sizeof(so.rsa);
  17330. #if !defined(__ZEPHYR__)
  17331. int on = 1;
  17332. #endif
  17333. memset(&so, 0, sizeof(so));
  17334. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17335. == INVALID_SOCKET) {
  17336. } else if (check_acl(ctx, &so.rsa) != 1) {
  17337. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17338. mg_cry_ctx_internal(ctx,
  17339. "%s: %s is not allowed to connect",
  17340. __func__,
  17341. src_addr);
  17342. closesocket(so.sock);
  17343. } else {
  17344. /* Put so socket structure into the queue */
  17345. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17346. set_close_on_exec(so.sock, NULL, ctx);
  17347. so.is_ssl = listener->is_ssl;
  17348. so.ssl_redir = listener->ssl_redir;
  17349. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17350. mg_cry_ctx_internal(ctx,
  17351. "%s: getsockname() failed: %s",
  17352. __func__,
  17353. strerror(ERRNO));
  17354. }
  17355. #if !defined(__ZEPHYR__)
  17356. if ((so.lsa.sa.sa_family == AF_INET)
  17357. || (so.lsa.sa.sa_family == AF_INET6)) {
  17358. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17359. * This is needed because if HTTP-level keep-alive
  17360. * is enabled, and client resets the connection, server won't get
  17361. * TCP FIN or RST and will keep the connection open forever. With
  17362. * TCP keep-alive, next keep-alive handshake will figure out that
  17363. * the client is down and will close the server end.
  17364. * Thanks to Igor Klopov who suggested the patch. */
  17365. if (setsockopt(so.sock,
  17366. SOL_SOCKET,
  17367. SO_KEEPALIVE,
  17368. (SOCK_OPT_TYPE)&on,
  17369. sizeof(on))
  17370. != 0) {
  17371. mg_cry_ctx_internal(
  17372. ctx,
  17373. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17374. __func__,
  17375. strerror(ERRNO));
  17376. }
  17377. }
  17378. #endif
  17379. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17380. * to effectively fill up the underlying IP packet payload and
  17381. * reduce the overhead of sending lots of small buffers. However
  17382. * this hurts the server's throughput (ie. operations per second)
  17383. * when HTTP 1.1 persistent connections are used and the responses
  17384. * are relatively small (eg. less than 1400 bytes).
  17385. */
  17386. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17387. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17388. if (set_tcp_nodelay(&so, 1) != 0) {
  17389. mg_cry_ctx_internal(
  17390. ctx,
  17391. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17392. __func__,
  17393. strerror(ERRNO));
  17394. }
  17395. }
  17396. /* The "non blocking" property should already be
  17397. * inherited from the parent socket. Set it for
  17398. * non-compliant socket implementations. */
  17399. set_non_blocking_mode(so.sock);
  17400. so.in_use = 0;
  17401. produce_socket(ctx, &so);
  17402. }
  17403. }
  17404. static void
  17405. master_thread_run(struct mg_context *ctx)
  17406. {
  17407. struct mg_workerTLS tls;
  17408. struct mg_pollfd *pfd;
  17409. unsigned int i;
  17410. unsigned int workerthreadcount;
  17411. if (!ctx) {
  17412. return;
  17413. }
  17414. mg_set_thread_name("master");
  17415. /* Increase priority of the master thread */
  17416. #if defined(_WIN32)
  17417. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17418. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17419. int min_prio = sched_get_priority_min(SCHED_RR);
  17420. int max_prio = sched_get_priority_max(SCHED_RR);
  17421. if ((min_prio >= 0) && (max_prio >= 0)
  17422. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17423. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17424. struct sched_param sched_param = {0};
  17425. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17426. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17427. }
  17428. #endif
  17429. /* Initialize thread local storage */
  17430. #if defined(_WIN32)
  17431. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17432. #endif
  17433. tls.is_master = 1;
  17434. pthread_setspecific(sTlsKey, &tls);
  17435. if (ctx->callbacks.init_thread) {
  17436. /* Callback for the master thread (type 0) */
  17437. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17438. } else {
  17439. tls.user_ptr = NULL;
  17440. }
  17441. /* Lua background script "start" event */
  17442. #if defined(USE_LUA)
  17443. if (ctx->lua_background_state) {
  17444. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17445. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17446. /* call "start()" in Lua */
  17447. lua_getglobal(lstate, "start");
  17448. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17449. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17450. if (ret != 0) {
  17451. struct mg_connection fc;
  17452. lua_cry(fake_connection(&fc, ctx),
  17453. ret,
  17454. lstate,
  17455. "lua_background_script",
  17456. "start");
  17457. }
  17458. } else {
  17459. lua_pop(lstate, 1);
  17460. }
  17461. /* determine if there is a "log()" function in Lua background script */
  17462. lua_getglobal(lstate, "log");
  17463. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17464. ctx->lua_bg_log_available = 1;
  17465. }
  17466. lua_pop(lstate, 1);
  17467. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17468. }
  17469. #endif
  17470. /* Server starts *now* */
  17471. ctx->start_time = time(NULL);
  17472. /* Server accept loop */
  17473. pfd = ctx->listening_socket_fds;
  17474. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17475. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17476. pfd[i].fd = ctx->listening_sockets[i].sock;
  17477. pfd[i].events = POLLIN;
  17478. }
  17479. if (mg_poll(pfd,
  17480. ctx->num_listening_sockets,
  17481. SOCKET_TIMEOUT_QUANTUM,
  17482. &(ctx->stop_flag))
  17483. > 0) {
  17484. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17485. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17486. * successful poll, and POLLIN is defined as
  17487. * (POLLRDNORM | POLLRDBAND)
  17488. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17489. * pfd[i].revents == POLLIN. */
  17490. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17491. && (pfd[i].revents & POLLIN)) {
  17492. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17493. }
  17494. }
  17495. }
  17496. }
  17497. /* Here stop_flag is 1 - Initiate shutdown. */
  17498. DEBUG_TRACE("%s", "stopping workers");
  17499. /* Stop signal received: somebody called mg_stop. Quit. */
  17500. close_all_listening_sockets(ctx);
  17501. /* Wakeup workers that are waiting for connections to handle. */
  17502. #if defined(ALTERNATIVE_QUEUE)
  17503. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17504. event_signal(ctx->client_wait_events[i]);
  17505. }
  17506. #else
  17507. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17508. pthread_cond_broadcast(&ctx->sq_full);
  17509. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17510. #endif
  17511. /* Join all worker threads to avoid leaking threads. */
  17512. workerthreadcount = ctx->spawned_worker_threads;
  17513. for (i = 0; i < workerthreadcount; i++) {
  17514. if (ctx->worker_threadids[i] != 0) {
  17515. mg_join_thread(ctx->worker_threadids[i]);
  17516. }
  17517. }
  17518. #if defined(USE_LUA)
  17519. /* Free Lua state of lua background task */
  17520. if (ctx->lua_background_state) {
  17521. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17522. ctx->lua_bg_log_available = 0;
  17523. /* call "stop()" in Lua */
  17524. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17525. lua_getglobal(lstate, "stop");
  17526. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17527. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17528. if (ret != 0) {
  17529. struct mg_connection fc;
  17530. lua_cry(fake_connection(&fc, ctx),
  17531. ret,
  17532. lstate,
  17533. "lua_background_script",
  17534. "stop");
  17535. }
  17536. }
  17537. DEBUG_TRACE("Close Lua background state %p", lstate);
  17538. lua_close(lstate);
  17539. ctx->lua_background_state = 0;
  17540. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17541. }
  17542. #endif
  17543. DEBUG_TRACE("%s", "exiting");
  17544. /* call exit thread callback */
  17545. if (ctx->callbacks.exit_thread) {
  17546. /* Callback for the master thread (type 0) */
  17547. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17548. }
  17549. #if defined(_WIN32)
  17550. CloseHandle(tls.pthread_cond_helper_mutex);
  17551. #endif
  17552. pthread_setspecific(sTlsKey, NULL);
  17553. /* Signal mg_stop() that we're done.
  17554. * WARNING: This must be the very last thing this
  17555. * thread does, as ctx becomes invalid after this line. */
  17556. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17557. }
  17558. /* Threads have different return types on Windows and Unix. */
  17559. #if defined(_WIN32)
  17560. static unsigned __stdcall master_thread(void *thread_func_param)
  17561. {
  17562. master_thread_run((struct mg_context *)thread_func_param);
  17563. return 0;
  17564. }
  17565. #else
  17566. static void *
  17567. master_thread(void *thread_func_param)
  17568. {
  17569. #if !defined(__ZEPHYR__)
  17570. struct sigaction sa;
  17571. /* Ignore SIGPIPE */
  17572. memset(&sa, 0, sizeof(sa));
  17573. sa.sa_handler = SIG_IGN;
  17574. sigaction(SIGPIPE, &sa, NULL);
  17575. #endif
  17576. master_thread_run((struct mg_context *)thread_func_param);
  17577. return NULL;
  17578. }
  17579. #endif /* _WIN32 */
  17580. static void
  17581. free_context(struct mg_context *ctx)
  17582. {
  17583. int i;
  17584. struct mg_handler_info *tmp_rh;
  17585. if (ctx == NULL) {
  17586. return;
  17587. }
  17588. /* Call user callback */
  17589. if (ctx->callbacks.exit_context) {
  17590. ctx->callbacks.exit_context(ctx);
  17591. }
  17592. /* All threads exited, no sync is needed. Destroy thread mutex and
  17593. * condvars
  17594. */
  17595. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17596. #if defined(ALTERNATIVE_QUEUE)
  17597. mg_free(ctx->client_socks);
  17598. if (ctx->client_wait_events != NULL) {
  17599. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17600. event_destroy(ctx->client_wait_events[i]);
  17601. }
  17602. mg_free(ctx->client_wait_events);
  17603. }
  17604. #else
  17605. (void)pthread_cond_destroy(&ctx->sq_empty);
  17606. (void)pthread_cond_destroy(&ctx->sq_full);
  17607. mg_free(ctx->squeue);
  17608. #endif
  17609. /* Destroy other context global data structures mutex */
  17610. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17611. #if defined(USE_LUA)
  17612. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17613. #endif
  17614. /* Deallocate config parameters */
  17615. for (i = 0; i < NUM_OPTIONS; i++) {
  17616. if (ctx->dd.config[i] != NULL) {
  17617. #if defined(_MSC_VER)
  17618. #pragma warning(suppress : 6001)
  17619. #endif
  17620. mg_free(ctx->dd.config[i]);
  17621. }
  17622. }
  17623. /* Deallocate request handlers */
  17624. while (ctx->dd.handlers) {
  17625. tmp_rh = ctx->dd.handlers;
  17626. ctx->dd.handlers = tmp_rh->next;
  17627. mg_free(tmp_rh->uri);
  17628. mg_free(tmp_rh);
  17629. }
  17630. #if defined(USE_MBEDTLS)
  17631. if (ctx->dd.ssl_ctx != NULL) {
  17632. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17633. mg_free(ctx->dd.ssl_ctx);
  17634. ctx->dd.ssl_ctx = NULL;
  17635. }
  17636. #elif !defined(NO_SSL)
  17637. /* Deallocate SSL context */
  17638. if (ctx->dd.ssl_ctx != NULL) {
  17639. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17640. int callback_ret =
  17641. (ctx->callbacks.external_ssl_ctx == NULL)
  17642. ? 0
  17643. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17644. if (callback_ret == 0) {
  17645. SSL_CTX_free(ctx->dd.ssl_ctx);
  17646. }
  17647. /* else: ignore error and omit SSL_CTX_free in case
  17648. * callback_ret is 1 */
  17649. }
  17650. #endif /* !NO_SSL */
  17651. /* Deallocate worker thread ID array */
  17652. mg_free(ctx->worker_threadids);
  17653. /* Deallocate worker thread ID array */
  17654. mg_free(ctx->worker_connections);
  17655. /* deallocate system name string */
  17656. mg_free(ctx->systemName);
  17657. /* Deallocate context itself */
  17658. mg_free(ctx);
  17659. }
  17660. CIVETWEB_API void
  17661. mg_stop(struct mg_context *ctx)
  17662. {
  17663. pthread_t mt;
  17664. if (!ctx) {
  17665. return;
  17666. }
  17667. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17668. * two threads is not allowed. */
  17669. mt = ctx->masterthreadid;
  17670. if (mt == 0) {
  17671. return;
  17672. }
  17673. ctx->masterthreadid = 0;
  17674. /* Set stop flag, so all threads know they have to exit. */
  17675. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17676. /* Join timer thread */
  17677. #if defined(USE_TIMERS)
  17678. timers_exit(ctx);
  17679. #endif
  17680. /* Wait until everything has stopped. */
  17681. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17682. (void)mg_sleep(10);
  17683. }
  17684. /* Wait to stop master thread */
  17685. mg_join_thread(mt);
  17686. /* Close remaining Lua states */
  17687. #if defined(USE_LUA)
  17688. lua_ctx_exit(ctx);
  17689. #endif
  17690. /* Free memory */
  17691. free_context(ctx);
  17692. }
  17693. static void
  17694. get_system_name(char **sysName)
  17695. {
  17696. #if defined(_WIN32)
  17697. char name[128];
  17698. DWORD dwVersion = 0;
  17699. DWORD dwMajorVersion = 0;
  17700. DWORD dwMinorVersion = 0;
  17701. DWORD dwBuild = 0;
  17702. BOOL wowRet, isWoW = FALSE;
  17703. #if defined(_MSC_VER)
  17704. #pragma warning(push)
  17705. /* GetVersion was declared deprecated */
  17706. #pragma warning(disable : 4996)
  17707. #endif
  17708. dwVersion = GetVersion();
  17709. #if defined(_MSC_VER)
  17710. #pragma warning(pop)
  17711. #endif
  17712. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17713. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17714. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17715. (void)dwBuild;
  17716. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17717. sprintf(name,
  17718. "Windows %u.%u%s",
  17719. (unsigned)dwMajorVersion,
  17720. (unsigned)dwMinorVersion,
  17721. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17722. *sysName = mg_strdup(name);
  17723. #elif defined(__ZEPHYR__)
  17724. *sysName = mg_strdup("Zephyr OS");
  17725. #else
  17726. struct utsname name;
  17727. memset(&name, 0, sizeof(name));
  17728. uname(&name);
  17729. *sysName = mg_strdup(name.sysname);
  17730. #endif
  17731. }
  17732. static void
  17733. legacy_init(const char **options)
  17734. {
  17735. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17736. if (options) {
  17737. const char **run_options = options;
  17738. const char *optname = config_options[LISTENING_PORTS].name;
  17739. /* Try to find the "listening_ports" option */
  17740. while (*run_options) {
  17741. if (!strcmp(*run_options, optname)) {
  17742. ports_option = run_options[1];
  17743. }
  17744. run_options += 2;
  17745. }
  17746. }
  17747. if (is_ssl_port_used(ports_option)) {
  17748. /* Initialize with SSL support */
  17749. mg_init_library(MG_FEATURES_TLS);
  17750. } else {
  17751. /* Initialize without SSL support */
  17752. mg_init_library(MG_FEATURES_DEFAULT);
  17753. }
  17754. }
  17755. static int mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads) {
  17756. const unsigned int i = ctx->spawned_worker_threads;
  17757. if (i >= ctx->cfg_max_worker_threads) {
  17758. return -1; /* Oops, we hit our worker-thread limit! No more worker threads, ever! */
  17759. }
  17760. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17761. if ((only_if_no_idle_threads)&&(ctx->idle_worker_thread_count > 0)) {
  17762. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17763. return -2; /* There are idle threads available, so no need to spawn a new worker thread now */
  17764. }
  17765. ctx->idle_worker_thread_count++; /* we do this here to avoid a race condition while the thread is starting up */
  17766. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17767. ctx->worker_connections[i].phys_ctx = ctx;
  17768. int ret = mg_start_thread_with_id(worker_thread,
  17769. &ctx->worker_connections[i],
  17770. &ctx->worker_threadids[i]);
  17771. if (ret == 0) {
  17772. ctx->spawned_worker_threads++; /* note that we've filled another slot in the table */
  17773. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  17774. } else {
  17775. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17776. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  17777. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17778. }
  17779. return ret;
  17780. }
  17781. CIVETWEB_API struct mg_context *
  17782. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17783. {
  17784. struct mg_context *ctx;
  17785. const char *name, *value, *default_value;
  17786. int idx, ok, prespawnthreadcount, workerthreadcount;
  17787. unsigned int i;
  17788. int itmp;
  17789. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17790. const char **options =
  17791. ((init != NULL) ? (init->configuration_options) : (NULL));
  17792. struct mg_workerTLS tls;
  17793. if (error != NULL) {
  17794. error->code = MG_ERROR_DATA_CODE_OK;
  17795. error->code_sub = 0;
  17796. if (error->text_buffer_size > 0) {
  17797. *error->text = 0;
  17798. }
  17799. }
  17800. if (mg_init_library_called == 0) {
  17801. /* Legacy INIT, if mg_start is called without mg_init_library.
  17802. * Note: This will cause a memory leak when unloading the library.
  17803. */
  17804. legacy_init(options);
  17805. }
  17806. if (mg_init_library_called == 0) {
  17807. if (error != NULL) {
  17808. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17809. mg_snprintf(NULL,
  17810. NULL, /* No truncation check for error buffers */
  17811. error->text,
  17812. error->text_buffer_size,
  17813. "%s",
  17814. "Library uninitialized");
  17815. }
  17816. return NULL;
  17817. }
  17818. /* Allocate context and initialize reasonable general case defaults. */
  17819. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17820. if (ctx == NULL) {
  17821. if (error != NULL) {
  17822. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17823. error->code_sub = (unsigned)sizeof(*ctx);
  17824. mg_snprintf(NULL,
  17825. NULL, /* No truncation check for error buffers */
  17826. error->text,
  17827. error->text_buffer_size,
  17828. "%s",
  17829. "Out of memory");
  17830. }
  17831. return NULL;
  17832. }
  17833. /* Random number generator will initialize at the first call */
  17834. ctx->dd.auth_nonce_mask =
  17835. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17836. /* Save started thread index to reuse in other external API calls
  17837. * For the sake of thread synchronization all non-civetweb threads
  17838. * can be considered as single external thread */
  17839. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17840. tls.is_master = -1; /* Thread calling mg_start */
  17841. tls.thread_idx = ctx->starter_thread_idx;
  17842. #if defined(_WIN32)
  17843. tls.pthread_cond_helper_mutex = NULL;
  17844. #endif
  17845. pthread_setspecific(sTlsKey, &tls);
  17846. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17847. #if !defined(ALTERNATIVE_QUEUE)
  17848. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17849. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17850. ctx->sq_blocked = 0;
  17851. #endif
  17852. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17853. #if defined(USE_LUA)
  17854. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17855. #endif
  17856. if (!ok) {
  17857. unsigned error_id = (unsigned)ERRNO;
  17858. const char *err_msg =
  17859. "Cannot initialize thread synchronization objects";
  17860. /* Fatal error - abort start. However, this situation should never
  17861. * occur in practice. */
  17862. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17863. if (error != NULL) {
  17864. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17865. error->code_sub = error_id;
  17866. mg_snprintf(NULL,
  17867. NULL, /* No truncation check for error buffers */
  17868. error->text,
  17869. error->text_buffer_size,
  17870. "%s",
  17871. err_msg);
  17872. }
  17873. mg_free(ctx);
  17874. pthread_setspecific(sTlsKey, NULL);
  17875. return NULL;
  17876. }
  17877. if ((init != NULL) && (init->callbacks != NULL)) {
  17878. /* Set all callbacks except exit_context. */
  17879. ctx->callbacks = *init->callbacks;
  17880. exit_callback = init->callbacks->exit_context;
  17881. /* The exit callback is activated once the context is successfully
  17882. * created. It should not be called, if an incomplete context object
  17883. * is deleted during a failed initialization. */
  17884. ctx->callbacks.exit_context = 0;
  17885. }
  17886. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17887. ctx->dd.handlers = NULL;
  17888. ctx->dd.next = NULL;
  17889. #if defined(USE_LUA)
  17890. lua_ctx_init(ctx);
  17891. #endif
  17892. /* Store options */
  17893. while (options && (name = *options++) != NULL) {
  17894. idx = get_option_index(name);
  17895. if (idx == -1) {
  17896. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17897. if (error != NULL) {
  17898. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17899. error->code_sub = (unsigned)-1;
  17900. mg_snprintf(NULL,
  17901. NULL, /* No truncation check for error buffers */
  17902. error->text,
  17903. error->text_buffer_size,
  17904. "Invalid configuration option: %s",
  17905. name);
  17906. }
  17907. free_context(ctx);
  17908. pthread_setspecific(sTlsKey, NULL);
  17909. return NULL;
  17910. } else if ((value = *options++) == NULL) {
  17911. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17912. if (error != NULL) {
  17913. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17914. error->code_sub = (unsigned)idx;
  17915. mg_snprintf(NULL,
  17916. NULL, /* No truncation check for error buffers */
  17917. error->text,
  17918. error->text_buffer_size,
  17919. "Invalid configuration option value: %s",
  17920. name);
  17921. }
  17922. free_context(ctx);
  17923. pthread_setspecific(sTlsKey, NULL);
  17924. return NULL;
  17925. }
  17926. if (ctx->dd.config[idx] != NULL) {
  17927. /* A duplicate configuration option is not an error - the last
  17928. * option value will be used. */
  17929. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17930. mg_free(ctx->dd.config[idx]);
  17931. }
  17932. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17933. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17934. }
  17935. /* Set default value if needed */
  17936. for (i = 0; config_options[i].name != NULL; i++) {
  17937. default_value = config_options[i].default_value;
  17938. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17939. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17940. }
  17941. }
  17942. /* Request size option */
  17943. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17944. if (itmp < 1024) {
  17945. mg_cry_ctx_internal(ctx,
  17946. "%s too small",
  17947. config_options[MAX_REQUEST_SIZE].name);
  17948. if (error != NULL) {
  17949. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17950. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17951. mg_snprintf(NULL,
  17952. NULL, /* No truncation check for error buffers */
  17953. error->text,
  17954. error->text_buffer_size,
  17955. "Invalid configuration option value: %s",
  17956. config_options[MAX_REQUEST_SIZE].name);
  17957. }
  17958. free_context(ctx);
  17959. pthread_setspecific(sTlsKey, NULL);
  17960. return NULL;
  17961. }
  17962. ctx->max_request_size = (unsigned)itmp;
  17963. /* Queue length */
  17964. #if !defined(ALTERNATIVE_QUEUE)
  17965. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17966. if (itmp < 1) {
  17967. mg_cry_ctx_internal(ctx,
  17968. "%s too small",
  17969. config_options[CONNECTION_QUEUE_SIZE].name);
  17970. if (error != NULL) {
  17971. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17972. error->code_sub = CONNECTION_QUEUE_SIZE;
  17973. mg_snprintf(NULL,
  17974. NULL, /* No truncation check for error buffers */
  17975. error->text,
  17976. error->text_buffer_size,
  17977. "Invalid configuration option value: %s",
  17978. config_options[CONNECTION_QUEUE_SIZE].name);
  17979. }
  17980. free_context(ctx);
  17981. pthread_setspecific(sTlsKey, NULL);
  17982. return NULL;
  17983. }
  17984. ctx->squeue =
  17985. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17986. if (ctx->squeue == NULL) {
  17987. mg_cry_ctx_internal(ctx,
  17988. "Out of memory: Cannot allocate %s",
  17989. config_options[CONNECTION_QUEUE_SIZE].name);
  17990. if (error != NULL) {
  17991. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17992. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17993. mg_snprintf(NULL,
  17994. NULL, /* No truncation check for error buffers */
  17995. error->text,
  17996. error->text_buffer_size,
  17997. "Out of memory: Cannot allocate %s",
  17998. config_options[CONNECTION_QUEUE_SIZE].name);
  17999. }
  18000. free_context(ctx);
  18001. pthread_setspecific(sTlsKey, NULL);
  18002. return NULL;
  18003. }
  18004. ctx->sq_size = itmp;
  18005. #endif
  18006. /* Worker thread count option */
  18007. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18008. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18009. if ((prespawnthreadcount < 0)||(prespawnthreadcount > workerthreadcount)) {
  18010. prespawnthreadcount = workerthreadcount; /* can't prespawn more than all of them! */
  18011. }
  18012. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18013. if (workerthreadcount <= 0) {
  18014. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18015. } else {
  18016. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18017. }
  18018. if (error != NULL) {
  18019. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18020. error->code_sub = NUM_THREADS;
  18021. mg_snprintf(NULL,
  18022. NULL, /* No truncation check for error buffers */
  18023. error->text,
  18024. error->text_buffer_size,
  18025. "Invalid configuration option value: %s",
  18026. config_options[NUM_THREADS].name);
  18027. }
  18028. free_context(ctx);
  18029. pthread_setspecific(sTlsKey, NULL);
  18030. return NULL;
  18031. }
  18032. /* Document root */
  18033. #if defined(NO_FILES)
  18034. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18035. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18036. if (error != NULL) {
  18037. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18038. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18039. mg_snprintf(NULL,
  18040. NULL, /* No truncation check for error buffers */
  18041. error->text,
  18042. error->text_buffer_size,
  18043. "Invalid configuration option value: %s",
  18044. config_options[DOCUMENT_ROOT].name);
  18045. }
  18046. free_context(ctx);
  18047. pthread_setspecific(sTlsKey, NULL);
  18048. return NULL;
  18049. }
  18050. #endif
  18051. get_system_name(&ctx->systemName);
  18052. #if defined(USE_LUA)
  18053. /* If a Lua background script has been configured, start it. */
  18054. ctx->lua_bg_log_available = 0;
  18055. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18056. char ebuf[256];
  18057. struct vec opt_vec;
  18058. struct vec eq_vec;
  18059. const char *sparams;
  18060. memset(ebuf, 0, sizeof(ebuf));
  18061. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18062. /* Create a Lua state, load all standard libraries and the mg table */
  18063. lua_State *state = mg_lua_context_script_prepare(
  18064. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18065. if (!state) {
  18066. mg_cry_ctx_internal(ctx,
  18067. "lua_background_script load error: %s",
  18068. ebuf);
  18069. if (error != NULL) {
  18070. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18071. mg_snprintf(NULL,
  18072. NULL, /* No truncation check for error buffers */
  18073. error->text,
  18074. error->text_buffer_size,
  18075. "Error in script %s: %s",
  18076. config_options[LUA_BACKGROUND_SCRIPT].name,
  18077. ebuf);
  18078. }
  18079. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18080. free_context(ctx);
  18081. pthread_setspecific(sTlsKey, NULL);
  18082. return NULL;
  18083. }
  18084. /* Add a table with parameters into mg.params */
  18085. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18086. if (sparams && sparams[0]) {
  18087. lua_getglobal(state, "mg");
  18088. lua_pushstring(state, "params");
  18089. lua_newtable(state);
  18090. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18091. != NULL) {
  18092. reg_llstring(
  18093. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18094. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18095. break;
  18096. }
  18097. lua_rawset(state, -3);
  18098. lua_pop(state, 1);
  18099. }
  18100. /* Call script */
  18101. state = mg_lua_context_script_run(state,
  18102. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18103. ctx,
  18104. ebuf,
  18105. sizeof(ebuf));
  18106. if (!state) {
  18107. mg_cry_ctx_internal(ctx,
  18108. "lua_background_script start error: %s",
  18109. ebuf);
  18110. if (error != NULL) {
  18111. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18112. mg_snprintf(NULL,
  18113. NULL, /* No truncation check for error buffers */
  18114. error->text,
  18115. error->text_buffer_size,
  18116. "Error in script %s: %s",
  18117. config_options[DOCUMENT_ROOT].name,
  18118. ebuf);
  18119. }
  18120. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18121. free_context(ctx);
  18122. pthread_setspecific(sTlsKey, NULL);
  18123. return NULL;
  18124. }
  18125. /* state remains valid */
  18126. ctx->lua_background_state = (void *)state;
  18127. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18128. } else {
  18129. ctx->lua_background_state = 0;
  18130. }
  18131. #endif
  18132. /* Step by step initialization of ctx - depending on build options */
  18133. #if !defined(NO_FILESYSTEMS)
  18134. if (!set_gpass_option(ctx, NULL)) {
  18135. const char *err_msg = "Invalid global password file";
  18136. /* Fatal error - abort start. */
  18137. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18138. if (error != NULL) {
  18139. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18140. mg_snprintf(NULL,
  18141. NULL, /* No truncation check for error buffers */
  18142. error->text,
  18143. error->text_buffer_size,
  18144. "%s",
  18145. err_msg);
  18146. }
  18147. free_context(ctx);
  18148. pthread_setspecific(sTlsKey, NULL);
  18149. return NULL;
  18150. }
  18151. #endif
  18152. #if defined(USE_MBEDTLS)
  18153. if (!mg_sslctx_init(ctx, NULL)) {
  18154. const char *err_msg = "Error initializing SSL context";
  18155. /* Fatal error - abort start. */
  18156. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18157. if (error != NULL) {
  18158. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18159. mg_snprintf(NULL,
  18160. NULL, /* No truncation check for error buffers */
  18161. error->text,
  18162. error->text_buffer_size,
  18163. "%s",
  18164. err_msg);
  18165. }
  18166. free_context(ctx);
  18167. pthread_setspecific(sTlsKey, NULL);
  18168. return NULL;
  18169. }
  18170. #elif !defined(NO_SSL)
  18171. if (!init_ssl_ctx(ctx, NULL)) {
  18172. const char *err_msg = "Error initializing SSL context";
  18173. /* Fatal error - abort start. */
  18174. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18175. if (error != NULL) {
  18176. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18177. mg_snprintf(NULL,
  18178. NULL, /* No truncation check for error buffers */
  18179. error->text,
  18180. error->text_buffer_size,
  18181. "%s",
  18182. err_msg);
  18183. }
  18184. free_context(ctx);
  18185. pthread_setspecific(sTlsKey, NULL);
  18186. return NULL;
  18187. }
  18188. #endif
  18189. if (!set_ports_option(ctx)) {
  18190. const char *err_msg = "Failed to setup server ports";
  18191. /* Fatal error - abort start. */
  18192. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18193. if (error != NULL) {
  18194. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18195. mg_snprintf(NULL,
  18196. NULL, /* No truncation check for error buffers */
  18197. error->text,
  18198. error->text_buffer_size,
  18199. "%s",
  18200. err_msg);
  18201. }
  18202. free_context(ctx);
  18203. pthread_setspecific(sTlsKey, NULL);
  18204. return NULL;
  18205. }
  18206. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18207. if (!set_uid_option(ctx)) {
  18208. const char *err_msg = "Failed to run as configured user";
  18209. /* Fatal error - abort start. */
  18210. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18211. if (error != NULL) {
  18212. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18213. mg_snprintf(NULL,
  18214. NULL, /* No truncation check for error buffers */
  18215. error->text,
  18216. error->text_buffer_size,
  18217. "%s",
  18218. err_msg);
  18219. }
  18220. free_context(ctx);
  18221. pthread_setspecific(sTlsKey, NULL);
  18222. return NULL;
  18223. }
  18224. #endif
  18225. if (!set_acl_option(ctx)) {
  18226. const char *err_msg = "Failed to setup access control list";
  18227. /* Fatal error - abort start. */
  18228. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18229. if (error != NULL) {
  18230. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18231. mg_snprintf(NULL,
  18232. NULL, /* No truncation check for error buffers */
  18233. error->text,
  18234. error->text_buffer_size,
  18235. "%s",
  18236. err_msg);
  18237. }
  18238. free_context(ctx);
  18239. pthread_setspecific(sTlsKey, NULL);
  18240. return NULL;
  18241. }
  18242. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18243. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18244. sizeof(pthread_t),
  18245. ctx);
  18246. if (ctx->worker_threadids == NULL) {
  18247. const char *err_msg = "Not enough memory for worker thread ID array";
  18248. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18249. if (error != NULL) {
  18250. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18251. error->code_sub =
  18252. (unsigned)ctx->cfg_max_worker_threads * (unsigned)sizeof(pthread_t);
  18253. mg_snprintf(NULL,
  18254. NULL, /* No truncation check for error buffers */
  18255. error->text,
  18256. error->text_buffer_size,
  18257. "%s",
  18258. err_msg);
  18259. }
  18260. free_context(ctx);
  18261. pthread_setspecific(sTlsKey, NULL);
  18262. return NULL;
  18263. }
  18264. ctx->worker_connections =
  18265. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18266. sizeof(struct mg_connection),
  18267. ctx);
  18268. if (ctx->worker_connections == NULL) {
  18269. const char *err_msg =
  18270. "Not enough memory for worker thread connection array";
  18271. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18272. if (error != NULL) {
  18273. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18274. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18275. * (unsigned)sizeof(struct mg_connection);
  18276. mg_snprintf(NULL,
  18277. NULL, /* No truncation check for error buffers */
  18278. error->text,
  18279. error->text_buffer_size,
  18280. "%s",
  18281. err_msg);
  18282. }
  18283. free_context(ctx);
  18284. pthread_setspecific(sTlsKey, NULL);
  18285. return NULL;
  18286. }
  18287. #if defined(ALTERNATIVE_QUEUE)
  18288. ctx->client_wait_events =
  18289. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18290. sizeof(ctx->client_wait_events[0]),
  18291. ctx);
  18292. if (ctx->client_wait_events == NULL) {
  18293. const char *err_msg = "Not enough memory for worker event array";
  18294. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18295. mg_free(ctx->worker_threadids);
  18296. if (error != NULL) {
  18297. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18298. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18299. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18300. mg_snprintf(NULL,
  18301. NULL, /* No truncation check for error buffers */
  18302. error->text,
  18303. error->text_buffer_size,
  18304. "%s",
  18305. err_msg);
  18306. }
  18307. free_context(ctx);
  18308. pthread_setspecific(sTlsKey, NULL);
  18309. return NULL;
  18310. }
  18311. ctx->client_socks =
  18312. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18313. sizeof(ctx->client_socks[0]),
  18314. ctx);
  18315. if (ctx->client_socks == NULL) {
  18316. const char *err_msg = "Not enough memory for worker socket array";
  18317. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18318. mg_free(ctx->client_wait_events);
  18319. mg_free(ctx->worker_threadids);
  18320. if (error != NULL) {
  18321. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18322. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18323. * (unsigned)sizeof(ctx->client_socks[0]);
  18324. mg_snprintf(NULL,
  18325. NULL, /* No truncation check for error buffers */
  18326. error->text,
  18327. error->text_buffer_size,
  18328. "%s",
  18329. err_msg);
  18330. }
  18331. free_context(ctx);
  18332. pthread_setspecific(sTlsKey, NULL);
  18333. return NULL;
  18334. }
  18335. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18336. ctx->client_wait_events[i] = event_create();
  18337. if (ctx->client_wait_events[i] == 0) {
  18338. const char *err_msg = "Error creating worker event %i";
  18339. mg_cry_ctx_internal(ctx, err_msg, i);
  18340. while (i > 0) {
  18341. i--;
  18342. event_destroy(ctx->client_wait_events[i]);
  18343. }
  18344. mg_free(ctx->client_socks);
  18345. mg_free(ctx->client_wait_events);
  18346. mg_free(ctx->worker_threadids);
  18347. if (error != NULL) {
  18348. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18349. error->code_sub = (unsigned)ERRNO;
  18350. mg_snprintf(NULL,
  18351. NULL, /* No truncation check for error buffers */
  18352. error->text,
  18353. error->text_buffer_size,
  18354. err_msg,
  18355. i);
  18356. }
  18357. free_context(ctx);
  18358. pthread_setspecific(sTlsKey, NULL);
  18359. return NULL;
  18360. }
  18361. }
  18362. #endif
  18363. #if defined(USE_TIMERS)
  18364. if (timers_init(ctx) != 0) {
  18365. const char *err_msg = "Error creating timers";
  18366. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18367. if (error != NULL) {
  18368. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18369. error->code_sub = (unsigned)ERRNO;
  18370. mg_snprintf(NULL,
  18371. NULL, /* No truncation check for error buffers */
  18372. error->text,
  18373. error->text_buffer_size,
  18374. "%s",
  18375. err_msg);
  18376. }
  18377. free_context(ctx);
  18378. pthread_setspecific(sTlsKey, NULL);
  18379. return NULL;
  18380. }
  18381. #endif
  18382. /* Context has been created - init user libraries */
  18383. if (ctx->callbacks.init_context) {
  18384. ctx->callbacks.init_context(ctx);
  18385. }
  18386. /* From now, the context is successfully created.
  18387. * When it is destroyed, the exit callback should be called. */
  18388. ctx->callbacks.exit_context = exit_callback;
  18389. ctx->context_type = CONTEXT_SERVER; /* server context */
  18390. /* Start worker threads */
  18391. for (int i = 0; i < prespawnthreadcount; i++) {
  18392. /* worker_thread sets up the other fields */
  18393. if (mg_start_worker_thread(ctx, 0) != 0) {
  18394. long error_no = (long)ERRNO;
  18395. /* thread was not created */
  18396. if (ctx->spawned_worker_threads > 0) {
  18397. /* If the second, third, ... thread cannot be created, set a
  18398. * warning, but keep running. */
  18399. mg_cry_ctx_internal(ctx,
  18400. "Cannot start worker thread %i: error %ld",
  18401. ctx->spawned_worker_threads + 1,
  18402. error_no);
  18403. /* If the server initialization should stop here, all
  18404. * threads that have already been created must be stopped
  18405. * first, before any free_context(ctx) call.
  18406. */
  18407. } else {
  18408. /* If the first worker thread cannot be created, stop
  18409. * initialization and free the entire server context. */
  18410. mg_cry_ctx_internal(ctx,
  18411. "Cannot create threads: error %ld",
  18412. error_no);
  18413. if (error != NULL) {
  18414. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18415. error->code_sub = (unsigned)error_no;
  18416. mg_snprintf(
  18417. NULL,
  18418. NULL, /* No truncation check for error buffers */
  18419. error->text,
  18420. error->text_buffer_size,
  18421. "Cannot create first worker thread: error %ld",
  18422. error_no);
  18423. }
  18424. free_context(ctx);
  18425. pthread_setspecific(sTlsKey, NULL);
  18426. return NULL;
  18427. }
  18428. break;
  18429. }
  18430. }
  18431. /* Start master (listening) thread */
  18432. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18433. pthread_setspecific(sTlsKey, NULL);
  18434. return ctx;
  18435. }
  18436. CIVETWEB_API struct mg_context *
  18437. mg_start(const struct mg_callbacks *callbacks,
  18438. void *user_data,
  18439. const char **options)
  18440. {
  18441. struct mg_init_data init = {0};
  18442. init.callbacks = callbacks;
  18443. init.user_data = user_data;
  18444. init.configuration_options = options;
  18445. return mg_start2(&init, NULL);
  18446. }
  18447. /* Add an additional domain to an already running web server. */
  18448. CIVETWEB_API int
  18449. mg_start_domain2(struct mg_context *ctx,
  18450. const char **options,
  18451. struct mg_error_data *error)
  18452. {
  18453. const char *name;
  18454. const char *value;
  18455. const char *default_value;
  18456. struct mg_domain_context *new_dom;
  18457. struct mg_domain_context *dom;
  18458. int idx, i;
  18459. if (error != NULL) {
  18460. error->code = MG_ERROR_DATA_CODE_OK;
  18461. error->code_sub = 0;
  18462. if (error->text_buffer_size > 0) {
  18463. *error->text = 0;
  18464. }
  18465. }
  18466. if ((ctx == NULL) || (options == NULL)) {
  18467. if (error != NULL) {
  18468. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18469. mg_snprintf(NULL,
  18470. NULL, /* No truncation check for error buffers */
  18471. error->text,
  18472. error->text_buffer_size,
  18473. "%s",
  18474. "Invalid parameters");
  18475. }
  18476. return -1;
  18477. }
  18478. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18479. if (error != NULL) {
  18480. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18481. mg_snprintf(NULL,
  18482. NULL, /* No truncation check for error buffers */
  18483. error->text,
  18484. error->text_buffer_size,
  18485. "%s",
  18486. "Server already stopped");
  18487. }
  18488. return -7;
  18489. }
  18490. new_dom = (struct mg_domain_context *)
  18491. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18492. if (!new_dom) {
  18493. /* Out of memory */
  18494. if (error != NULL) {
  18495. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18496. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18497. mg_snprintf(NULL,
  18498. NULL, /* No truncation check for error buffers */
  18499. error->text,
  18500. error->text_buffer_size,
  18501. "%s",
  18502. "Out or memory");
  18503. }
  18504. return -6;
  18505. }
  18506. /* Store options - TODO: unite duplicate code */
  18507. while (options && (name = *options++) != NULL) {
  18508. idx = get_option_index(name);
  18509. if (idx == -1) {
  18510. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18511. if (error != NULL) {
  18512. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18513. error->code_sub = (unsigned)-1;
  18514. mg_snprintf(NULL,
  18515. NULL, /* No truncation check for error buffers */
  18516. error->text,
  18517. error->text_buffer_size,
  18518. "Invalid option: %s",
  18519. name);
  18520. }
  18521. mg_free(new_dom);
  18522. return -2;
  18523. } else if ((value = *options++) == NULL) {
  18524. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18525. if (error != NULL) {
  18526. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18527. error->code_sub = (unsigned)idx;
  18528. mg_snprintf(NULL,
  18529. NULL, /* No truncation check for error buffers */
  18530. error->text,
  18531. error->text_buffer_size,
  18532. "Invalid option value: %s",
  18533. name);
  18534. }
  18535. mg_free(new_dom);
  18536. return -2;
  18537. }
  18538. if (new_dom->config[idx] != NULL) {
  18539. /* Duplicate option: Later values overwrite earlier ones. */
  18540. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18541. mg_free(new_dom->config[idx]);
  18542. }
  18543. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18544. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18545. }
  18546. /* Authentication domain is mandatory */
  18547. /* TODO: Maybe use a new option hostname? */
  18548. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18549. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18550. if (error != NULL) {
  18551. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18552. error->code_sub = AUTHENTICATION_DOMAIN;
  18553. mg_snprintf(NULL,
  18554. NULL, /* No truncation check for error buffers */
  18555. error->text,
  18556. error->text_buffer_size,
  18557. "Mandatory option %s missing",
  18558. config_options[AUTHENTICATION_DOMAIN].name);
  18559. }
  18560. mg_free(new_dom);
  18561. return -4;
  18562. }
  18563. /* Set default value if needed. Take the config value from
  18564. * ctx as a default value. */
  18565. for (i = 0; config_options[i].name != NULL; i++) {
  18566. default_value = ctx->dd.config[i];
  18567. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18568. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18569. }
  18570. }
  18571. new_dom->handlers = NULL;
  18572. new_dom->next = NULL;
  18573. new_dom->nonce_count = 0;
  18574. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18575. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18576. new_dom->shared_lua_websockets = NULL;
  18577. #endif
  18578. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18579. if (!init_ssl_ctx(ctx, new_dom)) {
  18580. /* Init SSL failed */
  18581. if (error != NULL) {
  18582. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18583. mg_snprintf(NULL,
  18584. NULL, /* No truncation check for error buffers */
  18585. error->text,
  18586. error->text_buffer_size,
  18587. "%s",
  18588. "Initializing SSL context failed");
  18589. }
  18590. mg_free(new_dom);
  18591. return -3;
  18592. }
  18593. #endif
  18594. /* Add element to linked list. */
  18595. mg_lock_context(ctx);
  18596. idx = 0;
  18597. dom = &(ctx->dd);
  18598. for (;;) {
  18599. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18600. dom->config[AUTHENTICATION_DOMAIN])) {
  18601. /* Domain collision */
  18602. mg_cry_ctx_internal(ctx,
  18603. "domain %s already in use",
  18604. new_dom->config[AUTHENTICATION_DOMAIN]);
  18605. if (error != NULL) {
  18606. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18607. mg_snprintf(NULL,
  18608. NULL, /* No truncation check for error buffers */
  18609. error->text,
  18610. error->text_buffer_size,
  18611. "Domain %s specified by %s is already in use",
  18612. new_dom->config[AUTHENTICATION_DOMAIN],
  18613. config_options[AUTHENTICATION_DOMAIN].name);
  18614. }
  18615. mg_free(new_dom);
  18616. mg_unlock_context(ctx);
  18617. return -5;
  18618. }
  18619. /* Count number of domains */
  18620. idx++;
  18621. if (dom->next == NULL) {
  18622. dom->next = new_dom;
  18623. break;
  18624. }
  18625. dom = dom->next;
  18626. }
  18627. mg_unlock_context(ctx);
  18628. /* Return domain number */
  18629. return idx;
  18630. }
  18631. CIVETWEB_API int
  18632. mg_start_domain(struct mg_context *ctx, const char **options)
  18633. {
  18634. return mg_start_domain2(ctx, options, NULL);
  18635. }
  18636. /* Feature check API function */
  18637. CIVETWEB_API unsigned
  18638. mg_check_feature(unsigned feature)
  18639. {
  18640. static const unsigned feature_set = 0
  18641. /* Set bits for available features according to API documentation.
  18642. * This bit mask is created at compile time, according to the active
  18643. * preprocessor defines. It is a single const value at runtime. */
  18644. #if !defined(NO_FILES)
  18645. | MG_FEATURES_FILES
  18646. #endif
  18647. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18648. | MG_FEATURES_SSL
  18649. #endif
  18650. #if !defined(NO_CGI)
  18651. | MG_FEATURES_CGI
  18652. #endif
  18653. #if defined(USE_IPV6)
  18654. | MG_FEATURES_IPV6
  18655. #endif
  18656. #if defined(USE_WEBSOCKET)
  18657. | MG_FEATURES_WEBSOCKET
  18658. #endif
  18659. #if defined(USE_LUA)
  18660. | MG_FEATURES_LUA
  18661. #endif
  18662. #if defined(USE_DUKTAPE)
  18663. | MG_FEATURES_SSJS
  18664. #endif
  18665. #if !defined(NO_CACHING)
  18666. | MG_FEATURES_CACHE
  18667. #endif
  18668. #if defined(USE_SERVER_STATS)
  18669. | MG_FEATURES_STATS
  18670. #endif
  18671. #if defined(USE_ZLIB)
  18672. | MG_FEATURES_COMPRESSION
  18673. #endif
  18674. #if defined(USE_HTTP2)
  18675. | MG_FEATURES_HTTP2
  18676. #endif
  18677. #if defined(USE_X_DOM_SOCKET)
  18678. | MG_FEATURES_X_DOMAIN_SOCKET
  18679. #endif
  18680. /* Set some extra bits not defined in the API documentation.
  18681. * These bits may change without further notice. */
  18682. #if defined(MG_LEGACY_INTERFACE)
  18683. | 0x80000000u
  18684. #endif
  18685. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18686. | 0x40000000u
  18687. #endif
  18688. #if !defined(NO_RESPONSE_BUFFERING)
  18689. | 0x20000000u
  18690. #endif
  18691. #if defined(MEMORY_DEBUGGING)
  18692. | 0x10000000u
  18693. #endif
  18694. ;
  18695. return (feature & feature_set);
  18696. }
  18697. static size_t
  18698. mg_str_append(char **dst, char *end, const char *src)
  18699. {
  18700. size_t len = strlen(src);
  18701. if (*dst != end) {
  18702. /* Append src if enough space, or close dst. */
  18703. if ((size_t)(end - *dst) > len) {
  18704. strcpy(*dst, src);
  18705. *dst += len;
  18706. } else {
  18707. *dst = end;
  18708. }
  18709. }
  18710. return len;
  18711. }
  18712. /* Get system information. It can be printed or stored by the caller.
  18713. * Return the size of available information. */
  18714. CIVETWEB_API int
  18715. mg_get_system_info(char *buffer, int buflen)
  18716. {
  18717. char *end, *append_eoobj = NULL, block[256];
  18718. size_t system_info_length = 0;
  18719. #if defined(_WIN32)
  18720. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18721. #else
  18722. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18723. #endif
  18724. if ((buffer == NULL) || (buflen < 1)) {
  18725. buflen = 0;
  18726. end = buffer;
  18727. } else {
  18728. *buffer = 0;
  18729. end = buffer + buflen;
  18730. }
  18731. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18732. /* has enough space to append eoobj */
  18733. append_eoobj = buffer;
  18734. if (end) {
  18735. end -= sizeof(eoobj) - 1;
  18736. }
  18737. }
  18738. system_info_length += mg_str_append(&buffer, end, "{");
  18739. /* Server version */
  18740. {
  18741. const char *version = mg_version();
  18742. mg_snprintf(NULL,
  18743. NULL,
  18744. block,
  18745. sizeof(block),
  18746. "%s\"version\" : \"%s\"",
  18747. eol,
  18748. version);
  18749. system_info_length += mg_str_append(&buffer, end, block);
  18750. }
  18751. /* System info */
  18752. {
  18753. #if defined(_WIN32)
  18754. DWORD dwVersion = 0;
  18755. DWORD dwMajorVersion = 0;
  18756. DWORD dwMinorVersion = 0;
  18757. SYSTEM_INFO si;
  18758. GetSystemInfo(&si);
  18759. #if defined(_MSC_VER)
  18760. #pragma warning(push)
  18761. /* GetVersion was declared deprecated */
  18762. #pragma warning(disable : 4996)
  18763. #endif
  18764. dwVersion = GetVersion();
  18765. #if defined(_MSC_VER)
  18766. #pragma warning(pop)
  18767. #endif
  18768. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18769. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18770. mg_snprintf(NULL,
  18771. NULL,
  18772. block,
  18773. sizeof(block),
  18774. ",%s\"os\" : \"Windows %u.%u\"",
  18775. eol,
  18776. (unsigned)dwMajorVersion,
  18777. (unsigned)dwMinorVersion);
  18778. system_info_length += mg_str_append(&buffer, end, block);
  18779. mg_snprintf(NULL,
  18780. NULL,
  18781. block,
  18782. sizeof(block),
  18783. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18784. eol,
  18785. (unsigned)si.wProcessorArchitecture,
  18786. (unsigned)si.dwNumberOfProcessors,
  18787. (unsigned)si.dwActiveProcessorMask);
  18788. system_info_length += mg_str_append(&buffer, end, block);
  18789. #elif defined(__ZEPHYR__)
  18790. mg_snprintf(NULL,
  18791. NULL,
  18792. block,
  18793. sizeof(block),
  18794. ",%s\"os\" : \"%s %s\"",
  18795. eol,
  18796. "Zephyr OS",
  18797. ZEPHYR_VERSION);
  18798. system_info_length += mg_str_append(&buffer, end, block);
  18799. #else
  18800. struct utsname name;
  18801. memset(&name, 0, sizeof(name));
  18802. uname(&name);
  18803. mg_snprintf(NULL,
  18804. NULL,
  18805. block,
  18806. sizeof(block),
  18807. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18808. eol,
  18809. name.sysname,
  18810. name.version,
  18811. name.release,
  18812. name.machine);
  18813. system_info_length += mg_str_append(&buffer, end, block);
  18814. #endif
  18815. }
  18816. /* Features */
  18817. {
  18818. mg_snprintf(NULL,
  18819. NULL,
  18820. block,
  18821. sizeof(block),
  18822. ",%s\"features\" : %lu"
  18823. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18824. eol,
  18825. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18826. eol,
  18827. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18828. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18829. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18830. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18831. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18832. : "",
  18833. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18834. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18835. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18836. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18837. system_info_length += mg_str_append(&buffer, end, block);
  18838. #if defined(USE_LUA)
  18839. mg_snprintf(NULL,
  18840. NULL,
  18841. block,
  18842. sizeof(block),
  18843. ",%s\"lua_version\" : \"%u (%s)\"",
  18844. eol,
  18845. (unsigned)LUA_VERSION_NUM,
  18846. LUA_RELEASE);
  18847. system_info_length += mg_str_append(&buffer, end, block);
  18848. #endif
  18849. #if defined(USE_DUKTAPE)
  18850. mg_snprintf(NULL,
  18851. NULL,
  18852. block,
  18853. sizeof(block),
  18854. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18855. eol,
  18856. (unsigned)DUK_VERSION / 10000,
  18857. ((unsigned)DUK_VERSION / 100) % 100,
  18858. (unsigned)DUK_VERSION % 100);
  18859. system_info_length += mg_str_append(&buffer, end, block);
  18860. #endif
  18861. }
  18862. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18863. {
  18864. #if defined(BUILD_DATE)
  18865. const char *bd = BUILD_DATE;
  18866. #else
  18867. #if defined(GCC_DIAGNOSTIC)
  18868. #if GCC_VERSION >= 40900
  18869. #pragma GCC diagnostic push
  18870. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18871. * does not work in some versions. If "BUILD_DATE" is defined to some
  18872. * string, it is used instead of __DATE__. */
  18873. #pragma GCC diagnostic ignored "-Wdate-time"
  18874. #endif
  18875. #endif
  18876. const char *bd = __DATE__;
  18877. #if defined(GCC_DIAGNOSTIC)
  18878. #if GCC_VERSION >= 40900
  18879. #pragma GCC diagnostic pop
  18880. #endif
  18881. #endif
  18882. #endif
  18883. mg_snprintf(
  18884. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18885. system_info_length += mg_str_append(&buffer, end, block);
  18886. }
  18887. /* Compiler information */
  18888. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18889. {
  18890. #if defined(_MSC_VER)
  18891. mg_snprintf(NULL,
  18892. NULL,
  18893. block,
  18894. sizeof(block),
  18895. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18896. eol,
  18897. (unsigned)_MSC_VER,
  18898. (unsigned)_MSC_FULL_VER);
  18899. system_info_length += mg_str_append(&buffer, end, block);
  18900. #elif defined(__MINGW64__)
  18901. mg_snprintf(NULL,
  18902. NULL,
  18903. block,
  18904. sizeof(block),
  18905. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18906. eol,
  18907. (unsigned)__MINGW64_VERSION_MAJOR,
  18908. (unsigned)__MINGW64_VERSION_MINOR);
  18909. system_info_length += mg_str_append(&buffer, end, block);
  18910. mg_snprintf(NULL,
  18911. NULL,
  18912. block,
  18913. sizeof(block),
  18914. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18915. eol,
  18916. (unsigned)__MINGW32_MAJOR_VERSION,
  18917. (unsigned)__MINGW32_MINOR_VERSION);
  18918. system_info_length += mg_str_append(&buffer, end, block);
  18919. #elif defined(__MINGW32__)
  18920. mg_snprintf(NULL,
  18921. NULL,
  18922. block,
  18923. sizeof(block),
  18924. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18925. eol,
  18926. (unsigned)__MINGW32_MAJOR_VERSION,
  18927. (unsigned)__MINGW32_MINOR_VERSION);
  18928. system_info_length += mg_str_append(&buffer, end, block);
  18929. #elif defined(__clang__)
  18930. mg_snprintf(NULL,
  18931. NULL,
  18932. block,
  18933. sizeof(block),
  18934. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18935. eol,
  18936. __clang_major__,
  18937. __clang_minor__,
  18938. __clang_patchlevel__,
  18939. __clang_version__);
  18940. system_info_length += mg_str_append(&buffer, end, block);
  18941. #elif defined(__GNUC__)
  18942. mg_snprintf(NULL,
  18943. NULL,
  18944. block,
  18945. sizeof(block),
  18946. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18947. eol,
  18948. (unsigned)__GNUC__,
  18949. (unsigned)__GNUC_MINOR__,
  18950. (unsigned)__GNUC_PATCHLEVEL__);
  18951. system_info_length += mg_str_append(&buffer, end, block);
  18952. #elif defined(__INTEL_COMPILER)
  18953. mg_snprintf(NULL,
  18954. NULL,
  18955. block,
  18956. sizeof(block),
  18957. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18958. eol,
  18959. (unsigned)__INTEL_COMPILER);
  18960. system_info_length += mg_str_append(&buffer, end, block);
  18961. #elif defined(__BORLANDC__)
  18962. mg_snprintf(NULL,
  18963. NULL,
  18964. block,
  18965. sizeof(block),
  18966. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18967. eol,
  18968. (unsigned)__BORLANDC__);
  18969. system_info_length += mg_str_append(&buffer, end, block);
  18970. #elif defined(__SUNPRO_C)
  18971. mg_snprintf(NULL,
  18972. NULL,
  18973. block,
  18974. sizeof(block),
  18975. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18976. eol,
  18977. (unsigned)__SUNPRO_C);
  18978. system_info_length += mg_str_append(&buffer, end, block);
  18979. #else
  18980. mg_snprintf(NULL,
  18981. NULL,
  18982. block,
  18983. sizeof(block),
  18984. ",%s\"compiler\" : \"other\"",
  18985. eol);
  18986. system_info_length += mg_str_append(&buffer, end, block);
  18987. #endif
  18988. }
  18989. /* Determine 32/64 bit data mode.
  18990. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18991. {
  18992. mg_snprintf(NULL,
  18993. NULL,
  18994. block,
  18995. sizeof(block),
  18996. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18997. "char:%u/%u, "
  18998. "ptr:%u, size:%u, time:%u\"",
  18999. eol,
  19000. (unsigned)sizeof(short),
  19001. (unsigned)sizeof(int),
  19002. (unsigned)sizeof(long),
  19003. (unsigned)sizeof(long long),
  19004. (unsigned)sizeof(float),
  19005. (unsigned)sizeof(double),
  19006. (unsigned)sizeof(long double),
  19007. (unsigned)sizeof(char),
  19008. (unsigned)sizeof(wchar_t),
  19009. (unsigned)sizeof(void *),
  19010. (unsigned)sizeof(size_t),
  19011. (unsigned)sizeof(time_t));
  19012. system_info_length += mg_str_append(&buffer, end, block);
  19013. }
  19014. /* Terminate string */
  19015. if (append_eoobj) {
  19016. strcat(append_eoobj, eoobj);
  19017. }
  19018. system_info_length += sizeof(eoobj) - 1;
  19019. return (int)system_info_length;
  19020. }
  19021. /* Get context information. It can be printed or stored by the caller.
  19022. * Return the size of available information. */
  19023. CIVETWEB_API int
  19024. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19025. {
  19026. #if defined(USE_SERVER_STATS)
  19027. char *end, *append_eoobj = NULL, block[256];
  19028. size_t context_info_length = 0;
  19029. #if defined(_WIN32)
  19030. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19031. #else
  19032. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19033. #endif
  19034. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19035. if ((buffer == NULL) || (buflen < 1)) {
  19036. buflen = 0;
  19037. end = buffer;
  19038. } else {
  19039. *buffer = 0;
  19040. end = buffer + buflen;
  19041. }
  19042. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19043. /* has enough space to append eoobj */
  19044. append_eoobj = buffer;
  19045. end -= sizeof(eoobj) - 1;
  19046. }
  19047. context_info_length += mg_str_append(&buffer, end, "{");
  19048. if (ms) { /* <-- should be always true */
  19049. /* Memory information */
  19050. int blockCount = (int)ms->blockCount;
  19051. int64_t totalMemUsed = ms->totalMemUsed;
  19052. int64_t maxMemUsed = ms->maxMemUsed;
  19053. if (totalMemUsed > maxMemUsed) {
  19054. maxMemUsed = totalMemUsed;
  19055. }
  19056. mg_snprintf(NULL,
  19057. NULL,
  19058. block,
  19059. sizeof(block),
  19060. "%s\"memory\" : {%s"
  19061. "\"blocks\" : %i,%s"
  19062. "\"used\" : %" INT64_FMT ",%s"
  19063. "\"maxUsed\" : %" INT64_FMT "%s"
  19064. "}",
  19065. eol,
  19066. eol,
  19067. blockCount,
  19068. eol,
  19069. totalMemUsed,
  19070. eol,
  19071. maxMemUsed,
  19072. eol);
  19073. context_info_length += mg_str_append(&buffer, end, block);
  19074. }
  19075. if (ctx) {
  19076. /* Declare all variables at begin of the block, to comply
  19077. * with old C standards. */
  19078. char start_time_str[64] = {0};
  19079. char now_str[64] = {0};
  19080. time_t start_time = ctx->start_time;
  19081. time_t now = time(NULL);
  19082. int64_t total_data_read, total_data_written;
  19083. int active_connections = (int)ctx->active_connections;
  19084. int max_active_connections = (int)ctx->max_active_connections;
  19085. int total_connections = (int)ctx->total_connections;
  19086. if (active_connections > max_active_connections) {
  19087. max_active_connections = active_connections;
  19088. }
  19089. if (active_connections > total_connections) {
  19090. total_connections = active_connections;
  19091. }
  19092. /* Connections information */
  19093. mg_snprintf(NULL,
  19094. NULL,
  19095. block,
  19096. sizeof(block),
  19097. ",%s\"connections\" : {%s"
  19098. "\"active\" : %i,%s"
  19099. "\"maxActive\" : %i,%s"
  19100. "\"total\" : %i%s"
  19101. "}",
  19102. eol,
  19103. eol,
  19104. active_connections,
  19105. eol,
  19106. max_active_connections,
  19107. eol,
  19108. total_connections,
  19109. eol);
  19110. context_info_length += mg_str_append(&buffer, end, block);
  19111. /* Queue information */
  19112. #if !defined(ALTERNATIVE_QUEUE)
  19113. mg_snprintf(NULL,
  19114. NULL,
  19115. block,
  19116. sizeof(block),
  19117. ",%s\"queue\" : {%s"
  19118. "\"length\" : %i,%s"
  19119. "\"filled\" : %i,%s"
  19120. "\"maxFilled\" : %i,%s"
  19121. "\"full\" : %s%s"
  19122. "}",
  19123. eol,
  19124. eol,
  19125. ctx->sq_size,
  19126. eol,
  19127. ctx->sq_head - ctx->sq_tail,
  19128. eol,
  19129. ctx->sq_max_fill,
  19130. eol,
  19131. (ctx->sq_blocked ? "true" : "false"),
  19132. eol);
  19133. context_info_length += mg_str_append(&buffer, end, block);
  19134. #endif
  19135. /* Requests information */
  19136. mg_snprintf(NULL,
  19137. NULL,
  19138. block,
  19139. sizeof(block),
  19140. ",%s\"requests\" : {%s"
  19141. "\"total\" : %lu%s"
  19142. "}",
  19143. eol,
  19144. eol,
  19145. (unsigned long)ctx->total_requests,
  19146. eol);
  19147. context_info_length += mg_str_append(&buffer, end, block);
  19148. /* Data information */
  19149. total_data_read =
  19150. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19151. total_data_written =
  19152. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19153. mg_snprintf(NULL,
  19154. NULL,
  19155. block,
  19156. sizeof(block),
  19157. ",%s\"data\" : {%s"
  19158. "\"read\" : %" INT64_FMT ",%s"
  19159. "\"written\" : %" INT64_FMT "%s"
  19160. "}",
  19161. eol,
  19162. eol,
  19163. total_data_read,
  19164. eol,
  19165. total_data_written,
  19166. eol);
  19167. context_info_length += mg_str_append(&buffer, end, block);
  19168. /* Execution time information */
  19169. gmt_time_string(start_time_str,
  19170. sizeof(start_time_str) - 1,
  19171. &start_time);
  19172. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19173. mg_snprintf(NULL,
  19174. NULL,
  19175. block,
  19176. sizeof(block),
  19177. ",%s\"time\" : {%s"
  19178. "\"uptime\" : %.0f,%s"
  19179. "\"start\" : \"%s\",%s"
  19180. "\"now\" : \"%s\"%s"
  19181. "}",
  19182. eol,
  19183. eol,
  19184. difftime(now, start_time),
  19185. eol,
  19186. start_time_str,
  19187. eol,
  19188. now_str,
  19189. eol);
  19190. context_info_length += mg_str_append(&buffer, end, block);
  19191. }
  19192. /* Terminate string */
  19193. if (append_eoobj) {
  19194. strcat(append_eoobj, eoobj);
  19195. }
  19196. context_info_length += sizeof(eoobj) - 1;
  19197. return (int)context_info_length;
  19198. #else
  19199. (void)ctx;
  19200. if ((buffer != NULL) && (buflen > 0)) {
  19201. *buffer = 0;
  19202. }
  19203. return 0;
  19204. #endif
  19205. }
  19206. CIVETWEB_API void
  19207. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19208. {
  19209. /* https://github.com/civetweb/civetweb/issues/727 */
  19210. if (conn != NULL) {
  19211. conn->must_close = 1;
  19212. }
  19213. }
  19214. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19215. /* Get connection information. It can be printed or stored by the caller.
  19216. * Return the size of available information. */
  19217. CIVETWEB_API int
  19218. mg_get_connection_info(const struct mg_context *ctx,
  19219. int idx,
  19220. char *buffer,
  19221. int buflen)
  19222. {
  19223. const struct mg_connection *conn;
  19224. const struct mg_request_info *ri;
  19225. char *end, *append_eoobj = NULL, block[256];
  19226. size_t connection_info_length = 0;
  19227. int state = 0;
  19228. const char *state_str = "unknown";
  19229. #if defined(_WIN32)
  19230. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19231. #else
  19232. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19233. #endif
  19234. if ((buffer == NULL) || (buflen < 1)) {
  19235. buflen = 0;
  19236. end = buffer;
  19237. } else {
  19238. *buffer = 0;
  19239. end = buffer + buflen;
  19240. }
  19241. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19242. /* has enough space to append eoobj */
  19243. append_eoobj = buffer;
  19244. end -= sizeof(eoobj) - 1;
  19245. }
  19246. if ((ctx == NULL) || (idx < 0)) {
  19247. /* Parameter error */
  19248. return 0;
  19249. }
  19250. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19251. /* Out of range */
  19252. return 0;
  19253. }
  19254. /* Take connection [idx]. This connection is not locked in
  19255. * any way, so some other thread might use it. */
  19256. conn = (ctx->worker_connections) + idx;
  19257. /* Initialize output string */
  19258. connection_info_length += mg_str_append(&buffer, end, "{");
  19259. /* Init variables */
  19260. ri = &(conn->request_info);
  19261. #if defined(USE_SERVER_STATS)
  19262. state = conn->conn_state;
  19263. /* State as string */
  19264. switch (state) {
  19265. case 0:
  19266. state_str = "undefined";
  19267. break;
  19268. case 1:
  19269. state_str = "not used";
  19270. break;
  19271. case 2:
  19272. state_str = "init";
  19273. break;
  19274. case 3:
  19275. state_str = "ready";
  19276. break;
  19277. case 4:
  19278. state_str = "processing";
  19279. break;
  19280. case 5:
  19281. state_str = "processed";
  19282. break;
  19283. case 6:
  19284. state_str = "to close";
  19285. break;
  19286. case 7:
  19287. state_str = "closing";
  19288. break;
  19289. case 8:
  19290. state_str = "closed";
  19291. break;
  19292. case 9:
  19293. state_str = "done";
  19294. break;
  19295. }
  19296. #endif
  19297. /* Connection info */
  19298. if ((state >= 3) && (state < 9)) {
  19299. mg_snprintf(NULL,
  19300. NULL,
  19301. block,
  19302. sizeof(block),
  19303. "%s\"connection\" : {%s"
  19304. "\"remote\" : {%s"
  19305. "\"protocol\" : \"%s\",%s"
  19306. "\"addr\" : \"%s\",%s"
  19307. "\"port\" : %u%s"
  19308. "},%s"
  19309. "\"handled_requests\" : %u%s"
  19310. "}",
  19311. eol,
  19312. eol,
  19313. eol,
  19314. get_proto_name(conn),
  19315. eol,
  19316. ri->remote_addr,
  19317. eol,
  19318. ri->remote_port,
  19319. eol,
  19320. eol,
  19321. conn->handled_requests,
  19322. eol);
  19323. connection_info_length += mg_str_append(&buffer, end, block);
  19324. }
  19325. /* Request info */
  19326. if ((state >= 4) && (state < 6)) {
  19327. mg_snprintf(NULL,
  19328. NULL,
  19329. block,
  19330. sizeof(block),
  19331. "%s%s\"request_info\" : {%s"
  19332. "\"method\" : \"%s\",%s"
  19333. "\"uri\" : \"%s\",%s"
  19334. "\"query\" : %s%s%s%s"
  19335. "}",
  19336. (connection_info_length > 1 ? "," : ""),
  19337. eol,
  19338. eol,
  19339. ri->request_method,
  19340. eol,
  19341. ri->request_uri,
  19342. eol,
  19343. ri->query_string ? "\"" : "",
  19344. ri->query_string ? ri->query_string : "null",
  19345. ri->query_string ? "\"" : "",
  19346. eol);
  19347. connection_info_length += mg_str_append(&buffer, end, block);
  19348. }
  19349. /* Execution time information */
  19350. if ((state >= 2) && (state < 9)) {
  19351. char start_time_str[64] = {0};
  19352. char close_time_str[64] = {0};
  19353. time_t start_time = conn->conn_birth_time;
  19354. time_t close_time = 0;
  19355. double time_diff;
  19356. gmt_time_string(start_time_str,
  19357. sizeof(start_time_str) - 1,
  19358. &start_time);
  19359. #if defined(USE_SERVER_STATS)
  19360. close_time = conn->conn_close_time;
  19361. #endif
  19362. if (close_time != 0) {
  19363. time_diff = difftime(close_time, start_time);
  19364. gmt_time_string(close_time_str,
  19365. sizeof(close_time_str) - 1,
  19366. &close_time);
  19367. } else {
  19368. time_t now = time(NULL);
  19369. time_diff = difftime(now, start_time);
  19370. close_time_str[0] = 0; /* or use "now" ? */
  19371. }
  19372. mg_snprintf(NULL,
  19373. NULL,
  19374. block,
  19375. sizeof(block),
  19376. "%s%s\"time\" : {%s"
  19377. "\"uptime\" : %.0f,%s"
  19378. "\"start\" : \"%s\",%s"
  19379. "\"closed\" : \"%s\"%s"
  19380. "}",
  19381. (connection_info_length > 1 ? "," : ""),
  19382. eol,
  19383. eol,
  19384. time_diff,
  19385. eol,
  19386. start_time_str,
  19387. eol,
  19388. close_time_str,
  19389. eol);
  19390. connection_info_length += mg_str_append(&buffer, end, block);
  19391. }
  19392. /* Remote user name */
  19393. if ((ri->remote_user) && (state < 9)) {
  19394. mg_snprintf(NULL,
  19395. NULL,
  19396. block,
  19397. sizeof(block),
  19398. "%s%s\"user\" : {%s"
  19399. "\"name\" : \"%s\",%s"
  19400. "}",
  19401. (connection_info_length > 1 ? "," : ""),
  19402. eol,
  19403. eol,
  19404. ri->remote_user,
  19405. eol);
  19406. connection_info_length += mg_str_append(&buffer, end, block);
  19407. }
  19408. /* Data block */
  19409. if (state >= 3) {
  19410. mg_snprintf(NULL,
  19411. NULL,
  19412. block,
  19413. sizeof(block),
  19414. "%s%s\"data\" : {%s"
  19415. "\"read\" : %" INT64_FMT ",%s"
  19416. "\"written\" : %" INT64_FMT "%s"
  19417. "}",
  19418. (connection_info_length > 1 ? "," : ""),
  19419. eol,
  19420. eol,
  19421. conn->consumed_content,
  19422. eol,
  19423. conn->num_bytes_sent,
  19424. eol);
  19425. connection_info_length += mg_str_append(&buffer, end, block);
  19426. }
  19427. /* State */
  19428. mg_snprintf(NULL,
  19429. NULL,
  19430. block,
  19431. sizeof(block),
  19432. "%s%s\"state\" : \"%s\"",
  19433. (connection_info_length > 1 ? "," : ""),
  19434. eol,
  19435. state_str);
  19436. connection_info_length += mg_str_append(&buffer, end, block);
  19437. /* Terminate string */
  19438. if (append_eoobj) {
  19439. strcat(append_eoobj, eoobj);
  19440. }
  19441. connection_info_length += sizeof(eoobj) - 1;
  19442. return (int)connection_info_length;
  19443. }
  19444. #if 0
  19445. /* Get handler information. Not fully implemented. Is it required? */
  19446. CIVETWEB_API int
  19447. mg_get_handler_info(struct mg_context *ctx,
  19448. char *buffer,
  19449. int buflen)
  19450. {
  19451. int handler_info_len = 0;
  19452. struct mg_handler_info *tmp_rh;
  19453. mg_lock_context(ctx);
  19454. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19455. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19456. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19457. }
  19458. handler_info_len += tmp_rh->uri_len;
  19459. switch (tmp_rh->handler_type) {
  19460. case REQUEST_HANDLER:
  19461. (void)tmp_rh->handler;
  19462. break;
  19463. case WEBSOCKET_HANDLER:
  19464. (void)tmp_rh->connect_handler;
  19465. (void)tmp_rh->ready_handler;
  19466. (void)tmp_rh->data_handler;
  19467. (void)tmp_rh->close_handler;
  19468. break;
  19469. case AUTH_HANDLER:
  19470. (void)tmp_rh->auth_handler;
  19471. break;
  19472. }
  19473. (void)cbdata;
  19474. }
  19475. mg_unlock_context(ctx);
  19476. return handler_info_len;
  19477. }
  19478. #endif
  19479. #endif
  19480. /* Initialize this library. This function does not need to be thread safe.
  19481. */
  19482. CIVETWEB_API unsigned
  19483. mg_init_library(unsigned features)
  19484. {
  19485. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19486. unsigned features_inited = features_to_init;
  19487. if (mg_init_library_called <= 0) {
  19488. /* Not initialized yet */
  19489. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19490. return 0;
  19491. }
  19492. }
  19493. mg_global_lock();
  19494. if (mg_init_library_called <= 0) {
  19495. int i;
  19496. size_t len;
  19497. #if defined(_WIN32)
  19498. int file_mutex_init = 1;
  19499. int wsa = 1;
  19500. #else
  19501. int mutexattr_init = 1;
  19502. #endif
  19503. int failed = 1;
  19504. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19505. if (key_create == 0) {
  19506. #if defined(_WIN32)
  19507. file_mutex_init =
  19508. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19509. if (file_mutex_init == 0) {
  19510. /* Start WinSock */
  19511. WSADATA data;
  19512. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19513. }
  19514. #else
  19515. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19516. if (mutexattr_init == 0) {
  19517. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19518. PTHREAD_MUTEX_RECURSIVE);
  19519. }
  19520. #endif
  19521. }
  19522. if (failed) {
  19523. #if defined(_WIN32)
  19524. if (wsa == 0) {
  19525. (void)WSACleanup();
  19526. }
  19527. if (file_mutex_init == 0) {
  19528. (void)pthread_mutex_destroy(&global_log_file_lock);
  19529. }
  19530. #else
  19531. if (mutexattr_init == 0) {
  19532. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19533. }
  19534. #endif
  19535. if (key_create == 0) {
  19536. (void)pthread_key_delete(sTlsKey);
  19537. }
  19538. mg_global_unlock();
  19539. (void)pthread_mutex_destroy(&global_lock_mutex);
  19540. return 0;
  19541. }
  19542. len = 1;
  19543. for (i = 0; http_methods[i].name != NULL; i++) {
  19544. size_t sl = strlen(http_methods[i].name);
  19545. len += sl;
  19546. if (i > 0) {
  19547. len += 2;
  19548. }
  19549. }
  19550. all_methods = (char *)mg_malloc(len);
  19551. if (!all_methods) {
  19552. /* Must never happen */
  19553. mg_global_unlock();
  19554. (void)pthread_mutex_destroy(&global_lock_mutex);
  19555. return 0;
  19556. }
  19557. all_methods[0] = 0;
  19558. for (i = 0; http_methods[i].name != NULL; i++) {
  19559. if (i > 0) {
  19560. strcat(all_methods, ", ");
  19561. strcat(all_methods, http_methods[i].name);
  19562. } else {
  19563. strcpy(all_methods, http_methods[i].name);
  19564. }
  19565. }
  19566. }
  19567. #if defined(USE_LUA)
  19568. lua_init_optional_libraries();
  19569. #endif
  19570. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19571. || defined(OPENSSL_API_3_0)) \
  19572. && !defined(NO_SSL)
  19573. if (features_to_init & MG_FEATURES_SSL) {
  19574. if (!mg_openssl_initialized) {
  19575. char ebuf[128];
  19576. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19577. mg_openssl_initialized = 1;
  19578. } else {
  19579. (void)ebuf;
  19580. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19581. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19582. }
  19583. } else {
  19584. /* ssl already initialized */
  19585. }
  19586. }
  19587. #endif
  19588. if (mg_init_library_called <= 0) {
  19589. mg_init_library_called = 1;
  19590. } else {
  19591. mg_init_library_called++;
  19592. }
  19593. mg_global_unlock();
  19594. return features_inited;
  19595. }
  19596. /* Un-initialize this library. */
  19597. CIVETWEB_API unsigned
  19598. mg_exit_library(void)
  19599. {
  19600. if (mg_init_library_called <= 0) {
  19601. return 0;
  19602. }
  19603. mg_global_lock();
  19604. mg_init_library_called--;
  19605. if (mg_init_library_called == 0) {
  19606. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19607. if (mg_openssl_initialized) {
  19608. uninitialize_openssl();
  19609. mg_openssl_initialized = 0;
  19610. }
  19611. #endif
  19612. #if defined(_WIN32)
  19613. (void)WSACleanup();
  19614. (void)pthread_mutex_destroy(&global_log_file_lock);
  19615. #else
  19616. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19617. #endif
  19618. (void)pthread_key_delete(sTlsKey);
  19619. #if defined(USE_LUA)
  19620. lua_exit_optional_libraries();
  19621. #endif
  19622. mg_free(all_methods);
  19623. all_methods = NULL;
  19624. mg_global_unlock();
  19625. (void)pthread_mutex_destroy(&global_lock_mutex);
  19626. return 1;
  19627. }
  19628. mg_global_unlock();
  19629. return 1;
  19630. }
  19631. /* End of civetweb.c */