civetweb.c 600 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553
  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. RUN_AS_USER,
  1633. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1634. * socket option typedef TCP_NODELAY. */
  1635. MAX_REQUEST_SIZE,
  1636. LINGER_TIMEOUT,
  1637. CONNECTION_QUEUE_SIZE,
  1638. LISTEN_BACKLOG_SIZE,
  1639. #if defined(__linux__)
  1640. ALLOW_SENDFILE_CALL,
  1641. #endif
  1642. #if defined(_WIN32)
  1643. CASE_SENSITIVE_FILES,
  1644. #endif
  1645. THROTTLE,
  1646. ENABLE_KEEP_ALIVE,
  1647. REQUEST_TIMEOUT,
  1648. KEEP_ALIVE_TIMEOUT,
  1649. #if defined(USE_WEBSOCKET)
  1650. WEBSOCKET_TIMEOUT,
  1651. ENABLE_WEBSOCKET_PING_PONG,
  1652. #endif
  1653. DECODE_URL,
  1654. DECODE_QUERY_STRING,
  1655. #if defined(USE_LUA)
  1656. LUA_BACKGROUND_SCRIPT,
  1657. LUA_BACKGROUND_SCRIPT_PARAMS,
  1658. #endif
  1659. #if defined(USE_HTTP2)
  1660. ENABLE_HTTP2,
  1661. #endif
  1662. /* Once for each domain */
  1663. DOCUMENT_ROOT,
  1664. FALLBACK_DOCUMENT_ROOT,
  1665. ACCESS_LOG_FILE,
  1666. ERROR_LOG_FILE,
  1667. CGI_EXTENSIONS,
  1668. CGI_ENVIRONMENT,
  1669. CGI_INTERPRETER,
  1670. CGI_INTERPRETER_ARGS,
  1671. #if defined(USE_TIMERS)
  1672. CGI_TIMEOUT,
  1673. #endif
  1674. CGI_BUFFERING,
  1675. CGI2_EXTENSIONS,
  1676. CGI2_ENVIRONMENT,
  1677. CGI2_INTERPRETER,
  1678. CGI2_INTERPRETER_ARGS,
  1679. #if defined(USE_TIMERS)
  1680. CGI2_TIMEOUT,
  1681. #endif
  1682. CGI2_BUFFERING,
  1683. #if defined(USE_4_CGI)
  1684. CGI3_EXTENSIONS,
  1685. CGI3_ENVIRONMENT,
  1686. CGI3_INTERPRETER,
  1687. CGI3_INTERPRETER_ARGS,
  1688. #if defined(USE_TIMERS)
  1689. CGI3_TIMEOUT,
  1690. #endif
  1691. CGI3_BUFFERING,
  1692. CGI4_EXTENSIONS,
  1693. CGI4_ENVIRONMENT,
  1694. CGI4_INTERPRETER,
  1695. CGI4_INTERPRETER_ARGS,
  1696. #if defined(USE_TIMERS)
  1697. CGI4_TIMEOUT,
  1698. #endif
  1699. CGI4_BUFFERING,
  1700. #endif
  1701. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1702. PROTECT_URI,
  1703. AUTHENTICATION_DOMAIN,
  1704. ENABLE_AUTH_DOMAIN_CHECK,
  1705. SSI_EXTENSIONS,
  1706. ENABLE_DIRECTORY_LISTING,
  1707. ENABLE_WEBDAV,
  1708. GLOBAL_PASSWORDS_FILE,
  1709. INDEX_FILES,
  1710. ACCESS_CONTROL_LIST,
  1711. EXTRA_MIME_TYPES,
  1712. SSL_CERTIFICATE,
  1713. SSL_CERTIFICATE_CHAIN,
  1714. URL_REWRITE_PATTERN,
  1715. HIDE_FILES,
  1716. SSL_DO_VERIFY_PEER,
  1717. SSL_CACHE_TIMEOUT,
  1718. SSL_CA_PATH,
  1719. SSL_CA_FILE,
  1720. SSL_VERIFY_DEPTH,
  1721. SSL_DEFAULT_VERIFY_PATHS,
  1722. SSL_CIPHER_LIST,
  1723. SSL_PROTOCOL_VERSION,
  1724. SSL_SHORT_TRUST,
  1725. #if defined(USE_LUA)
  1726. LUA_PRELOAD_FILE,
  1727. LUA_SCRIPT_EXTENSIONS,
  1728. LUA_SERVER_PAGE_EXTENSIONS,
  1729. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1730. LUA_DEBUG_PARAMS,
  1731. #endif
  1732. #endif
  1733. #if defined(USE_DUKTAPE)
  1734. DUKTAPE_SCRIPT_EXTENSIONS,
  1735. #endif
  1736. #if defined(USE_WEBSOCKET)
  1737. WEBSOCKET_ROOT,
  1738. FALLBACK_WEBSOCKET_ROOT,
  1739. #endif
  1740. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1741. LUA_WEBSOCKET_EXTENSIONS,
  1742. #endif
  1743. ACCESS_CONTROL_ALLOW_ORIGIN,
  1744. ACCESS_CONTROL_ALLOW_METHODS,
  1745. ACCESS_CONTROL_ALLOW_HEADERS,
  1746. ERROR_PAGES,
  1747. #if !defined(NO_CACHING)
  1748. STATIC_FILE_MAX_AGE,
  1749. STATIC_FILE_CACHE_CONTROL,
  1750. #endif
  1751. #if !defined(NO_SSL)
  1752. STRICT_HTTPS_MAX_AGE,
  1753. #endif
  1754. ADDITIONAL_HEADER,
  1755. ALLOW_INDEX_SCRIPT_SUB_RES,
  1756. NUM_OPTIONS
  1757. };
  1758. /* Config option name, config types, default value.
  1759. * Must be in the same order as the enum const above.
  1760. */
  1761. static const struct mg_option config_options[] = {
  1762. /* Once for each server */
  1763. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1764. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1765. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1766. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1767. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1768. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1769. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1770. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1771. #if defined(__linux__)
  1772. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1773. #endif
  1774. #if defined(_WIN32)
  1775. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1776. #endif
  1777. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1778. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1779. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1780. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1781. #if defined(USE_WEBSOCKET)
  1782. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1783. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1784. #endif
  1785. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1786. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1787. #if defined(USE_LUA)
  1788. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1789. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1790. #endif
  1791. #if defined(USE_HTTP2)
  1792. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1793. #endif
  1794. /* Once for each domain */
  1795. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1796. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1797. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1798. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1799. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1800. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1801. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1802. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1803. #if defined(USE_TIMERS)
  1804. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1805. #endif
  1806. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1807. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1808. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1809. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1810. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1811. #if defined(USE_TIMERS)
  1812. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1813. #endif
  1814. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1815. #if defined(USE_4_CGI)
  1816. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1817. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1818. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1819. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1820. #if defined(USE_TIMERS)
  1821. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1822. #endif
  1823. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1824. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1825. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1826. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1827. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1828. #if defined(USE_TIMERS)
  1829. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1830. #endif
  1831. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1832. #endif
  1833. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1834. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1835. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1836. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1837. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1838. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1839. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1840. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1841. {"index_files",
  1842. MG_CONFIG_TYPE_STRING_LIST,
  1843. #if defined(USE_LUA)
  1844. "index.xhtml,index.html,index.htm,"
  1845. "index.lp,index.lsp,index.lua,index.cgi,"
  1846. "index.shtml,index.php"},
  1847. #else
  1848. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1849. #endif
  1850. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1851. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1852. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1853. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1854. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1855. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1856. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1857. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1858. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1859. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1860. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1861. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1862. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1863. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1864. * as a minimum in 2020 */
  1865. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1866. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1867. #if defined(USE_LUA)
  1868. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1869. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1870. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1871. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1872. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1873. #endif
  1874. #endif
  1875. #if defined(USE_DUKTAPE)
  1876. /* The support for duktape is still in alpha version state.
  1877. * The name of this config option might change. */
  1878. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1879. #endif
  1880. #if defined(USE_WEBSOCKET)
  1881. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1882. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1883. #endif
  1884. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1885. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1886. #endif
  1887. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1888. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1889. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1890. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1891. #if !defined(NO_CACHING)
  1892. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1893. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1894. #endif
  1895. #if !defined(NO_SSL)
  1896. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1897. #endif
  1898. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1899. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1900. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1901. /* Check if the config_options and the corresponding enum have compatible
  1902. * sizes. */
  1903. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1904. == (NUM_OPTIONS + 1),
  1905. "config_options and enum not sync");
  1906. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1907. struct mg_handler_info {
  1908. /* Name/Pattern of the URI. */
  1909. char *uri;
  1910. size_t uri_len;
  1911. /* handler type */
  1912. int handler_type;
  1913. /* Handler for http/https or requests. */
  1914. mg_request_handler handler;
  1915. unsigned int refcount;
  1916. int removing;
  1917. /* Handler for ws/wss (websocket) requests. */
  1918. mg_websocket_connect_handler connect_handler;
  1919. mg_websocket_ready_handler ready_handler;
  1920. mg_websocket_data_handler data_handler;
  1921. mg_websocket_close_handler close_handler;
  1922. /* accepted subprotocols for ws/wss requests. */
  1923. struct mg_websocket_subprotocols *subprotocols;
  1924. /* Handler for authorization requests */
  1925. mg_authorization_handler auth_handler;
  1926. /* User supplied argument for the handler function. */
  1927. void *cbdata;
  1928. /* next handler in a linked list */
  1929. struct mg_handler_info *next;
  1930. };
  1931. enum {
  1932. CONTEXT_INVALID,
  1933. CONTEXT_SERVER,
  1934. CONTEXT_HTTP_CLIENT,
  1935. CONTEXT_WS_CLIENT
  1936. };
  1937. struct mg_domain_context {
  1938. SSL_CTX *ssl_ctx; /* SSL context */
  1939. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1940. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1941. int64_t ssl_cert_last_mtime;
  1942. /* Server nonce */
  1943. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1944. unsigned long nonce_count; /* Used nonces, used for authentication */
  1945. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1946. /* linked list of shared lua websockets */
  1947. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1948. #endif
  1949. /* Linked list of domains */
  1950. struct mg_domain_context *next;
  1951. };
  1952. /* Stop flag can be "volatile" or require a lock.
  1953. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1954. * states a read operation for int is always atomic. */
  1955. #if defined(STOP_FLAG_NEEDS_LOCK)
  1956. typedef ptrdiff_t volatile stop_flag_t;
  1957. static int
  1958. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1959. {
  1960. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1961. return (sf == 0);
  1962. }
  1963. static int
  1964. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1965. {
  1966. stop_flag_t sf = mg_atomic_add(f, 0);
  1967. return (sf == 2);
  1968. }
  1969. static void
  1970. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1971. {
  1972. stop_flag_t sf = 0;
  1973. do {
  1974. sf = mg_atomic_compare_and_swap(f, *f, v);
  1975. } while (sf != v);
  1976. }
  1977. #else /* STOP_FLAG_NEEDS_LOCK */
  1978. typedef int volatile stop_flag_t;
  1979. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1980. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1981. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1982. #endif /* STOP_FLAG_NEEDS_LOCK */
  1983. #if !defined(NUM_WEBDAV_LOCKS)
  1984. #define NUM_WEBDAV_LOCKS 10
  1985. #endif
  1986. #if !defined(LOCK_DURATION_S)
  1987. #define LOCK_DURATION_S 60
  1988. #endif
  1989. struct twebdav_lock {
  1990. uint64_t locktime;
  1991. char token[33];
  1992. char path[UTF8_PATH_MAX * 2];
  1993. char user[UTF8_PATH_MAX * 2];
  1994. };
  1995. struct mg_context {
  1996. /* Part 1 - Physical context:
  1997. * This holds threads, ports, timeouts, ...
  1998. * set for the entire server, independent from the
  1999. * addressed hostname.
  2000. */
  2001. /* Connection related */
  2002. int context_type; /* See CONTEXT_* above */
  2003. struct socket *listening_sockets;
  2004. struct mg_pollfd *listening_socket_fds;
  2005. unsigned int num_listening_sockets;
  2006. struct mg_connection *worker_connections; /* The connection struct, pre-
  2007. * allocated for each worker */
  2008. #if defined(USE_SERVER_STATS)
  2009. volatile ptrdiff_t active_connections;
  2010. volatile ptrdiff_t max_active_connections;
  2011. volatile ptrdiff_t total_connections;
  2012. volatile ptrdiff_t total_requests;
  2013. volatile int64_t total_data_read;
  2014. volatile int64_t total_data_written;
  2015. #endif
  2016. /* Thread related */
  2017. stop_flag_t stop_flag; /* Should we stop event loop */
  2018. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2019. pthread_t masterthreadid; /* The master thread ID */
  2020. unsigned int
  2021. cfg_worker_threads; /* The number of configured worker threads. */
  2022. pthread_t *worker_threadids; /* The worker thread IDs */
  2023. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2024. /* Connection to thread dispatching */
  2025. #if defined(ALTERNATIVE_QUEUE)
  2026. struct socket *client_socks;
  2027. void **client_wait_events;
  2028. #else
  2029. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2030. worker thread */
  2031. volatile int sq_head; /* Head of the socket queue */
  2032. volatile int sq_tail; /* Tail of the socket queue */
  2033. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2034. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2035. volatile int sq_blocked; /* Status information: sq is full */
  2036. int sq_size; /* No of elements in socket queue */
  2037. #if defined(USE_SERVER_STATS)
  2038. int sq_max_fill;
  2039. #endif /* USE_SERVER_STATS */
  2040. #endif /* ALTERNATIVE_QUEUE */
  2041. /* Memory related */
  2042. unsigned int max_request_size; /* The max request size */
  2043. #if defined(USE_SERVER_STATS)
  2044. struct mg_memory_stat ctx_memory;
  2045. #endif
  2046. /* WebDAV lock structures */
  2047. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2048. /* Operating system related */
  2049. char *systemName; /* What operating system is running */
  2050. time_t start_time; /* Server start time, used for authentication
  2051. * and for diagnstics. */
  2052. #if defined(USE_TIMERS)
  2053. struct ttimers *timers;
  2054. #endif
  2055. /* Lua specific: Background operations and shared websockets */
  2056. #if defined(USE_LUA)
  2057. void *lua_background_state; /* lua_State (here as void *) */
  2058. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2059. int lua_bg_log_available; /* Use Lua background state for access log */
  2060. #endif
  2061. /* Server nonce */
  2062. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2063. * ssl_cert_last_mtime, nonce_count, and
  2064. * next (linked list) */
  2065. /* Server callbacks */
  2066. struct mg_callbacks callbacks; /* User-defined callback function */
  2067. void *user_data; /* User-defined data */
  2068. /* Part 2 - Logical domain:
  2069. * This holds hostname, TLS certificate, document root, ...
  2070. * set for a domain hosted at the server.
  2071. * There may be multiple domains hosted at one physical server.
  2072. * The default domain "dd" is the first element of a list of
  2073. * domains.
  2074. */
  2075. struct mg_domain_context dd; /* default domain */
  2076. };
  2077. #if defined(USE_SERVER_STATS)
  2078. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2079. static struct mg_memory_stat *
  2080. get_memory_stat(struct mg_context *ctx)
  2081. {
  2082. if (ctx) {
  2083. return &(ctx->ctx_memory);
  2084. }
  2085. return &mg_common_memory;
  2086. }
  2087. #endif
  2088. enum {
  2089. CONNECTION_TYPE_INVALID = 0,
  2090. CONNECTION_TYPE_REQUEST = 1,
  2091. CONNECTION_TYPE_RESPONSE = 2
  2092. };
  2093. enum {
  2094. PROTOCOL_TYPE_HTTP1 = 0,
  2095. PROTOCOL_TYPE_WEBSOCKET = 1,
  2096. PROTOCOL_TYPE_HTTP2 = 2
  2097. };
  2098. #if defined(USE_HTTP2)
  2099. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2100. #define HTTP2_DYN_TABLE_SIZE (256)
  2101. #endif
  2102. struct mg_http2_connection {
  2103. uint32_t stream_id;
  2104. uint32_t dyn_table_size;
  2105. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2106. };
  2107. #endif
  2108. struct mg_connection {
  2109. int connection_type; /* see CONNECTION_TYPE_* above */
  2110. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2111. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2112. fully sent */
  2113. #if defined(USE_HTTP2)
  2114. struct mg_http2_connection http2;
  2115. #endif
  2116. struct mg_request_info request_info;
  2117. struct mg_response_info response_info;
  2118. struct mg_context *phys_ctx;
  2119. struct mg_domain_context *dom_ctx;
  2120. #if defined(USE_SERVER_STATS)
  2121. int conn_state; /* 0 = undef, numerical value may change in different
  2122. * versions. For the current definition, see
  2123. * mg_get_connection_info_impl */
  2124. #endif
  2125. SSL *ssl; /* SSL descriptor */
  2126. struct socket client; /* Connected client */
  2127. time_t conn_birth_time; /* Time (wall clock) when connection was
  2128. * established */
  2129. #if defined(USE_SERVER_STATS)
  2130. time_t conn_close_time; /* Time (wall clock) when connection was
  2131. * closed (or 0 if still open) */
  2132. double processing_time; /* Processing time for one request. */
  2133. #endif
  2134. struct timespec req_time; /* Time (since system start) when the request
  2135. * was received */
  2136. int64_t num_bytes_sent; /* Total bytes sent to client */
  2137. int64_t content_len; /* How many bytes of content can be read
  2138. * !is_chunked: Content-Length header value
  2139. * or -1 (until connection closed,
  2140. * not allowed for a request)
  2141. * is_chunked: >= 0, appended gradually
  2142. */
  2143. int64_t consumed_content; /* How many bytes of content have been read */
  2144. int is_chunked; /* Transfer-Encoding is chunked:
  2145. * 0 = not chunked,
  2146. * 1 = chunked, not yet, or some data read,
  2147. * 2 = chunked, has error,
  2148. * 3 = chunked, all data read except trailer,
  2149. * 4 = chunked, all data read
  2150. */
  2151. char *buf; /* Buffer for received data */
  2152. char *path_info; /* PATH_INFO part of the URL */
  2153. int must_close; /* 1 if connection must be closed */
  2154. int accept_gzip; /* 1 if gzip encoding is accepted */
  2155. int in_error_handler; /* 1 if in handler for user defined error
  2156. * pages */
  2157. #if defined(USE_WEBSOCKET)
  2158. int in_websocket_handling; /* 1 if in read_websocket */
  2159. #endif
  2160. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2161. && defined(MG_EXPERIMENTAL_INTERFACES)
  2162. /* Parameters for websocket data compression according to rfc7692 */
  2163. int websocket_deflate_server_max_windows_bits;
  2164. int websocket_deflate_client_max_windows_bits;
  2165. int websocket_deflate_server_no_context_takeover;
  2166. int websocket_deflate_client_no_context_takeover;
  2167. int websocket_deflate_initialized;
  2168. int websocket_deflate_flush;
  2169. z_stream websocket_deflate_state;
  2170. z_stream websocket_inflate_state;
  2171. #endif
  2172. int handled_requests; /* Number of requests handled by this connection
  2173. */
  2174. int buf_size; /* Buffer size */
  2175. int request_len; /* Size of the request + headers in a buffer */
  2176. int data_len; /* Total size of data in a buffer */
  2177. int status_code; /* HTTP reply status code, e.g. 200 */
  2178. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2179. * throttle */
  2180. time_t last_throttle_time; /* Last time throttled data was sent */
  2181. int last_throttle_bytes; /* Bytes sent this second */
  2182. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2183. * atomic transmissions for websockets */
  2184. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2185. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2186. #endif
  2187. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2188. * for quick access */
  2189. };
  2190. /* Directory entry */
  2191. struct de {
  2192. char *file_name;
  2193. struct mg_file_stat file;
  2194. };
  2195. #define mg_cry_internal(conn, fmt, ...) \
  2196. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2197. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2198. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2199. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2200. struct mg_context *ctx,
  2201. const char *func,
  2202. unsigned line,
  2203. const char *fmt,
  2204. ...) PRINTF_ARGS(5, 6);
  2205. #if !defined(NO_THREAD_NAME)
  2206. #if defined(_WIN32) && defined(_MSC_VER)
  2207. /* Set the thread name for debugging purposes in Visual Studio
  2208. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2209. */
  2210. #pragma pack(push, 8)
  2211. typedef struct tagTHREADNAME_INFO {
  2212. DWORD dwType; /* Must be 0x1000. */
  2213. LPCSTR szName; /* Pointer to name (in user addr space). */
  2214. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2215. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2216. } THREADNAME_INFO;
  2217. #pragma pack(pop)
  2218. #elif defined(__linux__)
  2219. #include <sys/prctl.h>
  2220. #include <sys/sendfile.h>
  2221. #if defined(ALTERNATIVE_QUEUE)
  2222. #include <sys/eventfd.h>
  2223. #endif /* ALTERNATIVE_QUEUE */
  2224. #if defined(ALTERNATIVE_QUEUE)
  2225. static void *
  2226. event_create(void)
  2227. {
  2228. int evhdl = eventfd(0, EFD_CLOEXEC);
  2229. int *ret;
  2230. if (evhdl == -1) {
  2231. /* Linux uses -1 on error, Windows NULL. */
  2232. /* However, Linux does not return 0 on success either. */
  2233. return 0;
  2234. }
  2235. ret = (int *)mg_malloc(sizeof(int));
  2236. if (ret) {
  2237. *ret = evhdl;
  2238. } else {
  2239. (void)close(evhdl);
  2240. }
  2241. return (void *)ret;
  2242. }
  2243. static int
  2244. event_wait(void *eventhdl)
  2245. {
  2246. uint64_t u;
  2247. int evhdl, s;
  2248. if (!eventhdl) {
  2249. /* error */
  2250. return 0;
  2251. }
  2252. evhdl = *(int *)eventhdl;
  2253. s = (int)read(evhdl, &u, sizeof(u));
  2254. if (s != sizeof(u)) {
  2255. /* error */
  2256. return 0;
  2257. }
  2258. (void)u; /* the value is not required */
  2259. return 1;
  2260. }
  2261. static int
  2262. event_signal(void *eventhdl)
  2263. {
  2264. uint64_t u = 1;
  2265. int evhdl, s;
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return 0;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. s = (int)write(evhdl, &u, sizeof(u));
  2272. if (s != sizeof(u)) {
  2273. /* error */
  2274. return 0;
  2275. }
  2276. return 1;
  2277. }
  2278. static void
  2279. event_destroy(void *eventhdl)
  2280. {
  2281. int evhdl;
  2282. if (!eventhdl) {
  2283. /* error */
  2284. return;
  2285. }
  2286. evhdl = *(int *)eventhdl;
  2287. close(evhdl);
  2288. mg_free(eventhdl);
  2289. }
  2290. #endif
  2291. #endif
  2292. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2293. struct posix_event {
  2294. pthread_mutex_t mutex;
  2295. pthread_cond_t cond;
  2296. int signaled;
  2297. };
  2298. static void *
  2299. event_create(void)
  2300. {
  2301. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2302. if (ret == 0) {
  2303. /* out of memory */
  2304. return 0;
  2305. }
  2306. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2307. /* pthread mutex not available */
  2308. mg_free(ret);
  2309. return 0;
  2310. }
  2311. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2312. /* pthread cond not available */
  2313. pthread_mutex_destroy(&(ret->mutex));
  2314. mg_free(ret);
  2315. return 0;
  2316. }
  2317. ret->signaled = 0;
  2318. return (void *)ret;
  2319. }
  2320. static int
  2321. event_wait(void *eventhdl)
  2322. {
  2323. struct posix_event *ev = (struct posix_event *)eventhdl;
  2324. pthread_mutex_lock(&(ev->mutex));
  2325. while (!ev->signaled) {
  2326. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2327. }
  2328. ev->signaled = 0;
  2329. pthread_mutex_unlock(&(ev->mutex));
  2330. return 1;
  2331. }
  2332. static int
  2333. event_signal(void *eventhdl)
  2334. {
  2335. struct posix_event *ev = (struct posix_event *)eventhdl;
  2336. pthread_mutex_lock(&(ev->mutex));
  2337. pthread_cond_signal(&(ev->cond));
  2338. ev->signaled = 1;
  2339. pthread_mutex_unlock(&(ev->mutex));
  2340. return 1;
  2341. }
  2342. static void
  2343. event_destroy(void *eventhdl)
  2344. {
  2345. struct posix_event *ev = (struct posix_event *)eventhdl;
  2346. pthread_cond_destroy(&(ev->cond));
  2347. pthread_mutex_destroy(&(ev->mutex));
  2348. mg_free(ev);
  2349. }
  2350. #endif
  2351. static void
  2352. mg_set_thread_name(const char *name)
  2353. {
  2354. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2355. mg_snprintf(
  2356. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2357. #if defined(_WIN32)
  2358. #if defined(_MSC_VER)
  2359. /* Windows and Visual Studio Compiler */
  2360. __try {
  2361. THREADNAME_INFO info;
  2362. info.dwType = 0x1000;
  2363. info.szName = threadName;
  2364. info.dwThreadID = ~0U;
  2365. info.dwFlags = 0;
  2366. RaiseException(0x406D1388,
  2367. 0,
  2368. sizeof(info) / sizeof(ULONG_PTR),
  2369. (ULONG_PTR *)&info);
  2370. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2371. }
  2372. #elif defined(__MINGW32__)
  2373. /* No option known to set thread name for MinGW known */
  2374. #endif
  2375. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2376. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2377. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2378. #if defined(__MACH__) && defined(__APPLE__)
  2379. /* OS X only current thread name can be changed */
  2380. (void)pthread_setname_np(threadName);
  2381. #else
  2382. (void)pthread_setname_np(pthread_self(), threadName);
  2383. #endif
  2384. #elif defined(__linux__)
  2385. /* On Linux we can use the prctl function.
  2386. * When building for Linux Standard Base (LSB) use
  2387. * NO_THREAD_NAME. However, thread names are a big
  2388. * help for debugging, so the stadard is to set them.
  2389. */
  2390. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2391. #endif
  2392. }
  2393. #else /* !defined(NO_THREAD_NAME) */
  2394. static void
  2395. mg_set_thread_name(const char *threadName)
  2396. {
  2397. }
  2398. #endif
  2399. CIVETWEB_API const struct mg_option *
  2400. mg_get_valid_options(void)
  2401. {
  2402. return config_options;
  2403. }
  2404. /* Do not open file (unused) */
  2405. #define MG_FOPEN_MODE_NONE (0)
  2406. /* Open file for read only access */
  2407. #define MG_FOPEN_MODE_READ (1)
  2408. /* Open file for writing, create and overwrite */
  2409. #define MG_FOPEN_MODE_WRITE (2)
  2410. /* Open file for writing, create and append */
  2411. #define MG_FOPEN_MODE_APPEND (4)
  2412. static int
  2413. is_file_opened(const struct mg_file_access *fileacc)
  2414. {
  2415. if (!fileacc) {
  2416. return 0;
  2417. }
  2418. return (fileacc->fp != NULL);
  2419. }
  2420. #if !defined(NO_FILESYSTEMS)
  2421. static int mg_stat(const struct mg_connection *conn,
  2422. const char *path,
  2423. struct mg_file_stat *filep);
  2424. /* Reject files with special characters (for Windows) */
  2425. static int
  2426. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2427. {
  2428. const uint8_t *c = (const uint8_t *)path;
  2429. (void)conn; /* not used */
  2430. if ((c == NULL) || (c[0] == 0)) {
  2431. /* Null pointer or empty path --> suspicious */
  2432. return 1;
  2433. }
  2434. #if defined(_WIN32)
  2435. while (*c) {
  2436. if (*c < 32) {
  2437. /* Control character */
  2438. return 1;
  2439. }
  2440. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2441. /* stdin/stdout redirection character */
  2442. return 1;
  2443. }
  2444. if ((*c == '*') || (*c == '?')) {
  2445. /* Wildcard character */
  2446. return 1;
  2447. }
  2448. if (*c == '"') {
  2449. /* Windows quotation */
  2450. return 1;
  2451. }
  2452. c++;
  2453. }
  2454. #endif
  2455. /* Nothing suspicious found */
  2456. return 0;
  2457. }
  2458. /* mg_fopen will open a file either in memory or on the disk.
  2459. * The input parameter path is a string in UTF-8 encoding.
  2460. * The input parameter mode is MG_FOPEN_MODE_*
  2461. * On success, fp will be set in the output struct mg_file.
  2462. * All status members will also be set.
  2463. * The function returns 1 on success, 0 on error. */
  2464. static int
  2465. mg_fopen(const struct mg_connection *conn,
  2466. const char *path,
  2467. int mode,
  2468. struct mg_file *filep)
  2469. {
  2470. int found;
  2471. if (!filep) {
  2472. return 0;
  2473. }
  2474. filep->access.fp = NULL;
  2475. if (mg_path_suspicious(conn, path)) {
  2476. return 0;
  2477. }
  2478. /* filep is initialized in mg_stat: all fields with memset to,
  2479. * some fields like size and modification date with values */
  2480. found = mg_stat(conn, path, &(filep->stat));
  2481. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2482. /* file does not exist and will not be created */
  2483. return 0;
  2484. }
  2485. #if defined(_WIN32)
  2486. {
  2487. wchar_t wbuf[UTF16_PATH_MAX];
  2488. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2489. switch (mode) {
  2490. case MG_FOPEN_MODE_READ:
  2491. filep->access.fp = _wfopen(wbuf, L"rb");
  2492. break;
  2493. case MG_FOPEN_MODE_WRITE:
  2494. filep->access.fp = _wfopen(wbuf, L"wb");
  2495. break;
  2496. case MG_FOPEN_MODE_APPEND:
  2497. filep->access.fp = _wfopen(wbuf, L"ab");
  2498. break;
  2499. }
  2500. }
  2501. #else
  2502. /* Linux et al already use unicode. No need to convert. */
  2503. switch (mode) {
  2504. case MG_FOPEN_MODE_READ:
  2505. filep->access.fp = fopen(path, "r");
  2506. break;
  2507. case MG_FOPEN_MODE_WRITE:
  2508. filep->access.fp = fopen(path, "w");
  2509. break;
  2510. case MG_FOPEN_MODE_APPEND:
  2511. filep->access.fp = fopen(path, "a");
  2512. break;
  2513. }
  2514. #endif
  2515. if (!found) {
  2516. /* File did not exist before fopen was called.
  2517. * Maybe it has been created now. Get stat info
  2518. * like creation time now. */
  2519. found = mg_stat(conn, path, &(filep->stat));
  2520. (void)found;
  2521. }
  2522. /* return OK if file is opened */
  2523. return (filep->access.fp != NULL);
  2524. }
  2525. /* return 0 on success, just like fclose */
  2526. static int
  2527. mg_fclose(struct mg_file_access *fileacc)
  2528. {
  2529. int ret = -1;
  2530. if (fileacc != NULL) {
  2531. if (fileacc->fp != NULL) {
  2532. ret = fclose(fileacc->fp);
  2533. }
  2534. /* reset all members of fileacc */
  2535. memset(fileacc, 0, sizeof(*fileacc));
  2536. }
  2537. return ret;
  2538. }
  2539. #endif /* NO_FILESYSTEMS */
  2540. static void
  2541. mg_strlcpy(char *dst, const char *src, size_t n)
  2542. {
  2543. for (; *src != '\0' && n > 1; n--) {
  2544. *dst++ = *src++;
  2545. }
  2546. *dst = '\0';
  2547. }
  2548. static int
  2549. lowercase(const char *s)
  2550. {
  2551. return tolower((unsigned char)*s);
  2552. }
  2553. CIVETWEB_API int
  2554. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2555. {
  2556. int diff = 0;
  2557. if (len > 0) {
  2558. do {
  2559. diff = lowercase(s1++) - lowercase(s2++);
  2560. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2561. }
  2562. return diff;
  2563. }
  2564. CIVETWEB_API int
  2565. mg_strcasecmp(const char *s1, const char *s2)
  2566. {
  2567. int diff;
  2568. do {
  2569. diff = lowercase(s1++) - lowercase(s2++);
  2570. } while (diff == 0 && s1[-1] != '\0');
  2571. return diff;
  2572. }
  2573. static char *
  2574. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2575. {
  2576. char *p;
  2577. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2578. * defined */
  2579. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2580. mg_strlcpy(p, ptr, len + 1);
  2581. }
  2582. return p;
  2583. }
  2584. static char *
  2585. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2586. {
  2587. return mg_strndup_ctx(str, strlen(str), ctx);
  2588. }
  2589. static char *
  2590. mg_strdup(const char *str)
  2591. {
  2592. return mg_strndup_ctx(str, strlen(str), NULL);
  2593. }
  2594. static const char *
  2595. mg_strcasestr(const char *big_str, const char *small_str)
  2596. {
  2597. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2598. if (big_len >= small_len) {
  2599. for (i = 0; i <= (big_len - small_len); i++) {
  2600. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2601. return big_str + i;
  2602. }
  2603. }
  2604. }
  2605. return NULL;
  2606. }
  2607. /* Return null terminated string of given maximum length.
  2608. * Report errors if length is exceeded. */
  2609. static void
  2610. mg_vsnprintf(const struct mg_connection *conn,
  2611. int *truncated,
  2612. char *buf,
  2613. size_t buflen,
  2614. const char *fmt,
  2615. va_list ap)
  2616. {
  2617. int n, ok;
  2618. if (buflen == 0) {
  2619. if (truncated) {
  2620. *truncated = 1;
  2621. }
  2622. return;
  2623. }
  2624. #if defined(__clang__)
  2625. #pragma clang diagnostic push
  2626. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2627. /* Using fmt as a non-literal is intended here, since it is mostly called
  2628. * indirectly by mg_snprintf */
  2629. #endif
  2630. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2631. ok = (n >= 0) && ((size_t)n < buflen);
  2632. #if defined(__clang__)
  2633. #pragma clang diagnostic pop
  2634. #endif
  2635. if (ok) {
  2636. if (truncated) {
  2637. *truncated = 0;
  2638. }
  2639. } else {
  2640. if (truncated) {
  2641. *truncated = 1;
  2642. }
  2643. mg_cry_internal(conn,
  2644. "truncating vsnprintf buffer: [%.*s]",
  2645. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2646. buf);
  2647. n = (int)buflen - 1;
  2648. }
  2649. buf[n] = '\0';
  2650. }
  2651. static void
  2652. mg_snprintf(const struct mg_connection *conn,
  2653. int *truncated,
  2654. char *buf,
  2655. size_t buflen,
  2656. const char *fmt,
  2657. ...)
  2658. {
  2659. va_list ap;
  2660. va_start(ap, fmt);
  2661. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2662. va_end(ap);
  2663. }
  2664. static int
  2665. get_option_index(const char *name)
  2666. {
  2667. int i;
  2668. for (i = 0; config_options[i].name != NULL; i++) {
  2669. if (strcmp(config_options[i].name, name) == 0) {
  2670. return i;
  2671. }
  2672. }
  2673. return -1;
  2674. }
  2675. CIVETWEB_API const char *
  2676. mg_get_option(const struct mg_context *ctx, const char *name)
  2677. {
  2678. int i;
  2679. if ((i = get_option_index(name)) == -1) {
  2680. return NULL;
  2681. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2682. return "";
  2683. } else {
  2684. return ctx->dd.config[i];
  2685. }
  2686. }
  2687. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2688. CIVETWEB_API struct mg_context *
  2689. mg_get_context(const struct mg_connection *conn)
  2690. {
  2691. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2692. }
  2693. CIVETWEB_API void *
  2694. mg_get_user_data(const struct mg_context *ctx)
  2695. {
  2696. return (ctx == NULL) ? NULL : ctx->user_data;
  2697. }
  2698. CIVETWEB_API void *
  2699. mg_get_user_context_data(const struct mg_connection *conn)
  2700. {
  2701. return mg_get_user_data(mg_get_context(conn));
  2702. }
  2703. CIVETWEB_API void *
  2704. mg_get_thread_pointer(const struct mg_connection *conn)
  2705. {
  2706. /* both methods should return the same pointer */
  2707. if (conn) {
  2708. /* quick access, in case conn is known */
  2709. return conn->tls_user_ptr;
  2710. } else {
  2711. /* otherwise get pointer from thread local storage (TLS) */
  2712. struct mg_workerTLS *tls =
  2713. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2714. return tls->user_ptr;
  2715. }
  2716. }
  2717. CIVETWEB_API void
  2718. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2719. {
  2720. if (const_conn != NULL) {
  2721. /* Const cast, since "const struct mg_connection *" does not mean
  2722. * the connection object is not modified. Here "const" is used,
  2723. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2724. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2725. conn->request_info.conn_data = data;
  2726. }
  2727. }
  2728. CIVETWEB_API void *
  2729. mg_get_user_connection_data(const struct mg_connection *conn)
  2730. {
  2731. if (conn != NULL) {
  2732. return conn->request_info.conn_data;
  2733. }
  2734. return NULL;
  2735. }
  2736. CIVETWEB_API int
  2737. mg_get_server_ports(const struct mg_context *ctx,
  2738. int size,
  2739. struct mg_server_port *ports)
  2740. {
  2741. int i, cnt = 0;
  2742. if (size <= 0) {
  2743. return -1;
  2744. }
  2745. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2746. if (!ctx) {
  2747. return -1;
  2748. }
  2749. if (!ctx->listening_sockets) {
  2750. return -1;
  2751. }
  2752. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2753. ports[cnt].port =
  2754. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2755. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2756. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2757. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2758. /* IPv4 */
  2759. ports[cnt].protocol = 1;
  2760. cnt++;
  2761. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2762. /* IPv6 */
  2763. ports[cnt].protocol = 3;
  2764. cnt++;
  2765. }
  2766. }
  2767. return cnt;
  2768. }
  2769. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2770. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2771. #endif
  2772. static void
  2773. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2774. {
  2775. buf[0] = '\0';
  2776. if (!usa) {
  2777. return;
  2778. }
  2779. if (usa->sa.sa_family == AF_INET) {
  2780. getnameinfo(&usa->sa,
  2781. sizeof(usa->sin),
  2782. buf,
  2783. (unsigned)len,
  2784. NULL,
  2785. 0,
  2786. NI_NUMERICHOST);
  2787. }
  2788. #if defined(USE_IPV6)
  2789. else if (usa->sa.sa_family == AF_INET6) {
  2790. getnameinfo(&usa->sa,
  2791. sizeof(usa->sin6),
  2792. buf,
  2793. (unsigned)len,
  2794. NULL,
  2795. 0,
  2796. NI_NUMERICHOST);
  2797. }
  2798. #endif
  2799. #if defined(USE_X_DOM_SOCKET)
  2800. else if (usa->sa.sa_family == AF_UNIX) {
  2801. /* TODO: Define a remote address for unix domain sockets.
  2802. * This code will always return "localhost", identical to http+tcp:
  2803. getnameinfo(&usa->sa,
  2804. sizeof(usa->sun),
  2805. buf,
  2806. (unsigned)len,
  2807. NULL,
  2808. 0,
  2809. NI_NUMERICHOST);
  2810. */
  2811. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2812. }
  2813. #endif
  2814. }
  2815. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2816. * included in all responses other than 100, 101, 5xx. */
  2817. static void
  2818. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2819. {
  2820. #if !defined(REENTRANT_TIME)
  2821. struct tm *tm;
  2822. tm = ((t != NULL) ? gmtime(t) : NULL);
  2823. if (tm != NULL) {
  2824. #else
  2825. struct tm _tm;
  2826. struct tm *tm = &_tm;
  2827. if (t != NULL) {
  2828. gmtime_r(t, tm);
  2829. #endif
  2830. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2831. } else {
  2832. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2833. }
  2834. }
  2835. /* difftime for struct timespec. Return value is in seconds. */
  2836. static double
  2837. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2838. {
  2839. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2840. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2841. }
  2842. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2843. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2844. const char *func,
  2845. unsigned line,
  2846. const char *fmt,
  2847. va_list ap);
  2848. #include "external_mg_cry_internal_impl.inl"
  2849. #elif !defined(NO_FILESYSTEMS)
  2850. /* Print error message to the opened error log stream. */
  2851. static void
  2852. mg_cry_internal_impl(const struct mg_connection *conn,
  2853. const char *func,
  2854. unsigned line,
  2855. const char *fmt,
  2856. va_list ap)
  2857. {
  2858. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2859. struct mg_file fi;
  2860. time_t timestamp;
  2861. /* Unused, in the RELEASE build */
  2862. (void)func;
  2863. (void)line;
  2864. #if defined(GCC_DIAGNOSTIC)
  2865. #pragma GCC diagnostic push
  2866. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2867. #endif
  2868. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2869. #if defined(GCC_DIAGNOSTIC)
  2870. #pragma GCC diagnostic pop
  2871. #endif
  2872. buf[sizeof(buf) - 1] = 0;
  2873. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2874. if (!conn) {
  2875. puts(buf);
  2876. return;
  2877. }
  2878. /* Do not lock when getting the callback value, here and below.
  2879. * I suppose this is fine, since function cannot disappear in the
  2880. * same way string option can. */
  2881. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2882. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2883. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2884. if (mg_fopen(conn,
  2885. conn->dom_ctx->config[ERROR_LOG_FILE],
  2886. MG_FOPEN_MODE_APPEND,
  2887. &fi)
  2888. == 0) {
  2889. fi.access.fp = NULL;
  2890. }
  2891. } else {
  2892. fi.access.fp = NULL;
  2893. }
  2894. if (fi.access.fp != NULL) {
  2895. flockfile(fi.access.fp);
  2896. timestamp = time(NULL);
  2897. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2898. fprintf(fi.access.fp,
  2899. "[%010lu] [error] [client %s] ",
  2900. (unsigned long)timestamp,
  2901. src_addr);
  2902. if (conn->request_info.request_method != NULL) {
  2903. fprintf(fi.access.fp,
  2904. "%s %s: ",
  2905. conn->request_info.request_method,
  2906. conn->request_info.request_uri
  2907. ? conn->request_info.request_uri
  2908. : "");
  2909. }
  2910. fprintf(fi.access.fp, "%s", buf);
  2911. fputc('\n', fi.access.fp);
  2912. fflush(fi.access.fp);
  2913. funlockfile(fi.access.fp);
  2914. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2915. * mg_cry here anyway ;-) */
  2916. }
  2917. }
  2918. }
  2919. #else
  2920. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2921. #endif /* Externally provided function */
  2922. /* Construct fake connection structure. Used for logging, if connection
  2923. * is not applicable at the moment of logging. */
  2924. static struct mg_connection *
  2925. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2926. {
  2927. static const struct mg_connection conn_zero = {0};
  2928. *fc = conn_zero;
  2929. fc->phys_ctx = ctx;
  2930. fc->dom_ctx = &(ctx->dd);
  2931. return fc;
  2932. }
  2933. static void
  2934. mg_cry_internal_wrap(const struct mg_connection *conn,
  2935. struct mg_context *ctx,
  2936. const char *func,
  2937. unsigned line,
  2938. const char *fmt,
  2939. ...)
  2940. {
  2941. va_list ap;
  2942. va_start(ap, fmt);
  2943. if (!conn && ctx) {
  2944. struct mg_connection fc;
  2945. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2946. } else {
  2947. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2948. }
  2949. va_end(ap);
  2950. }
  2951. CIVETWEB_API void
  2952. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2953. {
  2954. va_list ap;
  2955. va_start(ap, fmt);
  2956. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2957. va_end(ap);
  2958. }
  2959. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2960. CIVETWEB_API const char *
  2961. mg_version(void)
  2962. {
  2963. return CIVETWEB_VERSION;
  2964. }
  2965. CIVETWEB_API const struct mg_request_info *
  2966. mg_get_request_info(const struct mg_connection *conn)
  2967. {
  2968. if (!conn) {
  2969. return NULL;
  2970. }
  2971. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2972. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2973. char txt[16];
  2974. struct mg_workerTLS *tls =
  2975. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2976. sprintf(txt, "%03i", conn->response_info.status_code);
  2977. if (strlen(txt) == 3) {
  2978. memcpy(tls->txtbuf, txt, 4);
  2979. } else {
  2980. strcpy(tls->txtbuf, "ERR");
  2981. }
  2982. ((struct mg_connection *)conn)->request_info.local_uri =
  2983. tls->txtbuf; /* use thread safe buffer */
  2984. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2985. tls->txtbuf; /* use the same thread safe buffer */
  2986. ((struct mg_connection *)conn)->request_info.request_uri =
  2987. tls->txtbuf; /* use the same thread safe buffer */
  2988. ((struct mg_connection *)conn)->request_info.num_headers =
  2989. conn->response_info.num_headers;
  2990. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2991. conn->response_info.http_headers,
  2992. sizeof(conn->response_info.http_headers));
  2993. } else
  2994. #endif
  2995. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2996. return NULL;
  2997. }
  2998. return &conn->request_info;
  2999. }
  3000. CIVETWEB_API const struct mg_response_info *
  3001. mg_get_response_info(const struct mg_connection *conn)
  3002. {
  3003. if (!conn) {
  3004. return NULL;
  3005. }
  3006. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3007. return NULL;
  3008. }
  3009. return &conn->response_info;
  3010. }
  3011. static const char *
  3012. get_proto_name(const struct mg_connection *conn)
  3013. {
  3014. #if defined(__clang__)
  3015. #pragma clang diagnostic push
  3016. #pragma clang diagnostic ignored "-Wunreachable-code"
  3017. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3018. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3019. * unreachable, but splitting into four different #ifdef clauses here is
  3020. * more complicated.
  3021. */
  3022. #endif
  3023. const struct mg_request_info *ri = &conn->request_info;
  3024. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3025. ? (ri->is_ssl ? "wss" : "ws")
  3026. : (ri->is_ssl ? "https" : "http"));
  3027. return proto;
  3028. #if defined(__clang__)
  3029. #pragma clang diagnostic pop
  3030. #endif
  3031. }
  3032. static int
  3033. mg_construct_local_link(const struct mg_connection *conn,
  3034. char *buf,
  3035. size_t buflen,
  3036. const char *define_proto,
  3037. int define_port,
  3038. const char *define_uri)
  3039. {
  3040. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3041. return -1;
  3042. } else {
  3043. int i, j;
  3044. int truncated = 0;
  3045. const struct mg_request_info *ri = &conn->request_info;
  3046. const char *proto =
  3047. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3048. const char *uri =
  3049. (define_uri != NULL)
  3050. ? define_uri
  3051. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3052. int port = (define_port > 0) ? define_port : ri->server_port;
  3053. int default_port = 80;
  3054. char *uri_encoded;
  3055. size_t uri_encoded_len;
  3056. if (uri == NULL) {
  3057. return -1;
  3058. }
  3059. uri_encoded_len = strlen(uri) * 3 + 1;
  3060. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3061. if (uri_encoded == NULL) {
  3062. return -1;
  3063. }
  3064. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3065. /* Directory separator should be preserved. */
  3066. for (i = j = 0; uri_encoded[i]; j++) {
  3067. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3068. uri_encoded[j] = '/';
  3069. i += 3;
  3070. } else {
  3071. uri_encoded[j] = uri_encoded[i++];
  3072. }
  3073. }
  3074. uri_encoded[j] = '\0';
  3075. #if defined(USE_X_DOM_SOCKET)
  3076. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3077. /* TODO: Define and document a link for UNIX domain sockets. */
  3078. /* There seems to be no official standard for this.
  3079. * Common uses seem to be "httpunix://", "http.unix://" or
  3080. * "http+unix://" as a protocol definition string, followed by
  3081. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3082. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3083. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3084. * "" (completely skipping the server name part). In any case, the
  3085. * last part is the server local path. */
  3086. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3087. mg_snprintf(conn,
  3088. &truncated,
  3089. buf,
  3090. buflen,
  3091. "%s.unix://%s%s",
  3092. proto,
  3093. server_name,
  3094. ri->local_uri);
  3095. default_port = 0;
  3096. mg_free(uri_encoded);
  3097. return 0;
  3098. }
  3099. #endif
  3100. if (define_proto) {
  3101. /* If we got a protocol name, use the default port accordingly. */
  3102. if ((0 == strcmp(define_proto, "https"))
  3103. || (0 == strcmp(define_proto, "wss"))) {
  3104. default_port = 443;
  3105. }
  3106. } else if (ri->is_ssl) {
  3107. /* If we did not get a protocol name, use TLS as default if it is
  3108. * already used. */
  3109. default_port = 443;
  3110. }
  3111. {
  3112. #if defined(USE_IPV6)
  3113. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3114. #endif
  3115. int auth_domain_check_enabled =
  3116. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3117. && (!mg_strcasecmp(
  3118. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3119. const char *server_domain =
  3120. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3121. char portstr[16];
  3122. char server_ip[48];
  3123. if (port != default_port) {
  3124. sprintf(portstr, ":%u", (unsigned)port);
  3125. } else {
  3126. portstr[0] = 0;
  3127. }
  3128. if (!auth_domain_check_enabled || !server_domain) {
  3129. sockaddr_to_string(server_ip,
  3130. sizeof(server_ip),
  3131. &conn->client.lsa);
  3132. server_domain = server_ip;
  3133. }
  3134. mg_snprintf(conn,
  3135. &truncated,
  3136. buf,
  3137. buflen,
  3138. #if defined(USE_IPV6)
  3139. "%s://%s%s%s%s%s",
  3140. proto,
  3141. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3142. server_domain,
  3143. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3144. #else
  3145. "%s://%s%s%s",
  3146. proto,
  3147. server_domain,
  3148. #endif
  3149. portstr,
  3150. uri_encoded);
  3151. mg_free(uri_encoded);
  3152. if (truncated) {
  3153. return -1;
  3154. }
  3155. return 0;
  3156. }
  3157. }
  3158. }
  3159. CIVETWEB_API int
  3160. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3161. {
  3162. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3163. }
  3164. /* Skip the characters until one of the delimiters characters found.
  3165. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3166. * Advance pointer to buffer to the next word. Return found 0-terminated
  3167. * word.
  3168. * Delimiters can be quoted with quotechar. */
  3169. static char *
  3170. skip_quoted(char **buf,
  3171. const char *delimiters,
  3172. const char *whitespace,
  3173. char quotechar)
  3174. {
  3175. char *p, *begin_word, *end_word, *end_whitespace;
  3176. begin_word = *buf;
  3177. end_word = begin_word + strcspn(begin_word, delimiters);
  3178. /* Check for quotechar */
  3179. if (end_word > begin_word) {
  3180. p = end_word - 1;
  3181. while (*p == quotechar) {
  3182. /* While the delimiter is quoted, look for the next delimiter. */
  3183. /* This happens, e.g., in calls from parse_auth_header,
  3184. * if the user name contains a " character. */
  3185. /* If there is anything beyond end_word, copy it. */
  3186. if (*end_word != '\0') {
  3187. size_t end_off = strcspn(end_word + 1, delimiters);
  3188. memmove(p, end_word, end_off + 1);
  3189. p += end_off; /* p must correspond to end_word - 1 */
  3190. end_word += end_off + 1;
  3191. } else {
  3192. *p = '\0';
  3193. break;
  3194. }
  3195. }
  3196. for (p++; p < end_word; p++) {
  3197. *p = '\0';
  3198. }
  3199. }
  3200. if (*end_word == '\0') {
  3201. *buf = end_word;
  3202. } else {
  3203. #if defined(GCC_DIAGNOSTIC)
  3204. /* Disable spurious conversion warning for GCC */
  3205. #pragma GCC diagnostic push
  3206. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3207. #endif /* defined(GCC_DIAGNOSTIC) */
  3208. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3209. #if defined(GCC_DIAGNOSTIC)
  3210. #pragma GCC diagnostic pop
  3211. #endif /* defined(GCC_DIAGNOSTIC) */
  3212. for (p = end_word; p < end_whitespace; p++) {
  3213. *p = '\0';
  3214. }
  3215. *buf = end_whitespace;
  3216. }
  3217. return begin_word;
  3218. }
  3219. /* Return HTTP header value, or NULL if not found. */
  3220. static const char *
  3221. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3222. {
  3223. int i;
  3224. for (i = 0; i < num_hdr; i++) {
  3225. if (!mg_strcasecmp(name, hdr[i].name)) {
  3226. return hdr[i].value;
  3227. }
  3228. }
  3229. return NULL;
  3230. }
  3231. /* Retrieve requested HTTP header multiple values, and return the number of
  3232. * found occurrences */
  3233. static int
  3234. get_req_headers(const struct mg_request_info *ri,
  3235. const char *name,
  3236. const char **output,
  3237. int output_max_size)
  3238. {
  3239. int i;
  3240. int cnt = 0;
  3241. if (ri) {
  3242. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3243. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3244. output[cnt++] = ri->http_headers[i].value;
  3245. }
  3246. }
  3247. }
  3248. return cnt;
  3249. }
  3250. CIVETWEB_API const char *
  3251. mg_get_header(const struct mg_connection *conn, const char *name)
  3252. {
  3253. if (!conn) {
  3254. return NULL;
  3255. }
  3256. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3257. return get_header(conn->request_info.http_headers,
  3258. conn->request_info.num_headers,
  3259. name);
  3260. }
  3261. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3262. return get_header(conn->response_info.http_headers,
  3263. conn->response_info.num_headers,
  3264. name);
  3265. }
  3266. return NULL;
  3267. }
  3268. static const char *
  3269. get_http_version(const struct mg_connection *conn)
  3270. {
  3271. if (!conn) {
  3272. return NULL;
  3273. }
  3274. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3275. return conn->request_info.http_version;
  3276. }
  3277. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3278. return conn->response_info.http_version;
  3279. }
  3280. return NULL;
  3281. }
  3282. /* A helper function for traversing a comma separated list of values.
  3283. * It returns a list pointer shifted to the next value, or NULL if the end
  3284. * of the list found.
  3285. * Value is stored in val vector. If value has form "x=y", then eq_val
  3286. * vector is initialized to point to the "y" part, and val vector length
  3287. * is adjusted to point only to "x". */
  3288. static const char *
  3289. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3290. {
  3291. int end;
  3292. reparse:
  3293. if (val == NULL || list == NULL || *list == '\0') {
  3294. /* End of the list */
  3295. return NULL;
  3296. }
  3297. /* Skip over leading LWS */
  3298. while (*list == ' ' || *list == '\t')
  3299. list++;
  3300. val->ptr = list;
  3301. if ((list = strchr(val->ptr, ',')) != NULL) {
  3302. /* Comma found. Store length and shift the list ptr */
  3303. val->len = ((size_t)(list - val->ptr));
  3304. list++;
  3305. } else {
  3306. /* This value is the last one */
  3307. list = val->ptr + strlen(val->ptr);
  3308. val->len = ((size_t)(list - val->ptr));
  3309. }
  3310. /* Adjust length for trailing LWS */
  3311. end = (int)val->len - 1;
  3312. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3313. end--;
  3314. val->len = (size_t)(end) + (size_t)(1);
  3315. if (val->len == 0) {
  3316. /* Ignore any empty entries. */
  3317. goto reparse;
  3318. }
  3319. if (eq_val != NULL) {
  3320. /* Value has form "x=y", adjust pointers and lengths
  3321. * so that val points to "x", and eq_val points to "y". */
  3322. eq_val->len = 0;
  3323. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3324. if (eq_val->ptr != NULL) {
  3325. eq_val->ptr++; /* Skip over '=' character */
  3326. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3327. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3328. }
  3329. }
  3330. return list;
  3331. }
  3332. /* A helper function for checking if a comma separated list of values
  3333. * contains
  3334. * the given option (case insensitvely).
  3335. * 'header' can be NULL, in which case false is returned. */
  3336. static int
  3337. header_has_option(const char *header, const char *option)
  3338. {
  3339. struct vec opt_vec;
  3340. struct vec eq_vec;
  3341. DEBUG_ASSERT(option != NULL);
  3342. DEBUG_ASSERT(option[0] != '\0');
  3343. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3344. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3345. return 1;
  3346. }
  3347. return 0;
  3348. }
  3349. /* Sorting function implemented in a separate file */
  3350. #include "sort.inl"
  3351. /* Pattern matching has been reimplemented in a new file */
  3352. #include "match.inl"
  3353. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3354. * This function must tolerate situations when connection info is not
  3355. * set up, for example if request parsing failed. */
  3356. static int
  3357. should_keep_alive(const struct mg_connection *conn)
  3358. {
  3359. const char *http_version;
  3360. const char *header;
  3361. /* First satisfy needs of the server */
  3362. if ((conn == NULL) || conn->must_close) {
  3363. /* Close, if civetweb framework needs to close */
  3364. return 0;
  3365. }
  3366. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3367. /* Close, if keep alive is not enabled */
  3368. return 0;
  3369. }
  3370. /* Check explicit wish of the client */
  3371. header = mg_get_header(conn, "Connection");
  3372. if (header) {
  3373. /* If there is a connection header from the client, obey */
  3374. if (header_has_option(header, "keep-alive")) {
  3375. return 1;
  3376. }
  3377. return 0;
  3378. }
  3379. /* Use default of the standard */
  3380. http_version = get_http_version(conn);
  3381. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3382. /* HTTP 1.1 default is keep alive */
  3383. return 1;
  3384. }
  3385. /* HTTP 1.0 (and earlier) default is to close the connection */
  3386. return 0;
  3387. }
  3388. static int
  3389. should_decode_url(const struct mg_connection *conn)
  3390. {
  3391. if (!conn || !conn->dom_ctx) {
  3392. return 0;
  3393. }
  3394. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3395. }
  3396. static int
  3397. should_decode_query_string(const struct mg_connection *conn)
  3398. {
  3399. if (!conn || !conn->dom_ctx) {
  3400. return 0;
  3401. }
  3402. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3403. == 0);
  3404. }
  3405. static const char *
  3406. suggest_connection_header(const struct mg_connection *conn)
  3407. {
  3408. return should_keep_alive(conn) ? "keep-alive" : "close";
  3409. }
  3410. #include "response.inl"
  3411. static void
  3412. send_no_cache_header(struct mg_connection *conn)
  3413. {
  3414. /* Send all current and obsolete cache opt-out directives. */
  3415. mg_response_header_add(conn,
  3416. "Cache-Control",
  3417. "no-cache, no-store, "
  3418. "must-revalidate, private, max-age=0",
  3419. -1);
  3420. mg_response_header_add(conn, "Expires", "0", -1);
  3421. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3422. /* Obsolete, but still send it for HTTP/1.0 */
  3423. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3424. }
  3425. }
  3426. static void
  3427. send_static_cache_header(struct mg_connection *conn)
  3428. {
  3429. #if !defined(NO_CACHING)
  3430. int max_age;
  3431. char val[64];
  3432. const char *cache_control =
  3433. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3434. /* If there is a full cache-control option configured,0 use it */
  3435. if (cache_control != NULL) {
  3436. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3437. return;
  3438. }
  3439. /* Read the server config to check how long a file may be cached.
  3440. * The configuration is in seconds. */
  3441. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3442. if (max_age <= 0) {
  3443. /* 0 means "do not cache". All values <0 are reserved
  3444. * and may be used differently in the future. */
  3445. /* If a file should not be cached, do not only send
  3446. * max-age=0, but also pragmas and Expires headers. */
  3447. send_no_cache_header(conn);
  3448. return;
  3449. }
  3450. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3451. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3452. /* See also https://www.mnot.net/cache_docs/ */
  3453. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3454. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3455. * leap
  3456. * year to 31622400 seconds. For the moment, we just send whatever has
  3457. * been configured, still the behavior for >1 year should be considered
  3458. * as undefined. */
  3459. mg_snprintf(
  3460. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3461. mg_response_header_add(conn, "Cache-Control", val, -1);
  3462. #else /* NO_CACHING */
  3463. send_no_cache_header(conn);
  3464. #endif /* !NO_CACHING */
  3465. }
  3466. static void
  3467. send_additional_header(struct mg_connection *conn)
  3468. {
  3469. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3470. #if !defined(NO_SSL)
  3471. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3472. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3473. if (max_age >= 0) {
  3474. char val[64];
  3475. mg_snprintf(conn,
  3476. NULL,
  3477. val,
  3478. sizeof(val),
  3479. "max-age=%lu",
  3480. (unsigned long)max_age);
  3481. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3482. }
  3483. }
  3484. #endif
  3485. if (header && header[0]) {
  3486. mg_response_header_add_lines(conn, header);
  3487. }
  3488. }
  3489. static void
  3490. send_cors_header(struct mg_connection *conn)
  3491. {
  3492. const char *origin_hdr = mg_get_header(conn, "Origin");
  3493. const char *cors_orig_cfg =
  3494. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3495. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3496. /* Cross-origin resource sharing (CORS), see
  3497. * http://www.html5rocks.com/en/tutorials/cors/,
  3498. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3499. * CORS preflight is not supported for files. */
  3500. mg_response_header_add(conn,
  3501. "Access-Control-Allow-Origin",
  3502. cors_orig_cfg,
  3503. -1);
  3504. }
  3505. }
  3506. #if !defined(NO_FILESYSTEMS)
  3507. static void handle_file_based_request(struct mg_connection *conn,
  3508. const char *path,
  3509. struct mg_file *filep);
  3510. #endif /* NO_FILESYSTEMS */
  3511. CIVETWEB_API const char *
  3512. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3513. {
  3514. /* See IANA HTTP status code assignment:
  3515. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3516. */
  3517. switch (response_code) {
  3518. /* RFC2616 Section 10.1 - Informational 1xx */
  3519. case 100:
  3520. return "Continue"; /* RFC2616 Section 10.1.1 */
  3521. case 101:
  3522. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3523. case 102:
  3524. return "Processing"; /* RFC2518 Section 10.1 */
  3525. /* RFC2616 Section 10.2 - Successful 2xx */
  3526. case 200:
  3527. return "OK"; /* RFC2616 Section 10.2.1 */
  3528. case 201:
  3529. return "Created"; /* RFC2616 Section 10.2.2 */
  3530. case 202:
  3531. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3532. case 203:
  3533. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3534. case 204:
  3535. return "No Content"; /* RFC2616 Section 10.2.5 */
  3536. case 205:
  3537. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3538. case 206:
  3539. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3540. case 207:
  3541. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3542. */
  3543. case 208:
  3544. return "Already Reported"; /* RFC5842 Section 7.1 */
  3545. case 226:
  3546. return "IM used"; /* RFC3229 Section 10.4.1 */
  3547. /* RFC2616 Section 10.3 - Redirection 3xx */
  3548. case 300:
  3549. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3550. case 301:
  3551. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3552. case 302:
  3553. return "Found"; /* RFC2616 Section 10.3.3 */
  3554. case 303:
  3555. return "See Other"; /* RFC2616 Section 10.3.4 */
  3556. case 304:
  3557. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3558. case 305:
  3559. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3560. case 307:
  3561. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3562. case 308:
  3563. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3564. /* RFC2616 Section 10.4 - Client Error 4xx */
  3565. case 400:
  3566. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3567. case 401:
  3568. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3569. case 402:
  3570. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3571. case 403:
  3572. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3573. case 404:
  3574. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3575. case 405:
  3576. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3577. case 406:
  3578. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3579. case 407:
  3580. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3581. case 408:
  3582. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3583. case 409:
  3584. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3585. case 410:
  3586. return "Gone"; /* RFC2616 Section 10.4.11 */
  3587. case 411:
  3588. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3589. case 412:
  3590. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3591. case 413:
  3592. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3593. case 414:
  3594. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3595. case 415:
  3596. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3597. case 416:
  3598. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3599. */
  3600. case 417:
  3601. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3602. case 421:
  3603. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3604. case 422:
  3605. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3606. * Section 11.2 */
  3607. case 423:
  3608. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3609. case 424:
  3610. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3611. * Section 11.4 */
  3612. case 426:
  3613. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3614. case 428:
  3615. return "Precondition Required"; /* RFC 6585, Section 3 */
  3616. case 429:
  3617. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3618. case 431:
  3619. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3620. case 451:
  3621. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3622. * Section 3 */
  3623. /* RFC2616 Section 10.5 - Server Error 5xx */
  3624. case 500:
  3625. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3626. case 501:
  3627. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3628. case 502:
  3629. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3630. case 503:
  3631. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3632. case 504:
  3633. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3634. case 505:
  3635. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3636. case 506:
  3637. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3638. case 507:
  3639. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3640. * Section 11.5 */
  3641. case 508:
  3642. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3643. case 510:
  3644. return "Not Extended"; /* RFC 2774, Section 7 */
  3645. case 511:
  3646. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3647. /* Other status codes, not shown in the IANA HTTP status code
  3648. * assignment.
  3649. * E.g., "de facto" standards due to common use, ... */
  3650. case 418:
  3651. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3652. case 419:
  3653. return "Authentication Timeout"; /* common use */
  3654. case 420:
  3655. return "Enhance Your Calm"; /* common use */
  3656. case 440:
  3657. return "Login Timeout"; /* common use */
  3658. case 509:
  3659. return "Bandwidth Limit Exceeded"; /* common use */
  3660. default:
  3661. /* This error code is unknown. This should not happen. */
  3662. if (conn) {
  3663. mg_cry_internal(conn,
  3664. "Unknown HTTP response code: %u",
  3665. response_code);
  3666. }
  3667. /* Return at least a category according to RFC 2616 Section 10. */
  3668. if (response_code >= 100 && response_code < 200) {
  3669. /* Unknown informational status code */
  3670. return "Information";
  3671. }
  3672. if (response_code >= 200 && response_code < 300) {
  3673. /* Unknown success code */
  3674. return "Success";
  3675. }
  3676. if (response_code >= 300 && response_code < 400) {
  3677. /* Unknown redirection code */
  3678. return "Redirection";
  3679. }
  3680. if (response_code >= 400 && response_code < 500) {
  3681. /* Unknown request error code */
  3682. return "Client Error";
  3683. }
  3684. if (response_code >= 500 && response_code < 600) {
  3685. /* Unknown server error code */
  3686. return "Server Error";
  3687. }
  3688. /* Response code not even within reasonable range */
  3689. return "";
  3690. }
  3691. }
  3692. static int
  3693. mg_send_http_error_impl(struct mg_connection *conn,
  3694. int status,
  3695. const char *fmt,
  3696. va_list args)
  3697. {
  3698. char errmsg_buf[MG_BUF_LEN];
  3699. va_list ap;
  3700. int has_body;
  3701. #if !defined(NO_FILESYSTEMS)
  3702. char path_buf[UTF8_PATH_MAX];
  3703. int len, i, page_handler_found, scope, truncated;
  3704. const char *error_handler = NULL;
  3705. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3706. const char *error_page_file_ext, *tstr;
  3707. #endif /* NO_FILESYSTEMS */
  3708. int handled_by_callback = 0;
  3709. if ((conn == NULL) || (fmt == NULL)) {
  3710. return -2;
  3711. }
  3712. /* Set status (for log) */
  3713. conn->status_code = status;
  3714. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3715. has_body = ((status > 199) && (status != 204) && (status != 304));
  3716. /* Prepare message in buf, if required */
  3717. if (has_body
  3718. || (!conn->in_error_handler
  3719. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3720. /* Store error message in errmsg_buf */
  3721. va_copy(ap, args);
  3722. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3723. va_end(ap);
  3724. /* In a debug build, print all html errors */
  3725. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3726. }
  3727. /* If there is a http_error callback, call it.
  3728. * But don't do it recursively, if callback calls mg_send_http_error again.
  3729. */
  3730. if (!conn->in_error_handler
  3731. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3732. /* Mark in_error_handler to avoid recursion and call user callback. */
  3733. conn->in_error_handler = 1;
  3734. handled_by_callback =
  3735. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3736. == 0);
  3737. conn->in_error_handler = 0;
  3738. }
  3739. if (!handled_by_callback) {
  3740. /* Check for recursion */
  3741. if (conn->in_error_handler) {
  3742. DEBUG_TRACE(
  3743. "Recursion when handling error %u - fall back to default",
  3744. status);
  3745. #if !defined(NO_FILESYSTEMS)
  3746. } else {
  3747. /* Send user defined error pages, if defined */
  3748. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3749. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3750. page_handler_found = 0;
  3751. if (error_handler != NULL) {
  3752. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3753. switch (scope) {
  3754. case 1: /* Handler for specific error, e.g. 404 error */
  3755. mg_snprintf(conn,
  3756. &truncated,
  3757. path_buf,
  3758. sizeof(path_buf) - 32,
  3759. "%serror%03u.",
  3760. error_handler,
  3761. status);
  3762. break;
  3763. case 2: /* Handler for error group, e.g., 5xx error
  3764. * handler
  3765. * for all server errors (500-599) */
  3766. mg_snprintf(conn,
  3767. &truncated,
  3768. path_buf,
  3769. sizeof(path_buf) - 32,
  3770. "%serror%01uxx.",
  3771. error_handler,
  3772. status / 100);
  3773. break;
  3774. default: /* Handler for all errors */
  3775. mg_snprintf(conn,
  3776. &truncated,
  3777. path_buf,
  3778. sizeof(path_buf) - 32,
  3779. "%serror.",
  3780. error_handler);
  3781. break;
  3782. }
  3783. /* String truncation in buf may only occur if
  3784. * error_handler is too long. This string is
  3785. * from the config, not from a client. */
  3786. (void)truncated;
  3787. /* The following code is redundant, but it should avoid
  3788. * false positives in static source code analyzers and
  3789. * vulnerability scanners.
  3790. */
  3791. path_buf[sizeof(path_buf) - 32] = 0;
  3792. len = (int)strlen(path_buf);
  3793. if (len > (int)sizeof(path_buf) - 32) {
  3794. len = (int)sizeof(path_buf) - 32;
  3795. }
  3796. /* Start with the file extension from the configuration. */
  3797. tstr = strchr(error_page_file_ext, '.');
  3798. while (tstr) {
  3799. for (i = 1;
  3800. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3801. i++) {
  3802. /* buffer overrun is not possible here, since
  3803. * (i < 32) && (len < sizeof(path_buf) - 32)
  3804. * ==> (i + len) < sizeof(path_buf) */
  3805. path_buf[len + i - 1] = tstr[i];
  3806. }
  3807. /* buffer overrun is not possible here, since
  3808. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3809. * ==> (i + len) <= sizeof(path_buf) */
  3810. path_buf[len + i - 1] = 0;
  3811. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3812. DEBUG_TRACE("Check error page %s - found",
  3813. path_buf);
  3814. page_handler_found = 1;
  3815. break;
  3816. }
  3817. DEBUG_TRACE("Check error page %s - not found",
  3818. path_buf);
  3819. /* Continue with the next file extension from the
  3820. * configuration (if there is a next one). */
  3821. tstr = strchr(tstr + i, '.');
  3822. }
  3823. }
  3824. }
  3825. if (page_handler_found) {
  3826. conn->in_error_handler = 1;
  3827. handle_file_based_request(conn, path_buf, &error_page_file);
  3828. conn->in_error_handler = 0;
  3829. return 0;
  3830. }
  3831. #endif /* NO_FILESYSTEMS */
  3832. }
  3833. /* No custom error page. Send default error page. */
  3834. conn->must_close = 1;
  3835. mg_response_header_start(conn, status);
  3836. send_no_cache_header(conn);
  3837. send_additional_header(conn);
  3838. send_cors_header(conn);
  3839. if (has_body) {
  3840. mg_response_header_add(conn,
  3841. "Content-Type",
  3842. "text/plain; charset=utf-8",
  3843. -1);
  3844. }
  3845. mg_response_header_send(conn);
  3846. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3847. if (has_body) {
  3848. /* For other errors, send a generic error message. */
  3849. const char *status_text = mg_get_response_code_text(conn, status);
  3850. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3851. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3852. } else {
  3853. /* No body allowed. Close the connection. */
  3854. DEBUG_TRACE("Error %i", status);
  3855. }
  3856. }
  3857. return 0;
  3858. }
  3859. CIVETWEB_API int
  3860. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3861. {
  3862. va_list ap;
  3863. int ret;
  3864. va_start(ap, fmt);
  3865. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3866. va_end(ap);
  3867. return ret;
  3868. }
  3869. CIVETWEB_API int
  3870. mg_send_http_ok(struct mg_connection *conn,
  3871. const char *mime_type,
  3872. long long content_length)
  3873. {
  3874. if ((mime_type == NULL) || (*mime_type == 0)) {
  3875. /* No content type defined: default to text/html */
  3876. mime_type = "text/html";
  3877. }
  3878. mg_response_header_start(conn, 200);
  3879. send_no_cache_header(conn);
  3880. send_additional_header(conn);
  3881. send_cors_header(conn);
  3882. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3883. if (content_length < 0) {
  3884. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3885. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3886. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3887. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3888. }
  3889. } else {
  3890. char len[32];
  3891. int trunc = 0;
  3892. mg_snprintf(conn,
  3893. &trunc,
  3894. len,
  3895. sizeof(len),
  3896. "%" UINT64_FMT,
  3897. (uint64_t)content_length);
  3898. if (!trunc) {
  3899. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3900. * !trunc is always true */
  3901. mg_response_header_add(conn, "Content-Length", len, -1);
  3902. }
  3903. }
  3904. mg_response_header_send(conn);
  3905. return 0;
  3906. }
  3907. CIVETWEB_API int
  3908. mg_send_http_redirect(struct mg_connection *conn,
  3909. const char *target_url,
  3910. int redirect_code)
  3911. {
  3912. /* Send a 30x redirect response.
  3913. *
  3914. * Redirect types (status codes):
  3915. *
  3916. * Status | Perm/Temp | Method | Version
  3917. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3918. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3919. * 303 | temporary | always use GET | HTTP/1.1
  3920. * 307 | temporary | always keep method | HTTP/1.1
  3921. * 308 | permanent | always keep method | HTTP/1.1
  3922. */
  3923. #if defined(MG_SEND_REDIRECT_BODY)
  3924. char redirect_body[MG_BUF_LEN];
  3925. size_t content_len = 0;
  3926. char content_len_text[32];
  3927. #endif
  3928. /* In case redirect_code=0, use 307. */
  3929. if (redirect_code == 0) {
  3930. redirect_code = 307;
  3931. }
  3932. /* In case redirect_code is none of the above, return error. */
  3933. if ((redirect_code != 301) && (redirect_code != 302)
  3934. && (redirect_code != 303) && (redirect_code != 307)
  3935. && (redirect_code != 308)) {
  3936. /* Parameter error */
  3937. return -2;
  3938. }
  3939. /* If target_url is not defined, redirect to "/". */
  3940. if ((target_url == NULL) || (*target_url == 0)) {
  3941. target_url = "/";
  3942. }
  3943. #if defined(MG_SEND_REDIRECT_BODY)
  3944. /* TODO: condition name? */
  3945. /* Prepare a response body with a hyperlink.
  3946. *
  3947. * According to RFC2616 (and RFC1945 before):
  3948. * Unless the request method was HEAD, the entity of the
  3949. * response SHOULD contain a short hypertext note with a hyperlink to
  3950. * the new URI(s).
  3951. *
  3952. * However, this response body is not useful in M2M communication.
  3953. * Probably the original reason in the RFC was, clients not supporting
  3954. * a 30x HTTP redirect could still show the HTML page and let the user
  3955. * press the link. Since current browsers support 30x HTTP, the additional
  3956. * HTML body does not seem to make sense anymore.
  3957. *
  3958. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3959. * but it only notes:
  3960. * The server's response payload usually contains a short
  3961. * hypertext note with a hyperlink to the new URI(s).
  3962. *
  3963. * Deactivated by default. If you need the 30x body, set the define.
  3964. */
  3965. mg_snprintf(
  3966. conn,
  3967. NULL /* ignore truncation */,
  3968. redirect_body,
  3969. sizeof(redirect_body),
  3970. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3971. redirect_text,
  3972. target_url,
  3973. target_url);
  3974. content_len = strlen(reply);
  3975. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3976. #endif
  3977. /* Send all required headers */
  3978. mg_response_header_start(conn, redirect_code);
  3979. mg_response_header_add(conn, "Location", target_url, -1);
  3980. if ((redirect_code == 301) || (redirect_code == 308)) {
  3981. /* Permanent redirect */
  3982. send_static_cache_header(conn);
  3983. } else {
  3984. /* Temporary redirect */
  3985. send_no_cache_header(conn);
  3986. }
  3987. send_additional_header(conn);
  3988. send_cors_header(conn);
  3989. #if defined(MG_SEND_REDIRECT_BODY)
  3990. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3991. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3992. #else
  3993. mg_response_header_add(conn, "Content-Length", "0", 1);
  3994. #endif
  3995. mg_response_header_send(conn);
  3996. #if defined(MG_SEND_REDIRECT_BODY)
  3997. /* Send response body */
  3998. /* ... unless it is a HEAD request */
  3999. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4000. ret = mg_write(conn, redirect_body, content_len);
  4001. }
  4002. #endif
  4003. return 1;
  4004. }
  4005. #if defined(_WIN32)
  4006. /* Create substitutes for POSIX functions in Win32. */
  4007. #if defined(GCC_DIAGNOSTIC)
  4008. /* Show no warning in case system functions are not used. */
  4009. #pragma GCC diagnostic push
  4010. #pragma GCC diagnostic ignored "-Wunused-function"
  4011. #endif
  4012. static int
  4013. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4014. {
  4015. (void)unused;
  4016. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4017. InitializeCriticalSection(&mutex->sec);
  4018. return 0;
  4019. }
  4020. static int
  4021. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4022. {
  4023. DeleteCriticalSection(&mutex->sec);
  4024. return 0;
  4025. }
  4026. static int
  4027. pthread_mutex_lock(pthread_mutex_t *mutex)
  4028. {
  4029. EnterCriticalSection(&mutex->sec);
  4030. return 0;
  4031. }
  4032. static int
  4033. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4034. {
  4035. LeaveCriticalSection(&mutex->sec);
  4036. return 0;
  4037. }
  4038. FUNCTION_MAY_BE_UNUSED
  4039. static int
  4040. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4041. {
  4042. (void)unused;
  4043. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4044. cv->waiting_thread = NULL;
  4045. return 0;
  4046. }
  4047. FUNCTION_MAY_BE_UNUSED
  4048. static int
  4049. pthread_cond_timedwait(pthread_cond_t *cv,
  4050. pthread_mutex_t *mutex,
  4051. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4052. {
  4053. struct mg_workerTLS **ptls,
  4054. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4055. int ok;
  4056. uint64_t nsnow, nswaitabs;
  4057. int64_t nswaitrel;
  4058. DWORD mswaitrel;
  4059. pthread_mutex_lock(&cv->threadIdSec);
  4060. /* Add this thread to cv's waiting list */
  4061. ptls = &cv->waiting_thread;
  4062. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4063. ;
  4064. tls->next_waiting_thread = NULL;
  4065. *ptls = tls;
  4066. pthread_mutex_unlock(&cv->threadIdSec);
  4067. if (abstime) {
  4068. nsnow = mg_get_current_time_ns();
  4069. nswaitabs =
  4070. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4071. nswaitrel = nswaitabs - nsnow;
  4072. if (nswaitrel < 0) {
  4073. nswaitrel = 0;
  4074. }
  4075. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4076. } else {
  4077. mswaitrel = (DWORD)INFINITE;
  4078. }
  4079. pthread_mutex_unlock(mutex);
  4080. ok = (WAIT_OBJECT_0
  4081. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4082. if (!ok) {
  4083. ok = 1;
  4084. pthread_mutex_lock(&cv->threadIdSec);
  4085. ptls = &cv->waiting_thread;
  4086. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4087. if (*ptls == tls) {
  4088. *ptls = tls->next_waiting_thread;
  4089. ok = 0;
  4090. break;
  4091. }
  4092. }
  4093. pthread_mutex_unlock(&cv->threadIdSec);
  4094. if (ok) {
  4095. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4096. (DWORD)INFINITE);
  4097. }
  4098. }
  4099. /* This thread has been removed from cv's waiting list */
  4100. pthread_mutex_lock(mutex);
  4101. return ok ? 0 : -1;
  4102. }
  4103. FUNCTION_MAY_BE_UNUSED
  4104. static int
  4105. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4106. {
  4107. return pthread_cond_timedwait(cv, mutex, NULL);
  4108. }
  4109. FUNCTION_MAY_BE_UNUSED
  4110. static int
  4111. pthread_cond_signal(pthread_cond_t *cv)
  4112. {
  4113. HANDLE wkup = NULL;
  4114. BOOL ok = FALSE;
  4115. pthread_mutex_lock(&cv->threadIdSec);
  4116. if (cv->waiting_thread) {
  4117. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4118. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4119. ok = SetEvent(wkup);
  4120. DEBUG_ASSERT(ok);
  4121. }
  4122. pthread_mutex_unlock(&cv->threadIdSec);
  4123. return ok ? 0 : 1;
  4124. }
  4125. FUNCTION_MAY_BE_UNUSED
  4126. static int
  4127. pthread_cond_broadcast(pthread_cond_t *cv)
  4128. {
  4129. pthread_mutex_lock(&cv->threadIdSec);
  4130. while (cv->waiting_thread) {
  4131. pthread_cond_signal(cv);
  4132. }
  4133. pthread_mutex_unlock(&cv->threadIdSec);
  4134. return 0;
  4135. }
  4136. FUNCTION_MAY_BE_UNUSED
  4137. static int
  4138. pthread_cond_destroy(pthread_cond_t *cv)
  4139. {
  4140. pthread_mutex_lock(&cv->threadIdSec);
  4141. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4142. pthread_mutex_unlock(&cv->threadIdSec);
  4143. pthread_mutex_destroy(&cv->threadIdSec);
  4144. return 0;
  4145. }
  4146. #if defined(ALTERNATIVE_QUEUE)
  4147. FUNCTION_MAY_BE_UNUSED
  4148. static void *
  4149. event_create(void)
  4150. {
  4151. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4152. }
  4153. FUNCTION_MAY_BE_UNUSED
  4154. static int
  4155. event_wait(void *eventhdl)
  4156. {
  4157. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4158. return (res == WAIT_OBJECT_0);
  4159. }
  4160. FUNCTION_MAY_BE_UNUSED
  4161. static int
  4162. event_signal(void *eventhdl)
  4163. {
  4164. return (int)SetEvent((HANDLE)eventhdl);
  4165. }
  4166. FUNCTION_MAY_BE_UNUSED
  4167. static void
  4168. event_destroy(void *eventhdl)
  4169. {
  4170. CloseHandle((HANDLE)eventhdl);
  4171. }
  4172. #endif
  4173. #if defined(GCC_DIAGNOSTIC)
  4174. /* Enable unused function warning again */
  4175. #pragma GCC diagnostic pop
  4176. #endif
  4177. /* For Windows, change all slashes to backslashes in path names. */
  4178. static void
  4179. change_slashes_to_backslashes(char *path)
  4180. {
  4181. int i;
  4182. for (i = 0; path[i] != '\0'; i++) {
  4183. if (path[i] == '/') {
  4184. path[i] = '\\';
  4185. }
  4186. /* remove double backslash (check i > 0 to preserve UNC paths,
  4187. * like \\server\file.txt) */
  4188. if ((i > 0) && (path[i] == '\\')) {
  4189. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4190. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4191. }
  4192. }
  4193. }
  4194. }
  4195. static int
  4196. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4197. {
  4198. int diff;
  4199. do {
  4200. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4201. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4202. s1++;
  4203. s2++;
  4204. } while ((diff == 0) && (s1[-1] != L'\0'));
  4205. return diff;
  4206. }
  4207. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4208. * wbuf and wbuf_len is a target buffer and its length. */
  4209. static void
  4210. path_to_unicode(const struct mg_connection *conn,
  4211. const char *path,
  4212. wchar_t *wbuf,
  4213. size_t wbuf_len)
  4214. {
  4215. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4216. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4217. DWORD long_len, err;
  4218. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4219. mg_strlcpy(buf, path, sizeof(buf));
  4220. change_slashes_to_backslashes(buf);
  4221. /* Convert to Unicode and back. If doubly-converted string does not
  4222. * match the original, something is fishy, reject. */
  4223. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4224. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4225. WideCharToMultiByte(
  4226. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4227. if (strcmp(buf, buf2) != 0) {
  4228. wbuf[0] = L'\0';
  4229. }
  4230. /* Windows file systems are not case sensitive, but you can still use
  4231. * uppercase and lowercase letters (on all modern file systems).
  4232. * The server can check if the URI uses the same upper/lowercase
  4233. * letters an the file system, effectively making Windows servers
  4234. * case sensitive (like Linux servers are). It is still not possible
  4235. * to use two files with the same name in different cases on Windows
  4236. * (like /a and /A) - this would be possible in Linux.
  4237. * As a default, Windows is not case sensitive, but the case sensitive
  4238. * file name check can be activated by an additional configuration. */
  4239. if (conn) {
  4240. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4241. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4242. "yes")) {
  4243. /* Use case sensitive compare function */
  4244. fcompare = wcscmp;
  4245. }
  4246. }
  4247. (void)conn; /* conn is currently unused */
  4248. /* Only accept a full file path, not a Windows short (8.3) path. */
  4249. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4250. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4251. if (long_len == 0) {
  4252. err = GetLastError();
  4253. if (err == ERROR_FILE_NOT_FOUND) {
  4254. /* File does not exist. This is not always a problem here. */
  4255. return;
  4256. }
  4257. }
  4258. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4259. /* Short name is used. */
  4260. wbuf[0] = L'\0';
  4261. }
  4262. }
  4263. #if !defined(NO_FILESYSTEMS)
  4264. /* Get file information, return 1 if file exists, 0 if not */
  4265. static int
  4266. mg_stat(const struct mg_connection *conn,
  4267. const char *path,
  4268. struct mg_file_stat *filep)
  4269. {
  4270. wchar_t wbuf[UTF16_PATH_MAX];
  4271. WIN32_FILE_ATTRIBUTE_DATA info;
  4272. time_t creation_time;
  4273. size_t len;
  4274. if (!filep) {
  4275. return 0;
  4276. }
  4277. memset(filep, 0, sizeof(*filep));
  4278. if (mg_path_suspicious(conn, path)) {
  4279. return 0;
  4280. }
  4281. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4282. /* Windows happily opens files with some garbage at the end of file name.
  4283. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4284. * "a.cgi", despite one would expect an error back. */
  4285. len = strlen(path);
  4286. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4287. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4288. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4289. filep->last_modified =
  4290. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4291. info.ftLastWriteTime.dwHighDateTime);
  4292. /* On Windows, the file creation time can be higher than the
  4293. * modification time, e.g. when a file is copied.
  4294. * Since the Last-Modified timestamp is used for caching
  4295. * it should be based on the most recent timestamp. */
  4296. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4297. info.ftCreationTime.dwHighDateTime);
  4298. if (creation_time > filep->last_modified) {
  4299. filep->last_modified = creation_time;
  4300. }
  4301. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4302. return 1;
  4303. }
  4304. return 0;
  4305. }
  4306. #endif
  4307. static int
  4308. mg_remove(const struct mg_connection *conn, const char *path)
  4309. {
  4310. wchar_t wbuf[UTF16_PATH_MAX];
  4311. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4312. return DeleteFileW(wbuf) ? 0 : -1;
  4313. }
  4314. static int
  4315. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4316. {
  4317. wchar_t wbuf[UTF16_PATH_MAX];
  4318. (void)mode;
  4319. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4320. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4321. }
  4322. /* Create substitutes for POSIX functions in Win32. */
  4323. #if defined(GCC_DIAGNOSTIC)
  4324. /* Show no warning in case system functions are not used. */
  4325. #pragma GCC diagnostic push
  4326. #pragma GCC diagnostic ignored "-Wunused-function"
  4327. #endif
  4328. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4329. FUNCTION_MAY_BE_UNUSED
  4330. static DIR *
  4331. mg_opendir(const struct mg_connection *conn, const char *name)
  4332. {
  4333. DIR *dir = NULL;
  4334. wchar_t wpath[UTF16_PATH_MAX];
  4335. DWORD attrs;
  4336. if (name == NULL) {
  4337. SetLastError(ERROR_BAD_ARGUMENTS);
  4338. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4339. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4340. } else {
  4341. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4342. attrs = GetFileAttributesW(wpath);
  4343. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4344. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4345. (void)wcscat(wpath, L"\\*");
  4346. dir->handle = FindFirstFileW(wpath, &dir->info);
  4347. dir->result.d_name[0] = '\0';
  4348. } else {
  4349. mg_free(dir);
  4350. dir = NULL;
  4351. }
  4352. }
  4353. return dir;
  4354. }
  4355. FUNCTION_MAY_BE_UNUSED
  4356. static int
  4357. mg_closedir(DIR *dir)
  4358. {
  4359. int result = 0;
  4360. if (dir != NULL) {
  4361. if (dir->handle != INVALID_HANDLE_VALUE)
  4362. result = FindClose(dir->handle) ? 0 : -1;
  4363. mg_free(dir);
  4364. } else {
  4365. result = -1;
  4366. SetLastError(ERROR_BAD_ARGUMENTS);
  4367. }
  4368. return result;
  4369. }
  4370. FUNCTION_MAY_BE_UNUSED
  4371. static struct dirent *
  4372. mg_readdir(DIR *dir)
  4373. {
  4374. struct dirent *result = 0;
  4375. if (dir) {
  4376. if (dir->handle != INVALID_HANDLE_VALUE) {
  4377. result = &dir->result;
  4378. (void)WideCharToMultiByte(CP_UTF8,
  4379. 0,
  4380. dir->info.cFileName,
  4381. -1,
  4382. result->d_name,
  4383. sizeof(result->d_name),
  4384. NULL,
  4385. NULL);
  4386. if (!FindNextFileW(dir->handle, &dir->info)) {
  4387. (void)FindClose(dir->handle);
  4388. dir->handle = INVALID_HANDLE_VALUE;
  4389. }
  4390. } else {
  4391. SetLastError(ERROR_FILE_NOT_FOUND);
  4392. }
  4393. } else {
  4394. SetLastError(ERROR_BAD_ARGUMENTS);
  4395. }
  4396. return result;
  4397. }
  4398. #if !defined(HAVE_POLL)
  4399. #undef POLLIN
  4400. #undef POLLPRI
  4401. #undef POLLOUT
  4402. #undef POLLERR
  4403. #define POLLIN (1) /* Data ready - read will not block. */
  4404. #define POLLPRI (2) /* Priority data ready. */
  4405. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4406. #define POLLERR (8) /* Error event */
  4407. FUNCTION_MAY_BE_UNUSED
  4408. static int
  4409. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4410. {
  4411. struct timeval tv;
  4412. fd_set rset;
  4413. fd_set wset;
  4414. fd_set eset;
  4415. unsigned int i;
  4416. int result;
  4417. SOCKET maxfd = 0;
  4418. memset(&tv, 0, sizeof(tv));
  4419. tv.tv_sec = milliseconds / 1000;
  4420. tv.tv_usec = (milliseconds % 1000) * 1000;
  4421. FD_ZERO(&rset);
  4422. FD_ZERO(&wset);
  4423. FD_ZERO(&eset);
  4424. for (i = 0; i < n; i++) {
  4425. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4426. if (pfd[i].events & POLLIN) {
  4427. FD_SET(pfd[i].fd, &rset);
  4428. }
  4429. if (pfd[i].events & POLLOUT) {
  4430. FD_SET(pfd[i].fd, &wset);
  4431. }
  4432. /* Check for errors for any FD in the set */
  4433. FD_SET(pfd[i].fd, &eset);
  4434. }
  4435. pfd[i].revents = 0;
  4436. if (pfd[i].fd > maxfd) {
  4437. maxfd = pfd[i].fd;
  4438. }
  4439. }
  4440. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4441. for (i = 0; i < n; i++) {
  4442. if (FD_ISSET(pfd[i].fd, &rset)) {
  4443. pfd[i].revents |= POLLIN;
  4444. }
  4445. if (FD_ISSET(pfd[i].fd, &wset)) {
  4446. pfd[i].revents |= POLLOUT;
  4447. }
  4448. if (FD_ISSET(pfd[i].fd, &eset)) {
  4449. pfd[i].revents |= POLLERR;
  4450. }
  4451. }
  4452. }
  4453. /* We should subtract the time used in select from remaining
  4454. * "milliseconds", in particular if called from mg_poll with a
  4455. * timeout quantum.
  4456. * Unfortunately, the remaining time is not stored in "tv" in all
  4457. * implementations, so the result in "tv" must be considered undefined.
  4458. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4459. return result;
  4460. }
  4461. #endif /* HAVE_POLL */
  4462. #if defined(GCC_DIAGNOSTIC)
  4463. /* Enable unused function warning again */
  4464. #pragma GCC diagnostic pop
  4465. #endif
  4466. static void
  4467. set_close_on_exec(SOCKET sock,
  4468. const struct mg_connection *conn /* may be null */,
  4469. struct mg_context *ctx /* may be null */)
  4470. {
  4471. (void)conn; /* Unused. */
  4472. (void)ctx;
  4473. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4474. }
  4475. CIVETWEB_API int
  4476. mg_start_thread(mg_thread_func_t f, void *p)
  4477. {
  4478. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4479. /* Compile-time option to control stack size, e.g.
  4480. * -DUSE_STACK_SIZE=16384
  4481. */
  4482. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4483. == ((uintptr_t)(-1L)))
  4484. ? -1
  4485. : 0);
  4486. #else
  4487. return (
  4488. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4489. ? -1
  4490. : 0);
  4491. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4492. }
  4493. /* Start a thread storing the thread context. */
  4494. static int
  4495. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4496. void *p,
  4497. pthread_t *threadidptr)
  4498. {
  4499. uintptr_t uip;
  4500. HANDLE threadhandle;
  4501. int result = -1;
  4502. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4503. threadhandle = (HANDLE)uip;
  4504. if ((uip != 0) && (threadidptr != NULL)) {
  4505. *threadidptr = threadhandle;
  4506. result = 0;
  4507. }
  4508. return result;
  4509. }
  4510. /* Wait for a thread to finish. */
  4511. static int
  4512. mg_join_thread(pthread_t threadid)
  4513. {
  4514. int result;
  4515. DWORD dwevent;
  4516. result = -1;
  4517. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4518. if (dwevent == WAIT_FAILED) {
  4519. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4520. } else {
  4521. if (dwevent == WAIT_OBJECT_0) {
  4522. CloseHandle(threadid);
  4523. result = 0;
  4524. }
  4525. }
  4526. return result;
  4527. }
  4528. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4529. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4530. /* Create substitutes for POSIX functions in Win32. */
  4531. #if defined(GCC_DIAGNOSTIC)
  4532. /* Show no warning in case system functions are not used. */
  4533. #pragma GCC diagnostic push
  4534. #pragma GCC diagnostic ignored "-Wunused-function"
  4535. #endif
  4536. FUNCTION_MAY_BE_UNUSED
  4537. static HANDLE
  4538. dlopen(const char *dll_name, int flags)
  4539. {
  4540. wchar_t wbuf[UTF16_PATH_MAX];
  4541. (void)flags;
  4542. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4543. return LoadLibraryW(wbuf);
  4544. }
  4545. FUNCTION_MAY_BE_UNUSED
  4546. static int
  4547. dlclose(void *handle)
  4548. {
  4549. int result;
  4550. if (FreeLibrary((HMODULE)handle) != 0) {
  4551. result = 0;
  4552. } else {
  4553. result = -1;
  4554. }
  4555. return result;
  4556. }
  4557. #if defined(GCC_DIAGNOSTIC)
  4558. /* Enable unused function warning again */
  4559. #pragma GCC diagnostic pop
  4560. #endif
  4561. #endif
  4562. #if !defined(NO_CGI)
  4563. #define SIGKILL (0)
  4564. static int
  4565. kill(pid_t pid, int sig_num)
  4566. {
  4567. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4568. (void)CloseHandle((HANDLE)pid);
  4569. return 0;
  4570. }
  4571. #if !defined(WNOHANG)
  4572. #define WNOHANG (1)
  4573. #endif
  4574. static pid_t
  4575. waitpid(pid_t pid, int *status, int flags)
  4576. {
  4577. DWORD timeout = INFINITE;
  4578. DWORD waitres;
  4579. (void)status; /* Currently not used by any client here */
  4580. if ((flags | WNOHANG) == WNOHANG) {
  4581. timeout = 0;
  4582. }
  4583. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4584. if (waitres == WAIT_OBJECT_0) {
  4585. return pid;
  4586. }
  4587. if (waitres == WAIT_TIMEOUT) {
  4588. return 0;
  4589. }
  4590. return (pid_t)-1;
  4591. }
  4592. static void
  4593. trim_trailing_whitespaces(char *s)
  4594. {
  4595. char *e = s + strlen(s);
  4596. while ((e > s) && isspace((unsigned char)e[-1])) {
  4597. *(--e) = '\0';
  4598. }
  4599. }
  4600. static pid_t
  4601. spawn_process(struct mg_connection *conn,
  4602. const char *prog,
  4603. char *envblk,
  4604. char *envp[],
  4605. int fdin[2],
  4606. int fdout[2],
  4607. int fderr[2],
  4608. const char *dir,
  4609. int cgi_config_idx)
  4610. {
  4611. HANDLE me;
  4612. char *interp;
  4613. char *interp_arg = 0;
  4614. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4615. int truncated;
  4616. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4617. STARTUPINFOA si;
  4618. PROCESS_INFORMATION pi = {0};
  4619. (void)envp;
  4620. memset(&si, 0, sizeof(si));
  4621. si.cb = sizeof(si);
  4622. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4623. si.wShowWindow = SW_HIDE;
  4624. me = GetCurrentProcess();
  4625. DuplicateHandle(me,
  4626. (HANDLE)_get_osfhandle(fdin[0]),
  4627. me,
  4628. &si.hStdInput,
  4629. 0,
  4630. TRUE,
  4631. DUPLICATE_SAME_ACCESS);
  4632. DuplicateHandle(me,
  4633. (HANDLE)_get_osfhandle(fdout[1]),
  4634. me,
  4635. &si.hStdOutput,
  4636. 0,
  4637. TRUE,
  4638. DUPLICATE_SAME_ACCESS);
  4639. DuplicateHandle(me,
  4640. (HANDLE)_get_osfhandle(fderr[1]),
  4641. me,
  4642. &si.hStdError,
  4643. 0,
  4644. TRUE,
  4645. DUPLICATE_SAME_ACCESS);
  4646. /* Mark handles that should not be inherited. See
  4647. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4648. */
  4649. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4650. HANDLE_FLAG_INHERIT,
  4651. 0);
  4652. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4653. HANDLE_FLAG_INHERIT,
  4654. 0);
  4655. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4656. HANDLE_FLAG_INHERIT,
  4657. 0);
  4658. /* First check, if there is a CGI interpreter configured for all CGI
  4659. * scripts. */
  4660. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4661. if (interp != NULL) {
  4662. /* If there is a configured interpreter, check for additional arguments
  4663. */
  4664. interp_arg =
  4665. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4666. } else {
  4667. /* Otherwise, the interpreter must be stated in the first line of the
  4668. * CGI script file, after a #! (shebang) mark. */
  4669. buf[0] = buf[1] = '\0';
  4670. /* Get the full script path */
  4671. mg_snprintf(
  4672. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4673. if (truncated) {
  4674. pi.hProcess = (pid_t)-1;
  4675. goto spawn_cleanup;
  4676. }
  4677. /* Open the script file, to read the first line */
  4678. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4679. /* Read the first line of the script into the buffer */
  4680. mg_fgets(buf, sizeof(buf), &file);
  4681. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4682. buf[sizeof(buf) - 1] = '\0';
  4683. }
  4684. if ((buf[0] == '#') && (buf[1] == '!')) {
  4685. trim_trailing_whitespaces(buf + 2);
  4686. } else {
  4687. buf[2] = '\0';
  4688. }
  4689. interp = buf + 2;
  4690. }
  4691. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4692. if (interp[0] != '\0') {
  4693. /* This is an interpreted script file. We must call the interpreter. */
  4694. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4695. mg_snprintf(conn,
  4696. &truncated,
  4697. cmdline,
  4698. sizeof(cmdline),
  4699. "\"%s\" %s \"%s\\%s\"",
  4700. interp,
  4701. interp_arg,
  4702. full_dir,
  4703. prog);
  4704. } else {
  4705. mg_snprintf(conn,
  4706. &truncated,
  4707. cmdline,
  4708. sizeof(cmdline),
  4709. "\"%s\" \"%s\\%s\"",
  4710. interp,
  4711. full_dir,
  4712. prog);
  4713. }
  4714. } else {
  4715. /* This is (probably) a compiled program. We call it directly. */
  4716. mg_snprintf(conn,
  4717. &truncated,
  4718. cmdline,
  4719. sizeof(cmdline),
  4720. "\"%s\\%s\"",
  4721. full_dir,
  4722. prog);
  4723. }
  4724. if (truncated) {
  4725. pi.hProcess = (pid_t)-1;
  4726. goto spawn_cleanup;
  4727. }
  4728. DEBUG_TRACE("Running [%s]", cmdline);
  4729. if (CreateProcessA(NULL,
  4730. cmdline,
  4731. NULL,
  4732. NULL,
  4733. TRUE,
  4734. CREATE_NEW_PROCESS_GROUP,
  4735. envblk,
  4736. NULL,
  4737. &si,
  4738. &pi)
  4739. == 0) {
  4740. mg_cry_internal(
  4741. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4742. pi.hProcess = (pid_t)-1;
  4743. /* goto spawn_cleanup; */
  4744. }
  4745. spawn_cleanup:
  4746. (void)CloseHandle(si.hStdOutput);
  4747. (void)CloseHandle(si.hStdError);
  4748. (void)CloseHandle(si.hStdInput);
  4749. if (pi.hThread != NULL) {
  4750. (void)CloseHandle(pi.hThread);
  4751. }
  4752. return (pid_t)pi.hProcess;
  4753. }
  4754. #endif /* !NO_CGI */
  4755. static int
  4756. set_blocking_mode(SOCKET sock)
  4757. {
  4758. unsigned long non_blocking = 0;
  4759. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4760. }
  4761. static int
  4762. set_non_blocking_mode(SOCKET sock)
  4763. {
  4764. unsigned long non_blocking = 1;
  4765. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4766. }
  4767. #else
  4768. #if !defined(NO_FILESYSTEMS)
  4769. static int
  4770. mg_stat(const struct mg_connection *conn,
  4771. const char *path,
  4772. struct mg_file_stat *filep)
  4773. {
  4774. struct stat st;
  4775. if (!filep) {
  4776. return 0;
  4777. }
  4778. memset(filep, 0, sizeof(*filep));
  4779. if (mg_path_suspicious(conn, path)) {
  4780. return 0;
  4781. }
  4782. if (0 == stat(path, &st)) {
  4783. filep->size = (uint64_t)(st.st_size);
  4784. filep->last_modified = st.st_mtime;
  4785. filep->is_directory = S_ISDIR(st.st_mode);
  4786. return 1;
  4787. }
  4788. return 0;
  4789. }
  4790. #endif /* NO_FILESYSTEMS */
  4791. static void
  4792. set_close_on_exec(int fd,
  4793. const struct mg_connection *conn /* may be null */,
  4794. struct mg_context *ctx /* may be null */)
  4795. {
  4796. #if defined(__ZEPHYR__)
  4797. (void)fd;
  4798. (void)conn;
  4799. (void)ctx;
  4800. #else
  4801. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4802. if (conn || ctx) {
  4803. struct mg_connection fc;
  4804. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4805. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4806. __func__,
  4807. strerror(ERRNO));
  4808. }
  4809. }
  4810. #endif
  4811. }
  4812. CIVETWEB_API int
  4813. mg_start_thread(mg_thread_func_t func, void *param)
  4814. {
  4815. pthread_t thread_id;
  4816. pthread_attr_t attr;
  4817. int result;
  4818. (void)pthread_attr_init(&attr);
  4819. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4820. #if defined(__ZEPHYR__)
  4821. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4822. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4823. /* Compile-time option to control stack size,
  4824. * e.g. -DUSE_STACK_SIZE=16384 */
  4825. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4826. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4827. result = pthread_create(&thread_id, &attr, func, param);
  4828. pthread_attr_destroy(&attr);
  4829. return result;
  4830. }
  4831. /* Start a thread storing the thread context. */
  4832. static int
  4833. mg_start_thread_with_id(mg_thread_func_t func,
  4834. void *param,
  4835. pthread_t *threadidptr)
  4836. {
  4837. pthread_t thread_id;
  4838. pthread_attr_t attr;
  4839. int result;
  4840. (void)pthread_attr_init(&attr);
  4841. #if defined(__ZEPHYR__)
  4842. pthread_attr_setstack(&attr,
  4843. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4844. ZEPHYR_STACK_SIZE);
  4845. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4846. /* Compile-time option to control stack size,
  4847. * e.g. -DUSE_STACK_SIZE=16384 */
  4848. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4849. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4850. result = pthread_create(&thread_id, &attr, func, param);
  4851. pthread_attr_destroy(&attr);
  4852. if ((result == 0) && (threadidptr != NULL)) {
  4853. *threadidptr = thread_id;
  4854. }
  4855. return result;
  4856. }
  4857. /* Wait for a thread to finish. */
  4858. static int
  4859. mg_join_thread(pthread_t threadid)
  4860. {
  4861. int result;
  4862. result = pthread_join(threadid, NULL);
  4863. return result;
  4864. }
  4865. #if !defined(NO_CGI)
  4866. static pid_t
  4867. spawn_process(struct mg_connection *conn,
  4868. const char *prog,
  4869. char *envblk,
  4870. char *envp[],
  4871. int fdin[2],
  4872. int fdout[2],
  4873. int fderr[2],
  4874. const char *dir,
  4875. int cgi_config_idx)
  4876. {
  4877. pid_t pid;
  4878. const char *interp;
  4879. (void)envblk;
  4880. if ((pid = fork()) == -1) {
  4881. /* Parent */
  4882. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4883. } else if (pid != 0) {
  4884. /* Make sure children close parent-side descriptors.
  4885. * The caller will close the child-side immediately. */
  4886. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4887. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4888. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4889. } else {
  4890. /* Child */
  4891. if (chdir(dir) != 0) {
  4892. mg_cry_internal(
  4893. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4894. } else if (dup2(fdin[0], 0) == -1) {
  4895. mg_cry_internal(conn,
  4896. "%s: dup2(%d, 0): %s",
  4897. __func__,
  4898. fdin[0],
  4899. strerror(ERRNO));
  4900. } else if (dup2(fdout[1], 1) == -1) {
  4901. mg_cry_internal(conn,
  4902. "%s: dup2(%d, 1): %s",
  4903. __func__,
  4904. fdout[1],
  4905. strerror(ERRNO));
  4906. } else if (dup2(fderr[1], 2) == -1) {
  4907. mg_cry_internal(conn,
  4908. "%s: dup2(%d, 2): %s",
  4909. __func__,
  4910. fderr[1],
  4911. strerror(ERRNO));
  4912. } else {
  4913. struct sigaction sa;
  4914. /* Keep stderr and stdout in two different pipes.
  4915. * Stdout will be sent back to the client,
  4916. * stderr should go into a server error log. */
  4917. (void)close(fdin[0]);
  4918. (void)close(fdout[1]);
  4919. (void)close(fderr[1]);
  4920. /* Close write end fdin and read end fdout and fderr */
  4921. (void)close(fdin[1]);
  4922. (void)close(fdout[0]);
  4923. (void)close(fderr[0]);
  4924. /* After exec, all signal handlers are restored to their default
  4925. * values, with one exception of SIGCHLD. According to
  4926. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4927. * will leave unchanged after exec if it was set to be ignored.
  4928. * Restore it to default action. */
  4929. memset(&sa, 0, sizeof(sa));
  4930. sa.sa_handler = SIG_DFL;
  4931. sigaction(SIGCHLD, &sa, NULL);
  4932. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4933. if (interp == NULL) {
  4934. /* no interpreter configured, call the program directly */
  4935. (void)execle(prog, prog, NULL, envp);
  4936. mg_cry_internal(conn,
  4937. "%s: execle(%s): %s",
  4938. __func__,
  4939. prog,
  4940. strerror(ERRNO));
  4941. } else {
  4942. /* call the configured interpreter */
  4943. const char *interp_args =
  4944. conn->dom_ctx
  4945. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4946. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4947. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4948. } else {
  4949. (void)execle(interp, interp, prog, NULL, envp);
  4950. }
  4951. mg_cry_internal(conn,
  4952. "%s: execle(%s %s): %s",
  4953. __func__,
  4954. interp,
  4955. prog,
  4956. strerror(ERRNO));
  4957. }
  4958. }
  4959. exit(EXIT_FAILURE);
  4960. }
  4961. return pid;
  4962. }
  4963. #endif /* !NO_CGI */
  4964. static int
  4965. set_non_blocking_mode(SOCKET sock)
  4966. {
  4967. int flags = fcntl(sock, F_GETFL, 0);
  4968. if (flags < 0) {
  4969. return -1;
  4970. }
  4971. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4972. return -1;
  4973. }
  4974. return 0;
  4975. }
  4976. static int
  4977. set_blocking_mode(SOCKET sock)
  4978. {
  4979. int flags = fcntl(sock, F_GETFL, 0);
  4980. if (flags < 0) {
  4981. return -1;
  4982. }
  4983. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4984. return -1;
  4985. }
  4986. return 0;
  4987. }
  4988. #endif /* _WIN32 / else */
  4989. /* End of initial operating system specific define block. */
  4990. /* Get a random number (independent of C rand function) */
  4991. static uint64_t
  4992. get_random(void)
  4993. {
  4994. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4995. static uint64_t lcg = 0; /* Linear congruential generator */
  4996. uint64_t now = mg_get_current_time_ns();
  4997. if (lfsr == 0) {
  4998. /* lfsr will be only 0 if has not been initialized,
  4999. * so this code is called only once. */
  5000. lfsr = mg_get_current_time_ns();
  5001. lcg = mg_get_current_time_ns();
  5002. } else {
  5003. /* Get the next step of both random number generators. */
  5004. lfsr = (lfsr >> 1)
  5005. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5006. << 63);
  5007. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5008. }
  5009. /* Combining two pseudo-random number generators and a high resolution
  5010. * part
  5011. * of the current server time will make it hard (impossible?) to guess
  5012. * the
  5013. * next number. */
  5014. return (lfsr ^ lcg ^ now);
  5015. }
  5016. static int
  5017. mg_poll(struct mg_pollfd *pfd,
  5018. unsigned int n,
  5019. int milliseconds,
  5020. const stop_flag_t *stop_flag)
  5021. {
  5022. /* Call poll, but only for a maximum time of a few seconds.
  5023. * This will allow to stop the server after some seconds, instead
  5024. * of having to wait for a long socket timeout. */
  5025. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5026. int check_pollerr = 0;
  5027. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5028. /* If we wait for only one file descriptor, wait on error as well */
  5029. pfd[0].events |= POLLERR;
  5030. check_pollerr = 1;
  5031. }
  5032. do {
  5033. int result;
  5034. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5035. /* Shut down signal */
  5036. return -2;
  5037. }
  5038. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5039. ms_now = milliseconds;
  5040. }
  5041. result = poll(pfd, n, ms_now);
  5042. if (result != 0) {
  5043. int err = ERRNO;
  5044. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5045. /* Poll returned either success (1) or error (-1).
  5046. * Forward both to the caller. */
  5047. if ((check_pollerr)
  5048. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5049. == POLLERR)) {
  5050. /* One and only file descriptor returned error */
  5051. return -1;
  5052. }
  5053. return result;
  5054. }
  5055. }
  5056. /* Poll returned timeout (0). */
  5057. if (milliseconds > 0) {
  5058. milliseconds -= ms_now;
  5059. }
  5060. } while (milliseconds > 0);
  5061. /* timeout: return 0 */
  5062. return 0;
  5063. }
  5064. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5065. * descriptor.
  5066. * Return value:
  5067. * >=0 .. number of bytes successfully written
  5068. * -1 .. timeout
  5069. * -2 .. error
  5070. */
  5071. static int
  5072. push_inner(struct mg_context *ctx,
  5073. FILE *fp,
  5074. SOCKET sock,
  5075. SSL *ssl,
  5076. const char *buf,
  5077. int len,
  5078. double timeout)
  5079. {
  5080. uint64_t start = 0, now = 0, timeout_ns = 0;
  5081. int n, err;
  5082. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5083. #if defined(_WIN32)
  5084. typedef int len_t;
  5085. #else
  5086. typedef size_t len_t;
  5087. #endif
  5088. if (timeout > 0) {
  5089. now = mg_get_current_time_ns();
  5090. start = now;
  5091. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5092. }
  5093. if (ctx == NULL) {
  5094. return -2;
  5095. }
  5096. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5097. if (ssl) {
  5098. return -2;
  5099. }
  5100. #endif
  5101. /* Try to read until it succeeds, fails, times out, or the server
  5102. * shuts down. */
  5103. for (;;) {
  5104. #if defined(USE_MBEDTLS)
  5105. if (ssl != NULL) {
  5106. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5107. if (n <= 0) {
  5108. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5109. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5110. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5111. n = 0;
  5112. } else {
  5113. fprintf(stderr, "SSL write failed, error %d\n", n);
  5114. return -2;
  5115. }
  5116. } else {
  5117. err = 0;
  5118. }
  5119. } else
  5120. #elif !defined(NO_SSL)
  5121. if (ssl != NULL) {
  5122. ERR_clear_error();
  5123. n = SSL_write(ssl, buf, len);
  5124. if (n <= 0) {
  5125. err = SSL_get_error(ssl, n);
  5126. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5127. err = ERRNO;
  5128. } else if ((err == SSL_ERROR_WANT_READ)
  5129. || (err == SSL_ERROR_WANT_WRITE)) {
  5130. n = 0;
  5131. } else {
  5132. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5133. ERR_clear_error();
  5134. return -2;
  5135. }
  5136. ERR_clear_error();
  5137. } else {
  5138. err = 0;
  5139. }
  5140. } else
  5141. #endif
  5142. if (fp != NULL) {
  5143. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5144. if (ferror(fp)) {
  5145. n = -1;
  5146. err = ERRNO;
  5147. } else {
  5148. err = 0;
  5149. }
  5150. } else {
  5151. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5152. err = (n < 0) ? ERRNO : 0;
  5153. if (ERROR_TRY_AGAIN(err)) {
  5154. err = 0;
  5155. n = 0;
  5156. }
  5157. if (n < 0) {
  5158. /* shutdown of the socket at client side */
  5159. return -2;
  5160. }
  5161. }
  5162. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5163. return -2;
  5164. }
  5165. if ((n > 0) || ((n == 0) && (len == 0))) {
  5166. /* some data has been read, or no data was requested */
  5167. return n;
  5168. }
  5169. if (n < 0) {
  5170. /* socket error - check errno */
  5171. DEBUG_TRACE("send() failed, error %d", err);
  5172. /* TODO (mid): error handling depending on the error code.
  5173. * These codes are different between Windows and Linux.
  5174. * Currently there is no problem with failing send calls,
  5175. * if there is a reproducible situation, it should be
  5176. * investigated in detail.
  5177. */
  5178. return -2;
  5179. }
  5180. /* Only in case n=0 (timeout), repeat calling the write function */
  5181. /* If send failed, wait before retry */
  5182. if (fp != NULL) {
  5183. /* For files, just wait a fixed time.
  5184. * Maybe it helps, maybe not. */
  5185. mg_sleep(5);
  5186. } else {
  5187. /* For sockets, wait for the socket using poll */
  5188. struct mg_pollfd pfd[1];
  5189. int pollres;
  5190. pfd[0].fd = sock;
  5191. pfd[0].events = POLLOUT;
  5192. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5193. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5194. return -2;
  5195. }
  5196. if (pollres > 0) {
  5197. continue;
  5198. }
  5199. }
  5200. if (timeout > 0) {
  5201. now = mg_get_current_time_ns();
  5202. if ((now - start) > timeout_ns) {
  5203. /* Timeout */
  5204. break;
  5205. }
  5206. }
  5207. }
  5208. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5209. used */
  5210. return -1;
  5211. }
  5212. static int
  5213. push_all(struct mg_context *ctx,
  5214. FILE *fp,
  5215. SOCKET sock,
  5216. SSL *ssl,
  5217. const char *buf,
  5218. int len)
  5219. {
  5220. double timeout = -1.0;
  5221. int n, nwritten = 0;
  5222. if (ctx == NULL) {
  5223. return -1;
  5224. }
  5225. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5226. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5227. }
  5228. if (timeout <= 0.0) {
  5229. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5230. / 1000.0;
  5231. }
  5232. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5233. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5234. if (n < 0) {
  5235. if (nwritten == 0) {
  5236. nwritten = -1; /* Propagate the error */
  5237. }
  5238. break;
  5239. } else if (n == 0) {
  5240. break; /* No more data to write */
  5241. } else {
  5242. nwritten += n;
  5243. len -= n;
  5244. }
  5245. }
  5246. return nwritten;
  5247. }
  5248. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5249. * Return value:
  5250. * >=0 .. number of bytes successfully read
  5251. * -1 .. timeout
  5252. * -2 .. error
  5253. */
  5254. static int
  5255. pull_inner(FILE *fp,
  5256. struct mg_connection *conn,
  5257. char *buf,
  5258. int len,
  5259. double timeout)
  5260. {
  5261. int nread, err = 0;
  5262. #if defined(_WIN32)
  5263. typedef int len_t;
  5264. #else
  5265. typedef size_t len_t;
  5266. #endif
  5267. /* We need an additional wait loop around this, because in some cases
  5268. * with TLSwe may get data from the socket but not from SSL_read.
  5269. * In this case we need to repeat at least once.
  5270. */
  5271. if (fp != NULL) {
  5272. /* Use read() instead of fread(), because if we're reading from the
  5273. * CGI pipe, fread() may block until IO buffer is filled up. We
  5274. * cannot afford to block and must pass all read bytes immediately
  5275. * to the client. */
  5276. nread = (int)read(fileno(fp), buf, (size_t)len);
  5277. err = (nread < 0) ? ERRNO : 0;
  5278. if ((nread == 0) && (len > 0)) {
  5279. /* Should get data, but got EOL */
  5280. return -2;
  5281. }
  5282. #if defined(USE_MBEDTLS)
  5283. } else if (conn->ssl != NULL) {
  5284. struct mg_pollfd pfd[1];
  5285. int to_read;
  5286. int pollres;
  5287. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5288. if (to_read > 0) {
  5289. /* We already know there is no more data buffered in conn->buf
  5290. * but there is more available in the SSL layer. So don't poll
  5291. * conn->client.sock yet. */
  5292. pollres = 1;
  5293. if (to_read > len)
  5294. to_read = len;
  5295. } else {
  5296. pfd[0].fd = conn->client.sock;
  5297. pfd[0].events = POLLIN;
  5298. to_read = len;
  5299. pollres = mg_poll(pfd,
  5300. 1,
  5301. (int)(timeout * 1000.0),
  5302. &(conn->phys_ctx->stop_flag));
  5303. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5304. return -2;
  5305. }
  5306. }
  5307. if (pollres > 0) {
  5308. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5309. if (nread <= 0) {
  5310. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5311. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5312. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5313. nread = 0;
  5314. } else {
  5315. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5316. return -2;
  5317. }
  5318. } else {
  5319. err = 0;
  5320. }
  5321. } else if (pollres < 0) {
  5322. /* Error */
  5323. return -2;
  5324. } else {
  5325. /* pollres = 0 means timeout */
  5326. nread = 0;
  5327. }
  5328. #elif !defined(NO_SSL)
  5329. } else if (conn->ssl != NULL) {
  5330. int ssl_pending;
  5331. struct mg_pollfd pfd[1];
  5332. int pollres;
  5333. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5334. /* We already know there is no more data buffered in conn->buf
  5335. * but there is more available in the SSL layer. So don't poll
  5336. * conn->client.sock yet. */
  5337. if (ssl_pending > len) {
  5338. ssl_pending = len;
  5339. }
  5340. pollres = 1;
  5341. } else {
  5342. pfd[0].fd = conn->client.sock;
  5343. pfd[0].events = POLLIN;
  5344. pollres = mg_poll(pfd,
  5345. 1,
  5346. (int)(timeout * 1000.0),
  5347. &(conn->phys_ctx->stop_flag));
  5348. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5349. return -2;
  5350. }
  5351. }
  5352. if (pollres > 0) {
  5353. ERR_clear_error();
  5354. nread =
  5355. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5356. if (nread <= 0) {
  5357. err = SSL_get_error(conn->ssl, nread);
  5358. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5359. err = ERRNO;
  5360. } else if ((err == SSL_ERROR_WANT_READ)
  5361. || (err == SSL_ERROR_WANT_WRITE)) {
  5362. nread = 0;
  5363. } else {
  5364. /* All errors should return -2 */
  5365. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5366. ERR_clear_error();
  5367. return -2;
  5368. }
  5369. ERR_clear_error();
  5370. } else {
  5371. err = 0;
  5372. }
  5373. } else if (pollres < 0) {
  5374. /* Error */
  5375. return -2;
  5376. } else {
  5377. /* pollres = 0 means timeout */
  5378. nread = 0;
  5379. }
  5380. #endif
  5381. } else {
  5382. struct mg_pollfd pfd[1];
  5383. int pollres;
  5384. pfd[0].fd = conn->client.sock;
  5385. pfd[0].events = POLLIN;
  5386. pollres = mg_poll(pfd,
  5387. 1,
  5388. (int)(timeout * 1000.0),
  5389. &(conn->phys_ctx->stop_flag));
  5390. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5391. return -2;
  5392. }
  5393. if (pollres > 0) {
  5394. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5395. err = (nread < 0) ? ERRNO : 0;
  5396. if (nread <= 0) {
  5397. /* shutdown of the socket at client side */
  5398. return -2;
  5399. }
  5400. } else if (pollres < 0) {
  5401. /* error calling poll */
  5402. return -2;
  5403. } else {
  5404. /* pollres = 0 means timeout */
  5405. nread = 0;
  5406. }
  5407. }
  5408. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5409. return -2;
  5410. }
  5411. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5412. /* some data has been read, or no data was requested */
  5413. return nread;
  5414. }
  5415. if (nread < 0) {
  5416. /* socket error - check errno */
  5417. #if defined(_WIN32)
  5418. if (err == WSAEWOULDBLOCK) {
  5419. /* TODO (low): check if this is still required */
  5420. /* standard case if called from close_socket_gracefully */
  5421. return -2;
  5422. } else if (err == WSAETIMEDOUT) {
  5423. /* TODO (low): check if this is still required */
  5424. /* timeout is handled by the while loop */
  5425. return 0;
  5426. } else if (err == WSAECONNABORTED) {
  5427. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5428. return -2;
  5429. } else {
  5430. DEBUG_TRACE("recv() failed, error %d", err);
  5431. return -2;
  5432. }
  5433. #else
  5434. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5435. * if the timeout is reached and if the socket was set to non-
  5436. * blocking in close_socket_gracefully, so we can not distinguish
  5437. * here. We have to wait for the timeout in both cases for now.
  5438. */
  5439. if (ERROR_TRY_AGAIN(err)) {
  5440. /* TODO (low): check if this is still required */
  5441. /* EAGAIN/EWOULDBLOCK:
  5442. * standard case if called from close_socket_gracefully
  5443. * => should return -1 */
  5444. /* or timeout occurred
  5445. * => the code must stay in the while loop */
  5446. /* EINTR can be generated on a socket with a timeout set even
  5447. * when SA_RESTART is effective for all relevant signals
  5448. * (see signal(7)).
  5449. * => stay in the while loop */
  5450. } else {
  5451. DEBUG_TRACE("recv() failed, error %d", err);
  5452. return -2;
  5453. }
  5454. #endif
  5455. }
  5456. /* Timeout occurred, but no data available. */
  5457. return -1;
  5458. }
  5459. static int
  5460. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5461. {
  5462. int n, nread = 0;
  5463. double timeout = -1.0;
  5464. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5465. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5466. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5467. }
  5468. if (timeout <= 0.0) {
  5469. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5470. / 1000.0;
  5471. }
  5472. start_time = mg_get_current_time_ns();
  5473. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5474. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5475. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5476. if (n == -2) {
  5477. if (nread == 0) {
  5478. nread = -1; /* Propagate the error */
  5479. }
  5480. break;
  5481. } else if (n == -1) {
  5482. /* timeout */
  5483. if (timeout >= 0.0) {
  5484. now = mg_get_current_time_ns();
  5485. if ((now - start_time) <= timeout_ns) {
  5486. continue;
  5487. }
  5488. }
  5489. break;
  5490. } else if (n == 0) {
  5491. break; /* No more data to read */
  5492. } else {
  5493. nread += n;
  5494. len -= n;
  5495. }
  5496. }
  5497. return nread;
  5498. }
  5499. static void
  5500. discard_unread_request_data(struct mg_connection *conn)
  5501. {
  5502. char buf[MG_BUF_LEN];
  5503. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5504. ;
  5505. }
  5506. static int
  5507. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5508. {
  5509. int64_t content_len, n, buffered_len, nread;
  5510. int64_t len64 =
  5511. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5512. * int, we may not read more
  5513. * bytes */
  5514. const char *body;
  5515. if (conn == NULL) {
  5516. return 0;
  5517. }
  5518. /* If Content-Length is not set for a response with body data,
  5519. * we do not know in advance how much data should be read. */
  5520. content_len = conn->content_len;
  5521. if (content_len < 0) {
  5522. /* The body data is completed when the connection is closed. */
  5523. content_len = INT64_MAX;
  5524. }
  5525. nread = 0;
  5526. if (conn->consumed_content < content_len) {
  5527. /* Adjust number of bytes to read. */
  5528. int64_t left_to_read = content_len - conn->consumed_content;
  5529. if (left_to_read < len64) {
  5530. /* Do not read more than the total content length of the
  5531. * request.
  5532. */
  5533. len64 = left_to_read;
  5534. }
  5535. /* Return buffered data */
  5536. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5537. - conn->consumed_content;
  5538. if (buffered_len > 0) {
  5539. if (len64 < buffered_len) {
  5540. buffered_len = len64;
  5541. }
  5542. body = conn->buf + conn->request_len + conn->consumed_content;
  5543. memcpy(buf, body, (size_t)buffered_len);
  5544. len64 -= buffered_len;
  5545. conn->consumed_content += buffered_len;
  5546. nread += buffered_len;
  5547. buf = (char *)buf + buffered_len;
  5548. }
  5549. /* We have returned all buffered data. Read new data from the remote
  5550. * socket.
  5551. */
  5552. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5553. conn->consumed_content += n;
  5554. nread += n;
  5555. } else {
  5556. nread = ((nread > 0) ? nread : n);
  5557. }
  5558. }
  5559. return (int)nread;
  5560. }
  5561. /* Forward declarations */
  5562. static void handle_request(struct mg_connection *);
  5563. static void log_access(const struct mg_connection *);
  5564. /* Handle request, update statistics and call access log */
  5565. static void
  5566. handle_request_stat_log(struct mg_connection *conn)
  5567. {
  5568. #if defined(USE_SERVER_STATS)
  5569. struct timespec tnow;
  5570. conn->conn_state = 4; /* processing */
  5571. #endif
  5572. handle_request(conn);
  5573. #if defined(USE_SERVER_STATS)
  5574. conn->conn_state = 5; /* processed */
  5575. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5576. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5577. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5578. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5579. conn->num_bytes_sent);
  5580. #endif
  5581. DEBUG_TRACE("%s", "handle_request done");
  5582. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5583. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5584. DEBUG_TRACE("%s", "end_request callback done");
  5585. }
  5586. log_access(conn);
  5587. }
  5588. #if defined(USE_HTTP2)
  5589. #if defined(NO_SSL)
  5590. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5591. #endif
  5592. #define USE_ALPN
  5593. #include "http2.inl"
  5594. /* Not supported with HTTP/2 */
  5595. #define HTTP1_only \
  5596. { \
  5597. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5598. http2_must_use_http1(conn); \
  5599. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5600. return; \
  5601. } \
  5602. }
  5603. #else
  5604. #define HTTP1_only
  5605. #endif
  5606. CIVETWEB_API int
  5607. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5608. {
  5609. if (len > INT_MAX) {
  5610. len = INT_MAX;
  5611. }
  5612. if (conn == NULL) {
  5613. return 0;
  5614. }
  5615. if (conn->is_chunked) {
  5616. size_t all_read = 0;
  5617. while (len > 0) {
  5618. if (conn->is_chunked >= 3) {
  5619. /* No more data left to read */
  5620. return 0;
  5621. }
  5622. if (conn->is_chunked != 1) {
  5623. /* Has error */
  5624. return -1;
  5625. }
  5626. if (conn->consumed_content != conn->content_len) {
  5627. /* copy from the current chunk */
  5628. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5629. if (read_ret < 1) {
  5630. /* read error */
  5631. conn->is_chunked = 2;
  5632. return -1;
  5633. }
  5634. all_read += (size_t)read_ret;
  5635. len -= (size_t)read_ret;
  5636. if (conn->consumed_content == conn->content_len) {
  5637. /* Add data bytes in the current chunk have been read,
  5638. * so we are expecting \r\n now. */
  5639. char x[2];
  5640. conn->content_len += 2;
  5641. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5642. || (x[1] != '\n')) {
  5643. /* Protocol violation */
  5644. conn->is_chunked = 2;
  5645. return -1;
  5646. }
  5647. }
  5648. } else {
  5649. /* fetch a new chunk */
  5650. size_t i;
  5651. char lenbuf[64];
  5652. char *end = NULL;
  5653. unsigned long chunkSize = 0;
  5654. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5655. conn->content_len++;
  5656. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5657. lenbuf[i] = 0;
  5658. }
  5659. if ((i > 0) && (lenbuf[i] == ';')) {
  5660. // chunk extension --> skip chars until next CR
  5661. //
  5662. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5663. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5664. //
  5665. // chunk = chunk-size [ chunk-extension ] CRLF
  5666. // chunk-data CRLF
  5667. // ...
  5668. // chunk-extension= *( ";" chunk-ext-name [ "="
  5669. // chunk-ext-val ] )
  5670. do
  5671. ++conn->content_len;
  5672. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5673. && lenbuf[i] != '\r');
  5674. }
  5675. if ((i > 0) && (lenbuf[i] == '\r')
  5676. && (lenbuf[i - 1] != '\r')) {
  5677. continue;
  5678. }
  5679. if ((i > 1) && (lenbuf[i] == '\n')
  5680. && (lenbuf[i - 1] == '\r')) {
  5681. lenbuf[i + 1] = 0;
  5682. chunkSize = strtoul(lenbuf, &end, 16);
  5683. if (chunkSize == 0) {
  5684. /* regular end of content */
  5685. conn->is_chunked = 3;
  5686. }
  5687. break;
  5688. }
  5689. if (!isxdigit((unsigned char)lenbuf[i])) {
  5690. /* illegal character for chunk length */
  5691. conn->is_chunked = 2;
  5692. return -1;
  5693. }
  5694. }
  5695. if ((end == NULL) || (*end != '\r')) {
  5696. /* chunksize not set correctly */
  5697. conn->is_chunked = 2;
  5698. return -1;
  5699. }
  5700. if (conn->is_chunked == 3) {
  5701. /* try discarding trailer for keep-alive */
  5702. // We found the last chunk (length 0) including the
  5703. // CRLF that terminates that chunk. Now follows a possibly
  5704. // empty trailer and a final CRLF.
  5705. //
  5706. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5707. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5708. //
  5709. // Chunked-Body = *chunk
  5710. // last-chunk
  5711. // trailer
  5712. // CRLF
  5713. // ...
  5714. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5715. // ...
  5716. // trailer = *(entity-header CRLF)
  5717. int crlf_count = 2; // one CRLF already determined
  5718. while (crlf_count < 4 && conn->is_chunked == 3) {
  5719. ++conn->content_len;
  5720. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5721. if ((crlf_count == 0 || crlf_count == 2)) {
  5722. if (lenbuf[0] == '\r')
  5723. ++crlf_count;
  5724. else
  5725. crlf_count = 0;
  5726. } else {
  5727. // previous character was a CR
  5728. // --> next character must be LF
  5729. if (lenbuf[0] == '\n')
  5730. ++crlf_count;
  5731. else
  5732. conn->is_chunked = 2;
  5733. }
  5734. } else
  5735. // premature end of trailer
  5736. conn->is_chunked = 2;
  5737. }
  5738. if (conn->is_chunked == 2)
  5739. return -1;
  5740. else
  5741. conn->is_chunked = 4;
  5742. break;
  5743. }
  5744. /* append a new chunk */
  5745. conn->content_len += (int64_t)chunkSize;
  5746. }
  5747. }
  5748. return (int)all_read;
  5749. }
  5750. return mg_read_inner(conn, buf, len);
  5751. }
  5752. CIVETWEB_API int
  5753. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5754. {
  5755. time_t now;
  5756. int n, total, allowed;
  5757. if (conn == NULL) {
  5758. return 0;
  5759. }
  5760. if (len > INT_MAX) {
  5761. return -1;
  5762. }
  5763. /* Mark connection as "data sent" */
  5764. conn->request_state = 10;
  5765. #if defined(USE_HTTP2)
  5766. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5767. http2_data_frame_head(conn, len, 0);
  5768. }
  5769. #endif
  5770. if (conn->throttle > 0) {
  5771. if ((now = time(NULL)) != conn->last_throttle_time) {
  5772. conn->last_throttle_time = now;
  5773. conn->last_throttle_bytes = 0;
  5774. }
  5775. allowed = conn->throttle - conn->last_throttle_bytes;
  5776. if (allowed > (int)len) {
  5777. allowed = (int)len;
  5778. }
  5779. total = push_all(conn->phys_ctx,
  5780. NULL,
  5781. conn->client.sock,
  5782. conn->ssl,
  5783. (const char *)buf,
  5784. allowed);
  5785. if (total == allowed) {
  5786. buf = (const char *)buf + total;
  5787. conn->last_throttle_bytes += total;
  5788. while ((total < (int)len)
  5789. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5790. allowed = (conn->throttle > ((int)len - total))
  5791. ? (int)len - total
  5792. : conn->throttle;
  5793. n = push_all(conn->phys_ctx,
  5794. NULL,
  5795. conn->client.sock,
  5796. conn->ssl,
  5797. (const char *)buf,
  5798. allowed);
  5799. if (n != allowed) {
  5800. break;
  5801. }
  5802. sleep(1);
  5803. conn->last_throttle_bytes = allowed;
  5804. conn->last_throttle_time = time(NULL);
  5805. buf = (const char *)buf + n;
  5806. total += n;
  5807. }
  5808. }
  5809. } else {
  5810. total = push_all(conn->phys_ctx,
  5811. NULL,
  5812. conn->client.sock,
  5813. conn->ssl,
  5814. (const char *)buf,
  5815. (int)len);
  5816. }
  5817. if (total > 0) {
  5818. conn->num_bytes_sent += total;
  5819. }
  5820. return total;
  5821. }
  5822. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5823. CIVETWEB_API int
  5824. mg_send_chunk(struct mg_connection *conn,
  5825. const char *chunk,
  5826. unsigned int chunk_len)
  5827. {
  5828. char lenbuf[16];
  5829. size_t lenbuf_len;
  5830. int ret;
  5831. int t;
  5832. /* First store the length information in a text buffer. */
  5833. sprintf(lenbuf, "%x\r\n", chunk_len);
  5834. lenbuf_len = strlen(lenbuf);
  5835. /* Then send length information, chunk and terminating \r\n. */
  5836. ret = mg_write(conn, lenbuf, lenbuf_len);
  5837. if (ret != (int)lenbuf_len) {
  5838. return -1;
  5839. }
  5840. t = ret;
  5841. ret = mg_write(conn, chunk, chunk_len);
  5842. if (ret != (int)chunk_len) {
  5843. return -1;
  5844. }
  5845. t += ret;
  5846. ret = mg_write(conn, "\r\n", 2);
  5847. if (ret != 2) {
  5848. return -1;
  5849. }
  5850. t += ret;
  5851. return t;
  5852. }
  5853. #if defined(GCC_DIAGNOSTIC)
  5854. /* This block forwards format strings to printf implementations,
  5855. * so we need to disable the format-nonliteral warning. */
  5856. #pragma GCC diagnostic push
  5857. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5858. #endif
  5859. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5860. static int
  5861. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5862. {
  5863. va_list ap_copy;
  5864. size_t size = MG_BUF_LEN / 4;
  5865. int len = -1;
  5866. *buf = NULL;
  5867. while (len < 0) {
  5868. if (*buf) {
  5869. mg_free(*buf);
  5870. }
  5871. size *= 4;
  5872. *buf = (char *)mg_malloc(size);
  5873. if (!*buf) {
  5874. break;
  5875. }
  5876. va_copy(ap_copy, ap);
  5877. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5878. va_end(ap_copy);
  5879. (*buf)[size - 1] = 0;
  5880. }
  5881. return len;
  5882. }
  5883. /* Print message to buffer. If buffer is large enough to hold the message,
  5884. * return buffer. If buffer is to small, allocate large enough buffer on
  5885. * heap,
  5886. * and return allocated buffer. */
  5887. static int
  5888. alloc_vprintf(char **out_buf,
  5889. char *prealloc_buf,
  5890. size_t prealloc_size,
  5891. const char *fmt,
  5892. va_list ap)
  5893. {
  5894. va_list ap_copy;
  5895. int len;
  5896. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5897. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5898. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5899. * Therefore, we make two passes: on first pass, get required message
  5900. * length.
  5901. * On second pass, actually print the message. */
  5902. va_copy(ap_copy, ap);
  5903. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5904. va_end(ap_copy);
  5905. if (len < 0) {
  5906. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5907. * Switch to alternative code path that uses incremental
  5908. * allocations.
  5909. */
  5910. va_copy(ap_copy, ap);
  5911. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5912. va_end(ap_copy);
  5913. } else if ((size_t)(len) >= prealloc_size) {
  5914. /* The pre-allocated buffer not large enough. */
  5915. /* Allocate a new buffer. */
  5916. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5917. if (!*out_buf) {
  5918. /* Allocation failed. Return -1 as "out of memory" error. */
  5919. return -1;
  5920. }
  5921. /* Buffer allocation successful. Store the string there. */
  5922. va_copy(ap_copy, ap);
  5923. IGNORE_UNUSED_RESULT(
  5924. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5925. va_end(ap_copy);
  5926. } else {
  5927. /* The pre-allocated buffer is large enough.
  5928. * Use it to store the string and return the address. */
  5929. va_copy(ap_copy, ap);
  5930. IGNORE_UNUSED_RESULT(
  5931. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5932. va_end(ap_copy);
  5933. *out_buf = prealloc_buf;
  5934. }
  5935. return len;
  5936. }
  5937. static int
  5938. alloc_printf(char **out_buf, const char *fmt, ...)
  5939. {
  5940. va_list ap;
  5941. int result;
  5942. va_start(ap, fmt);
  5943. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5944. va_end(ap);
  5945. return result;
  5946. }
  5947. #if defined(GCC_DIAGNOSTIC)
  5948. /* Enable format-nonliteral warning again. */
  5949. #pragma GCC diagnostic pop
  5950. #endif
  5951. static int
  5952. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5953. {
  5954. char mem[MG_BUF_LEN];
  5955. char *buf = NULL;
  5956. int len;
  5957. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5958. len = mg_write(conn, buf, (size_t)len);
  5959. }
  5960. if (buf != mem) {
  5961. mg_free(buf);
  5962. }
  5963. return len;
  5964. }
  5965. CIVETWEB_API int
  5966. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5967. {
  5968. va_list ap;
  5969. int result;
  5970. va_start(ap, fmt);
  5971. result = mg_vprintf(conn, fmt, ap);
  5972. va_end(ap);
  5973. return result;
  5974. }
  5975. CIVETWEB_API int
  5976. mg_url_decode(const char *src,
  5977. int src_len,
  5978. char *dst,
  5979. int dst_len,
  5980. int is_form_url_encoded)
  5981. {
  5982. int i, j, a, b;
  5983. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5984. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5985. if ((i < src_len - 2) && (src[i] == '%')
  5986. && isxdigit((unsigned char)src[i + 1])
  5987. && isxdigit((unsigned char)src[i + 2])) {
  5988. a = tolower((unsigned char)src[i + 1]);
  5989. b = tolower((unsigned char)src[i + 2]);
  5990. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5991. i += 2;
  5992. } else if (is_form_url_encoded && (src[i] == '+')) {
  5993. dst[j] = ' ';
  5994. } else {
  5995. dst[j] = src[i];
  5996. }
  5997. }
  5998. dst[j] = '\0'; /* Null-terminate the destination */
  5999. return (i >= src_len) ? j : -1;
  6000. }
  6001. /* form url decoding of an entire string */
  6002. static void
  6003. url_decode_in_place(char *buf)
  6004. {
  6005. int len = (int)strlen(buf);
  6006. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6007. }
  6008. CIVETWEB_API int
  6009. mg_get_var(const char *data,
  6010. size_t data_len,
  6011. const char *name,
  6012. char *dst,
  6013. size_t dst_len)
  6014. {
  6015. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6016. }
  6017. CIVETWEB_API int
  6018. mg_get_var2(const char *data,
  6019. size_t data_len,
  6020. const char *name,
  6021. char *dst,
  6022. size_t dst_len,
  6023. size_t occurrence)
  6024. {
  6025. const char *p, *e, *s;
  6026. size_t name_len;
  6027. int len;
  6028. if ((dst == NULL) || (dst_len == 0)) {
  6029. len = -2;
  6030. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6031. len = -1;
  6032. dst[0] = '\0';
  6033. } else {
  6034. name_len = strlen(name);
  6035. e = data + data_len;
  6036. len = -1;
  6037. dst[0] = '\0';
  6038. /* data is "var1=val1&var2=val2...". Find variable first */
  6039. for (p = data; p + name_len < e; p++) {
  6040. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6041. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6042. /* Point p to variable value */
  6043. p += name_len + 1;
  6044. /* Point s to the end of the value */
  6045. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6046. if (s == NULL) {
  6047. s = e;
  6048. }
  6049. DEBUG_ASSERT(s >= p);
  6050. if (s < p) {
  6051. return -3;
  6052. }
  6053. /* Decode variable into destination buffer */
  6054. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6055. /* Redirect error code from -1 to -2 (destination buffer too
  6056. * small). */
  6057. if (len == -1) {
  6058. len = -2;
  6059. }
  6060. break;
  6061. }
  6062. }
  6063. }
  6064. return len;
  6065. }
  6066. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6067. CIVETWEB_API int
  6068. mg_split_form_urlencoded(char *data,
  6069. struct mg_header *form_fields,
  6070. unsigned num_form_fields)
  6071. {
  6072. char *b;
  6073. int i;
  6074. int num = 0;
  6075. if (data == NULL) {
  6076. /* parameter error */
  6077. return -1;
  6078. }
  6079. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6080. /* determine the number of expected fields */
  6081. if (data[0] == 0) {
  6082. return 0;
  6083. }
  6084. /* count number of & to return the number of key-value-pairs */
  6085. num = 1;
  6086. while (*data) {
  6087. if (*data == '&') {
  6088. num++;
  6089. }
  6090. data++;
  6091. }
  6092. return num;
  6093. }
  6094. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6095. /* parameter error */
  6096. return -1;
  6097. }
  6098. for (i = 0; i < (int)num_form_fields; i++) {
  6099. /* extract key-value pairs from input data */
  6100. while ((*data == ' ') || (*data == '\t')) {
  6101. /* skip initial spaces */
  6102. data++;
  6103. }
  6104. if (*data == 0) {
  6105. /* end of string reached */
  6106. break;
  6107. }
  6108. form_fields[num].name = data;
  6109. /* find & or = */
  6110. b = data;
  6111. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6112. b++;
  6113. }
  6114. if (*b == 0) {
  6115. /* last key without value */
  6116. form_fields[num].value = NULL;
  6117. } else if (*b == '&') {
  6118. /* mid key without value */
  6119. form_fields[num].value = NULL;
  6120. } else {
  6121. /* terminate string */
  6122. *b = 0;
  6123. /* value starts after '=' */
  6124. data = b + 1;
  6125. form_fields[num].value = data;
  6126. }
  6127. /* new field is stored */
  6128. num++;
  6129. /* find a next key */
  6130. b = strchr(data, '&');
  6131. if (b == 0) {
  6132. /* no more data */
  6133. break;
  6134. } else {
  6135. /* terminate value of last field at '&' */
  6136. *b = 0;
  6137. /* next key-value-pairs starts after '&' */
  6138. data = b + 1;
  6139. }
  6140. }
  6141. /* Decode all values */
  6142. for (i = 0; i < num; i++) {
  6143. if (form_fields[i].name) {
  6144. url_decode_in_place((char *)form_fields[i].name);
  6145. }
  6146. if (form_fields[i].value) {
  6147. url_decode_in_place((char *)form_fields[i].value);
  6148. }
  6149. }
  6150. /* return number of fields found */
  6151. return num;
  6152. }
  6153. /* HCP24: some changes to compare whole var_name */
  6154. CIVETWEB_API int
  6155. mg_get_cookie(const char *cookie_header,
  6156. const char *var_name,
  6157. char *dst,
  6158. size_t dst_size)
  6159. {
  6160. const char *s, *p, *end;
  6161. int name_len, len = -1;
  6162. if ((dst == NULL) || (dst_size == 0)) {
  6163. return -2;
  6164. }
  6165. dst[0] = '\0';
  6166. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6167. return -1;
  6168. }
  6169. name_len = (int)strlen(var_name);
  6170. end = s + strlen(s);
  6171. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6172. if (s[name_len] == '=') {
  6173. /* HCP24: now check is it a substring or a full cookie name */
  6174. if ((s == cookie_header) || (s[-1] == ' ')) {
  6175. s += name_len + 1;
  6176. if ((p = strchr(s, ' ')) == NULL) {
  6177. p = end;
  6178. }
  6179. if (p[-1] == ';') {
  6180. p--;
  6181. }
  6182. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6183. s++;
  6184. p--;
  6185. }
  6186. if ((size_t)(p - s) < dst_size) {
  6187. len = (int)(p - s);
  6188. mg_strlcpy(dst, s, (size_t)len + 1);
  6189. } else {
  6190. len = -3;
  6191. }
  6192. break;
  6193. }
  6194. }
  6195. }
  6196. return len;
  6197. }
  6198. CIVETWEB_API int
  6199. mg_base64_encode(const unsigned char *src,
  6200. size_t src_len,
  6201. char *dst,
  6202. size_t *dst_len)
  6203. {
  6204. static const char *b64 =
  6205. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6206. size_t i, j;
  6207. int a, b, c;
  6208. if (dst_len != NULL) {
  6209. /* Expected length including 0 termination: */
  6210. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6211. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6212. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6213. if (*dst_len < expected_len) {
  6214. if (*dst_len > 0) {
  6215. dst[0] = '\0';
  6216. }
  6217. *dst_len = expected_len;
  6218. return 0;
  6219. }
  6220. }
  6221. for (i = j = 0; i < src_len; i += 3) {
  6222. a = src[i];
  6223. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6224. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6225. dst[j++] = b64[a >> 2];
  6226. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6227. if (i + 1 < src_len) {
  6228. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6229. }
  6230. if (i + 2 < src_len) {
  6231. dst[j++] = b64[c & 63];
  6232. }
  6233. }
  6234. while (j % 4 != 0) {
  6235. dst[j++] = '=';
  6236. }
  6237. dst[j++] = '\0';
  6238. if (dst_len != NULL) {
  6239. *dst_len = (size_t)j;
  6240. }
  6241. /* Return -1 for "OK" */
  6242. return -1;
  6243. }
  6244. static unsigned char
  6245. b64reverse(char letter)
  6246. {
  6247. if ((letter >= 'A') && (letter <= 'Z')) {
  6248. return (unsigned char)(letter - 'A');
  6249. }
  6250. if ((letter >= 'a') && (letter <= 'z')) {
  6251. return (unsigned char)(letter - 'a' + 26);
  6252. }
  6253. if ((letter >= '0') && (letter <= '9')) {
  6254. return (unsigned char)(letter - '0' + 52);
  6255. }
  6256. if (letter == '+') {
  6257. return 62;
  6258. }
  6259. if (letter == '/') {
  6260. return 63;
  6261. }
  6262. if (letter == '=') {
  6263. return 255; /* normal end */
  6264. }
  6265. return 254; /* error */
  6266. }
  6267. CIVETWEB_API int
  6268. mg_base64_decode(const char *src,
  6269. size_t src_len,
  6270. unsigned char *dst,
  6271. size_t *dst_len)
  6272. {
  6273. size_t i;
  6274. unsigned char a, b, c, d;
  6275. size_t dst_len_limit = (size_t)-1;
  6276. size_t dst_len_used = 0;
  6277. if (dst_len != NULL) {
  6278. dst_len_limit = *dst_len;
  6279. *dst_len = 0;
  6280. }
  6281. for (i = 0; i < src_len; i += 4) {
  6282. /* Read 4 characters from BASE64 string */
  6283. a = b64reverse(src[i]);
  6284. if (a >= 254) {
  6285. return (int)i;
  6286. }
  6287. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6288. if (b >= 254) {
  6289. return (int)i + 1;
  6290. }
  6291. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6292. if (c == 254) {
  6293. return (int)i + 2;
  6294. }
  6295. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6296. if (d == 254) {
  6297. return (int)i + 3;
  6298. }
  6299. /* Add first (of 3) decoded character */
  6300. if (dst_len_used < dst_len_limit) {
  6301. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6302. + (unsigned char)(b >> 4));
  6303. }
  6304. dst_len_used++;
  6305. if (c != 255) {
  6306. if (dst_len_used < dst_len_limit) {
  6307. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6308. + (unsigned char)(c >> 2));
  6309. }
  6310. dst_len_used++;
  6311. if (d != 255) {
  6312. if (dst_len_used < dst_len_limit) {
  6313. dst[dst_len_used] =
  6314. (unsigned char)((unsigned char)(c << 6) + d);
  6315. }
  6316. dst_len_used++;
  6317. }
  6318. }
  6319. }
  6320. /* Add terminating zero */
  6321. if (dst_len_used < dst_len_limit) {
  6322. dst[dst_len_used] = '\0';
  6323. }
  6324. dst_len_used++;
  6325. if (dst_len != NULL) {
  6326. *dst_len = dst_len_used;
  6327. }
  6328. if (dst_len_used > dst_len_limit) {
  6329. /* Out of memory */
  6330. return 0;
  6331. }
  6332. /* Return -1 for "OK" */
  6333. return -1;
  6334. }
  6335. static int
  6336. is_put_or_delete_method(const struct mg_connection *conn)
  6337. {
  6338. if (conn) {
  6339. const char *s = conn->request_info.request_method;
  6340. if (s != NULL) {
  6341. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6342. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6343. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6344. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6345. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6346. || !strcmp(s, "COPY"));
  6347. }
  6348. }
  6349. return 0;
  6350. }
  6351. static int
  6352. is_civetweb_webdav_method(const struct mg_connection *conn)
  6353. {
  6354. /* Note: Here we only have to identify the WebDav methods that need special
  6355. * handling in the CivetWeb code - not all methods used in WebDav. In
  6356. * particular, methods used on directories (when using Windows Explorer as
  6357. * WebDav client).
  6358. */
  6359. if (conn) {
  6360. const char *s = conn->request_info.request_method;
  6361. if (s != NULL) {
  6362. /* These are the civetweb builtin DAV methods */
  6363. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6364. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6365. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6366. }
  6367. }
  6368. return 0;
  6369. }
  6370. #if !defined(NO_FILES)
  6371. static int
  6372. extention_matches_script(
  6373. struct mg_connection *conn, /* in: request (must be valid) */
  6374. const char *filename /* in: filename (must be valid) */
  6375. )
  6376. {
  6377. #if !defined(NO_CGI)
  6378. int cgi_config_idx, inc, max;
  6379. #endif
  6380. #if defined(USE_LUA)
  6381. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6382. filename)
  6383. > 0) {
  6384. return 1;
  6385. }
  6386. #endif
  6387. #if defined(USE_DUKTAPE)
  6388. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6389. filename)
  6390. > 0) {
  6391. return 1;
  6392. }
  6393. #endif
  6394. #if !defined(NO_CGI)
  6395. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6396. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6397. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6398. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6399. && (match_prefix_strlen(
  6400. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6401. filename)
  6402. > 0)) {
  6403. return 1;
  6404. }
  6405. }
  6406. #endif
  6407. /* filename and conn could be unused, if all preocessor conditions
  6408. * are false (no script language supported). */
  6409. (void)filename;
  6410. (void)conn;
  6411. return 0;
  6412. }
  6413. static int
  6414. extention_matches_template_text(
  6415. struct mg_connection *conn, /* in: request (must be valid) */
  6416. const char *filename /* in: filename (must be valid) */
  6417. )
  6418. {
  6419. #if defined(USE_LUA)
  6420. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6421. filename)
  6422. > 0) {
  6423. return 1;
  6424. }
  6425. #endif
  6426. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6427. > 0) {
  6428. return 1;
  6429. }
  6430. return 0;
  6431. }
  6432. /* For given directory path, substitute it to valid index file.
  6433. * Return 1 if index file has been found, 0 if not found.
  6434. * If the file is found, it's stats is returned in stp. */
  6435. static int
  6436. substitute_index_file(struct mg_connection *conn,
  6437. char *path,
  6438. size_t path_len,
  6439. struct mg_file_stat *filestat)
  6440. {
  6441. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6442. struct vec filename_vec;
  6443. size_t n = strlen(path);
  6444. int found = 0;
  6445. /* The 'path' given to us points to the directory. Remove all trailing
  6446. * directory separator characters from the end of the path, and
  6447. * then append single directory separator character. */
  6448. while ((n > 0) && (path[n - 1] == '/')) {
  6449. n--;
  6450. }
  6451. path[n] = '/';
  6452. /* Traverse index files list. For each entry, append it to the given
  6453. * path and see if the file exists. If it exists, break the loop */
  6454. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6455. /* Ignore too long entries that may overflow path buffer */
  6456. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6457. continue;
  6458. }
  6459. /* Prepare full path to the index file */
  6460. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6461. /* Does it exist? */
  6462. if (mg_stat(conn, path, filestat)) {
  6463. /* Yes it does, break the loop */
  6464. found = 1;
  6465. break;
  6466. }
  6467. }
  6468. /* If no index file exists, restore directory path */
  6469. if (!found) {
  6470. path[n] = '\0';
  6471. }
  6472. return found;
  6473. }
  6474. #endif
  6475. static void
  6476. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6477. char *filename, /* out: filename */
  6478. size_t filename_buf_len, /* in: size of filename buffer */
  6479. struct mg_file_stat *filestat, /* out: file status structure */
  6480. int *is_found, /* out: file found (directly) */
  6481. int *is_script_resource, /* out: handled by a script? */
  6482. int *is_websocket_request, /* out: websocket connection? */
  6483. int *is_put_or_delete_request, /* out: put/delete a file? */
  6484. int *is_webdav_request, /* out: webdav request? */
  6485. int *is_template_text /* out: SSI file or LSP file? */
  6486. )
  6487. {
  6488. char const *accept_encoding;
  6489. #if !defined(NO_FILES)
  6490. const char *uri = conn->request_info.local_uri;
  6491. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT], conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT], NULL};
  6492. int fileExists = 0;
  6493. const char *rewrite;
  6494. struct vec a, b;
  6495. ptrdiff_t match_len;
  6496. char gz_path[UTF8_PATH_MAX];
  6497. int truncated;
  6498. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6499. char *tmp_str;
  6500. size_t tmp_str_len, sep_pos;
  6501. int allow_substitute_script_subresources;
  6502. #endif
  6503. #else
  6504. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6505. #endif
  6506. /* Step 1: Set all initially unknown outputs to zero */
  6507. memset(filestat, 0, sizeof(*filestat));
  6508. *filename = 0;
  6509. *is_found = 0;
  6510. *is_script_resource = 0;
  6511. *is_template_text = 0;
  6512. /* Step 2: Classify the request method */
  6513. /* Step 2a: Check if the request attempts to modify the file system */
  6514. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6515. /* Step 2b: Check if the request uses WebDav method that requires special
  6516. * handling */
  6517. *is_webdav_request = is_civetweb_webdav_method(conn);
  6518. /* Step 3: Check if it is a websocket request, and modify the document
  6519. * root if required */
  6520. #if defined(USE_WEBSOCKET)
  6521. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6522. #if !defined(NO_FILES)
  6523. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6524. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6525. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6526. }
  6527. #endif /* !NO_FILES */
  6528. #else /* USE_WEBSOCKET */
  6529. *is_websocket_request = 0;
  6530. #endif /* USE_WEBSOCKET */
  6531. /* Step 4: Check if gzip encoded response is allowed */
  6532. conn->accept_gzip = 0;
  6533. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6534. if (strstr(accept_encoding, "gzip") != NULL) {
  6535. conn->accept_gzip = 1;
  6536. }
  6537. }
  6538. #if !defined(NO_FILES)
  6539. /* Step 5: If there is no root directory, don't look for files. */
  6540. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6541. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6542. * config is not required. */
  6543. if (roots[0] == NULL) {
  6544. /* all file related outputs have already been set to 0, just return
  6545. */
  6546. return;
  6547. }
  6548. for (int i=0; roots[i] != NULL; i++)
  6549. {
  6550. /* Step 6: Determine the local file path from the root path and the
  6551. * request uri. */
  6552. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6553. * part of the path one byte on the right. */
  6554. truncated = 0;
  6555. mg_snprintf(
  6556. conn, &truncated, filename, filename_buf_len - 1, "%s%s", roots[i], uri);
  6557. if (truncated) {
  6558. goto interpret_cleanup;
  6559. }
  6560. /* Step 7: URI rewriting */
  6561. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6562. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6563. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6564. mg_snprintf(conn,
  6565. &truncated,
  6566. filename,
  6567. filename_buf_len - 1,
  6568. "%.*s%s",
  6569. (int)b.len,
  6570. b.ptr,
  6571. uri + match_len);
  6572. break;
  6573. }
  6574. }
  6575. if (truncated) {
  6576. goto interpret_cleanup;
  6577. }
  6578. /* Step 8: Check if the file exists at the server */
  6579. /* Local file path and name, corresponding to requested URI
  6580. * is now stored in "filename" variable. */
  6581. if (mg_stat(conn, filename, filestat)) {
  6582. fileExists = 1;
  6583. break;
  6584. }
  6585. }
  6586. if (fileExists) {
  6587. int uri_len = (int)strlen(uri);
  6588. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6589. /* 8.1: File exists. */
  6590. *is_found = 1;
  6591. /* 8.2: Check if it is a script type. */
  6592. if (extention_matches_script(conn, filename)) {
  6593. /* The request addresses a CGI resource, Lua script or
  6594. * server-side javascript.
  6595. * The URI corresponds to the script itself (like
  6596. * /path/script.cgi), and there is no additional resource
  6597. * path (like /path/script.cgi/something).
  6598. * Requests that modify (replace or delete) a resource, like
  6599. * PUT and DELETE requests, should replace/delete the script
  6600. * file.
  6601. * Requests that read or write from/to a resource, like GET and
  6602. * POST requests, should call the script and return the
  6603. * generated response. */
  6604. *is_script_resource = (!*is_put_or_delete_request);
  6605. }
  6606. /* 8.3: Check for SSI and LSP files */
  6607. if (extention_matches_template_text(conn, filename)) {
  6608. /* Same as above, but for *.lsp and *.shtml files. */
  6609. /* A "template text" is a file delivered directly to the client,
  6610. * but with some text tags replaced by dynamic content.
  6611. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6612. * (LP, LSP) file. */
  6613. *is_template_text = (!*is_put_or_delete_request);
  6614. }
  6615. /* 8.4: If the request target is a directory, there could be
  6616. * a substitute file (index.html, index.cgi, ...). */
  6617. /* But do not substitute a directory for a WebDav request */
  6618. if (filestat->is_directory && is_uri_end_slash
  6619. && (!*is_webdav_request)) {
  6620. /* Use a local copy here, since substitute_index_file will
  6621. * change the content of the file status */
  6622. struct mg_file_stat tmp_filestat;
  6623. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6624. if (substitute_index_file(
  6625. conn, filename, filename_buf_len, &tmp_filestat)) {
  6626. /* Substitute file found. Copy stat to the output, then
  6627. * check if the file is a script file */
  6628. *filestat = tmp_filestat;
  6629. if (extention_matches_script(conn, filename)) {
  6630. /* Substitute file is a script file */
  6631. *is_script_resource = 1;
  6632. } else if (extention_matches_template_text(conn, filename)) {
  6633. /* Substitute file is a LSP or SSI file */
  6634. *is_template_text = 1;
  6635. } else {
  6636. /* Substitute file is a regular file */
  6637. *is_script_resource = 0;
  6638. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6639. }
  6640. }
  6641. /* If there is no substitute file, the server could return
  6642. * a directory listing in a later step */
  6643. }
  6644. return;
  6645. }
  6646. /* Step 9: Check for zipped files: */
  6647. /* If we can't find the actual file, look for the file
  6648. * with the same name but a .gz extension. If we find it,
  6649. * use that and set the gzipped flag in the file struct
  6650. * to indicate that the response need to have the content-
  6651. * encoding: gzip header.
  6652. * We can only do this if the browser declares support. */
  6653. if (conn->accept_gzip) {
  6654. mg_snprintf(
  6655. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6656. if (truncated) {
  6657. goto interpret_cleanup;
  6658. }
  6659. if (mg_stat(conn, gz_path, filestat)) {
  6660. if (filestat) {
  6661. filestat->is_gzipped = 1;
  6662. *is_found = 1;
  6663. }
  6664. /* Currently gz files can not be scripts. */
  6665. return;
  6666. }
  6667. }
  6668. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6669. /* Step 10: Script resources may handle sub-resources */
  6670. /* Support PATH_INFO for CGI scripts. */
  6671. tmp_str_len = strlen(filename);
  6672. tmp_str =
  6673. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6674. if (!tmp_str) {
  6675. /* Out of memory */
  6676. goto interpret_cleanup;
  6677. }
  6678. memcpy(tmp_str, filename, tmp_str_len + 1);
  6679. /* Check config, if index scripts may have sub-resources */
  6680. allow_substitute_script_subresources =
  6681. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6682. "yes");
  6683. if (*is_webdav_request) {
  6684. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6685. * PROPFIND for their subresources? */
  6686. /* allow_substitute_script_subresources = 0; */
  6687. }
  6688. sep_pos = tmp_str_len;
  6689. while (sep_pos > 0) {
  6690. sep_pos--;
  6691. if (tmp_str[sep_pos] == '/') {
  6692. int is_script = 0, does_exist = 0;
  6693. tmp_str[sep_pos] = 0;
  6694. if (tmp_str[0]) {
  6695. is_script = extention_matches_script(conn, tmp_str);
  6696. does_exist = mg_stat(conn, tmp_str, filestat);
  6697. }
  6698. if (does_exist && is_script) {
  6699. filename[sep_pos] = 0;
  6700. memmove(filename + sep_pos + 2,
  6701. filename + sep_pos + 1,
  6702. strlen(filename + sep_pos + 1) + 1);
  6703. conn->path_info = filename + sep_pos + 1;
  6704. filename[sep_pos + 1] = '/';
  6705. *is_script_resource = 1;
  6706. *is_found = 1;
  6707. break;
  6708. }
  6709. if (allow_substitute_script_subresources) {
  6710. if (substitute_index_file(
  6711. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6712. /* some intermediate directory has an index file */
  6713. if (extention_matches_script(conn, tmp_str)) {
  6714. size_t script_name_len = strlen(tmp_str);
  6715. /* subres_name read before this memory locatio will be
  6716. overwritten */
  6717. char *subres_name = filename + sep_pos;
  6718. size_t subres_name_len = strlen(subres_name);
  6719. DEBUG_TRACE("Substitute script %s serving path %s",
  6720. tmp_str,
  6721. filename);
  6722. /* this index file is a script */
  6723. if ((script_name_len + subres_name_len + 2)
  6724. >= filename_buf_len) {
  6725. mg_free(tmp_str);
  6726. goto interpret_cleanup;
  6727. }
  6728. conn->path_info =
  6729. filename + script_name_len + 1; /* new target */
  6730. memmove(conn->path_info, subres_name, subres_name_len);
  6731. conn->path_info[subres_name_len] = 0;
  6732. memcpy(filename, tmp_str, script_name_len + 1);
  6733. *is_script_resource = 1;
  6734. *is_found = 1;
  6735. break;
  6736. } else {
  6737. DEBUG_TRACE("Substitute file %s serving path %s",
  6738. tmp_str,
  6739. filename);
  6740. /* non-script files will not have sub-resources */
  6741. filename[sep_pos] = 0;
  6742. conn->path_info = 0;
  6743. *is_script_resource = 0;
  6744. *is_found = 0;
  6745. break;
  6746. }
  6747. }
  6748. }
  6749. tmp_str[sep_pos] = '/';
  6750. }
  6751. }
  6752. mg_free(tmp_str);
  6753. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6754. #endif /* !defined(NO_FILES) */
  6755. return;
  6756. #if !defined(NO_FILES)
  6757. /* Reset all outputs */
  6758. interpret_cleanup:
  6759. memset(filestat, 0, sizeof(*filestat));
  6760. *filename = 0;
  6761. *is_found = 0;
  6762. *is_script_resource = 0;
  6763. *is_websocket_request = 0;
  6764. *is_put_or_delete_request = 0;
  6765. #endif /* !defined(NO_FILES) */
  6766. }
  6767. /* Check whether full request is buffered. Return:
  6768. * -1 if request or response is malformed
  6769. * 0 if request or response is not yet fully buffered
  6770. * >0 actual request length, including last \r\n\r\n */
  6771. static int
  6772. get_http_header_len(const char *buf, int buflen)
  6773. {
  6774. int i;
  6775. for (i = 0; i < buflen; i++) {
  6776. /* Do an unsigned comparison in some conditions below */
  6777. const unsigned char c = (unsigned char)buf[i];
  6778. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6779. && !isprint(c)) {
  6780. /* abort scan as soon as one malformed character is found */
  6781. return -1;
  6782. }
  6783. if (i < buflen - 1) {
  6784. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6785. /* Two newline, no carriage return - not standard compliant,
  6786. * but it should be accepted */
  6787. return i + 2;
  6788. }
  6789. }
  6790. if (i < buflen - 3) {
  6791. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6792. && (buf[i + 3] == '\n')) {
  6793. /* Two \r\n - standard compliant */
  6794. return i + 4;
  6795. }
  6796. }
  6797. }
  6798. return 0;
  6799. }
  6800. #if !defined(NO_CACHING)
  6801. /* Convert month to the month number. Return -1 on error, or month number */
  6802. static int
  6803. get_month_index(const char *s)
  6804. {
  6805. size_t i;
  6806. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6807. if (!strcmp(s, month_names[i])) {
  6808. return (int)i;
  6809. }
  6810. }
  6811. return -1;
  6812. }
  6813. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6814. static time_t
  6815. parse_date_string(const char *datetime)
  6816. {
  6817. char month_str[32] = {0};
  6818. int second, minute, hour, day, month, year;
  6819. time_t result = (time_t)0;
  6820. struct tm tm;
  6821. if ((sscanf(datetime,
  6822. "%d/%3s/%d %d:%d:%d",
  6823. &day,
  6824. month_str,
  6825. &year,
  6826. &hour,
  6827. &minute,
  6828. &second)
  6829. == 6)
  6830. || (sscanf(datetime,
  6831. "%d %3s %d %d:%d:%d",
  6832. &day,
  6833. month_str,
  6834. &year,
  6835. &hour,
  6836. &minute,
  6837. &second)
  6838. == 6)
  6839. || (sscanf(datetime,
  6840. "%*3s, %d %3s %d %d:%d:%d",
  6841. &day,
  6842. month_str,
  6843. &year,
  6844. &hour,
  6845. &minute,
  6846. &second)
  6847. == 6)
  6848. || (sscanf(datetime,
  6849. "%d-%3s-%d %d:%d:%d",
  6850. &day,
  6851. month_str,
  6852. &year,
  6853. &hour,
  6854. &minute,
  6855. &second)
  6856. == 6)) {
  6857. month = get_month_index(month_str);
  6858. if ((month >= 0) && (year >= 1970)) {
  6859. memset(&tm, 0, sizeof(tm));
  6860. tm.tm_year = year - 1900;
  6861. tm.tm_mon = month;
  6862. tm.tm_mday = day;
  6863. tm.tm_hour = hour;
  6864. tm.tm_min = minute;
  6865. tm.tm_sec = second;
  6866. result = timegm(&tm);
  6867. }
  6868. }
  6869. return result;
  6870. }
  6871. #endif /* !NO_CACHING */
  6872. /* Pre-process URIs according to RFC + protect against directory disclosure
  6873. * attacks by removing '..', excessive '/' and '\' characters */
  6874. static void
  6875. remove_dot_segments(char *inout)
  6876. {
  6877. /* Windows backend protection
  6878. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6879. * in URI by slash */
  6880. char *out_end = inout;
  6881. char *in = inout;
  6882. if (!in) {
  6883. /* Param error. */
  6884. return;
  6885. }
  6886. while (*in) {
  6887. if (*in == '\\') {
  6888. *in = '/';
  6889. }
  6890. in++;
  6891. }
  6892. /* Algorithm "remove_dot_segments" from
  6893. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6894. /* Step 1:
  6895. * The input buffer is initialized.
  6896. * The output buffer is initialized to the empty string.
  6897. */
  6898. in = inout;
  6899. /* Step 2:
  6900. * While the input buffer is not empty, loop as follows:
  6901. */
  6902. /* Less than out_end of the inout buffer is used as output, so keep
  6903. * condition: out_end <= in */
  6904. while (*in) {
  6905. /* Step 2a:
  6906. * If the input buffer begins with a prefix of "../" or "./",
  6907. * then remove that prefix from the input buffer;
  6908. */
  6909. if (!strncmp(in, "../", 3)) {
  6910. in += 3;
  6911. } else if (!strncmp(in, "./", 2)) {
  6912. in += 2;
  6913. }
  6914. /* otherwise */
  6915. /* Step 2b:
  6916. * if the input buffer begins with a prefix of "/./" or "/.",
  6917. * where "." is a complete path segment, then replace that
  6918. * prefix with "/" in the input buffer;
  6919. */
  6920. else if (!strncmp(in, "/./", 3)) {
  6921. in += 2;
  6922. } else if (!strcmp(in, "/.")) {
  6923. in[1] = 0;
  6924. }
  6925. /* otherwise */
  6926. /* Step 2c:
  6927. * if the input buffer begins with a prefix of "/../" or "/..",
  6928. * where ".." is a complete path segment, then replace that
  6929. * prefix with "/" in the input buffer and remove the last
  6930. * segment and its preceding "/" (if any) from the output
  6931. * buffer;
  6932. */
  6933. else if (!strncmp(in, "/../", 4)) {
  6934. in += 3;
  6935. if (inout != out_end) {
  6936. /* remove last segment */
  6937. do {
  6938. out_end--;
  6939. } while ((inout != out_end) && (*out_end != '/'));
  6940. }
  6941. } else if (!strcmp(in, "/..")) {
  6942. in[1] = 0;
  6943. if (inout != out_end) {
  6944. /* remove last segment */
  6945. do {
  6946. out_end--;
  6947. } while ((inout != out_end) && (*out_end != '/'));
  6948. }
  6949. }
  6950. /* otherwise */
  6951. /* Step 2d:
  6952. * if the input buffer consists only of "." or "..", then remove
  6953. * that from the input buffer;
  6954. */
  6955. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6956. *in = 0;
  6957. }
  6958. /* otherwise */
  6959. /* Step 2e:
  6960. * move the first path segment in the input buffer to the end of
  6961. * the output buffer, including the initial "/" character (if
  6962. * any) and any subsequent characters up to, but not including,
  6963. * the next "/" character or the end of the input buffer.
  6964. */
  6965. else {
  6966. do {
  6967. *out_end = *in;
  6968. out_end++;
  6969. in++;
  6970. } while ((*in != 0) && (*in != '/'));
  6971. }
  6972. }
  6973. /* Step 3:
  6974. * Finally, the output buffer is returned as the result of
  6975. * remove_dot_segments.
  6976. */
  6977. /* Terminate output */
  6978. *out_end = 0;
  6979. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6980. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6981. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6982. * or "//" anymore.
  6983. */
  6984. out_end = in = inout;
  6985. while (*in) {
  6986. if (*in == '.') {
  6987. /* remove . at the end or preceding of / */
  6988. char *in_ahead = in;
  6989. do {
  6990. in_ahead++;
  6991. } while (*in_ahead == '.');
  6992. if (*in_ahead == '/') {
  6993. in = in_ahead;
  6994. if ((out_end != inout) && (out_end[-1] == '/')) {
  6995. /* remove generated // */
  6996. out_end--;
  6997. }
  6998. } else if (*in_ahead == 0) {
  6999. in = in_ahead;
  7000. } else {
  7001. do {
  7002. *out_end++ = '.';
  7003. in++;
  7004. } while (in != in_ahead);
  7005. }
  7006. } else if (*in == '/') {
  7007. /* replace // by / */
  7008. *out_end++ = '/';
  7009. do {
  7010. in++;
  7011. } while (*in == '/');
  7012. } else {
  7013. *out_end++ = *in;
  7014. in++;
  7015. }
  7016. }
  7017. *out_end = 0;
  7018. }
  7019. static const struct {
  7020. const char *extension;
  7021. size_t ext_len;
  7022. const char *mime_type;
  7023. } builtin_mime_types[] = {
  7024. /* IANA registered MIME types
  7025. * (http://www.iana.org/assignments/media-types)
  7026. * application types */
  7027. {".bin", 4, "application/octet-stream"},
  7028. {".deb", 4, "application/octet-stream"},
  7029. {".dmg", 4, "application/octet-stream"},
  7030. {".dll", 4, "application/octet-stream"},
  7031. {".doc", 4, "application/msword"},
  7032. {".eps", 4, "application/postscript"},
  7033. {".exe", 4, "application/octet-stream"},
  7034. {".iso", 4, "application/octet-stream"},
  7035. {".js", 3, "application/javascript"},
  7036. {".json", 5, "application/json"},
  7037. {".msi", 4, "application/octet-stream"},
  7038. {".pdf", 4, "application/pdf"},
  7039. {".ps", 3, "application/postscript"},
  7040. {".rtf", 4, "application/rtf"},
  7041. {".xhtml", 6, "application/xhtml+xml"},
  7042. {".xsl", 4, "application/xml"},
  7043. {".xslt", 5, "application/xml"},
  7044. /* fonts */
  7045. {".ttf", 4, "application/font-sfnt"},
  7046. {".cff", 4, "application/font-sfnt"},
  7047. {".otf", 4, "application/font-sfnt"},
  7048. {".aat", 4, "application/font-sfnt"},
  7049. {".sil", 4, "application/font-sfnt"},
  7050. {".pfr", 4, "application/font-tdpfr"},
  7051. {".woff", 5, "application/font-woff"},
  7052. {".woff2", 6, "application/font-woff2"},
  7053. /* audio */
  7054. {".mp3", 4, "audio/mpeg"},
  7055. {".oga", 4, "audio/ogg"},
  7056. {".ogg", 4, "audio/ogg"},
  7057. /* image */
  7058. {".gif", 4, "image/gif"},
  7059. {".ief", 4, "image/ief"},
  7060. {".jpeg", 5, "image/jpeg"},
  7061. {".jpg", 4, "image/jpeg"},
  7062. {".jpm", 4, "image/jpm"},
  7063. {".jpx", 4, "image/jpx"},
  7064. {".png", 4, "image/png"},
  7065. {".svg", 4, "image/svg+xml"},
  7066. {".tif", 4, "image/tiff"},
  7067. {".tiff", 5, "image/tiff"},
  7068. /* model */
  7069. {".wrl", 4, "model/vrml"},
  7070. /* text */
  7071. {".css", 4, "text/css"},
  7072. {".csv", 4, "text/csv"},
  7073. {".htm", 4, "text/html"},
  7074. {".html", 5, "text/html"},
  7075. {".sgm", 4, "text/sgml"},
  7076. {".shtm", 5, "text/html"},
  7077. {".shtml", 6, "text/html"},
  7078. {".txt", 4, "text/plain"},
  7079. {".xml", 4, "text/xml"},
  7080. /* video */
  7081. {".mov", 4, "video/quicktime"},
  7082. {".mp4", 4, "video/mp4"},
  7083. {".mpeg", 5, "video/mpeg"},
  7084. {".mpg", 4, "video/mpeg"},
  7085. {".ogv", 4, "video/ogg"},
  7086. {".qt", 3, "video/quicktime"},
  7087. /* not registered types
  7088. * (http://reference.sitepoint.com/html/mime-types-full,
  7089. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7090. {".arj", 4, "application/x-arj-compressed"},
  7091. {".gz", 3, "application/x-gunzip"},
  7092. {".rar", 4, "application/x-arj-compressed"},
  7093. {".swf", 4, "application/x-shockwave-flash"},
  7094. {".tar", 4, "application/x-tar"},
  7095. {".tgz", 4, "application/x-tar-gz"},
  7096. {".torrent", 8, "application/x-bittorrent"},
  7097. {".ppt", 4, "application/x-mspowerpoint"},
  7098. {".xls", 4, "application/x-msexcel"},
  7099. {".zip", 4, "application/x-zip-compressed"},
  7100. {".aac",
  7101. 4,
  7102. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7103. {".flac", 5, "audio/flac"},
  7104. {".aif", 4, "audio/x-aif"},
  7105. {".m3u", 4, "audio/x-mpegurl"},
  7106. {".mid", 4, "audio/x-midi"},
  7107. {".ra", 3, "audio/x-pn-realaudio"},
  7108. {".ram", 4, "audio/x-pn-realaudio"},
  7109. {".wav", 4, "audio/x-wav"},
  7110. {".bmp", 4, "image/bmp"},
  7111. {".ico", 4, "image/x-icon"},
  7112. {".pct", 4, "image/x-pct"},
  7113. {".pict", 5, "image/pict"},
  7114. {".rgb", 4, "image/x-rgb"},
  7115. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7116. {".asf", 4, "video/x-ms-asf"},
  7117. {".avi", 4, "video/x-msvideo"},
  7118. {".m4v", 4, "video/x-m4v"},
  7119. {NULL, 0, NULL}};
  7120. CIVETWEB_API const char *
  7121. mg_get_builtin_mime_type(const char *path)
  7122. {
  7123. const char *ext;
  7124. size_t i, path_len;
  7125. path_len = strlen(path);
  7126. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7127. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7128. if ((path_len > builtin_mime_types[i].ext_len)
  7129. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7130. return builtin_mime_types[i].mime_type;
  7131. }
  7132. }
  7133. return "text/plain";
  7134. }
  7135. /* Look at the "path" extension and figure what mime type it has.
  7136. * Store mime type in the vector. */
  7137. static void
  7138. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7139. {
  7140. struct vec ext_vec, mime_vec;
  7141. const char *list, *ext;
  7142. size_t path_len;
  7143. path_len = strlen(path);
  7144. if ((conn == NULL) || (vec == NULL)) {
  7145. if (vec != NULL) {
  7146. memset(vec, '\0', sizeof(struct vec));
  7147. }
  7148. return;
  7149. }
  7150. /* Scan user-defined mime types first, in case user wants to
  7151. * override default mime types. */
  7152. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7153. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7154. /* ext now points to the path suffix */
  7155. ext = path + path_len - ext_vec.len;
  7156. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7157. *vec = mime_vec;
  7158. return;
  7159. }
  7160. }
  7161. vec->ptr = mg_get_builtin_mime_type(path);
  7162. vec->len = strlen(vec->ptr);
  7163. }
  7164. /* Stringify binary data. Output buffer must be twice as big as input,
  7165. * because each byte takes 2 bytes in string representation */
  7166. static void
  7167. bin2str(char *to, const unsigned char *p, size_t len)
  7168. {
  7169. static const char *hex = "0123456789abcdef";
  7170. for (; len--; p++) {
  7171. *to++ = hex[p[0] >> 4];
  7172. *to++ = hex[p[0] & 0x0f];
  7173. }
  7174. *to = '\0';
  7175. }
  7176. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7177. */
  7178. CIVETWEB_API char *
  7179. mg_md5(char buf[33], ...)
  7180. {
  7181. md5_byte_t hash[16];
  7182. const char *p;
  7183. va_list ap;
  7184. md5_state_t ctx;
  7185. md5_init(&ctx);
  7186. va_start(ap, buf);
  7187. while ((p = va_arg(ap, const char *)) != NULL) {
  7188. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7189. }
  7190. va_end(ap);
  7191. md5_finish(&ctx, hash);
  7192. bin2str(buf, hash, sizeof(hash));
  7193. return buf;
  7194. }
  7195. /* Check the user's password, return 1 if OK */
  7196. static int
  7197. check_password_digest(const char *method,
  7198. const char *ha1,
  7199. const char *uri,
  7200. const char *nonce,
  7201. const char *nc,
  7202. const char *cnonce,
  7203. const char *qop,
  7204. const char *response)
  7205. {
  7206. char ha2[32 + 1], expected_response[32 + 1];
  7207. /* Some of the parameters may be NULL */
  7208. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7209. || (qop == NULL) || (response == NULL)) {
  7210. return 0;
  7211. }
  7212. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7213. if (strlen(response) != 32) {
  7214. return 0;
  7215. }
  7216. mg_md5(ha2, method, ":", uri, NULL);
  7217. mg_md5(expected_response,
  7218. ha1,
  7219. ":",
  7220. nonce,
  7221. ":",
  7222. nc,
  7223. ":",
  7224. cnonce,
  7225. ":",
  7226. qop,
  7227. ":",
  7228. ha2,
  7229. NULL);
  7230. return mg_strcasecmp(response, expected_response) == 0;
  7231. }
  7232. #if !defined(NO_FILESYSTEMS)
  7233. /* Use the global passwords file, if specified by auth_gpass option,
  7234. * or search for .htpasswd in the requested directory. */
  7235. static void
  7236. open_auth_file(struct mg_connection *conn,
  7237. const char *path,
  7238. struct mg_file *filep)
  7239. {
  7240. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7241. char name[UTF8_PATH_MAX];
  7242. const char *p, *e,
  7243. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7244. int truncated;
  7245. if (gpass != NULL) {
  7246. /* Use global passwords file */
  7247. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7248. #if defined(DEBUG)
  7249. /* Use mg_cry_internal here, since gpass has been
  7250. * configured. */
  7251. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7252. #endif
  7253. }
  7254. /* Important: using local struct mg_file to test path for
  7255. * is_directory flag. If filep is used, mg_stat() makes it
  7256. * appear as if auth file was opened.
  7257. * TODO(mid): Check if this is still required after rewriting
  7258. * mg_stat */
  7259. } else if (mg_stat(conn, path, &filep->stat)
  7260. && filep->stat.is_directory) {
  7261. mg_snprintf(conn,
  7262. &truncated,
  7263. name,
  7264. sizeof(name),
  7265. "%s/%s",
  7266. path,
  7267. PASSWORDS_FILE_NAME);
  7268. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7269. #if defined(DEBUG)
  7270. /* Don't use mg_cry_internal here, but only a trace, since
  7271. * this is a typical case. It will occur for every directory
  7272. * without a password file. */
  7273. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7274. #endif
  7275. }
  7276. } else {
  7277. /* Try to find .htpasswd in requested directory. */
  7278. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7279. if (e[0] == '/') {
  7280. break;
  7281. }
  7282. }
  7283. mg_snprintf(conn,
  7284. &truncated,
  7285. name,
  7286. sizeof(name),
  7287. "%.*s/%s",
  7288. (int)(e - p),
  7289. p,
  7290. PASSWORDS_FILE_NAME);
  7291. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7292. #if defined(DEBUG)
  7293. /* Don't use mg_cry_internal here, but only a trace, since
  7294. * this is a typical case. It will occur for every directory
  7295. * without a password file. */
  7296. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7297. #endif
  7298. }
  7299. }
  7300. }
  7301. }
  7302. #endif /* NO_FILESYSTEMS */
  7303. /* Parsed Authorization header */
  7304. struct ah {
  7305. char *user;
  7306. int type; /* 1 = basic, 2 = digest */
  7307. char *plain_password; /* Basic only */
  7308. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7309. };
  7310. /* Return 1 on success. Always initializes the ah structure. */
  7311. static int
  7312. parse_auth_header(struct mg_connection *conn,
  7313. char *buf,
  7314. size_t buf_size,
  7315. struct ah *ah)
  7316. {
  7317. char *name, *value, *s;
  7318. const char *auth_header;
  7319. uint64_t nonce;
  7320. if (!ah || !conn) {
  7321. return 0;
  7322. }
  7323. (void)memset(ah, 0, sizeof(*ah));
  7324. auth_header = mg_get_header(conn, "Authorization");
  7325. if (auth_header == NULL) {
  7326. /* No Authorization header at all */
  7327. return 0;
  7328. }
  7329. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7330. /* Basic Auth (we never asked for this, but some client may send it) */
  7331. char *split;
  7332. const char *userpw_b64 = auth_header + 6;
  7333. size_t userpw_b64_len = strlen(userpw_b64);
  7334. size_t buf_len_r = buf_size;
  7335. if (mg_base64_decode(
  7336. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7337. != -1) {
  7338. return 0; /* decode error */
  7339. }
  7340. split = strchr(buf, ':');
  7341. if (!split) {
  7342. return 0; /* Format error */
  7343. }
  7344. /* Separate string at ':' */
  7345. *split = 0;
  7346. /* User name is before ':', Password is after ':' */
  7347. ah->user = buf;
  7348. ah->type = 1;
  7349. ah->plain_password = split + 1;
  7350. return 1;
  7351. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7352. /* Digest Auth ... implemented below */
  7353. ah->type = 2;
  7354. } else {
  7355. /* Unknown or invalid Auth method */
  7356. return 0;
  7357. }
  7358. /* Make modifiable copy of the auth header */
  7359. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7360. s = buf;
  7361. /* Parse authorization header */
  7362. for (;;) {
  7363. /* Gobble initial spaces */
  7364. while (isspace((unsigned char)*s)) {
  7365. s++;
  7366. }
  7367. name = skip_quoted(&s, "=", " ", 0);
  7368. /* Value is either quote-delimited, or ends at first comma or space.
  7369. */
  7370. if (s[0] == '\"') {
  7371. s++;
  7372. value = skip_quoted(&s, "\"", " ", '\\');
  7373. if (s[0] == ',') {
  7374. s++;
  7375. }
  7376. } else {
  7377. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7378. * uses spaces */
  7379. }
  7380. if (*name == '\0') {
  7381. break;
  7382. }
  7383. if (!strcmp(name, "username")) {
  7384. ah->user = value;
  7385. } else if (!strcmp(name, "cnonce")) {
  7386. ah->cnonce = value;
  7387. } else if (!strcmp(name, "response")) {
  7388. ah->response = value;
  7389. } else if (!strcmp(name, "uri")) {
  7390. ah->uri = value;
  7391. } else if (!strcmp(name, "qop")) {
  7392. ah->qop = value;
  7393. } else if (!strcmp(name, "nc")) {
  7394. ah->nc = value;
  7395. } else if (!strcmp(name, "nonce")) {
  7396. ah->nonce = value;
  7397. }
  7398. }
  7399. #if !defined(NO_NONCE_CHECK)
  7400. /* Read the nonce from the response. */
  7401. if (ah->nonce == NULL) {
  7402. return 0;
  7403. }
  7404. s = NULL;
  7405. nonce = strtoull(ah->nonce, &s, 10);
  7406. if ((s == NULL) || (*s != 0)) {
  7407. return 0;
  7408. }
  7409. /* Convert the nonce from the client to a number. */
  7410. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7411. /* The converted number corresponds to the time the nounce has been
  7412. * created. This should not be earlier than the server start. */
  7413. /* Server side nonce check is valuable in all situations but one:
  7414. * if the server restarts frequently, but the client should not see
  7415. * that, so the server should accept nonces from previous starts. */
  7416. /* However, the reasonable default is to not accept a nonce from a
  7417. * previous start, so if anyone changed the access rights between
  7418. * two restarts, a new login is required. */
  7419. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7420. /* nonce is from a previous start of the server and no longer valid
  7421. * (replay attack?) */
  7422. return 0;
  7423. }
  7424. /* Check if the nonce is too high, so it has not (yet) been used by the
  7425. * server. */
  7426. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7427. + conn->dom_ctx->nonce_count)) {
  7428. return 0;
  7429. }
  7430. #else
  7431. (void)nonce;
  7432. #endif
  7433. return (ah->user != NULL);
  7434. }
  7435. static const char *
  7436. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7437. {
  7438. if (!filep) {
  7439. return NULL;
  7440. }
  7441. if (filep->access.fp != NULL) {
  7442. return fgets(buf, (int)size, filep->access.fp);
  7443. } else {
  7444. return NULL;
  7445. }
  7446. }
  7447. /* Define the initial recursion depth for procesesing htpasswd files that
  7448. * include other htpasswd
  7449. * (or even the same) files. It is not difficult to provide a file or files
  7450. * s.t. they force civetweb
  7451. * to infinitely recurse and then crash.
  7452. */
  7453. #define INITIAL_DEPTH 9
  7454. #if INITIAL_DEPTH <= 0
  7455. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7456. #endif
  7457. #if !defined(NO_FILESYSTEMS)
  7458. struct read_auth_file_struct {
  7459. struct mg_connection *conn;
  7460. struct ah ah;
  7461. const char *domain;
  7462. char buf[256 + 256 + 40];
  7463. const char *f_user;
  7464. const char *f_domain;
  7465. const char *f_ha1;
  7466. };
  7467. static int
  7468. read_auth_file(struct mg_file *filep,
  7469. struct read_auth_file_struct *workdata,
  7470. int depth)
  7471. {
  7472. int is_authorized = 0;
  7473. struct mg_file fp;
  7474. size_t l;
  7475. if (!filep || !workdata || (0 == depth)) {
  7476. return 0;
  7477. }
  7478. /* Loop over passwords file */
  7479. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7480. l = strlen(workdata->buf);
  7481. while (l > 0) {
  7482. if (isspace((unsigned char)workdata->buf[l - 1])
  7483. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7484. l--;
  7485. workdata->buf[l] = 0;
  7486. } else
  7487. break;
  7488. }
  7489. if (l < 1) {
  7490. continue;
  7491. }
  7492. workdata->f_user = workdata->buf;
  7493. if (workdata->f_user[0] == ':') {
  7494. /* user names may not contain a ':' and may not be empty,
  7495. * so lines starting with ':' may be used for a special purpose
  7496. */
  7497. if (workdata->f_user[1] == '#') {
  7498. /* :# is a comment */
  7499. continue;
  7500. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7501. if (mg_fopen(workdata->conn,
  7502. workdata->f_user + 9,
  7503. MG_FOPEN_MODE_READ,
  7504. &fp)) {
  7505. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7506. (void)mg_fclose(
  7507. &fp.access); /* ignore error on read only file */
  7508. /* No need to continue processing files once we have a
  7509. * match, since nothing will reset it back
  7510. * to 0.
  7511. */
  7512. if (is_authorized) {
  7513. return is_authorized;
  7514. }
  7515. } else {
  7516. mg_cry_internal(workdata->conn,
  7517. "%s: cannot open authorization file: %s",
  7518. __func__,
  7519. workdata->buf);
  7520. }
  7521. continue;
  7522. }
  7523. /* everything is invalid for the moment (might change in the
  7524. * future) */
  7525. mg_cry_internal(workdata->conn,
  7526. "%s: syntax error in authorization file: %s",
  7527. __func__,
  7528. workdata->buf);
  7529. continue;
  7530. }
  7531. workdata->f_domain = strchr(workdata->f_user, ':');
  7532. if (workdata->f_domain == NULL) {
  7533. mg_cry_internal(workdata->conn,
  7534. "%s: syntax error in authorization file: %s",
  7535. __func__,
  7536. workdata->buf);
  7537. continue;
  7538. }
  7539. *(char *)(workdata->f_domain) = 0;
  7540. (workdata->f_domain)++;
  7541. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7542. if (workdata->f_ha1 == NULL) {
  7543. mg_cry_internal(workdata->conn,
  7544. "%s: syntax error in authorization file: %s",
  7545. __func__,
  7546. workdata->buf);
  7547. continue;
  7548. }
  7549. *(char *)(workdata->f_ha1) = 0;
  7550. (workdata->f_ha1)++;
  7551. if (!strcmp(workdata->ah.user, workdata->f_user)
  7552. && !strcmp(workdata->domain, workdata->f_domain)) {
  7553. switch (workdata->ah.type) {
  7554. case 1: /* Basic */
  7555. {
  7556. char md5[33];
  7557. mg_md5(md5,
  7558. workdata->f_user,
  7559. ":",
  7560. workdata->domain,
  7561. ":",
  7562. workdata->ah.plain_password,
  7563. NULL);
  7564. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7565. }
  7566. case 2: /* Digest */
  7567. return check_password_digest(
  7568. workdata->conn->request_info.request_method,
  7569. workdata->f_ha1,
  7570. workdata->ah.uri,
  7571. workdata->ah.nonce,
  7572. workdata->ah.nc,
  7573. workdata->ah.cnonce,
  7574. workdata->ah.qop,
  7575. workdata->ah.response);
  7576. default: /* None/Other/Unknown */
  7577. return 0;
  7578. }
  7579. }
  7580. }
  7581. return is_authorized;
  7582. }
  7583. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7584. static int
  7585. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7586. {
  7587. struct read_auth_file_struct workdata;
  7588. char buf[MG_BUF_LEN];
  7589. if (!conn || !conn->dom_ctx) {
  7590. return 0;
  7591. }
  7592. memset(&workdata, 0, sizeof(workdata));
  7593. workdata.conn = conn;
  7594. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7595. return 0;
  7596. }
  7597. /* CGI needs it as REMOTE_USER */
  7598. conn->request_info.remote_user =
  7599. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7600. if (realm) {
  7601. workdata.domain = realm;
  7602. } else {
  7603. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7604. }
  7605. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7606. }
  7607. /* Public function to check http digest authentication header */
  7608. CIVETWEB_API int
  7609. mg_check_digest_access_authentication(struct mg_connection *conn,
  7610. const char *realm,
  7611. const char *filename)
  7612. {
  7613. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7614. int auth;
  7615. if (!conn || !filename) {
  7616. return -1;
  7617. }
  7618. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7619. return -2;
  7620. }
  7621. auth = authorize(conn, &file, realm);
  7622. mg_fclose(&file.access);
  7623. return auth;
  7624. }
  7625. #endif /* NO_FILESYSTEMS */
  7626. /* Return 1 if request is authorised, 0 otherwise. */
  7627. static int
  7628. check_authorization(struct mg_connection *conn, const char *path)
  7629. {
  7630. #if !defined(NO_FILESYSTEMS)
  7631. char fname[UTF8_PATH_MAX];
  7632. struct vec uri_vec, filename_vec;
  7633. const char *list;
  7634. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7635. int authorized = 1, truncated;
  7636. if (!conn || !conn->dom_ctx) {
  7637. return 0;
  7638. }
  7639. list = conn->dom_ctx->config[PROTECT_URI];
  7640. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7641. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7642. mg_snprintf(conn,
  7643. &truncated,
  7644. fname,
  7645. sizeof(fname),
  7646. "%.*s",
  7647. (int)filename_vec.len,
  7648. filename_vec.ptr);
  7649. if (truncated
  7650. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7651. mg_cry_internal(conn,
  7652. "%s: cannot open %s: %s",
  7653. __func__,
  7654. fname,
  7655. strerror(errno));
  7656. }
  7657. break;
  7658. }
  7659. }
  7660. if (!is_file_opened(&file.access)) {
  7661. open_auth_file(conn, path, &file);
  7662. }
  7663. if (is_file_opened(&file.access)) {
  7664. authorized = authorize(conn, &file, NULL);
  7665. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7666. }
  7667. return authorized;
  7668. #else
  7669. (void)conn;
  7670. (void)path;
  7671. return 1;
  7672. #endif /* NO_FILESYSTEMS */
  7673. }
  7674. /* Internal function. Assumes conn is valid */
  7675. static void
  7676. send_authorization_request(struct mg_connection *conn, const char *realm)
  7677. {
  7678. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7679. int trunc = 0;
  7680. char buf[128];
  7681. if (!realm) {
  7682. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7683. }
  7684. mg_lock_context(conn->phys_ctx);
  7685. nonce += conn->dom_ctx->nonce_count;
  7686. ++conn->dom_ctx->nonce_count;
  7687. mg_unlock_context(conn->phys_ctx);
  7688. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7689. conn->must_close = 1;
  7690. /* Create 401 response */
  7691. mg_response_header_start(conn, 401);
  7692. send_no_cache_header(conn);
  7693. send_additional_header(conn);
  7694. mg_response_header_add(conn, "Content-Length", "0", -1);
  7695. /* Content for "WWW-Authenticate" header */
  7696. mg_snprintf(conn,
  7697. &trunc,
  7698. buf,
  7699. sizeof(buf),
  7700. "Digest qop=\"auth\", realm=\"%s\", "
  7701. "nonce=\"%" UINT64_FMT "\"",
  7702. realm,
  7703. nonce);
  7704. if (!trunc) {
  7705. /* !trunc should always be true */
  7706. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7707. }
  7708. /* Send all headers */
  7709. mg_response_header_send(conn);
  7710. }
  7711. /* Interface function. Parameters are provided by the user, so do
  7712. * at least some basic checks.
  7713. */
  7714. CIVETWEB_API int
  7715. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7716. const char *realm)
  7717. {
  7718. if (conn && conn->dom_ctx) {
  7719. send_authorization_request(conn, realm);
  7720. return 0;
  7721. }
  7722. return -1;
  7723. }
  7724. #if !defined(NO_FILES)
  7725. static int
  7726. is_authorized_for_put(struct mg_connection *conn)
  7727. {
  7728. int ret = 0;
  7729. if (conn) {
  7730. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7731. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7732. if (passfile != NULL
  7733. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7734. ret = authorize(conn, &file, NULL);
  7735. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7736. }
  7737. }
  7738. DEBUG_TRACE("file write authorization: %i", ret);
  7739. return ret;
  7740. }
  7741. #endif
  7742. CIVETWEB_API int
  7743. mg_modify_passwords_file_ha1(const char *fname,
  7744. const char *domain,
  7745. const char *user,
  7746. const char *ha1)
  7747. {
  7748. int found = 0, i, result = 1;
  7749. char line[512], u[256], d[256], h[256];
  7750. struct stat st = {0};
  7751. FILE *fp = NULL;
  7752. char *temp_file = NULL;
  7753. int temp_file_offs = 0;
  7754. /* Regard empty password as no password - remove user record. */
  7755. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7756. ha1 = NULL;
  7757. }
  7758. /* Other arguments must not be empty */
  7759. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7760. return 0;
  7761. }
  7762. /* Using the given file format, user name and domain must not contain
  7763. * the ':' character */
  7764. if (strchr(user, ':') != NULL) {
  7765. return 0;
  7766. }
  7767. if (strchr(domain, ':') != NULL) {
  7768. return 0;
  7769. }
  7770. /* Do not allow control characters like newline in user name and domain.
  7771. * Do not allow excessively long names either. */
  7772. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7773. if (iscntrl((unsigned char)user[i])) {
  7774. return 0;
  7775. }
  7776. }
  7777. if (user[i]) {
  7778. return 0; /* user name too long */
  7779. }
  7780. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7781. if (iscntrl((unsigned char)domain[i])) {
  7782. return 0;
  7783. }
  7784. }
  7785. if (domain[i]) {
  7786. return 0; /* domain name too long */
  7787. }
  7788. /* The maximum length of the path to the password file is limited */
  7789. if (strlen(fname) >= UTF8_PATH_MAX) {
  7790. return 0;
  7791. }
  7792. /* Check if the file exists, and get file size */
  7793. if (0 == stat(fname, &st)) {
  7794. int temp_buf_len;
  7795. if (st.st_size > 10485760) {
  7796. /* Some funster provided a >10 MB text file */
  7797. return 0;
  7798. }
  7799. /* Add enough space for one more line */
  7800. temp_buf_len = (int)st.st_size + 1024;
  7801. /* Allocate memory (instead of using a temporary file) */
  7802. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  7803. if (!temp_file) {
  7804. /* Out of memory */
  7805. return 0;
  7806. }
  7807. /* File exists. Read it into a memory buffer. */
  7808. fp = fopen(fname, "r");
  7809. if (fp == NULL) {
  7810. /* Cannot read file. No permission? */
  7811. mg_free(temp_file);
  7812. return 0;
  7813. }
  7814. /* Read content and store in memory */
  7815. while ((fgets(line, sizeof(line), fp) != NULL)
  7816. && ((temp_file_offs + 600) < temp_buf_len)) {
  7817. /* file format is "user:domain:hash\n" */
  7818. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7819. continue;
  7820. }
  7821. u[255] = 0;
  7822. d[255] = 0;
  7823. h[255] = 0;
  7824. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7825. /* Found the user: change the password hash or drop the user
  7826. */
  7827. if ((ha1 != NULL) && (!found)) {
  7828. i = sprintf(temp_file + temp_file_offs,
  7829. "%s:%s:%s\n",
  7830. user,
  7831. domain,
  7832. ha1);
  7833. if (i < 1) {
  7834. fclose(fp);
  7835. mg_free(temp_file);
  7836. return 0;
  7837. }
  7838. temp_file_offs += i;
  7839. }
  7840. found = 1;
  7841. } else {
  7842. /* Copy existing user, including password hash */
  7843. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7844. if (i < 1) {
  7845. fclose(fp);
  7846. mg_free(temp_file);
  7847. return 0;
  7848. }
  7849. temp_file_offs += i;
  7850. }
  7851. }
  7852. fclose(fp);
  7853. }
  7854. /* Create new file */
  7855. fp = fopen(fname, "w");
  7856. if (!fp) {
  7857. mg_free(temp_file);
  7858. return 0;
  7859. }
  7860. #if !defined(_WIN32)
  7861. /* On Linux & co., restrict file read/write permissions to the owner */
  7862. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7863. result = 0;
  7864. }
  7865. #endif
  7866. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7867. /* Store buffered content of old file */
  7868. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  7869. != (size_t)temp_file_offs) {
  7870. result = 0;
  7871. }
  7872. }
  7873. /* If new user, just add it */
  7874. if ((ha1 != NULL) && (!found)) {
  7875. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7876. result = 0;
  7877. }
  7878. }
  7879. /* All data written */
  7880. if (fclose(fp) != 0) {
  7881. result = 0;
  7882. }
  7883. mg_free(temp_file);
  7884. return result;
  7885. }
  7886. CIVETWEB_API int
  7887. mg_modify_passwords_file(const char *fname,
  7888. const char *domain,
  7889. const char *user,
  7890. const char *pass)
  7891. {
  7892. char ha1buf[33];
  7893. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7894. return 0;
  7895. }
  7896. if ((pass == NULL) || (pass[0] == 0)) {
  7897. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7898. }
  7899. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7900. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7901. }
  7902. static int
  7903. is_valid_port(unsigned long port)
  7904. {
  7905. return (port <= 0xffff);
  7906. }
  7907. static int
  7908. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7909. {
  7910. struct addrinfo hints, *res, *ressave;
  7911. int func_ret = 0;
  7912. int gai_ret;
  7913. memset(&hints, 0, sizeof(struct addrinfo));
  7914. hints.ai_family = af;
  7915. if (!resolve_src) {
  7916. hints.ai_flags = AI_NUMERICHOST;
  7917. }
  7918. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7919. if (gai_ret != 0) {
  7920. /* gai_strerror could be used to convert gai_ret to a string */
  7921. /* POSIX return values: see
  7922. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7923. */
  7924. /* Windows return values: see
  7925. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7926. */
  7927. return 0;
  7928. }
  7929. ressave = res;
  7930. while (res) {
  7931. if ((dstlen >= (size_t)res->ai_addrlen)
  7932. && (res->ai_addr->sa_family == af)) {
  7933. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7934. func_ret = 1;
  7935. }
  7936. res = res->ai_next;
  7937. }
  7938. freeaddrinfo(ressave);
  7939. return func_ret;
  7940. }
  7941. static int
  7942. connect_socket(
  7943. struct mg_context *ctx /* may be NULL */,
  7944. const char *host,
  7945. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7946. int use_ssl, /* 0 or 1 */
  7947. struct mg_error_data *error,
  7948. SOCKET *sock /* output: socket, must not be NULL */,
  7949. union usa *sa /* output: socket address, must not be NULL */
  7950. )
  7951. {
  7952. int ip_ver = 0;
  7953. int conn_ret = -1;
  7954. int sockerr = 0;
  7955. *sock = INVALID_SOCKET;
  7956. memset(sa, 0, sizeof(*sa));
  7957. if (host == NULL) {
  7958. if (error != NULL) {
  7959. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7960. mg_snprintf(NULL,
  7961. NULL, /* No truncation check for ebuf */
  7962. error->text,
  7963. error->text_buffer_size,
  7964. "%s",
  7965. "NULL host");
  7966. }
  7967. return 0;
  7968. }
  7969. #if defined(USE_X_DOM_SOCKET)
  7970. if (port == -99) {
  7971. /* Unix domain socket */
  7972. size_t hostlen = strlen(host);
  7973. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7974. if (error != NULL) {
  7975. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7976. mg_snprintf(NULL,
  7977. NULL, /* No truncation check for ebuf */
  7978. error->text,
  7979. error->text_buffer_size,
  7980. "%s",
  7981. "host length exceeds limit");
  7982. }
  7983. return 0;
  7984. }
  7985. } else
  7986. #endif
  7987. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7988. if (error != NULL) {
  7989. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7990. mg_snprintf(NULL,
  7991. NULL, /* No truncation check for ebuf */
  7992. error->text,
  7993. error->text_buffer_size,
  7994. "%s",
  7995. "invalid port");
  7996. }
  7997. return 0;
  7998. }
  7999. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8000. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8001. if (use_ssl && (TLS_client_method == NULL)) {
  8002. if (error != NULL) {
  8003. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8004. mg_snprintf(NULL,
  8005. NULL, /* No truncation check for ebuf */
  8006. error->text,
  8007. error->text_buffer_size,
  8008. "%s",
  8009. "SSL is not initialized");
  8010. }
  8011. return 0;
  8012. }
  8013. #else
  8014. if (use_ssl && (SSLv23_client_method == NULL)) {
  8015. if (error != 0) {
  8016. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8017. mg_snprintf(NULL,
  8018. NULL, /* No truncation check for ebuf */
  8019. error->text,
  8020. error->text_buffer_size,
  8021. "%s",
  8022. "SSL is not initialized");
  8023. }
  8024. return 0;
  8025. }
  8026. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8027. #else
  8028. (void)use_ssl;
  8029. #endif /* NO SSL */
  8030. #if defined(USE_X_DOM_SOCKET)
  8031. if (port == -99) {
  8032. size_t hostlen = strlen(host);
  8033. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8034. ip_ver = -99;
  8035. sa->sun.sun_family = AF_UNIX;
  8036. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8037. memcpy(sa->sun.sun_path, host, hostlen);
  8038. } else
  8039. #endif
  8040. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8041. sa->sin.sin_port = htons((uint16_t)port);
  8042. ip_ver = 4;
  8043. #if defined(USE_IPV6)
  8044. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8045. sa->sin6.sin6_port = htons((uint16_t)port);
  8046. ip_ver = 6;
  8047. } else if (host[0] == '[') {
  8048. /* While getaddrinfo on Windows will work with [::1],
  8049. * getaddrinfo on Linux only works with ::1 (without []). */
  8050. size_t l = strlen(host + 1);
  8051. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8052. if (h) {
  8053. h[l - 1] = 0;
  8054. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8055. sa->sin6.sin6_port = htons((uint16_t)port);
  8056. ip_ver = 6;
  8057. }
  8058. mg_free(h);
  8059. }
  8060. #endif
  8061. }
  8062. if (ip_ver == 0) {
  8063. if (error != NULL) {
  8064. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8065. mg_snprintf(NULL,
  8066. NULL, /* No truncation check for ebuf */
  8067. error->text,
  8068. error->text_buffer_size,
  8069. "%s",
  8070. "host not found");
  8071. }
  8072. return 0;
  8073. }
  8074. if (ip_ver == 4) {
  8075. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8076. }
  8077. #if defined(USE_IPV6)
  8078. else if (ip_ver == 6) {
  8079. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8080. }
  8081. #endif
  8082. #if defined(USE_X_DOM_SOCKET)
  8083. else if (ip_ver == -99) {
  8084. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8085. }
  8086. #endif
  8087. if (*sock == INVALID_SOCKET) {
  8088. if (error != NULL) {
  8089. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8090. error->code_sub = (unsigned)ERRNO;
  8091. mg_snprintf(NULL,
  8092. NULL, /* No truncation check for ebuf */
  8093. error->text,
  8094. error->text_buffer_size,
  8095. "socket(): %s",
  8096. strerror(ERRNO));
  8097. }
  8098. return 0;
  8099. }
  8100. if (0 != set_non_blocking_mode(*sock)) {
  8101. if (error != NULL) {
  8102. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8103. error->code_sub = (unsigned)ERRNO;
  8104. mg_snprintf(NULL,
  8105. NULL, /* No truncation check for ebuf */
  8106. error->text,
  8107. error->text_buffer_size,
  8108. "Cannot set socket to non-blocking: %s",
  8109. strerror(ERRNO));
  8110. }
  8111. closesocket(*sock);
  8112. *sock = INVALID_SOCKET;
  8113. return 0;
  8114. }
  8115. set_close_on_exec(*sock, NULL, ctx);
  8116. if (ip_ver == 4) {
  8117. /* connected with IPv4 */
  8118. conn_ret = connect(*sock,
  8119. (struct sockaddr *)((void *)&sa->sin),
  8120. sizeof(sa->sin));
  8121. }
  8122. #if defined(USE_IPV6)
  8123. else if (ip_ver == 6) {
  8124. /* connected with IPv6 */
  8125. conn_ret = connect(*sock,
  8126. (struct sockaddr *)((void *)&sa->sin6),
  8127. sizeof(sa->sin6));
  8128. }
  8129. #endif
  8130. #if defined(USE_X_DOM_SOCKET)
  8131. else if (ip_ver == -99) {
  8132. /* connected to domain socket */
  8133. conn_ret = connect(*sock,
  8134. (struct sockaddr *)((void *)&sa->sun),
  8135. sizeof(sa->sun));
  8136. }
  8137. #endif
  8138. if (conn_ret != 0) {
  8139. sockerr = ERRNO;
  8140. }
  8141. #if defined(_WIN32)
  8142. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8143. #else
  8144. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8145. #endif
  8146. /* Data for getsockopt */
  8147. void *psockerr = &sockerr;
  8148. int ret;
  8149. #if defined(_WIN32)
  8150. int len = (int)sizeof(sockerr);
  8151. #else
  8152. socklen_t len = (socklen_t)sizeof(sockerr);
  8153. #endif
  8154. /* Data for poll */
  8155. struct mg_pollfd pfd[1];
  8156. int pollres;
  8157. int ms_wait = 10000; /* 10 second timeout */
  8158. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8159. /* For a non-blocking socket, the connect sequence is:
  8160. * 1) call connect (will not block)
  8161. * 2) wait until the socket is ready for writing (select or poll)
  8162. * 3) check connection state with getsockopt
  8163. */
  8164. pfd[0].fd = *sock;
  8165. pfd[0].events = POLLOUT;
  8166. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8167. if (pollres != 1) {
  8168. /* Not connected */
  8169. if (error != NULL) {
  8170. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8171. mg_snprintf(NULL,
  8172. NULL, /* No truncation check for ebuf */
  8173. error->text,
  8174. error->text_buffer_size,
  8175. "connect(%s:%d): timeout",
  8176. host,
  8177. port);
  8178. }
  8179. closesocket(*sock);
  8180. *sock = INVALID_SOCKET;
  8181. return 0;
  8182. }
  8183. #if defined(_WIN32)
  8184. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8185. #else
  8186. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8187. #endif
  8188. if ((ret == 0) && (sockerr == 0)) {
  8189. conn_ret = 0;
  8190. }
  8191. }
  8192. if (conn_ret != 0) {
  8193. /* Not connected */
  8194. if (error != NULL) {
  8195. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8196. error->code_sub = (unsigned)ERRNO;
  8197. mg_snprintf(NULL,
  8198. NULL, /* No truncation check for ebuf */
  8199. error->text,
  8200. error->text_buffer_size,
  8201. "connect(%s:%d): error %s",
  8202. host,
  8203. port,
  8204. strerror(sockerr));
  8205. }
  8206. closesocket(*sock);
  8207. *sock = INVALID_SOCKET;
  8208. return 0;
  8209. }
  8210. return 1;
  8211. }
  8212. CIVETWEB_API int
  8213. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8214. {
  8215. static const char *dont_escape = "._-$,;~()";
  8216. static const char *hex = "0123456789abcdef";
  8217. char *pos = dst;
  8218. const char *end = dst + dst_len - 1;
  8219. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8220. if (isalnum((unsigned char)*src)
  8221. || (strchr(dont_escape, *src) != NULL)) {
  8222. *pos = *src;
  8223. } else if (pos + 2 < end) {
  8224. pos[0] = '%';
  8225. pos[1] = hex[(unsigned char)*src >> 4];
  8226. pos[2] = hex[(unsigned char)*src & 0xf];
  8227. pos += 2;
  8228. } else {
  8229. break;
  8230. }
  8231. }
  8232. *pos = '\0';
  8233. return (*src == '\0') ? (int)(pos - dst) : -1;
  8234. }
  8235. /* Return 0 on success, non-zero if an error occurs. */
  8236. static int
  8237. print_dir_entry(struct mg_connection *conn, struct de *de)
  8238. {
  8239. size_t namesize, escsize, i;
  8240. char *href, *esc, *p;
  8241. char size[64], mod[64];
  8242. #if defined(REENTRANT_TIME)
  8243. struct tm _tm;
  8244. struct tm *tm = &_tm;
  8245. #else
  8246. struct tm *tm;
  8247. #endif
  8248. /* Estimate worst case size for encoding and escaping */
  8249. namesize = strlen(de->file_name) + 1;
  8250. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8251. href = (char *)mg_malloc(namesize * 3 + escsize);
  8252. if (href == NULL) {
  8253. return -1;
  8254. }
  8255. mg_url_encode(de->file_name, href, namesize * 3);
  8256. esc = NULL;
  8257. if (escsize > 0) {
  8258. /* HTML escaping needed */
  8259. esc = href + namesize * 3;
  8260. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8261. mg_strlcpy(p, de->file_name + i, 2);
  8262. if (*p == '&') {
  8263. strcpy(p, "&amp;");
  8264. } else if (*p == '<') {
  8265. strcpy(p, "&lt;");
  8266. } else if (*p == '>') {
  8267. strcpy(p, "&gt;");
  8268. }
  8269. }
  8270. }
  8271. if (de->file.is_directory) {
  8272. mg_snprintf(conn,
  8273. NULL, /* Buffer is big enough */
  8274. size,
  8275. sizeof(size),
  8276. "%s",
  8277. "[DIRECTORY]");
  8278. } else {
  8279. /* We use (signed) cast below because MSVC 6 compiler cannot
  8280. * convert unsigned __int64 to double. Sigh. */
  8281. if (de->file.size < 1024) {
  8282. mg_snprintf(conn,
  8283. NULL, /* Buffer is big enough */
  8284. size,
  8285. sizeof(size),
  8286. "%d",
  8287. (int)de->file.size);
  8288. } else if (de->file.size < 0x100000) {
  8289. mg_snprintf(conn,
  8290. NULL, /* Buffer is big enough */
  8291. size,
  8292. sizeof(size),
  8293. "%.1fk",
  8294. (double)de->file.size / 1024.0);
  8295. } else if (de->file.size < 0x40000000) {
  8296. mg_snprintf(conn,
  8297. NULL, /* Buffer is big enough */
  8298. size,
  8299. sizeof(size),
  8300. "%.1fM",
  8301. (double)de->file.size / 1048576);
  8302. } else {
  8303. mg_snprintf(conn,
  8304. NULL, /* Buffer is big enough */
  8305. size,
  8306. sizeof(size),
  8307. "%.1fG",
  8308. (double)de->file.size / 1073741824);
  8309. }
  8310. }
  8311. /* Note: mg_snprintf will not cause a buffer overflow above.
  8312. * So, string truncation checks are not required here. */
  8313. #if defined(REENTRANT_TIME)
  8314. localtime_r(&de->file.last_modified, tm);
  8315. #else
  8316. tm = localtime(&de->file.last_modified);
  8317. #endif
  8318. if (tm != NULL) {
  8319. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8320. } else {
  8321. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8322. }
  8323. mg_printf(conn,
  8324. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8325. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8326. href,
  8327. de->file.is_directory ? "/" : "",
  8328. esc ? esc : de->file_name,
  8329. de->file.is_directory ? "/" : "",
  8330. mod,
  8331. size);
  8332. mg_free(href);
  8333. return 0;
  8334. }
  8335. /* This function is called from send_directory() and used for
  8336. * sorting directory entries by size, name, or modification time. */
  8337. static int
  8338. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8339. {
  8340. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8341. if (p1 && p2) {
  8342. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8343. int cmp_result = 0;
  8344. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8345. query_string = "n";
  8346. }
  8347. /* Sort Directories vs Files */
  8348. if (a->file.is_directory && !b->file.is_directory) {
  8349. return -1; /* Always put directories on top */
  8350. } else if (!a->file.is_directory && b->file.is_directory) {
  8351. return 1; /* Always put directories on top */
  8352. }
  8353. /* Sort by size or date */
  8354. if (*query_string == 's') {
  8355. cmp_result = (a->file.size == b->file.size)
  8356. ? 0
  8357. : ((a->file.size > b->file.size) ? 1 : -1);
  8358. } else if (*query_string == 'd') {
  8359. cmp_result =
  8360. (a->file.last_modified == b->file.last_modified)
  8361. ? 0
  8362. : ((a->file.last_modified > b->file.last_modified) ? 1
  8363. : -1);
  8364. }
  8365. /* Sort by name:
  8366. * if (*query_string == 'n') ...
  8367. * but also sort files of same size/date by name as secondary criterion.
  8368. */
  8369. if (cmp_result == 0) {
  8370. cmp_result = strcmp(a->file_name, b->file_name);
  8371. }
  8372. /* For descending order, invert result */
  8373. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8374. }
  8375. return 0;
  8376. }
  8377. static int
  8378. must_hide_file(struct mg_connection *conn, const char *path)
  8379. {
  8380. if (conn && conn->dom_ctx) {
  8381. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8382. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8383. return (match_prefix_strlen(pw_pattern, path) > 0)
  8384. || (match_prefix_strlen(pattern, path) > 0);
  8385. }
  8386. return 0;
  8387. }
  8388. #if !defined(NO_FILESYSTEMS)
  8389. static int
  8390. scan_directory(struct mg_connection *conn,
  8391. const char *dir,
  8392. void *data,
  8393. int (*cb)(struct de *, void *))
  8394. {
  8395. char path[UTF8_PATH_MAX];
  8396. struct dirent *dp;
  8397. DIR *dirp;
  8398. struct de de;
  8399. int truncated;
  8400. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8401. return 0;
  8402. } else {
  8403. while ((dp = mg_readdir(dirp)) != NULL) {
  8404. /* Do not show current dir and hidden files */
  8405. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8406. || must_hide_file(conn, dp->d_name)) {
  8407. continue;
  8408. }
  8409. mg_snprintf(
  8410. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8411. /* If we don't memset stat structure to zero, mtime will have
  8412. * garbage and strftime() will segfault later on in
  8413. * print_dir_entry(). memset is required only if mg_stat()
  8414. * fails. For more details, see
  8415. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8416. memset(&de.file, 0, sizeof(de.file));
  8417. if (truncated) {
  8418. /* If the path is not complete, skip processing. */
  8419. continue;
  8420. }
  8421. if (!mg_stat(conn, path, &de.file)) {
  8422. mg_cry_internal(conn,
  8423. "%s: mg_stat(%s) failed: %s",
  8424. __func__,
  8425. path,
  8426. strerror(ERRNO));
  8427. }
  8428. de.file_name = dp->d_name;
  8429. if (cb(&de, data)) {
  8430. /* stopped */
  8431. break;
  8432. }
  8433. }
  8434. (void)mg_closedir(dirp);
  8435. }
  8436. return 1;
  8437. }
  8438. #endif /* NO_FILESYSTEMS */
  8439. #if !defined(NO_FILES)
  8440. static int
  8441. remove_directory(struct mg_connection *conn, const char *dir)
  8442. {
  8443. char path[UTF8_PATH_MAX];
  8444. struct dirent *dp;
  8445. DIR *dirp;
  8446. struct de de;
  8447. int truncated;
  8448. int ok = 1;
  8449. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8450. return 0;
  8451. } else {
  8452. while ((dp = mg_readdir(dirp)) != NULL) {
  8453. /* Do not show current dir (but show hidden files as they will
  8454. * also be removed) */
  8455. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8456. continue;
  8457. }
  8458. mg_snprintf(
  8459. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8460. /* If we don't memset stat structure to zero, mtime will have
  8461. * garbage and strftime() will segfault later on in
  8462. * print_dir_entry(). memset is required only if mg_stat()
  8463. * fails. For more details, see
  8464. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8465. memset(&de.file, 0, sizeof(de.file));
  8466. if (truncated) {
  8467. /* Do not delete anything shorter */
  8468. ok = 0;
  8469. continue;
  8470. }
  8471. if (!mg_stat(conn, path, &de.file)) {
  8472. mg_cry_internal(conn,
  8473. "%s: mg_stat(%s) failed: %s",
  8474. __func__,
  8475. path,
  8476. strerror(ERRNO));
  8477. ok = 0;
  8478. }
  8479. if (de.file.is_directory) {
  8480. if (remove_directory(conn, path) == 0) {
  8481. ok = 0;
  8482. }
  8483. } else {
  8484. /* This will fail file is the file is in memory */
  8485. if (mg_remove(conn, path) == 0) {
  8486. ok = 0;
  8487. }
  8488. }
  8489. }
  8490. (void)mg_closedir(dirp);
  8491. IGNORE_UNUSED_RESULT(rmdir(dir));
  8492. }
  8493. return ok;
  8494. }
  8495. #endif
  8496. struct dir_scan_data {
  8497. struct de *entries;
  8498. size_t num_entries;
  8499. size_t arr_size;
  8500. };
  8501. #if !defined(NO_FILESYSTEMS)
  8502. static int
  8503. dir_scan_callback(struct de *de, void *data)
  8504. {
  8505. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8506. struct de *entries = dsd->entries;
  8507. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8508. /* Here "entries" is a temporary pointer and can be replaced,
  8509. * "dsd->entries" is the original pointer */
  8510. entries =
  8511. (struct de *)mg_realloc(entries,
  8512. dsd->arr_size * 2 * sizeof(entries[0]));
  8513. if (entries == NULL) {
  8514. /* stop scan */
  8515. return 1;
  8516. }
  8517. dsd->entries = entries;
  8518. dsd->arr_size *= 2;
  8519. }
  8520. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8521. if (entries[dsd->num_entries].file_name == NULL) {
  8522. /* stop scan */
  8523. return 1;
  8524. }
  8525. entries[dsd->num_entries].file = de->file;
  8526. dsd->num_entries++;
  8527. return 0;
  8528. }
  8529. static void
  8530. handle_directory_request(struct mg_connection *conn, const char *dir)
  8531. {
  8532. size_t i;
  8533. int sort_direction;
  8534. struct dir_scan_data data = {NULL, 0, 128};
  8535. char date[64], *esc, *p;
  8536. const char *title;
  8537. time_t curtime = time(NULL);
  8538. if (!conn) {
  8539. return;
  8540. }
  8541. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8542. mg_send_http_error(conn,
  8543. 500,
  8544. "Error: Cannot open directory\nopendir(%s): %s",
  8545. dir,
  8546. strerror(ERRNO));
  8547. return;
  8548. }
  8549. gmt_time_string(date, sizeof(date), &curtime);
  8550. esc = NULL;
  8551. title = conn->request_info.local_uri;
  8552. if (title[strcspn(title, "&<>")]) {
  8553. /* HTML escaping needed */
  8554. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8555. if (esc) {
  8556. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8557. mg_strlcpy(p, title + i, 2);
  8558. if (*p == '&') {
  8559. strcpy(p, "&amp;");
  8560. } else if (*p == '<') {
  8561. strcpy(p, "&lt;");
  8562. } else if (*p == '>') {
  8563. strcpy(p, "&gt;");
  8564. }
  8565. }
  8566. } else {
  8567. title = "";
  8568. }
  8569. }
  8570. sort_direction = ((conn->request_info.query_string != NULL)
  8571. && (conn->request_info.query_string[0] != '\0')
  8572. && (conn->request_info.query_string[1] == 'd'))
  8573. ? 'a'
  8574. : 'd';
  8575. conn->must_close = 1;
  8576. /* Create 200 OK response */
  8577. mg_response_header_start(conn, 200);
  8578. send_static_cache_header(conn);
  8579. send_additional_header(conn);
  8580. mg_response_header_add(conn,
  8581. "Content-Type",
  8582. "text/html; charset=utf-8",
  8583. -1);
  8584. /* Send all headers */
  8585. mg_response_header_send(conn);
  8586. /* Body */
  8587. mg_printf(conn,
  8588. "<!DOCTYPE html>"
  8589. "<html><head><title>Index of %s</title>"
  8590. "<style>th {text-align: left;}</style></head>"
  8591. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8592. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8593. "<th><a href=\"?d%c\">Modified</a></th>"
  8594. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8595. "<tr><td colspan=\"3\"><hr></td></tr>",
  8596. esc ? esc : title,
  8597. esc ? esc : title,
  8598. sort_direction,
  8599. sort_direction,
  8600. sort_direction);
  8601. mg_free(esc);
  8602. /* Print first entry - link to a parent directory */
  8603. mg_printf(conn,
  8604. "<tr><td><a href=\"%s\">%s</a></td>"
  8605. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8606. "..",
  8607. "Parent directory",
  8608. "-",
  8609. "-");
  8610. /* Sort and print directory entries */
  8611. if (data.entries != NULL) {
  8612. mg_sort(data.entries,
  8613. data.num_entries,
  8614. sizeof(data.entries[0]),
  8615. compare_dir_entries,
  8616. (void *)conn->request_info.query_string);
  8617. for (i = 0; i < data.num_entries; i++) {
  8618. print_dir_entry(conn, &data.entries[i]);
  8619. mg_free(data.entries[i].file_name);
  8620. }
  8621. mg_free(data.entries);
  8622. }
  8623. mg_printf(conn, "%s", "</table></pre></body></html>");
  8624. conn->status_code = 200;
  8625. }
  8626. #endif /* NO_FILESYSTEMS */
  8627. /* Send len bytes from the opened file to the client. */
  8628. static void
  8629. send_file_data(struct mg_connection *conn,
  8630. struct mg_file *filep,
  8631. int64_t offset,
  8632. int64_t len,
  8633. int no_buffering)
  8634. {
  8635. char buf[MG_BUF_LEN];
  8636. int to_read, num_read, num_written;
  8637. int64_t size;
  8638. if (!filep || !conn) {
  8639. return;
  8640. }
  8641. /* Sanity check the offset */
  8642. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8643. : (int64_t)(filep->stat.size);
  8644. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8645. if (len > 0 && filep->access.fp != NULL) {
  8646. /* file stored on disk */
  8647. #if defined(__linux__)
  8648. /* sendfile is only available for Linux */
  8649. if ((conn->ssl == 0) && (conn->throttle == 0)
  8650. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8651. "yes"))) {
  8652. off_t sf_offs = (off_t)offset;
  8653. ssize_t sf_sent;
  8654. int sf_file = fileno(filep->access.fp);
  8655. int loop_cnt = 0;
  8656. do {
  8657. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8658. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8659. size_t sf_tosend =
  8660. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8661. sf_sent =
  8662. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8663. if (sf_sent > 0) {
  8664. len -= sf_sent;
  8665. offset += sf_sent;
  8666. } else if (loop_cnt == 0) {
  8667. /* This file can not be sent using sendfile.
  8668. * This might be the case for pseudo-files in the
  8669. * /sys/ and /proc/ file system.
  8670. * Use the regular user mode copy code instead. */
  8671. break;
  8672. } else if (sf_sent == 0) {
  8673. /* No error, but 0 bytes sent. May be EOF? */
  8674. return;
  8675. }
  8676. loop_cnt++;
  8677. } while ((len > 0) && (sf_sent >= 0));
  8678. if (sf_sent > 0) {
  8679. return; /* OK */
  8680. }
  8681. /* sf_sent<0 means error, thus fall back to the classic way */
  8682. /* This is always the case, if sf_file is not a "normal" file,
  8683. * e.g., for sending data from the output of a CGI process. */
  8684. offset = (int64_t)sf_offs;
  8685. }
  8686. #endif
  8687. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8688. mg_cry_internal(conn,
  8689. "%s: fseeko() failed: %s",
  8690. __func__,
  8691. strerror(ERRNO));
  8692. mg_send_http_error(
  8693. conn,
  8694. 500,
  8695. "%s",
  8696. "Error: Unable to access file at requested position.");
  8697. } else {
  8698. while (len > 0) {
  8699. /* Calculate how much to read from the file into the buffer. */
  8700. /* If no_buffering is set, we should not wait until the
  8701. * CGI->Server buffer is filled, but send everything
  8702. * immediately. In theory buffering could be turned off using
  8703. * setbuf(filep->access.fp, NULL);
  8704. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8705. * but in practice this does not work. A "Linux only" solution
  8706. * may be to use select(). The only portable way is to read byte
  8707. * by byte, but this is quite inefficient from a performance
  8708. * point of view. */
  8709. to_read = no_buffering ? 1 : sizeof(buf);
  8710. if ((int64_t)to_read > len) {
  8711. to_read = (int)len;
  8712. }
  8713. /* Read from file, exit the loop on error */
  8714. if ((num_read =
  8715. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8716. <= 0) {
  8717. break;
  8718. }
  8719. /* Send read bytes to the client, exit the loop on error */
  8720. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8721. != num_read) {
  8722. break;
  8723. }
  8724. /* Both read and were successful, adjust counters */
  8725. len -= num_written;
  8726. }
  8727. }
  8728. }
  8729. }
  8730. static int
  8731. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8732. {
  8733. return sscanf(header,
  8734. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8735. a,
  8736. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8737. // to an integer value, but function will not report
  8738. // conversion errors; consider using 'strtol' instead
  8739. }
  8740. static void
  8741. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8742. {
  8743. if ((filestat != NULL) && (buf != NULL)) {
  8744. mg_snprintf(NULL,
  8745. NULL, /* All calls to construct_etag use 64 byte buffer */
  8746. buf,
  8747. buf_len,
  8748. "\"%lx.%" INT64_FMT "\"",
  8749. (unsigned long)filestat->last_modified,
  8750. filestat->size);
  8751. }
  8752. }
  8753. static void
  8754. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8755. {
  8756. if (filep != NULL && filep->fp != NULL) {
  8757. #if defined(_WIN32)
  8758. (void)conn; /* Unused. */
  8759. #else
  8760. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8761. mg_cry_internal(conn,
  8762. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8763. __func__,
  8764. strerror(ERRNO));
  8765. }
  8766. #endif
  8767. }
  8768. }
  8769. #if defined(USE_ZLIB)
  8770. #include "mod_zlib.inl"
  8771. #endif
  8772. #if !defined(NO_FILESYSTEMS)
  8773. static void
  8774. handle_static_file_request(struct mg_connection *conn,
  8775. const char *path,
  8776. struct mg_file *filep,
  8777. const char *mime_type,
  8778. const char *additional_headers)
  8779. {
  8780. char lm[64], etag[64];
  8781. char range[128]; /* large enough, so there will be no overflow */
  8782. const char *range_hdr;
  8783. int64_t cl, r1, r2;
  8784. struct vec mime_vec;
  8785. int n, truncated;
  8786. char gz_path[UTF8_PATH_MAX];
  8787. const char *encoding = 0;
  8788. int is_head_request;
  8789. #if defined(USE_ZLIB)
  8790. /* Compression is allowed, unless there is a reason not to use
  8791. * compression. If the file is already compressed, too small or a
  8792. * "range" request was made, on the fly compression is not possible. */
  8793. int allow_on_the_fly_compression = 1;
  8794. #endif
  8795. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8796. return;
  8797. }
  8798. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8799. if (mime_type == NULL) {
  8800. get_mime_type(conn, path, &mime_vec);
  8801. } else {
  8802. mime_vec.ptr = mime_type;
  8803. mime_vec.len = strlen(mime_type);
  8804. }
  8805. if (filep->stat.size > INT64_MAX) {
  8806. mg_send_http_error(conn,
  8807. 500,
  8808. "Error: File size is too large to send\n%" INT64_FMT,
  8809. filep->stat.size);
  8810. return;
  8811. }
  8812. cl = (int64_t)filep->stat.size;
  8813. conn->status_code = 200;
  8814. range[0] = '\0';
  8815. #if defined(USE_ZLIB)
  8816. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8817. * it's important to rewrite the filename after resolving
  8818. * the mime type from it, to preserve the actual file's type */
  8819. if (!conn->accept_gzip) {
  8820. allow_on_the_fly_compression = 0;
  8821. }
  8822. #endif
  8823. /* Check if there is a range header */
  8824. range_hdr = mg_get_header(conn, "Range");
  8825. /* For gzipped files, add *.gz */
  8826. if (filep->stat.is_gzipped) {
  8827. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8828. if (truncated) {
  8829. mg_send_http_error(conn,
  8830. 500,
  8831. "Error: Path of zipped file too long (%s)",
  8832. path);
  8833. return;
  8834. }
  8835. path = gz_path;
  8836. encoding = "gzip";
  8837. #if defined(USE_ZLIB)
  8838. /* File is already compressed. No "on the fly" compression. */
  8839. allow_on_the_fly_compression = 0;
  8840. #endif
  8841. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8842. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8843. struct mg_file_stat file_stat;
  8844. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8845. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8846. && !file_stat.is_directory) {
  8847. file_stat.is_gzipped = 1;
  8848. filep->stat = file_stat;
  8849. cl = (int64_t)filep->stat.size;
  8850. path = gz_path;
  8851. encoding = "gzip";
  8852. #if defined(USE_ZLIB)
  8853. /* File is already compressed. No "on the fly" compression. */
  8854. allow_on_the_fly_compression = 0;
  8855. #endif
  8856. }
  8857. }
  8858. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8859. mg_send_http_error(conn,
  8860. 500,
  8861. "Error: Cannot open file\nfopen(%s): %s",
  8862. path,
  8863. strerror(ERRNO));
  8864. return;
  8865. }
  8866. fclose_on_exec(&filep->access, conn);
  8867. /* If "Range" request was made: parse header, send only selected part
  8868. * of the file. */
  8869. r1 = r2 = 0;
  8870. if ((range_hdr != NULL)
  8871. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8872. && (r2 >= 0)) {
  8873. /* actually, range requests don't play well with a pre-gzipped
  8874. * file (since the range is specified in the uncompressed space) */
  8875. if (filep->stat.is_gzipped) {
  8876. mg_send_http_error(
  8877. conn,
  8878. 416, /* 416 = Range Not Satisfiable */
  8879. "%s",
  8880. "Error: Range requests in gzipped files are not supported");
  8881. (void)mg_fclose(
  8882. &filep->access); /* ignore error on read only file */
  8883. return;
  8884. }
  8885. conn->status_code = 206;
  8886. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8887. mg_snprintf(conn,
  8888. NULL, /* range buffer is big enough */
  8889. range,
  8890. sizeof(range),
  8891. "bytes "
  8892. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8893. r1,
  8894. r1 + cl - 1,
  8895. filep->stat.size);
  8896. #if defined(USE_ZLIB)
  8897. /* Do not compress ranges. */
  8898. allow_on_the_fly_compression = 0;
  8899. #endif
  8900. }
  8901. /* Do not compress small files. Small files do not benefit from file
  8902. * compression, but there is still some overhead. */
  8903. #if defined(USE_ZLIB)
  8904. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8905. /* File is below the size limit. */
  8906. allow_on_the_fly_compression = 0;
  8907. }
  8908. #endif
  8909. /* Prepare Etag, and Last-Modified headers. */
  8910. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8911. construct_etag(etag, sizeof(etag), &filep->stat);
  8912. /* Create 2xx (200, 206) response */
  8913. mg_response_header_start(conn, conn->status_code);
  8914. send_static_cache_header(conn);
  8915. send_additional_header(conn);
  8916. send_cors_header(conn);
  8917. mg_response_header_add(conn,
  8918. "Content-Type",
  8919. mime_vec.ptr,
  8920. (int)mime_vec.len);
  8921. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8922. mg_response_header_add(conn, "Etag", etag, -1);
  8923. #if defined(USE_ZLIB)
  8924. /* On the fly compression allowed */
  8925. if (allow_on_the_fly_compression) {
  8926. /* For on the fly compression, we don't know the content size in
  8927. * advance, so we have to use chunked encoding */
  8928. encoding = "gzip";
  8929. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8930. /* HTTP/2 is always using "chunks" (frames) */
  8931. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8932. }
  8933. } else
  8934. #endif
  8935. {
  8936. /* Without on-the-fly compression, we know the content-length
  8937. * and we can use ranges (with on-the-fly compression we cannot).
  8938. * So we send these response headers only in this case. */
  8939. char len[32];
  8940. int trunc = 0;
  8941. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8942. if (!trunc) {
  8943. mg_response_header_add(conn, "Content-Length", len, -1);
  8944. }
  8945. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8946. }
  8947. if (encoding) {
  8948. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8949. }
  8950. if (range[0] != 0) {
  8951. mg_response_header_add(conn, "Content-Range", range, -1);
  8952. }
  8953. /* The code above does not add any header starting with X- to make
  8954. * sure no one of the additional_headers is included twice */
  8955. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8956. mg_response_header_add_lines(conn, additional_headers);
  8957. }
  8958. /* Send all headers */
  8959. mg_response_header_send(conn);
  8960. if (!is_head_request) {
  8961. #if defined(USE_ZLIB)
  8962. if (allow_on_the_fly_compression) {
  8963. /* Compress and send */
  8964. send_compressed_data(conn, filep);
  8965. } else
  8966. #endif
  8967. {
  8968. /* Send file directly */
  8969. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8970. }
  8971. }
  8972. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8973. }
  8974. CIVETWEB_API int
  8975. mg_send_file_body(struct mg_connection *conn, const char *path)
  8976. {
  8977. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8978. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8979. return -1;
  8980. }
  8981. fclose_on_exec(&file.access, conn);
  8982. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8983. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8984. return 0; /* >= 0 for OK */
  8985. }
  8986. #endif /* NO_FILESYSTEMS */
  8987. #if !defined(NO_CACHING)
  8988. /* Return True if we should reply 304 Not Modified. */
  8989. static int
  8990. is_not_modified(const struct mg_connection *conn,
  8991. const struct mg_file_stat *filestat)
  8992. {
  8993. char etag[64];
  8994. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8995. const char *inm = mg_get_header(conn, "If-None-Match");
  8996. construct_etag(etag, sizeof(etag), filestat);
  8997. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8998. || ((ims != NULL)
  8999. && (filestat->last_modified <= parse_date_string(ims)));
  9000. }
  9001. static void
  9002. handle_not_modified_static_file_request(struct mg_connection *conn,
  9003. struct mg_file *filep)
  9004. {
  9005. char lm[64], etag[64];
  9006. if ((conn == NULL) || (filep == NULL)) {
  9007. return;
  9008. }
  9009. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9010. construct_etag(etag, sizeof(etag), &filep->stat);
  9011. /* Create 304 "not modified" response */
  9012. mg_response_header_start(conn, 304);
  9013. send_static_cache_header(conn);
  9014. send_additional_header(conn);
  9015. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9016. mg_response_header_add(conn, "Etag", etag, -1);
  9017. /* Send all headers */
  9018. mg_response_header_send(conn);
  9019. }
  9020. #endif
  9021. #if !defined(NO_FILESYSTEMS)
  9022. CIVETWEB_API void
  9023. mg_send_file(struct mg_connection *conn, const char *path)
  9024. {
  9025. mg_send_mime_file2(conn, path, NULL, NULL);
  9026. }
  9027. CIVETWEB_API void
  9028. mg_send_mime_file(struct mg_connection *conn,
  9029. const char *path,
  9030. const char *mime_type)
  9031. {
  9032. mg_send_mime_file2(conn, path, mime_type, NULL);
  9033. }
  9034. CIVETWEB_API void
  9035. mg_send_mime_file2(struct mg_connection *conn,
  9036. const char *path,
  9037. const char *mime_type,
  9038. const char *additional_headers)
  9039. {
  9040. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9041. if (!conn) {
  9042. /* No conn */
  9043. return;
  9044. }
  9045. if (mg_stat(conn, path, &file.stat)) {
  9046. #if !defined(NO_CACHING)
  9047. if (is_not_modified(conn, &file.stat)) {
  9048. /* Send 304 "Not Modified" - this must not send any body data */
  9049. handle_not_modified_static_file_request(conn, &file);
  9050. } else
  9051. #endif /* NO_CACHING */
  9052. if (file.stat.is_directory) {
  9053. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9054. "yes")) {
  9055. handle_directory_request(conn, path);
  9056. } else {
  9057. mg_send_http_error(conn,
  9058. 403,
  9059. "%s",
  9060. "Error: Directory listing denied");
  9061. }
  9062. } else {
  9063. handle_static_file_request(
  9064. conn, path, &file, mime_type, additional_headers);
  9065. }
  9066. } else {
  9067. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9068. }
  9069. }
  9070. /* For a given PUT path, create all intermediate subdirectories.
  9071. * Return 0 if the path itself is a directory.
  9072. * Return 1 if the path leads to a file.
  9073. * Return -1 for if the path is too long.
  9074. * Return -2 if path can not be created.
  9075. */
  9076. static int
  9077. put_dir(struct mg_connection *conn, const char *path)
  9078. {
  9079. char buf[UTF8_PATH_MAX];
  9080. const char *s, *p;
  9081. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9082. size_t len;
  9083. int res = 1;
  9084. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9085. len = (size_t)(p - path);
  9086. if (len >= sizeof(buf)) {
  9087. /* path too long */
  9088. res = -1;
  9089. break;
  9090. }
  9091. memcpy(buf, path, len);
  9092. buf[len] = '\0';
  9093. /* Try to create intermediate directory */
  9094. DEBUG_TRACE("mkdir(%s)", buf);
  9095. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9096. /* path does not exist and can not be created */
  9097. res = -2;
  9098. break;
  9099. }
  9100. /* Is path itself a directory? */
  9101. if (p[1] == '\0') {
  9102. res = 0;
  9103. }
  9104. }
  9105. return res;
  9106. }
  9107. static void
  9108. remove_bad_file(const struct mg_connection *conn, const char *path)
  9109. {
  9110. int r = mg_remove(conn, path);
  9111. if (r != 0) {
  9112. mg_cry_internal(conn,
  9113. "%s: Cannot remove invalid file %s",
  9114. __func__,
  9115. path);
  9116. }
  9117. }
  9118. CIVETWEB_API long long
  9119. mg_store_body(struct mg_connection *conn, const char *path)
  9120. {
  9121. char buf[MG_BUF_LEN];
  9122. long long len = 0;
  9123. int ret, n;
  9124. struct mg_file fi;
  9125. if (conn->consumed_content != 0) {
  9126. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9127. return -11;
  9128. }
  9129. ret = put_dir(conn, path);
  9130. if (ret < 0) {
  9131. /* -1 for path too long,
  9132. * -2 for path can not be created. */
  9133. return ret;
  9134. }
  9135. if (ret != 1) {
  9136. /* Return 0 means, path itself is a directory. */
  9137. return 0;
  9138. }
  9139. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9140. return -12;
  9141. }
  9142. ret = mg_read(conn, buf, sizeof(buf));
  9143. while (ret > 0) {
  9144. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9145. if (n != ret) {
  9146. (void)mg_fclose(
  9147. &fi.access); /* File is bad and will be removed anyway. */
  9148. remove_bad_file(conn, path);
  9149. return -13;
  9150. }
  9151. len += ret;
  9152. ret = mg_read(conn, buf, sizeof(buf));
  9153. }
  9154. /* File is open for writing. If fclose fails, there was probably an
  9155. * error flushing the buffer to disk, so the file on disk might be
  9156. * broken. Delete it and return an error to the caller. */
  9157. if (mg_fclose(&fi.access) != 0) {
  9158. remove_bad_file(conn, path);
  9159. return -14;
  9160. }
  9161. return len;
  9162. }
  9163. #endif /* NO_FILESYSTEMS */
  9164. /* Parse a buffer:
  9165. * Forward the string pointer till the end of a word, then
  9166. * terminate it and forward till the begin of the next word.
  9167. */
  9168. static int
  9169. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9170. {
  9171. /* Forward until a space is found - use isgraph here */
  9172. /* See http://www.cplusplus.com/reference/cctype/ */
  9173. while (isgraph((unsigned char)**ppw)) {
  9174. (*ppw)++;
  9175. }
  9176. /* Check end of word */
  9177. if (eol) {
  9178. /* must be a end of line */
  9179. if ((**ppw != '\r') && (**ppw != '\n')) {
  9180. return -1;
  9181. }
  9182. } else {
  9183. /* must be a end of a word, but not a line */
  9184. if (**ppw != ' ') {
  9185. return -1;
  9186. }
  9187. }
  9188. /* Terminate and forward to the next word */
  9189. do {
  9190. **ppw = 0;
  9191. (*ppw)++;
  9192. } while (isspace((unsigned char)**ppw));
  9193. /* Check after term */
  9194. if (!eol) {
  9195. /* if it's not the end of line, there must be a next word */
  9196. if (!isgraph((unsigned char)**ppw)) {
  9197. return -1;
  9198. }
  9199. }
  9200. /* ok */
  9201. return 1;
  9202. }
  9203. /* Parse HTTP headers from the given buffer, advance buf pointer
  9204. * to the point where parsing stopped.
  9205. * All parameters must be valid pointers (not NULL).
  9206. * Return <0 on error. */
  9207. static int
  9208. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9209. {
  9210. int i;
  9211. int num_headers = 0;
  9212. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9213. char *dp = *buf;
  9214. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9215. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9216. dp++;
  9217. }
  9218. if (dp == *buf) {
  9219. /* End of headers reached. */
  9220. break;
  9221. }
  9222. /* Drop all spaces after header name before : */
  9223. while (*dp == ' ') {
  9224. *dp = 0;
  9225. dp++;
  9226. }
  9227. if (*dp != ':') {
  9228. /* This is not a valid field. */
  9229. return -1;
  9230. }
  9231. /* End of header key (*dp == ':') */
  9232. /* Truncate here and set the key name */
  9233. *dp = 0;
  9234. hdr[i].name = *buf;
  9235. /* Skip all spaces */
  9236. do {
  9237. dp++;
  9238. } while ((*dp == ' ') || (*dp == '\t'));
  9239. /* The rest of the line is the value */
  9240. hdr[i].value = dp;
  9241. /* Find end of line */
  9242. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9243. dp++;
  9244. };
  9245. /* eliminate \r */
  9246. if (*dp == '\r') {
  9247. *dp = 0;
  9248. dp++;
  9249. if (*dp != '\n') {
  9250. /* This is not a valid line. */
  9251. return -1;
  9252. }
  9253. }
  9254. /* here *dp is either 0 or '\n' */
  9255. /* in any case, we have a new header */
  9256. num_headers = i + 1;
  9257. if (*dp) {
  9258. *dp = 0;
  9259. dp++;
  9260. *buf = dp;
  9261. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9262. /* This is the end of the header */
  9263. break;
  9264. }
  9265. } else {
  9266. *buf = dp;
  9267. break;
  9268. }
  9269. }
  9270. return num_headers;
  9271. }
  9272. struct mg_http_method_info {
  9273. const char *name;
  9274. int request_has_body;
  9275. int response_has_body;
  9276. int is_safe;
  9277. int is_idempotent;
  9278. int is_cacheable;
  9279. };
  9280. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9281. static const struct mg_http_method_info http_methods[] = {
  9282. /* HTTP (RFC 2616) */
  9283. {"GET", 0, 1, 1, 1, 1},
  9284. {"POST", 1, 1, 0, 0, 0},
  9285. {"PUT", 1, 0, 0, 1, 0},
  9286. {"DELETE", 0, 0, 0, 1, 0},
  9287. {"HEAD", 0, 0, 1, 1, 1},
  9288. {"OPTIONS", 0, 0, 1, 1, 0},
  9289. {"CONNECT", 1, 1, 0, 0, 0},
  9290. /* TRACE method (RFC 2616) is not supported for security reasons */
  9291. /* PATCH method (RFC 5789) */
  9292. {"PATCH", 1, 0, 0, 0, 0},
  9293. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9294. /* WEBDAV (RFC 2518) */
  9295. {"PROPFIND", 0, 1, 1, 1, 0},
  9296. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9297. * Some PROPFIND results MAY be cached, with care,
  9298. * as there is no cache validation mechanism for
  9299. * most properties. This method is both safe and
  9300. * idempotent (see Section 9.1 of [RFC2616]). */
  9301. {"MKCOL", 0, 0, 0, 1, 0},
  9302. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9303. * When MKCOL is invoked without a request body,
  9304. * the newly created collection SHOULD have no
  9305. * members. A MKCOL request message may contain
  9306. * a message body. The precise behavior of a MKCOL
  9307. * request when the body is present is undefined,
  9308. * ... ==> We do not support MKCOL with body data.
  9309. * This method is idempotent, but not safe (see
  9310. * Section 9.1 of [RFC2616]). Responses to this
  9311. * method MUST NOT be cached. */
  9312. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9313. {"LOCK", 1, 1, 0, 0, 0},
  9314. {"UNLOCK", 1, 0, 0, 0, 0},
  9315. {"PROPPATCH", 1, 1, 0, 0, 0},
  9316. {"COPY", 1, 0, 0, 0, 0},
  9317. {"MOVE", 1, 1, 0, 0, 0},
  9318. /* Unsupported WEBDAV Methods: */
  9319. /* + 11 methods from RFC 3253 */
  9320. /* ORDERPATCH (RFC 3648) */
  9321. /* ACL (RFC 3744) */
  9322. /* SEARCH (RFC 5323) */
  9323. /* + MicroSoft extensions
  9324. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9325. /* REPORT method (RFC 3253) */
  9326. {"REPORT", 1, 1, 1, 1, 1},
  9327. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9328. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9329. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9330. * to be useful for REST in case a "GET request with body" is
  9331. * required. */
  9332. {NULL, 0, 0, 0, 0, 0}
  9333. /* end of list */
  9334. };
  9335. /* All method names */
  9336. static char *all_methods = NULL; /* Built by mg_init_library */
  9337. static const struct mg_http_method_info *
  9338. get_http_method_info(const char *method)
  9339. {
  9340. /* Check if the method is known to the server. The list of all known
  9341. * HTTP methods can be found here at
  9342. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9343. */
  9344. const struct mg_http_method_info *m = http_methods;
  9345. while (m->name) {
  9346. if (!strcmp(m->name, method)) {
  9347. return m;
  9348. }
  9349. m++;
  9350. }
  9351. return NULL;
  9352. }
  9353. static int
  9354. is_valid_http_method(const char *method)
  9355. {
  9356. return (get_http_method_info(method) != NULL);
  9357. }
  9358. /* Parse HTTP request, fill in mg_request_info structure.
  9359. * This function modifies the buffer by NUL-terminating
  9360. * HTTP request components, header names and header values.
  9361. * Parameters:
  9362. * buf (in/out): pointer to the HTTP header to parse and split
  9363. * len (in): length of HTTP header buffer
  9364. * re (out): parsed header as mg_request_info
  9365. * buf and ri must be valid pointers (not NULL), len>0.
  9366. * Returns <0 on error. */
  9367. static int
  9368. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9369. {
  9370. int request_length;
  9371. int init_skip = 0;
  9372. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9373. * remote_port */
  9374. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9375. NULL;
  9376. ri->num_headers = 0;
  9377. /* RFC says that all initial whitespaces should be ignored */
  9378. /* This included all leading \r and \n (isspace) */
  9379. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9380. while ((len > 0) && isspace((unsigned char)*buf)) {
  9381. buf++;
  9382. len--;
  9383. init_skip++;
  9384. }
  9385. if (len == 0) {
  9386. /* Incomplete request */
  9387. return 0;
  9388. }
  9389. /* Control characters are not allowed, including zero */
  9390. if (iscntrl((unsigned char)*buf)) {
  9391. return -1;
  9392. }
  9393. /* Find end of HTTP header */
  9394. request_length = get_http_header_len(buf, len);
  9395. if (request_length <= 0) {
  9396. return request_length;
  9397. }
  9398. buf[request_length - 1] = '\0';
  9399. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9400. return -1;
  9401. }
  9402. /* The first word has to be the HTTP method */
  9403. ri->request_method = buf;
  9404. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9405. return -1;
  9406. }
  9407. /* The second word is the URI */
  9408. ri->request_uri = buf;
  9409. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9410. return -1;
  9411. }
  9412. /* Next would be the HTTP version */
  9413. ri->http_version = buf;
  9414. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9415. return -1;
  9416. }
  9417. /* Check for a valid HTTP version key */
  9418. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9419. /* Invalid request */
  9420. return -1;
  9421. }
  9422. ri->http_version += 5;
  9423. /* Check for a valid http method */
  9424. if (!is_valid_http_method(ri->request_method)) {
  9425. return -1;
  9426. }
  9427. /* Parse all HTTP headers */
  9428. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9429. if (ri->num_headers < 0) {
  9430. /* Error while parsing headers */
  9431. return -1;
  9432. }
  9433. return request_length + init_skip;
  9434. }
  9435. static int
  9436. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9437. {
  9438. int response_length;
  9439. int init_skip = 0;
  9440. char *tmp, *tmp2;
  9441. long l;
  9442. /* Initialize elements. */
  9443. ri->http_version = ri->status_text = NULL;
  9444. ri->num_headers = ri->status_code = 0;
  9445. /* RFC says that all initial whitespaces should be ignored */
  9446. /* This included all leading \r and \n (isspace) */
  9447. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9448. while ((len > 0) && isspace((unsigned char)*buf)) {
  9449. buf++;
  9450. len--;
  9451. init_skip++;
  9452. }
  9453. if (len == 0) {
  9454. /* Incomplete request */
  9455. return 0;
  9456. }
  9457. /* Control characters are not allowed, including zero */
  9458. if (iscntrl((unsigned char)*buf)) {
  9459. return -1;
  9460. }
  9461. /* Find end of HTTP header */
  9462. response_length = get_http_header_len(buf, len);
  9463. if (response_length <= 0) {
  9464. return response_length;
  9465. }
  9466. buf[response_length - 1] = '\0';
  9467. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9468. return -1;
  9469. }
  9470. /* The first word is the HTTP version */
  9471. /* Check for a valid HTTP version key */
  9472. if (strncmp(buf, "HTTP/", 5) != 0) {
  9473. /* Invalid request */
  9474. return -1;
  9475. }
  9476. buf += 5;
  9477. if (!isgraph((unsigned char)buf[0])) {
  9478. /* Invalid request */
  9479. return -1;
  9480. }
  9481. ri->http_version = buf;
  9482. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9483. return -1;
  9484. }
  9485. /* The second word is the status as a number */
  9486. tmp = buf;
  9487. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9488. return -1;
  9489. }
  9490. l = strtol(tmp, &tmp2, 10);
  9491. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9492. /* Everything else but a 3 digit code is invalid */
  9493. return -1;
  9494. }
  9495. ri->status_code = (int)l;
  9496. /* The rest of the line is the status text */
  9497. ri->status_text = buf;
  9498. /* Find end of status text */
  9499. /* isgraph or isspace = isprint */
  9500. while (isprint((unsigned char)*buf)) {
  9501. buf++;
  9502. }
  9503. if ((*buf != '\r') && (*buf != '\n')) {
  9504. return -1;
  9505. }
  9506. /* Terminate string and forward buf to next line */
  9507. do {
  9508. *buf = 0;
  9509. buf++;
  9510. } while (isspace((unsigned char)*buf));
  9511. /* Parse all HTTP headers */
  9512. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9513. if (ri->num_headers < 0) {
  9514. /* Error while parsing headers */
  9515. return -1;
  9516. }
  9517. return response_length + init_skip;
  9518. }
  9519. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9520. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9521. * buffer (which marks the end of HTTP request). Buffer buf may already
  9522. * have some data. The length of the data is stored in nread.
  9523. * Upon every read operation, increase nread by the number of bytes read. */
  9524. static int
  9525. read_message(FILE *fp,
  9526. struct mg_connection *conn,
  9527. char *buf,
  9528. int bufsiz,
  9529. int *nread)
  9530. {
  9531. int request_len, n = 0;
  9532. struct timespec last_action_time;
  9533. double request_timeout;
  9534. if (!conn) {
  9535. return 0;
  9536. }
  9537. memset(&last_action_time, 0, sizeof(last_action_time));
  9538. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9539. /* value of request_timeout is in seconds, config in milliseconds */
  9540. request_timeout =
  9541. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9542. } else {
  9543. request_timeout =
  9544. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9545. / 1000.0;
  9546. }
  9547. if (conn->handled_requests > 0) {
  9548. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9549. request_timeout =
  9550. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9551. / 1000.0;
  9552. }
  9553. }
  9554. request_len = get_http_header_len(buf, *nread);
  9555. while (request_len == 0) {
  9556. /* Full request not yet received */
  9557. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9558. /* Server is to be stopped. */
  9559. return -1;
  9560. }
  9561. if (*nread >= bufsiz) {
  9562. /* Request too long */
  9563. return -2;
  9564. }
  9565. n = pull_inner(
  9566. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9567. if (n == -2) {
  9568. /* Receive error */
  9569. return -1;
  9570. }
  9571. /* update clock after every read request */
  9572. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9573. if (n > 0) {
  9574. *nread += n;
  9575. request_len = get_http_header_len(buf, *nread);
  9576. }
  9577. if ((request_len == 0) && (request_timeout >= 0)) {
  9578. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9579. > request_timeout) {
  9580. /* Timeout */
  9581. return -1;
  9582. }
  9583. }
  9584. }
  9585. return request_len;
  9586. }
  9587. #if !defined(NO_CGI) || !defined(NO_FILES)
  9588. static int
  9589. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9590. {
  9591. const char *expect;
  9592. char buf[MG_BUF_LEN];
  9593. int success = 0;
  9594. if (!conn) {
  9595. return 0;
  9596. }
  9597. expect = mg_get_header(conn, "Expect");
  9598. DEBUG_ASSERT(fp != NULL);
  9599. if (!fp) {
  9600. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9601. return 0;
  9602. }
  9603. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9604. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9605. */
  9606. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9607. } else {
  9608. if (expect != NULL) {
  9609. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9610. conn->status_code = 100;
  9611. } else {
  9612. conn->status_code = 200;
  9613. }
  9614. DEBUG_ASSERT(conn->consumed_content == 0);
  9615. if (conn->consumed_content != 0) {
  9616. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9617. return 0;
  9618. }
  9619. for (;;) {
  9620. int nread = mg_read(conn, buf, sizeof(buf));
  9621. if (nread <= 0) {
  9622. success = (nread == 0);
  9623. break;
  9624. }
  9625. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9626. break;
  9627. }
  9628. }
  9629. /* Each error code path in this function must send an error */
  9630. if (!success) {
  9631. /* NOTE: Maybe some data has already been sent. */
  9632. /* TODO (low): If some data has been sent, a correct error
  9633. * reply can no longer be sent, so just close the connection */
  9634. mg_send_http_error(conn, 500, "%s", "");
  9635. }
  9636. }
  9637. return success;
  9638. }
  9639. #endif
  9640. #if defined(USE_TIMERS)
  9641. #define TIMER_API static
  9642. #include "timer.inl"
  9643. #endif /* USE_TIMERS */
  9644. #if !defined(NO_CGI)
  9645. /* This structure helps to create an environment for the spawned CGI
  9646. * program.
  9647. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9648. * last element must be NULL.
  9649. * However, on Windows there is a requirement that all these
  9650. * VARIABLE=VALUE\0
  9651. * strings must reside in a contiguous buffer. The end of the buffer is
  9652. * marked by two '\0' characters.
  9653. * We satisfy both worlds: we create an envp array (which is vars), all
  9654. * entries are actually pointers inside buf. */
  9655. struct cgi_environment {
  9656. struct mg_connection *conn;
  9657. /* Data block */
  9658. char *buf; /* Environment buffer */
  9659. size_t buflen; /* Space available in buf */
  9660. size_t bufused; /* Space taken in buf */
  9661. /* Index block */
  9662. char **var; /* char **envp */
  9663. size_t varlen; /* Number of variables available in var */
  9664. size_t varused; /* Number of variables stored in var */
  9665. };
  9666. static void addenv(struct cgi_environment *env,
  9667. PRINTF_FORMAT_STRING(const char *fmt),
  9668. ...) PRINTF_ARGS(2, 3);
  9669. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9670. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9671. static void
  9672. addenv(struct cgi_environment *env, const char *fmt, ...)
  9673. {
  9674. size_t i, n, space;
  9675. int truncated = 0;
  9676. char *added;
  9677. va_list ap;
  9678. if ((env->varlen - env->varused) < 2) {
  9679. mg_cry_internal(env->conn,
  9680. "%s: Cannot register CGI variable [%s]",
  9681. __func__,
  9682. fmt);
  9683. return;
  9684. }
  9685. /* Calculate how much space is left in the buffer */
  9686. space = (env->buflen - env->bufused);
  9687. do {
  9688. /* Space for "\0\0" is always needed. */
  9689. if (space <= 2) {
  9690. /* Allocate new buffer */
  9691. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9692. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9693. if (!added) {
  9694. /* Out of memory */
  9695. mg_cry_internal(
  9696. env->conn,
  9697. "%s: Cannot allocate memory for CGI variable [%s]",
  9698. __func__,
  9699. fmt);
  9700. return;
  9701. }
  9702. /* Retarget pointers */
  9703. env->buf = added;
  9704. env->buflen = n;
  9705. for (i = 0, n = 0; i < env->varused; i++) {
  9706. env->var[i] = added + n;
  9707. n += strlen(added + n) + 1;
  9708. }
  9709. space = (env->buflen - env->bufused);
  9710. }
  9711. /* Make a pointer to the free space int the buffer */
  9712. added = env->buf + env->bufused;
  9713. /* Copy VARIABLE=VALUE\0 string into the free space */
  9714. va_start(ap, fmt);
  9715. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9716. va_end(ap);
  9717. /* Do not add truncated strings to the environment */
  9718. if (truncated) {
  9719. /* Reallocate the buffer */
  9720. space = 0;
  9721. }
  9722. } while (truncated);
  9723. /* Calculate number of bytes added to the environment */
  9724. n = strlen(added) + 1;
  9725. env->bufused += n;
  9726. /* Append a pointer to the added string into the envp array */
  9727. env->var[env->varused] = added;
  9728. env->varused++;
  9729. }
  9730. /* Return 0 on success, non-zero if an error occurs. */
  9731. static int
  9732. prepare_cgi_environment(struct mg_connection *conn,
  9733. const char *prog,
  9734. struct cgi_environment *env,
  9735. int cgi_config_idx)
  9736. {
  9737. const char *s;
  9738. struct vec var_vec;
  9739. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9740. int i, truncated, uri_len;
  9741. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9742. return -1;
  9743. }
  9744. env->conn = conn;
  9745. env->buflen = CGI_ENVIRONMENT_SIZE;
  9746. env->bufused = 0;
  9747. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9748. if (env->buf == NULL) {
  9749. mg_cry_internal(conn,
  9750. "%s: Not enough memory for environmental buffer",
  9751. __func__);
  9752. return -1;
  9753. }
  9754. env->varlen = MAX_CGI_ENVIR_VARS;
  9755. env->varused = 0;
  9756. env->var =
  9757. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9758. if (env->var == NULL) {
  9759. mg_cry_internal(conn,
  9760. "%s: Not enough memory for environmental variables",
  9761. __func__);
  9762. mg_free(env->buf);
  9763. return -1;
  9764. }
  9765. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9766. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9767. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9768. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  9769. addenv(env, "FALLBACK_DOCUMENT_ROOT=%s", conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  9770. }
  9771. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9772. /* Prepare the environment block */
  9773. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9774. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9775. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9776. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9777. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9778. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9779. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9780. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9781. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9782. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9783. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9784. /* SCRIPT_NAME */
  9785. uri_len = (int)strlen(conn->request_info.local_uri);
  9786. if (conn->path_info == NULL) {
  9787. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9788. /* URI: /path_to_script/script.cgi */
  9789. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9790. } else {
  9791. /* URI: /path_to_script/ ... using index.cgi */
  9792. const char *index_file = strrchr(prog, '/');
  9793. if (index_file) {
  9794. addenv(env,
  9795. "SCRIPT_NAME=%s%s",
  9796. conn->request_info.local_uri,
  9797. index_file + 1);
  9798. }
  9799. }
  9800. } else {
  9801. /* URI: /path_to_script/script.cgi/path_info */
  9802. addenv(env,
  9803. "SCRIPT_NAME=%.*s",
  9804. uri_len - (int)strlen(conn->path_info),
  9805. conn->request_info.local_uri);
  9806. }
  9807. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9808. if (conn->path_info == NULL) {
  9809. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9810. } else {
  9811. addenv(env,
  9812. "PATH_TRANSLATED=%s%s",
  9813. conn->dom_ctx->config[DOCUMENT_ROOT],
  9814. conn->path_info);
  9815. }
  9816. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9817. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9818. addenv(env, "CONTENT_TYPE=%s", s);
  9819. }
  9820. if (conn->request_info.query_string != NULL) {
  9821. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9822. }
  9823. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9824. addenv(env, "CONTENT_LENGTH=%s", s);
  9825. }
  9826. if ((s = getenv("PATH")) != NULL) {
  9827. addenv(env, "PATH=%s", s);
  9828. }
  9829. if (conn->path_info != NULL) {
  9830. addenv(env, "PATH_INFO=%s", conn->path_info);
  9831. }
  9832. if (conn->status_code > 0) {
  9833. /* CGI error handler should show the status code */
  9834. addenv(env, "STATUS=%d", conn->status_code);
  9835. }
  9836. #if defined(_WIN32)
  9837. if ((s = getenv("COMSPEC")) != NULL) {
  9838. addenv(env, "COMSPEC=%s", s);
  9839. }
  9840. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9841. addenv(env, "SYSTEMROOT=%s", s);
  9842. }
  9843. if ((s = getenv("SystemDrive")) != NULL) {
  9844. addenv(env, "SystemDrive=%s", s);
  9845. }
  9846. if ((s = getenv("ProgramFiles")) != NULL) {
  9847. addenv(env, "ProgramFiles=%s", s);
  9848. }
  9849. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9850. addenv(env, "ProgramFiles(x86)=%s", s);
  9851. }
  9852. #else
  9853. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9854. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9855. }
  9856. #endif /* _WIN32 */
  9857. if ((s = getenv("PERLLIB")) != NULL) {
  9858. addenv(env, "PERLLIB=%s", s);
  9859. }
  9860. if (conn->request_info.remote_user != NULL) {
  9861. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9862. addenv(env, "%s", "AUTH_TYPE=Digest");
  9863. }
  9864. /* Add all headers as HTTP_* variables */
  9865. for (i = 0; i < conn->request_info.num_headers; i++) {
  9866. (void)mg_snprintf(conn,
  9867. &truncated,
  9868. http_var_name,
  9869. sizeof(http_var_name),
  9870. "HTTP_%s",
  9871. conn->request_info.http_headers[i].name);
  9872. if (truncated) {
  9873. mg_cry_internal(conn,
  9874. "%s: HTTP header variable too long [%s]",
  9875. __func__,
  9876. conn->request_info.http_headers[i].name);
  9877. continue;
  9878. }
  9879. /* Convert variable name into uppercase, and change - to _ */
  9880. for (p = http_var_name; *p != '\0'; p++) {
  9881. if (*p == '-') {
  9882. *p = '_';
  9883. }
  9884. *p = (char)toupper((unsigned char)*p);
  9885. }
  9886. addenv(env,
  9887. "%s=%s",
  9888. http_var_name,
  9889. conn->request_info.http_headers[i].value);
  9890. }
  9891. /* Add user-specified variables */
  9892. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9893. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9894. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9895. }
  9896. env->var[env->varused] = NULL;
  9897. env->buf[env->bufused] = '\0';
  9898. return 0;
  9899. }
  9900. /* Data for CGI process control: PID and number of references */
  9901. struct process_control_data {
  9902. pid_t pid;
  9903. ptrdiff_t references;
  9904. };
  9905. static int
  9906. abort_cgi_process(void *data)
  9907. {
  9908. /* Waitpid checks for child status and won't work for a pid that does
  9909. * not identify a child of the current process. Thus, if the pid is
  9910. * reused, we will not affect a different process. */
  9911. struct process_control_data *proc = (struct process_control_data *)data;
  9912. int status = 0;
  9913. ptrdiff_t refs;
  9914. pid_t ret_pid;
  9915. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9916. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9917. /* Stop child process */
  9918. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9919. kill(proc->pid, SIGABRT);
  9920. /* Wait until process is terminated (don't leave zombies) */
  9921. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9922. ;
  9923. } else {
  9924. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9925. }
  9926. /* Dec reference counter */
  9927. refs = mg_atomic_dec(&proc->references);
  9928. if (refs == 0) {
  9929. /* no more references - free data */
  9930. mg_free(data);
  9931. }
  9932. return 0;
  9933. }
  9934. /* Local (static) function assumes all arguments are valid. */
  9935. static void
  9936. handle_cgi_request(struct mg_connection *conn,
  9937. const char *prog,
  9938. int cgi_config_idx)
  9939. {
  9940. char *buf;
  9941. size_t buflen;
  9942. int headers_len, data_len, i, truncated;
  9943. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9944. const char *status, *status_text;
  9945. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9946. struct mg_request_info ri;
  9947. struct cgi_environment blk;
  9948. FILE *in = NULL, *out = NULL, *err = NULL;
  9949. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9950. pid_t pid = (pid_t)-1;
  9951. struct process_control_data *proc = NULL;
  9952. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9953. int no_buffering = 0;
  9954. #if defined(USE_TIMERS)
  9955. double cgi_timeout;
  9956. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9957. /* Get timeout in seconds */
  9958. cgi_timeout =
  9959. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9960. } else {
  9961. cgi_timeout =
  9962. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9963. }
  9964. #endif
  9965. if (cfg_buffering != NULL) {
  9966. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9967. no_buffering = 1;
  9968. }
  9969. }
  9970. buf = NULL;
  9971. buflen = conn->phys_ctx->max_request_size;
  9972. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9973. if (i != 0) {
  9974. blk.buf = NULL;
  9975. blk.var = NULL;
  9976. goto done;
  9977. }
  9978. /* CGI must be executed in its own directory. 'dir' must point to the
  9979. * directory containing executable program, 'p' must point to the
  9980. * executable program name relative to 'dir'. */
  9981. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9982. if (truncated) {
  9983. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9984. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9985. goto done;
  9986. }
  9987. if ((p = strrchr(dir, '/')) != NULL) {
  9988. *p++ = '\0';
  9989. } else {
  9990. dir[0] = '.';
  9991. dir[1] = '\0';
  9992. p = (char *)prog;
  9993. }
  9994. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9995. status = strerror(ERRNO);
  9996. mg_cry_internal(
  9997. conn,
  9998. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9999. prog,
  10000. status);
  10001. mg_send_http_error(conn,
  10002. 500,
  10003. "Error: Cannot create CGI pipe: %s",
  10004. status);
  10005. goto done;
  10006. }
  10007. proc = (struct process_control_data *)
  10008. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10009. if (proc == NULL) {
  10010. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10011. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10012. goto done;
  10013. }
  10014. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10015. pid = spawn_process(
  10016. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10017. if (pid == (pid_t)-1) {
  10018. status = strerror(ERRNO);
  10019. mg_cry_internal(
  10020. conn,
  10021. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10022. prog,
  10023. status);
  10024. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10025. mg_free(proc);
  10026. proc = NULL;
  10027. goto done;
  10028. }
  10029. /* Store data in shared process_control_data */
  10030. proc->pid = pid;
  10031. proc->references = 1;
  10032. #if defined(USE_TIMERS)
  10033. if (cgi_timeout > 0.0) {
  10034. proc->references = 2;
  10035. // Start a timer for CGI
  10036. timer_add(conn->phys_ctx,
  10037. cgi_timeout /* in seconds */,
  10038. 0.0,
  10039. 1,
  10040. abort_cgi_process,
  10041. (void *)proc,
  10042. NULL);
  10043. }
  10044. #endif
  10045. /* Parent closes only one side of the pipes.
  10046. * If we don't mark them as closed, close() attempt before
  10047. * return from this function throws an exception on Windows.
  10048. * Windows does not like when closed descriptor is closed again. */
  10049. (void)close(fdin[0]);
  10050. (void)close(fdout[1]);
  10051. (void)close(fderr[1]);
  10052. fdin[0] = fdout[1] = fderr[1] = -1;
  10053. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10054. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10055. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10056. status = strerror(ERRNO);
  10057. mg_cry_internal(conn,
  10058. "Error: CGI program \"%s\": Can not open fd: %s",
  10059. prog,
  10060. status);
  10061. mg_send_http_error(conn,
  10062. 500,
  10063. "Error: CGI can not open fd\nfdopen: %s",
  10064. status);
  10065. goto done;
  10066. }
  10067. setbuf(in, NULL);
  10068. setbuf(out, NULL);
  10069. setbuf(err, NULL);
  10070. fout.access.fp = out;
  10071. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10072. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10073. conn->content_len);
  10074. /* This is a POST/PUT request, or another request with body data. */
  10075. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10076. /* Error sending the body data */
  10077. mg_cry_internal(
  10078. conn,
  10079. "Error: CGI program \"%s\": Forward body data failed",
  10080. prog);
  10081. goto done;
  10082. }
  10083. }
  10084. /* Close so child gets an EOF. */
  10085. fclose(in);
  10086. in = NULL;
  10087. fdin[1] = -1;
  10088. /* Now read CGI reply into a buffer. We need to set correct
  10089. * status code, thus we need to see all HTTP headers first.
  10090. * Do not send anything back to client, until we buffer in all
  10091. * HTTP headers. */
  10092. data_len = 0;
  10093. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10094. if (buf == NULL) {
  10095. mg_send_http_error(conn,
  10096. 500,
  10097. "Error: Not enough memory for CGI buffer (%u bytes)",
  10098. (unsigned int)buflen);
  10099. mg_cry_internal(
  10100. conn,
  10101. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10102. "bytes)",
  10103. prog,
  10104. (unsigned int)buflen);
  10105. goto done;
  10106. }
  10107. DEBUG_TRACE("CGI: %s", "wait for response");
  10108. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10109. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10110. if (headers_len <= 0) {
  10111. /* Could not parse the CGI response. Check if some error message on
  10112. * stderr. */
  10113. i = pull_all(err, conn, buf, (int)buflen);
  10114. if (i > 0) {
  10115. /* CGI program explicitly sent an error */
  10116. /* Write the error message to the internal log */
  10117. mg_cry_internal(conn,
  10118. "Error: CGI program \"%s\" sent error "
  10119. "message: [%.*s]",
  10120. prog,
  10121. i,
  10122. buf);
  10123. /* Don't send the error message back to the client */
  10124. mg_send_http_error(conn,
  10125. 500,
  10126. "Error: CGI program \"%s\" failed.",
  10127. prog);
  10128. } else {
  10129. /* CGI program did not explicitly send an error, but a broken
  10130. * respon header */
  10131. mg_cry_internal(conn,
  10132. "Error: CGI program sent malformed or too big "
  10133. "(>%u bytes) HTTP headers: [%.*s]",
  10134. (unsigned)buflen,
  10135. data_len,
  10136. buf);
  10137. mg_send_http_error(conn,
  10138. 500,
  10139. "Error: CGI program sent malformed or too big "
  10140. "(>%u bytes) HTTP headers: [%.*s]",
  10141. (unsigned)buflen,
  10142. data_len,
  10143. buf);
  10144. }
  10145. /* in both cases, abort processing CGI */
  10146. goto done;
  10147. }
  10148. pbuf = buf;
  10149. buf[headers_len - 1] = '\0';
  10150. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10151. /* Make up and send the status line */
  10152. status_text = "OK";
  10153. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10154. != NULL) {
  10155. conn->status_code = atoi(status);
  10156. status_text = status;
  10157. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10158. status_text++;
  10159. }
  10160. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10161. != NULL) {
  10162. conn->status_code = 307;
  10163. } else {
  10164. conn->status_code = 200;
  10165. }
  10166. if (!should_keep_alive(conn)) {
  10167. conn->must_close = 1;
  10168. }
  10169. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10170. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10171. /* Send headers */
  10172. for (i = 0; i < ri.num_headers; i++) {
  10173. DEBUG_TRACE("CGI header: %s: %s",
  10174. ri.http_headers[i].name,
  10175. ri.http_headers[i].value);
  10176. mg_printf(conn,
  10177. "%s: %s\r\n",
  10178. ri.http_headers[i].name,
  10179. ri.http_headers[i].value);
  10180. }
  10181. mg_write(conn, "\r\n", 2);
  10182. /* Send chunk of data that may have been read after the headers */
  10183. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10184. /* Read the rest of CGI output and send to the client */
  10185. DEBUG_TRACE("CGI: %s", "forward all data");
  10186. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10187. DEBUG_TRACE("CGI: %s", "all data sent");
  10188. done:
  10189. mg_free(blk.var);
  10190. mg_free(blk.buf);
  10191. if (pid != (pid_t)-1) {
  10192. abort_cgi_process((void *)proc);
  10193. }
  10194. if (fdin[0] != -1) {
  10195. close(fdin[0]);
  10196. }
  10197. if (fdout[1] != -1) {
  10198. close(fdout[1]);
  10199. }
  10200. if (fderr[1] != -1) {
  10201. close(fderr[1]);
  10202. }
  10203. if (in != NULL) {
  10204. fclose(in);
  10205. } else if (fdin[1] != -1) {
  10206. close(fdin[1]);
  10207. }
  10208. if (out != NULL) {
  10209. fclose(out);
  10210. } else if (fdout[0] != -1) {
  10211. close(fdout[0]);
  10212. }
  10213. if (err != NULL) {
  10214. fclose(err);
  10215. } else if (fderr[0] != -1) {
  10216. close(fderr[0]);
  10217. }
  10218. mg_free(buf);
  10219. }
  10220. #endif /* !NO_CGI */
  10221. #if !defined(NO_FILES)
  10222. static void
  10223. dav_mkcol(struct mg_connection *conn, const char *path)
  10224. {
  10225. int rc, body_len;
  10226. struct de de;
  10227. if (conn == NULL) {
  10228. return;
  10229. }
  10230. /* TODO (mid): Check the mg_send_http_error situations in this function
  10231. */
  10232. memset(&de.file, 0, sizeof(de.file));
  10233. if (!mg_stat(conn, path, &de.file)) {
  10234. mg_cry_internal(conn,
  10235. "%s: mg_stat(%s) failed: %s",
  10236. __func__,
  10237. path,
  10238. strerror(ERRNO));
  10239. }
  10240. if (de.file.last_modified) {
  10241. /* TODO (mid): This check does not seem to make any sense ! */
  10242. /* TODO (mid): Add a webdav unit test first, before changing
  10243. * anything here. */
  10244. mg_send_http_error(
  10245. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10246. return;
  10247. }
  10248. body_len = conn->data_len - conn->request_len;
  10249. if (body_len > 0) {
  10250. mg_send_http_error(
  10251. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10252. return;
  10253. }
  10254. rc = mg_mkdir(conn, path, 0755);
  10255. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10256. if (rc == 0) {
  10257. /* Create 201 "Created" response */
  10258. mg_response_header_start(conn, 201);
  10259. send_static_cache_header(conn);
  10260. send_additional_header(conn);
  10261. mg_response_header_add(conn, "Content-Length", "0", -1);
  10262. /* Send all headers - there is no body */
  10263. mg_response_header_send(conn);
  10264. } else {
  10265. int http_status = 500;
  10266. switch (errno) {
  10267. case EEXIST:
  10268. http_status = 405;
  10269. break;
  10270. case EACCES:
  10271. http_status = 403;
  10272. break;
  10273. case ENOENT:
  10274. http_status = 409;
  10275. break;
  10276. }
  10277. mg_send_http_error(conn,
  10278. http_status,
  10279. "Error processing %s: %s",
  10280. path,
  10281. strerror(ERRNO));
  10282. }
  10283. }
  10284. /* Forward decrlaration */
  10285. static int get_uri_type(const char *uri);
  10286. static const char *
  10287. get_rel_url_at_current_server(const char *uri,
  10288. const struct mg_connection *conn);
  10289. static void
  10290. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10291. {
  10292. const char *overwrite_hdr;
  10293. const char *destination_hdr;
  10294. const char *root;
  10295. int rc, dest_uri_type;
  10296. int http_status = 400;
  10297. int do_overwrite = 0;
  10298. int destination_ok = 0;
  10299. char dest_path[UTF8_PATH_MAX];
  10300. struct mg_file_stat ignored;
  10301. if (conn == NULL) {
  10302. return;
  10303. }
  10304. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10305. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10306. destination_hdr = mg_get_header(conn, "Destination");
  10307. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10308. do_overwrite = 1;
  10309. }
  10310. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10311. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10312. return;
  10313. }
  10314. if (root != NULL) {
  10315. char *local_dest = NULL;
  10316. dest_uri_type = get_uri_type(destination_hdr);
  10317. if (dest_uri_type == 2) {
  10318. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10319. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10320. const char *h =
  10321. get_rel_url_at_current_server(destination_hdr, conn);
  10322. if (h) {
  10323. size_t len = strlen(h);
  10324. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10325. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10326. }
  10327. }
  10328. if (local_dest != NULL) {
  10329. remove_dot_segments(local_dest);
  10330. if (local_dest[0] == '/') {
  10331. int trunc_check = 0;
  10332. mg_snprintf(conn,
  10333. &trunc_check,
  10334. dest_path,
  10335. sizeof(dest_path),
  10336. "%s/%s",
  10337. root,
  10338. local_dest);
  10339. if (trunc_check == 0) {
  10340. destination_ok = 1;
  10341. }
  10342. }
  10343. mg_free(local_dest);
  10344. }
  10345. }
  10346. if (!destination_ok) {
  10347. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10348. return;
  10349. }
  10350. /* Check now if this file exists */
  10351. if (mg_stat(conn, dest_path, &ignored)) {
  10352. /* File exists */
  10353. if (do_overwrite) {
  10354. /* Overwrite allowed: delete the file first */
  10355. if (0 != remove(dest_path)) {
  10356. /* No overwrite: return error */
  10357. mg_send_http_error(conn,
  10358. 403,
  10359. "Cannot overwrite file: %s",
  10360. dest_path);
  10361. return;
  10362. }
  10363. } else {
  10364. /* No overwrite: return error */
  10365. mg_send_http_error(conn,
  10366. 412,
  10367. "Destination already exists: %s",
  10368. dest_path);
  10369. return;
  10370. }
  10371. }
  10372. /* Copy / Move / Rename operation. */
  10373. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10374. #if defined(_WIN32)
  10375. {
  10376. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10377. wchar_t wSource[UTF16_PATH_MAX];
  10378. wchar_t wDest[UTF16_PATH_MAX];
  10379. BOOL ok;
  10380. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10381. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10382. if (do_copy) {
  10383. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10384. } else {
  10385. ok = MoveFileExW(wSource,
  10386. wDest,
  10387. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10388. }
  10389. if (ok) {
  10390. rc = 0;
  10391. } else {
  10392. DWORD lastErr = GetLastError();
  10393. if (lastErr == ERROR_ALREADY_EXISTS) {
  10394. mg_send_http_error(conn,
  10395. 412,
  10396. "Destination already exists: %s",
  10397. dest_path);
  10398. return;
  10399. }
  10400. rc = -1;
  10401. http_status = 400;
  10402. }
  10403. }
  10404. #else
  10405. {
  10406. /* Linux uses already UTF-8, we don't need to convert file names. */
  10407. if (do_copy) {
  10408. /* TODO: COPY for Linux. */
  10409. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10410. return;
  10411. }
  10412. rc = rename(path, dest_path);
  10413. if (rc) {
  10414. switch (errno) {
  10415. case EEXIST:
  10416. http_status = 412;
  10417. break;
  10418. case EACCES:
  10419. http_status = 403;
  10420. break;
  10421. case ENOENT:
  10422. http_status = 409;
  10423. break;
  10424. }
  10425. }
  10426. }
  10427. #endif
  10428. if (rc == 0) {
  10429. /* Create 204 "No Content" response */
  10430. mg_response_header_start(conn, 204);
  10431. mg_response_header_add(conn, "Content-Length", "0", -1);
  10432. /* Send all headers - there is no body */
  10433. mg_response_header_send(conn);
  10434. } else {
  10435. mg_send_http_error(conn, http_status, "Operation failed");
  10436. }
  10437. }
  10438. static void
  10439. put_file(struct mg_connection *conn, const char *path)
  10440. {
  10441. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10442. const char *range;
  10443. int64_t r1, r2;
  10444. int rc;
  10445. if (conn == NULL) {
  10446. return;
  10447. }
  10448. DEBUG_TRACE("store %s", path);
  10449. if (mg_stat(conn, path, &file.stat)) {
  10450. /* File already exists */
  10451. conn->status_code = 200;
  10452. if (file.stat.is_directory) {
  10453. /* This is an already existing directory,
  10454. * so there is nothing to do for the server. */
  10455. rc = 0;
  10456. } else {
  10457. /* File exists and is not a directory. */
  10458. /* Can it be replaced? */
  10459. /* Check if the server may write this file */
  10460. if (access(path, W_OK) == 0) {
  10461. /* Access granted */
  10462. rc = 1;
  10463. } else {
  10464. mg_send_http_error(
  10465. conn,
  10466. 403,
  10467. "Error: Put not possible\nReplacing %s is not allowed",
  10468. path);
  10469. return;
  10470. }
  10471. }
  10472. } else {
  10473. /* File should be created */
  10474. conn->status_code = 201;
  10475. rc = put_dir(conn, path);
  10476. }
  10477. if (rc == 0) {
  10478. /* put_dir returns 0 if path is a directory */
  10479. /* Create response */
  10480. mg_response_header_start(conn, conn->status_code);
  10481. send_no_cache_header(conn);
  10482. send_additional_header(conn);
  10483. mg_response_header_add(conn, "Content-Length", "0", -1);
  10484. /* Send all headers - there is no body */
  10485. mg_response_header_send(conn);
  10486. /* Request to create a directory has been fulfilled successfully.
  10487. * No need to put a file. */
  10488. return;
  10489. }
  10490. if (rc == -1) {
  10491. /* put_dir returns -1 if the path is too long */
  10492. mg_send_http_error(conn,
  10493. 414,
  10494. "Error: Path too long\nput_dir(%s): %s",
  10495. path,
  10496. strerror(ERRNO));
  10497. return;
  10498. }
  10499. if (rc == -2) {
  10500. /* put_dir returns -2 if the directory can not be created */
  10501. mg_send_http_error(conn,
  10502. 500,
  10503. "Error: Can not create directory\nput_dir(%s): %s",
  10504. path,
  10505. strerror(ERRNO));
  10506. return;
  10507. }
  10508. /* A file should be created or overwritten. */
  10509. /* Currently CivetWeb does not need read+write access. */
  10510. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10511. || file.access.fp == NULL) {
  10512. (void)mg_fclose(&file.access);
  10513. mg_send_http_error(conn,
  10514. 500,
  10515. "Error: Can not create file\nfopen(%s): %s",
  10516. path,
  10517. strerror(ERRNO));
  10518. return;
  10519. }
  10520. fclose_on_exec(&file.access, conn);
  10521. range = mg_get_header(conn, "Content-Range");
  10522. r1 = r2 = 0;
  10523. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10524. conn->status_code = 206; /* Partial content */
  10525. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10526. mg_send_http_error(conn,
  10527. 500,
  10528. "Error: Internal error processing file %s",
  10529. path);
  10530. return;
  10531. }
  10532. }
  10533. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10534. /* forward_body_data failed.
  10535. * The error code has already been sent to the client,
  10536. * and conn->status_code is already set. */
  10537. (void)mg_fclose(&file.access);
  10538. return;
  10539. }
  10540. if (mg_fclose(&file.access) != 0) {
  10541. /* fclose failed. This might have different reasons, but a likely
  10542. * one is "no space on disk", http 507. */
  10543. conn->status_code = 507;
  10544. }
  10545. /* Create response (status_code has been set before) */
  10546. mg_response_header_start(conn, conn->status_code);
  10547. send_no_cache_header(conn);
  10548. send_additional_header(conn);
  10549. mg_response_header_add(conn, "Content-Length", "0", -1);
  10550. /* Send all headers - there is no body */
  10551. mg_response_header_send(conn);
  10552. }
  10553. static void
  10554. delete_file(struct mg_connection *conn, const char *path)
  10555. {
  10556. struct de de;
  10557. memset(&de.file, 0, sizeof(de.file));
  10558. if (!mg_stat(conn, path, &de.file)) {
  10559. /* mg_stat returns 0 if the file does not exist */
  10560. mg_send_http_error(conn,
  10561. 404,
  10562. "Error: Cannot delete file\nFile %s not found",
  10563. path);
  10564. return;
  10565. }
  10566. DEBUG_TRACE("delete %s", path);
  10567. if (de.file.is_directory) {
  10568. if (remove_directory(conn, path)) {
  10569. /* Delete is successful: Return 204 without content. */
  10570. mg_send_http_error(conn, 204, "%s", "");
  10571. } else {
  10572. /* Delete is not successful: Return 500 (Server error). */
  10573. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10574. }
  10575. return;
  10576. }
  10577. /* This is an existing file (not a directory).
  10578. * Check if write permission is granted. */
  10579. if (access(path, W_OK) != 0) {
  10580. /* File is read only */
  10581. mg_send_http_error(
  10582. conn,
  10583. 403,
  10584. "Error: Delete not possible\nDeleting %s is not allowed",
  10585. path);
  10586. return;
  10587. }
  10588. /* Try to delete it. */
  10589. if (mg_remove(conn, path) == 0) {
  10590. /* Delete was successful: Return 204 without content. */
  10591. mg_response_header_start(conn, 204);
  10592. send_no_cache_header(conn);
  10593. send_additional_header(conn);
  10594. mg_response_header_add(conn, "Content-Length", "0", -1);
  10595. mg_response_header_send(conn);
  10596. } else {
  10597. /* Delete not successful (file locked). */
  10598. mg_send_http_error(conn,
  10599. 423,
  10600. "Error: Cannot delete file\nremove(%s): %s",
  10601. path,
  10602. strerror(ERRNO));
  10603. }
  10604. }
  10605. #endif /* !NO_FILES */
  10606. #if !defined(NO_FILESYSTEMS)
  10607. static void
  10608. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10609. static void
  10610. do_ssi_include(struct mg_connection *conn,
  10611. const char *ssi,
  10612. char *tag,
  10613. int include_level)
  10614. {
  10615. char file_name[MG_BUF_LEN], path[512], *p;
  10616. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10617. size_t len;
  10618. int truncated = 0;
  10619. if (conn == NULL) {
  10620. return;
  10621. }
  10622. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10623. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10624. * always < MG_BUF_LEN. */
  10625. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10626. /* File name is relative to the webserver root */
  10627. file_name[511] = 0;
  10628. (void)mg_snprintf(conn,
  10629. &truncated,
  10630. path,
  10631. sizeof(path),
  10632. "%s/%s",
  10633. conn->dom_ctx->config[DOCUMENT_ROOT],
  10634. file_name);
  10635. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10636. /* File name is relative to the webserver working directory
  10637. * or it is absolute system path */
  10638. file_name[511] = 0;
  10639. (void)
  10640. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10641. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10642. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10643. /* File name is relative to the current document */
  10644. file_name[511] = 0;
  10645. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10646. if (!truncated) {
  10647. if ((p = strrchr(path, '/')) != NULL) {
  10648. p[1] = '\0';
  10649. }
  10650. len = strlen(path);
  10651. (void)mg_snprintf(conn,
  10652. &truncated,
  10653. path + len,
  10654. sizeof(path) - len,
  10655. "%s",
  10656. file_name);
  10657. }
  10658. } else {
  10659. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10660. return;
  10661. }
  10662. if (truncated) {
  10663. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10664. return;
  10665. }
  10666. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10667. mg_cry_internal(conn,
  10668. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10669. tag,
  10670. path,
  10671. strerror(ERRNO));
  10672. } else {
  10673. fclose_on_exec(&file.access, conn);
  10674. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10675. > 0) {
  10676. send_ssi_file(conn, path, &file, include_level + 1);
  10677. } else {
  10678. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10679. }
  10680. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10681. }
  10682. }
  10683. #if !defined(NO_POPEN)
  10684. static void
  10685. do_ssi_exec(struct mg_connection *conn, char *tag)
  10686. {
  10687. char cmd[1024] = "";
  10688. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10689. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10690. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10691. } else {
  10692. cmd[1023] = 0;
  10693. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10694. mg_cry_internal(conn,
  10695. "Cannot SSI #exec: [%s]: %s",
  10696. cmd,
  10697. strerror(ERRNO));
  10698. } else {
  10699. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10700. pclose(file.access.fp);
  10701. }
  10702. }
  10703. }
  10704. #endif /* !NO_POPEN */
  10705. static int
  10706. mg_fgetc(struct mg_file *filep)
  10707. {
  10708. if (filep == NULL) {
  10709. return EOF;
  10710. }
  10711. if (filep->access.fp != NULL) {
  10712. return fgetc(filep->access.fp);
  10713. } else {
  10714. return EOF;
  10715. }
  10716. }
  10717. static void
  10718. send_ssi_file(struct mg_connection *conn,
  10719. const char *path,
  10720. struct mg_file *filep,
  10721. int include_level)
  10722. {
  10723. char buf[MG_BUF_LEN];
  10724. int ch, len, in_tag, in_ssi_tag;
  10725. if (include_level > 10) {
  10726. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10727. return;
  10728. }
  10729. in_tag = in_ssi_tag = len = 0;
  10730. /* Read file, byte by byte, and look for SSI include tags */
  10731. while ((ch = mg_fgetc(filep)) != EOF) {
  10732. if (in_tag) {
  10733. /* We are in a tag, either SSI tag or html tag */
  10734. if (ch == '>') {
  10735. /* Tag is closing */
  10736. buf[len++] = '>';
  10737. if (in_ssi_tag) {
  10738. /* Handle SSI tag */
  10739. buf[len] = 0;
  10740. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10741. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10742. #if !defined(NO_POPEN)
  10743. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10744. do_ssi_exec(conn, buf + 9);
  10745. #endif /* !NO_POPEN */
  10746. } else {
  10747. mg_cry_internal(conn,
  10748. "%s: unknown SSI "
  10749. "command: \"%s\"",
  10750. path,
  10751. buf);
  10752. }
  10753. len = 0;
  10754. in_ssi_tag = in_tag = 0;
  10755. } else {
  10756. /* Not an SSI tag */
  10757. /* Flush buffer */
  10758. (void)mg_write(conn, buf, (size_t)len);
  10759. len = 0;
  10760. in_tag = 0;
  10761. }
  10762. } else {
  10763. /* Tag is still open */
  10764. buf[len++] = (char)(ch & 0xff);
  10765. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10766. /* All SSI tags start with <!--# */
  10767. in_ssi_tag = 1;
  10768. }
  10769. if ((len + 2) > (int)sizeof(buf)) {
  10770. /* Tag to long for buffer */
  10771. mg_cry_internal(conn, "%s: tag is too large", path);
  10772. return;
  10773. }
  10774. }
  10775. } else {
  10776. /* We are not in a tag yet. */
  10777. if (ch == '<') {
  10778. /* Tag is opening */
  10779. in_tag = 1;
  10780. if (len > 0) {
  10781. /* Flush current buffer.
  10782. * Buffer is filled with "len" bytes. */
  10783. (void)mg_write(conn, buf, (size_t)len);
  10784. }
  10785. /* Store the < */
  10786. len = 1;
  10787. buf[0] = '<';
  10788. } else {
  10789. /* No Tag */
  10790. /* Add data to buffer */
  10791. buf[len++] = (char)(ch & 0xff);
  10792. /* Flush if buffer is full */
  10793. if (len == (int)sizeof(buf)) {
  10794. mg_write(conn, buf, (size_t)len);
  10795. len = 0;
  10796. }
  10797. }
  10798. }
  10799. }
  10800. /* Send the rest of buffered data */
  10801. if (len > 0) {
  10802. mg_write(conn, buf, (size_t)len);
  10803. }
  10804. }
  10805. static void
  10806. handle_ssi_file_request(struct mg_connection *conn,
  10807. const char *path,
  10808. struct mg_file *filep)
  10809. {
  10810. char date[64];
  10811. time_t curtime = time(NULL);
  10812. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10813. return;
  10814. }
  10815. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10816. /* File exists (precondition for calling this function),
  10817. * but can not be opened by the server. */
  10818. mg_send_http_error(conn,
  10819. 500,
  10820. "Error: Cannot read file\nfopen(%s): %s",
  10821. path,
  10822. strerror(ERRNO));
  10823. } else {
  10824. /* Set "must_close" for HTTP/1.x, since we do not know the
  10825. * content length */
  10826. conn->must_close = 1;
  10827. gmt_time_string(date, sizeof(date), &curtime);
  10828. fclose_on_exec(&filep->access, conn);
  10829. /* 200 OK response */
  10830. mg_response_header_start(conn, 200);
  10831. send_no_cache_header(conn);
  10832. send_additional_header(conn);
  10833. send_cors_header(conn);
  10834. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10835. mg_response_header_send(conn);
  10836. /* Header sent, now send body */
  10837. send_ssi_file(conn, path, filep, 0);
  10838. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10839. }
  10840. }
  10841. #endif /* NO_FILESYSTEMS */
  10842. #if !defined(NO_FILES)
  10843. static void
  10844. send_options(struct mg_connection *conn)
  10845. {
  10846. if (!conn || !all_methods) {
  10847. return;
  10848. }
  10849. /* We do not set a "Cache-Control" header here, but leave the default.
  10850. * Since browsers do not send an OPTIONS request, we can not test the
  10851. * effect anyway. */
  10852. mg_response_header_start(conn, 200);
  10853. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10854. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10855. /* Use the same as before */
  10856. mg_response_header_add(conn, "Allow", all_methods, -1);
  10857. mg_response_header_add(conn, "DAV", "1", -1);
  10858. } else {
  10859. /* TODO: Check this later for HTTP/2 */
  10860. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10861. }
  10862. send_additional_header(conn);
  10863. mg_response_header_send(conn);
  10864. }
  10865. /* Writes PROPFIND properties for a collection element */
  10866. static int
  10867. print_props(struct mg_connection *conn,
  10868. const char *uri,
  10869. const char *name,
  10870. struct mg_file_stat *filep)
  10871. {
  10872. size_t i;
  10873. char mtime[64];
  10874. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10875. char *link_concat;
  10876. size_t link_concat_len;
  10877. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10878. return 0;
  10879. }
  10880. link_concat_len = strlen(uri) + strlen(name) + 1;
  10881. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10882. if (!link_concat) {
  10883. return 0;
  10884. }
  10885. strcpy(link_concat, uri);
  10886. strcat(link_concat, name);
  10887. /* Get full link used in request */
  10888. mg_construct_local_link(
  10889. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10890. /*
  10891. OutputDebugStringA("print_props:\n uri: ");
  10892. OutputDebugStringA(uri);
  10893. OutputDebugStringA("\n name: ");
  10894. OutputDebugStringA(name);
  10895. OutputDebugStringA("\n link: ");
  10896. OutputDebugStringA(link_buf);
  10897. OutputDebugStringA("\n");
  10898. */
  10899. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10900. mg_printf(conn,
  10901. "<d:response>"
  10902. "<d:href>%s</d:href>"
  10903. "<d:propstat>"
  10904. "<d:prop>"
  10905. "<d:resourcetype>%s</d:resourcetype>"
  10906. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10907. "<d:getlastmodified>%s</d:getlastmodified>"
  10908. "<d:lockdiscovery>",
  10909. link_buf,
  10910. filep->is_directory ? "<d:collection/>" : "",
  10911. filep->size,
  10912. mtime);
  10913. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10914. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10915. if (!strcmp(dav_lock[i].path, link_buf)) {
  10916. mg_printf(conn,
  10917. "<d:activelock>"
  10918. "<d:locktype><d:write/></d:locktype>"
  10919. "<d:lockscope><d:exclusive/></d:lockscope>"
  10920. "<d:depth>0</d:depth>"
  10921. "<d:owner>%s</d:owner>"
  10922. "<d:timeout>Second-%u</d:timeout>"
  10923. "<d:locktoken>"
  10924. "<d:href>%s</d:href>"
  10925. "</d:locktoken>"
  10926. "</d:activelock>\n",
  10927. dav_lock[i].user,
  10928. (unsigned)LOCK_DURATION_S,
  10929. dav_lock[i].token);
  10930. }
  10931. }
  10932. mg_printf(conn,
  10933. "</d:lockdiscovery>"
  10934. "</d:prop>"
  10935. "<d:status>HTTP/1.1 200 OK</d:status>"
  10936. "</d:propstat>"
  10937. "</d:response>\n");
  10938. mg_free(link_concat);
  10939. return 1;
  10940. }
  10941. static int
  10942. print_dav_dir_entry(struct de *de, void *data)
  10943. {
  10944. struct mg_connection *conn = (struct mg_connection *)data;
  10945. if (!de || !conn
  10946. || !print_props(
  10947. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10948. /* stop scan */
  10949. return 1;
  10950. }
  10951. return 0;
  10952. }
  10953. static void
  10954. handle_propfind(struct mg_connection *conn,
  10955. const char *path,
  10956. struct mg_file_stat *filep)
  10957. {
  10958. const char *depth = mg_get_header(conn, "Depth");
  10959. if (!conn || !path || !filep || !conn->dom_ctx) {
  10960. return;
  10961. }
  10962. /* return 207 "Multi-Status" */
  10963. conn->must_close = 1;
  10964. mg_response_header_start(conn, 207);
  10965. send_static_cache_header(conn);
  10966. send_additional_header(conn);
  10967. mg_response_header_add(conn,
  10968. "Content-Type",
  10969. "application/xml; charset=utf-8",
  10970. -1);
  10971. mg_response_header_send(conn);
  10972. /* Content */
  10973. mg_printf(conn,
  10974. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10975. "<d:multistatus xmlns:d='DAV:'>\n");
  10976. /* Print properties for the requested resource itself */
  10977. print_props(conn, conn->request_info.local_uri, "", filep);
  10978. /* If it is a directory, print directory entries too if Depth is not 0
  10979. */
  10980. if (filep->is_directory
  10981. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10982. "yes")
  10983. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10984. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10985. }
  10986. mg_printf(conn, "%s\n", "</d:multistatus>");
  10987. }
  10988. static void
  10989. dav_lock_file(struct mg_connection *conn, const char *path)
  10990. {
  10991. /* internal function - therefore conn is assumed to be valid */
  10992. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10993. uint64_t new_locktime;
  10994. int lock_index = -1;
  10995. int i;
  10996. uint64_t LOCK_DURATION_NS =
  10997. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10998. struct twebdav_lock *dav_lock = NULL;
  10999. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11000. || !conn->phys_ctx) {
  11001. return;
  11002. }
  11003. dav_lock = conn->phys_ctx->webdav_lock;
  11004. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11005. /* const char *refresh = mg_get_header(conn, "If"); */
  11006. /* Link refresh should have an "If" header:
  11007. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11008. * But it seems Windows Explorer does not send them.
  11009. */
  11010. mg_lock_context(conn->phys_ctx);
  11011. new_locktime = mg_get_current_time_ns();
  11012. /* Find a slot for a lock */
  11013. while (lock_index < 0) {
  11014. /* find existing lock */
  11015. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11016. if (!strcmp(dav_lock[i].path, link_buf)) {
  11017. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11018. /* locked by the same user */
  11019. dav_lock[i].locktime = new_locktime;
  11020. lock_index = i;
  11021. break;
  11022. } else {
  11023. /* already locked by someone else */
  11024. if (new_locktime
  11025. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11026. /* Lock expired */
  11027. dav_lock[i].path[0] = 0;
  11028. } else {
  11029. /* Lock still valid */
  11030. mg_unlock_context(conn->phys_ctx);
  11031. mg_send_http_error(conn, 423, "%s", "Already locked");
  11032. return;
  11033. }
  11034. }
  11035. }
  11036. }
  11037. /* create new lock token */
  11038. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11039. if (dav_lock[i].path[0] == 0) {
  11040. char s[32];
  11041. dav_lock[i].locktime = mg_get_current_time_ns();
  11042. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11043. mg_md5(dav_lock[i].token,
  11044. link_buf,
  11045. "\x01",
  11046. s,
  11047. "\x01",
  11048. conn->request_info.remote_user,
  11049. NULL);
  11050. mg_strlcpy(dav_lock[i].path,
  11051. link_buf,
  11052. sizeof(dav_lock[i].path));
  11053. mg_strlcpy(dav_lock[i].user,
  11054. conn->request_info.remote_user,
  11055. sizeof(dav_lock[i].user));
  11056. lock_index = i;
  11057. break;
  11058. }
  11059. }
  11060. if (lock_index < 0) {
  11061. /* too many locks. Find oldest lock */
  11062. uint64_t oldest_locktime = dav_lock[0].locktime;
  11063. lock_index = 0;
  11064. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11065. if (dav_lock[i].locktime < oldest_locktime) {
  11066. oldest_locktime = dav_lock[i].locktime;
  11067. lock_index = i;
  11068. }
  11069. }
  11070. /* invalidate oldest lock */
  11071. dav_lock[lock_index].path[0] = 0;
  11072. }
  11073. }
  11074. mg_unlock_context(conn->phys_ctx);
  11075. /* return 200 "OK" */
  11076. conn->must_close = 1;
  11077. mg_response_header_start(conn, 200);
  11078. send_static_cache_header(conn);
  11079. send_additional_header(conn);
  11080. mg_response_header_add(conn,
  11081. "Content-Type",
  11082. "application/xml; charset=utf-8",
  11083. -1);
  11084. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11085. mg_response_header_send(conn);
  11086. /* Content */
  11087. mg_printf(conn,
  11088. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11089. "<d:prop xmlns:d=\"DAV:\">\n"
  11090. " <d:lockdiscovery>\n"
  11091. " <d:activelock>\n"
  11092. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11093. " <d:locktype><d:write/></d:locktype>\n"
  11094. " <d:owner>\n"
  11095. " <d:href>%s</d:href>\n"
  11096. " </d:owner>\n"
  11097. " <d:timeout>Second-%u</d:timeout>\n"
  11098. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11099. " <d:lockroot>\n"
  11100. " <d:href>%s</d:href>\n"
  11101. " </d:lockroot>\n"
  11102. " </d:activelock>\n"
  11103. " </d:lockdiscovery>\n"
  11104. " </d:prop>\n",
  11105. dav_lock[lock_index].user,
  11106. (LOCK_DURATION_S),
  11107. dav_lock[lock_index].token,
  11108. dav_lock[lock_index].path);
  11109. }
  11110. static void
  11111. dav_unlock_file(struct mg_connection *conn, const char *path)
  11112. {
  11113. /* internal function - therefore conn is assumed to be valid */
  11114. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11115. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11116. int lock_index;
  11117. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11118. return;
  11119. }
  11120. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11121. mg_lock_context(conn->phys_ctx);
  11122. /* find existing lock */
  11123. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11124. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11125. /* Success: return 204 "No Content" */
  11126. mg_unlock_context(conn->phys_ctx);
  11127. conn->must_close = 1;
  11128. mg_response_header_start(conn, 204);
  11129. mg_response_header_send(conn);
  11130. return;
  11131. }
  11132. }
  11133. mg_unlock_context(conn->phys_ctx);
  11134. /* Error: Cannot unlock a resource that is not locked */
  11135. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11136. }
  11137. static void
  11138. dav_proppatch(struct mg_connection *conn, const char *path)
  11139. {
  11140. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11141. if (!conn || !path || !conn->dom_ctx) {
  11142. return;
  11143. }
  11144. /* return 207 "Multi-Status" */
  11145. conn->must_close = 1;
  11146. mg_response_header_start(conn, 207);
  11147. send_static_cache_header(conn);
  11148. send_additional_header(conn);
  11149. mg_response_header_add(conn,
  11150. "Content-Type",
  11151. "application/xml; charset=utf-8",
  11152. -1);
  11153. mg_response_header_send(conn);
  11154. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11155. /* Content */
  11156. mg_printf(conn,
  11157. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11158. "<d:multistatus xmlns:d='DAV:'>\n"
  11159. "<d:response>\n<d:href>%s</d:href>\n",
  11160. link_buf);
  11161. mg_printf(conn,
  11162. "<d:propstat><d:status>HTTP/1.1 403 "
  11163. "Forbidden</d:status></d:propstat>\n");
  11164. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11165. }
  11166. #endif
  11167. CIVETWEB_API void
  11168. mg_lock_connection(struct mg_connection *conn)
  11169. {
  11170. if (conn) {
  11171. (void)pthread_mutex_lock(&conn->mutex);
  11172. }
  11173. }
  11174. CIVETWEB_API void
  11175. mg_unlock_connection(struct mg_connection *conn)
  11176. {
  11177. if (conn) {
  11178. (void)pthread_mutex_unlock(&conn->mutex);
  11179. }
  11180. }
  11181. CIVETWEB_API void
  11182. mg_lock_context(struct mg_context *ctx)
  11183. {
  11184. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11185. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11186. }
  11187. }
  11188. CIVETWEB_API void
  11189. mg_unlock_context(struct mg_context *ctx)
  11190. {
  11191. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11192. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11193. }
  11194. }
  11195. #if defined(USE_LUA)
  11196. #include "mod_lua.inl"
  11197. #endif /* USE_LUA */
  11198. #if defined(USE_DUKTAPE)
  11199. #include "mod_duktape.inl"
  11200. #endif /* USE_DUKTAPE */
  11201. #if defined(USE_WEBSOCKET)
  11202. #if !defined(NO_SSL_DL)
  11203. #if !defined(OPENSSL_API_3_0)
  11204. #define SHA_API static
  11205. #include "sha1.inl"
  11206. #endif
  11207. #endif
  11208. static int
  11209. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11210. {
  11211. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11212. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11213. size_t dst_len = sizeof(b64_sha);
  11214. #if !defined(OPENSSL_API_3_0)
  11215. SHA_CTX sha_ctx;
  11216. #endif
  11217. int truncated;
  11218. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11219. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11220. if (truncated) {
  11221. conn->must_close = 1;
  11222. return 0;
  11223. }
  11224. DEBUG_TRACE("%s", "Send websocket handshake");
  11225. #if defined(OPENSSL_API_3_0)
  11226. EVP_Digest((unsigned char *)buf,
  11227. (uint32_t)strlen(buf),
  11228. (unsigned char *)sha,
  11229. NULL,
  11230. EVP_get_digestbyname("sha1"),
  11231. NULL);
  11232. #else
  11233. SHA1_Init(&sha_ctx);
  11234. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11235. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11236. #endif
  11237. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11238. mg_printf(conn,
  11239. "HTTP/1.1 101 Switching Protocols\r\n"
  11240. "Upgrade: websocket\r\n"
  11241. "Connection: Upgrade\r\n"
  11242. "Sec-WebSocket-Accept: %s\r\n",
  11243. b64_sha);
  11244. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11245. // Send negotiated compression extension parameters
  11246. websocket_deflate_response(conn);
  11247. #endif
  11248. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11249. mg_printf(conn,
  11250. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11251. conn->request_info.acceptedWebSocketSubprotocol);
  11252. } else {
  11253. mg_printf(conn, "%s", "\r\n");
  11254. }
  11255. return 1;
  11256. }
  11257. #if !defined(MG_MAX_UNANSWERED_PING)
  11258. /* Configuration of the maximum number of websocket PINGs that might
  11259. * stay unanswered before the connection is considered broken.
  11260. * Note: The name of this define may still change (until it is
  11261. * defined as a compile parameter in a documentation).
  11262. */
  11263. #define MG_MAX_UNANSWERED_PING (5)
  11264. #endif
  11265. static void
  11266. read_websocket(struct mg_connection *conn,
  11267. mg_websocket_data_handler ws_data_handler,
  11268. void *callback_data)
  11269. {
  11270. /* Pointer to the beginning of the portion of the incoming websocket
  11271. * message queue.
  11272. * The original websocket upgrade request is never removed, so the queue
  11273. * begins after it. */
  11274. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11275. int n, error, exit_by_callback;
  11276. int ret;
  11277. /* body_len is the length of the entire queue in bytes
  11278. * len is the length of the current message
  11279. * data_len is the length of the current message's data payload
  11280. * header_len is the length of the current message's header */
  11281. size_t i, len, mask_len = 0, header_len, body_len;
  11282. uint64_t data_len = 0;
  11283. /* "The masking key is a 32-bit value chosen at random by the client."
  11284. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11285. */
  11286. unsigned char mask[4];
  11287. /* data points to the place where the message is stored when passed to
  11288. * the websocket_data callback. This is either mem on the stack, or a
  11289. * dynamically allocated buffer if it is too large. */
  11290. unsigned char mem[4096];
  11291. unsigned char mop; /* mask flag and opcode */
  11292. /* Variables used for connection monitoring */
  11293. double timeout = -1.0;
  11294. int enable_ping_pong = 0;
  11295. int ping_count = 0;
  11296. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11297. enable_ping_pong =
  11298. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11299. "yes");
  11300. }
  11301. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11302. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11303. }
  11304. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11305. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11306. }
  11307. if (timeout <= 0.0) {
  11308. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11309. }
  11310. /* Enter data processing loop */
  11311. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11312. conn->request_info.remote_addr,
  11313. conn->request_info.remote_port);
  11314. conn->in_websocket_handling = 1;
  11315. mg_set_thread_name("wsock");
  11316. /* Loop continuously, reading messages from the socket, invoking the
  11317. * callback, and waiting repeatedly until an error occurs. */
  11318. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11319. && (!conn->must_close)) {
  11320. header_len = 0;
  11321. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11322. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11323. len = buf[1] & 127;
  11324. mask_len = (buf[1] & 128) ? 4 : 0;
  11325. if ((len < 126) && (body_len >= mask_len)) {
  11326. /* inline 7-bit length field */
  11327. data_len = len;
  11328. header_len = 2 + mask_len;
  11329. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11330. /* 16-bit length field */
  11331. header_len = 4 + mask_len;
  11332. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11333. } else if (body_len >= (10 + mask_len)) {
  11334. /* 64-bit length field */
  11335. uint32_t l1, l2;
  11336. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11337. memcpy(&l2, &buf[6], 4);
  11338. header_len = 10 + mask_len;
  11339. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11340. if (data_len > (uint64_t)0x7FFF0000ul) {
  11341. /* no can do */
  11342. mg_cry_internal(
  11343. conn,
  11344. "%s",
  11345. "websocket out of memory; closing connection");
  11346. break;
  11347. }
  11348. }
  11349. }
  11350. if ((header_len > 0) && (body_len >= header_len)) {
  11351. /* Allocate space to hold websocket payload */
  11352. unsigned char *data = mem;
  11353. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11354. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11355. conn->phys_ctx);
  11356. if (data == NULL) {
  11357. /* Allocation failed, exit the loop and then close the
  11358. * connection */
  11359. mg_cry_internal(
  11360. conn,
  11361. "%s",
  11362. "websocket out of memory; closing connection");
  11363. break;
  11364. }
  11365. }
  11366. /* Copy the mask before we shift the queue and destroy it */
  11367. if (mask_len > 0) {
  11368. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11369. } else {
  11370. memset(mask, 0, sizeof(mask));
  11371. }
  11372. /* Read frame payload from the first message in the queue into
  11373. * data and advance the queue by moving the memory in place. */
  11374. DEBUG_ASSERT(body_len >= header_len);
  11375. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11376. mop = buf[0]; /* current mask and opcode */
  11377. /* Overflow case */
  11378. len = body_len - header_len;
  11379. memcpy(data, buf + header_len, len);
  11380. error = 0;
  11381. while ((uint64_t)len < data_len) {
  11382. n = pull_inner(NULL,
  11383. conn,
  11384. (char *)(data + len),
  11385. (int)(data_len - len),
  11386. timeout);
  11387. if (n <= -2) {
  11388. error = 1;
  11389. break;
  11390. } else if (n > 0) {
  11391. len += (size_t)n;
  11392. } else {
  11393. /* Timeout: should retry */
  11394. /* TODO: retry condition */
  11395. }
  11396. }
  11397. if (error) {
  11398. mg_cry_internal(
  11399. conn,
  11400. "%s",
  11401. "Websocket pull failed; closing connection");
  11402. if (data != mem) {
  11403. mg_free(data);
  11404. }
  11405. break;
  11406. }
  11407. conn->data_len = conn->request_len;
  11408. } else {
  11409. mop = buf[0]; /* current mask and opcode, overwritten by
  11410. * memmove() */
  11411. /* Length of the message being read at the front of the
  11412. * queue. Cast to 31 bit is OK, since we limited
  11413. * data_len before. */
  11414. len = (size_t)data_len + header_len;
  11415. /* Copy the data payload into the data pointer for the
  11416. * callback. Cast to 31 bit is OK, since we
  11417. * limited data_len */
  11418. memcpy(data, buf + header_len, (size_t)data_len);
  11419. /* Move the queue forward len bytes */
  11420. memmove(buf, buf + len, body_len - len);
  11421. /* Mark the queue as advanced */
  11422. conn->data_len -= (int)len;
  11423. }
  11424. /* Apply mask if necessary */
  11425. if (mask_len > 0) {
  11426. for (i = 0; i < (size_t)data_len; i++) {
  11427. data[i] ^= mask[i & 3];
  11428. }
  11429. }
  11430. exit_by_callback = 0;
  11431. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11432. /* filter PONG messages */
  11433. DEBUG_TRACE("PONG from %s:%u",
  11434. conn->request_info.remote_addr,
  11435. conn->request_info.remote_port);
  11436. /* No unanwered PINGs left */
  11437. ping_count = 0;
  11438. } else if (enable_ping_pong
  11439. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11440. /* reply PING messages */
  11441. DEBUG_TRACE("Reply PING from %s:%u",
  11442. conn->request_info.remote_addr,
  11443. conn->request_info.remote_port);
  11444. ret = mg_websocket_write(conn,
  11445. MG_WEBSOCKET_OPCODE_PONG,
  11446. (char *)data,
  11447. (size_t)data_len);
  11448. if (ret <= 0) {
  11449. /* Error: send failed */
  11450. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11451. break;
  11452. }
  11453. } else {
  11454. /* Exit the loop if callback signals to exit (server side),
  11455. * or "connection close" opcode received (client side). */
  11456. if (ws_data_handler != NULL) {
  11457. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11458. if (mop & 0x40) {
  11459. /* Inflate the data received if bit RSV1 is set. */
  11460. if (!conn->websocket_deflate_initialized) {
  11461. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11462. exit_by_callback = 1;
  11463. }
  11464. if (!exit_by_callback) {
  11465. size_t inflate_buf_size_old = 0;
  11466. size_t inflate_buf_size =
  11467. data_len
  11468. * 4; // Initial guess of the inflated message
  11469. // size. We double the memory when needed.
  11470. Bytef *inflated = NULL;
  11471. Bytef *new_mem = NULL;
  11472. conn->websocket_inflate_state.avail_in =
  11473. (uInt)(data_len + 4);
  11474. conn->websocket_inflate_state.next_in = data;
  11475. // Add trailing 0x00 0x00 0xff 0xff bytes
  11476. data[data_len] = '\x00';
  11477. data[data_len + 1] = '\x00';
  11478. data[data_len + 2] = '\xff';
  11479. data[data_len + 3] = '\xff';
  11480. do {
  11481. if (inflate_buf_size_old == 0) {
  11482. new_mem =
  11483. (Bytef *)mg_calloc(inflate_buf_size,
  11484. sizeof(Bytef));
  11485. } else {
  11486. inflate_buf_size *= 2;
  11487. new_mem =
  11488. (Bytef *)mg_realloc(inflated,
  11489. inflate_buf_size);
  11490. }
  11491. if (new_mem == NULL) {
  11492. mg_cry_internal(
  11493. conn,
  11494. "Out of memory: Cannot allocate "
  11495. "inflate buffer of %lu bytes",
  11496. (unsigned long)inflate_buf_size);
  11497. exit_by_callback = 1;
  11498. break;
  11499. }
  11500. inflated = new_mem;
  11501. conn->websocket_inflate_state.avail_out =
  11502. (uInt)(inflate_buf_size
  11503. - inflate_buf_size_old);
  11504. conn->websocket_inflate_state.next_out =
  11505. inflated + inflate_buf_size_old;
  11506. ret = inflate(&conn->websocket_inflate_state,
  11507. Z_SYNC_FLUSH);
  11508. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11509. || ret == Z_MEM_ERROR) {
  11510. mg_cry_internal(
  11511. conn,
  11512. "ZLIB inflate error: %i %s",
  11513. ret,
  11514. (conn->websocket_inflate_state.msg
  11515. ? conn->websocket_inflate_state.msg
  11516. : "<no error message>"));
  11517. exit_by_callback = 1;
  11518. break;
  11519. }
  11520. inflate_buf_size_old = inflate_buf_size;
  11521. } while (conn->websocket_inflate_state.avail_out
  11522. == 0);
  11523. inflate_buf_size -=
  11524. conn->websocket_inflate_state.avail_out;
  11525. if (!ws_data_handler(conn,
  11526. mop,
  11527. (char *)inflated,
  11528. inflate_buf_size,
  11529. callback_data)) {
  11530. exit_by_callback = 1;
  11531. }
  11532. mg_free(inflated);
  11533. }
  11534. } else
  11535. #endif
  11536. if (!ws_data_handler(conn,
  11537. mop,
  11538. (char *)data,
  11539. (size_t)data_len,
  11540. callback_data)) {
  11541. exit_by_callback = 1;
  11542. }
  11543. }
  11544. }
  11545. /* It a buffer has been allocated, free it again */
  11546. if (data != mem) {
  11547. mg_free(data);
  11548. }
  11549. if (exit_by_callback) {
  11550. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11551. conn->request_info.remote_addr,
  11552. conn->request_info.remote_port);
  11553. break;
  11554. }
  11555. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11556. /* Opcode == 8, connection close */
  11557. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11558. conn->request_info.remote_addr,
  11559. conn->request_info.remote_port);
  11560. break;
  11561. }
  11562. /* Not breaking the loop, process next websocket frame. */
  11563. } else {
  11564. /* Read from the socket into the next available location in the
  11565. * message queue. */
  11566. n = pull_inner(NULL,
  11567. conn,
  11568. conn->buf + conn->data_len,
  11569. conn->buf_size - conn->data_len,
  11570. timeout);
  11571. if (n <= -2) {
  11572. /* Error, no bytes read */
  11573. DEBUG_TRACE("PULL from %s:%u failed",
  11574. conn->request_info.remote_addr,
  11575. conn->request_info.remote_port);
  11576. break;
  11577. }
  11578. if (n > 0) {
  11579. conn->data_len += n;
  11580. /* Reset open PING count */
  11581. ping_count = 0;
  11582. } else {
  11583. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11584. && (!conn->must_close)) {
  11585. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11586. /* Stop sending PING */
  11587. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11588. "- closing connection",
  11589. ping_count,
  11590. conn->request_info.remote_addr,
  11591. conn->request_info.remote_port);
  11592. break;
  11593. }
  11594. if (enable_ping_pong) {
  11595. /* Send Websocket PING message */
  11596. DEBUG_TRACE("PING to %s:%u",
  11597. conn->request_info.remote_addr,
  11598. conn->request_info.remote_port);
  11599. ret = mg_websocket_write(conn,
  11600. MG_WEBSOCKET_OPCODE_PING,
  11601. NULL,
  11602. 0);
  11603. if (ret <= 0) {
  11604. /* Error: send failed */
  11605. DEBUG_TRACE("Send PING failed (%i)", ret);
  11606. break;
  11607. }
  11608. ping_count++;
  11609. }
  11610. }
  11611. /* Timeout: should retry */
  11612. /* TODO: get timeout def */
  11613. }
  11614. }
  11615. }
  11616. /* Leave data processing loop */
  11617. mg_set_thread_name("worker");
  11618. conn->in_websocket_handling = 0;
  11619. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11620. conn->request_info.remote_addr,
  11621. conn->request_info.remote_port);
  11622. }
  11623. static int
  11624. mg_websocket_write_exec(struct mg_connection *conn,
  11625. int opcode,
  11626. const char *data,
  11627. size_t dataLen,
  11628. uint32_t masking_key)
  11629. {
  11630. unsigned char header[14];
  11631. size_t headerLen;
  11632. int retval;
  11633. #if defined(GCC_DIAGNOSTIC)
  11634. /* Disable spurious conversion warning for GCC */
  11635. #pragma GCC diagnostic push
  11636. #pragma GCC diagnostic ignored "-Wconversion"
  11637. #endif
  11638. /* Note that POSIX/Winsock's send() is threadsafe
  11639. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11640. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11641. * push(), although that is only a problem if the packet is large or
  11642. * outgoing buffer is full). */
  11643. /* TODO: Check if this lock should be moved to user land.
  11644. * Currently the server sets this lock for websockets, but
  11645. * not for any other connection. It must be set for every
  11646. * conn read/written by more than one thread, no matter if
  11647. * it is a websocket or regular connection. */
  11648. (void)mg_lock_connection(conn);
  11649. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11650. size_t deflated_size = 0;
  11651. Bytef *deflated = 0;
  11652. // Deflate websocket messages over 100kb
  11653. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11654. if (use_deflate) {
  11655. if (!conn->websocket_deflate_initialized) {
  11656. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11657. return 0;
  11658. }
  11659. // Deflating the message
  11660. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11661. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11662. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11663. deflated_size = (size_t)compressBound((uLong)dataLen);
  11664. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11665. if (deflated == NULL) {
  11666. mg_cry_internal(
  11667. conn,
  11668. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11669. (unsigned long)deflated_size);
  11670. mg_unlock_connection(conn);
  11671. return -1;
  11672. }
  11673. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11674. conn->websocket_deflate_state.next_out = deflated;
  11675. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11676. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11677. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11678. } else
  11679. #endif
  11680. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11681. #if defined(GCC_DIAGNOSTIC)
  11682. #pragma GCC diagnostic pop
  11683. #endif
  11684. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11685. if (dataLen < 126) {
  11686. /* inline 7-bit length field */
  11687. header[1] = (unsigned char)dataLen;
  11688. headerLen = 2;
  11689. } else if (dataLen <= 0xFFFF) {
  11690. /* 16-bit length field */
  11691. uint16_t len = htons((uint16_t)dataLen);
  11692. header[1] = 126;
  11693. memcpy(header + 2, &len, 2);
  11694. headerLen = 4;
  11695. } else {
  11696. /* 64-bit length field */
  11697. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11698. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11699. header[1] = 127;
  11700. memcpy(header + 2, &len1, 4);
  11701. memcpy(header + 6, &len2, 4);
  11702. headerLen = 10;
  11703. }
  11704. if (masking_key) {
  11705. /* add mask */
  11706. header[1] |= 0x80;
  11707. memcpy(header + headerLen, &masking_key, 4);
  11708. headerLen += 4;
  11709. }
  11710. retval = mg_write(conn, header, headerLen);
  11711. if (retval != (int)headerLen) {
  11712. /* Did not send complete header */
  11713. retval = -1;
  11714. } else {
  11715. if (dataLen > 0) {
  11716. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11717. if (use_deflate) {
  11718. retval = mg_write(conn, deflated, dataLen);
  11719. mg_free(deflated);
  11720. } else
  11721. #endif
  11722. retval = mg_write(conn, data, dataLen);
  11723. }
  11724. /* if dataLen == 0, the header length (2) is returned */
  11725. }
  11726. /* TODO: Remove this unlock as well, when lock is removed. */
  11727. mg_unlock_connection(conn);
  11728. return retval;
  11729. }
  11730. CIVETWEB_API int
  11731. mg_websocket_write(struct mg_connection *conn,
  11732. int opcode,
  11733. const char *data,
  11734. size_t dataLen)
  11735. {
  11736. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11737. }
  11738. static void
  11739. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11740. {
  11741. size_t i = 0;
  11742. i = 0;
  11743. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11744. /* Convert in 32 bit words, if data is 4 byte aligned */
  11745. while (i < (in_len - 3)) {
  11746. *(uint32_t *)(void *)(out + i) =
  11747. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11748. i += 4;
  11749. }
  11750. }
  11751. if (i != in_len) {
  11752. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11753. while (i < in_len) {
  11754. *(uint8_t *)(void *)(out + i) =
  11755. *(uint8_t *)(void *)(in + i)
  11756. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11757. i++;
  11758. }
  11759. }
  11760. }
  11761. CIVETWEB_API int
  11762. mg_websocket_client_write(struct mg_connection *conn,
  11763. int opcode,
  11764. const char *data,
  11765. size_t dataLen)
  11766. {
  11767. int retval = -1;
  11768. char *masked_data =
  11769. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11770. uint32_t masking_key = 0;
  11771. if (masked_data == NULL) {
  11772. /* Return -1 in an error case */
  11773. mg_cry_internal(conn,
  11774. "%s",
  11775. "Cannot allocate buffer for masked websocket response: "
  11776. "Out of memory");
  11777. return -1;
  11778. }
  11779. do {
  11780. /* Get a masking key - but not 0 */
  11781. masking_key = (uint32_t)get_random();
  11782. } while (masking_key == 0);
  11783. mask_data(data, dataLen, masking_key, masked_data);
  11784. retval = mg_websocket_write_exec(
  11785. conn, opcode, masked_data, dataLen, masking_key);
  11786. mg_free(masked_data);
  11787. return retval;
  11788. }
  11789. static void
  11790. handle_websocket_request(struct mg_connection *conn,
  11791. const char *path,
  11792. int is_callback_resource,
  11793. struct mg_websocket_subprotocols *subprotocols,
  11794. mg_websocket_connect_handler ws_connect_handler,
  11795. mg_websocket_ready_handler ws_ready_handler,
  11796. mg_websocket_data_handler ws_data_handler,
  11797. mg_websocket_close_handler ws_close_handler,
  11798. void *cbData)
  11799. {
  11800. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11801. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11802. ptrdiff_t lua_websock = 0;
  11803. #if !defined(USE_LUA)
  11804. (void)path;
  11805. #endif
  11806. /* Step 1: Check websocket protocol version. */
  11807. /* Step 1.1: Check Sec-WebSocket-Key. */
  11808. if (!websock_key) {
  11809. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11810. * requires a Sec-WebSocket-Key header.
  11811. */
  11812. /* It could be the hixie draft version
  11813. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11814. */
  11815. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11816. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11817. char key3[8];
  11818. if ((key1 != NULL) && (key2 != NULL)) {
  11819. /* This version uses 8 byte body data in a GET request */
  11820. conn->content_len = 8;
  11821. if (8 == mg_read(conn, key3, 8)) {
  11822. /* This is the hixie version */
  11823. mg_send_http_error(conn,
  11824. 426,
  11825. "%s",
  11826. "Protocol upgrade to RFC 6455 required");
  11827. return;
  11828. }
  11829. }
  11830. /* This is an unknown version */
  11831. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11832. return;
  11833. }
  11834. /* Step 1.2: Check websocket protocol version. */
  11835. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11836. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11837. /* Reject wrong versions */
  11838. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11839. return;
  11840. }
  11841. /* Step 1.3: Could check for "Host", but we do not really need this
  11842. * value for anything, so just ignore it. */
  11843. /* Step 2: If a callback is responsible, call it. */
  11844. if (is_callback_resource) {
  11845. /* Step 2.1 check and select subprotocol */
  11846. const char *protocols[64]; // max 64 headers
  11847. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11848. "Sec-WebSocket-Protocol",
  11849. protocols,
  11850. 64);
  11851. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11852. int headerNo, idx;
  11853. size_t len;
  11854. const char *sep, *curSubProtocol,
  11855. *acceptedWebSocketSubprotocol = NULL;
  11856. /* look for matching subprotocol */
  11857. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11858. /* There might be multiple headers ... */
  11859. const char *protocol = protocols[headerNo];
  11860. curSubProtocol = protocol;
  11861. /* ... and in every header there might be a , separated list */
  11862. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11863. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11864. curSubProtocol++;
  11865. sep = strchr(curSubProtocol, ',');
  11866. if (sep) {
  11867. len = (size_t)(sep - curSubProtocol);
  11868. } else {
  11869. len = strlen(curSubProtocol);
  11870. }
  11871. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11872. // COMPARE: curSubProtocol ==
  11873. // subprotocols->subprotocols[idx]
  11874. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11875. && (strncmp(curSubProtocol,
  11876. subprotocols->subprotocols[idx],
  11877. len)
  11878. == 0)) {
  11879. acceptedWebSocketSubprotocol =
  11880. subprotocols->subprotocols[idx];
  11881. break;
  11882. }
  11883. }
  11884. curSubProtocol += len;
  11885. }
  11886. }
  11887. conn->request_info.acceptedWebSocketSubprotocol =
  11888. acceptedWebSocketSubprotocol;
  11889. }
  11890. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11891. websocket_deflate_negotiate(conn);
  11892. #endif
  11893. if ((ws_connect_handler != NULL)
  11894. && (ws_connect_handler(conn, cbData) != 0)) {
  11895. /* C callback has returned non-zero, do not proceed with
  11896. * handshake.
  11897. */
  11898. /* Note that C callbacks are no longer called when Lua is
  11899. * responsible, so C can no longer filter callbacks for Lua. */
  11900. return;
  11901. }
  11902. }
  11903. #if defined(USE_LUA)
  11904. /* Step 3: No callback. Check if Lua is responsible. */
  11905. else {
  11906. /* Step 3.1: Check if Lua is responsible. */
  11907. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11908. lua_websock = match_prefix_strlen(
  11909. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11910. }
  11911. if (lua_websock > 0) {
  11912. /* Step 3.2: Lua is responsible: call it. */
  11913. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11914. if (!conn->lua_websocket_state) {
  11915. /* Lua rejected the new client */
  11916. return;
  11917. }
  11918. }
  11919. }
  11920. #endif
  11921. /* Step 4: Check if there is a responsible websocket handler. */
  11922. if (!is_callback_resource && !lua_websock) {
  11923. /* There is no callback, and Lua is not responsible either. */
  11924. /* Reply with a 404 Not Found. We are still at a standard
  11925. * HTTP request here, before the websocket handshake, so
  11926. * we can still send standard HTTP error replies. */
  11927. mg_send_http_error(conn, 404, "%s", "Not found");
  11928. return;
  11929. }
  11930. /* Step 5: The websocket connection has been accepted */
  11931. if (!send_websocket_handshake(conn, websock_key)) {
  11932. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11933. return;
  11934. }
  11935. /* Step 6: Call the ready handler */
  11936. if (is_callback_resource) {
  11937. if (ws_ready_handler != NULL) {
  11938. ws_ready_handler(conn, cbData);
  11939. }
  11940. #if defined(USE_LUA)
  11941. } else if (lua_websock) {
  11942. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11943. /* the ready handler returned false */
  11944. return;
  11945. }
  11946. #endif
  11947. }
  11948. /* Step 7: Enter the read loop */
  11949. if (is_callback_resource) {
  11950. read_websocket(conn, ws_data_handler, cbData);
  11951. #if defined(USE_LUA)
  11952. } else if (lua_websock) {
  11953. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11954. #endif
  11955. }
  11956. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11957. /* Step 8: Close the deflate & inflate buffers */
  11958. if (conn->websocket_deflate_initialized) {
  11959. deflateEnd(&conn->websocket_deflate_state);
  11960. inflateEnd(&conn->websocket_inflate_state);
  11961. }
  11962. #endif
  11963. /* Step 9: Call the close handler */
  11964. if (ws_close_handler) {
  11965. ws_close_handler(conn, cbData);
  11966. }
  11967. }
  11968. #endif /* !USE_WEBSOCKET */
  11969. /* Is upgrade request:
  11970. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11971. * 1 = upgrade to websocket
  11972. * 2 = upgrade to HTTP/2
  11973. * -1 = upgrade to unknown protocol
  11974. */
  11975. static int
  11976. should_switch_to_protocol(const struct mg_connection *conn)
  11977. {
  11978. const char *connection_headers[8];
  11979. const char *upgrade_to;
  11980. int connection_header_count, i, should_upgrade;
  11981. /* A websocket protocol has the following HTTP headers:
  11982. *
  11983. * Connection: Upgrade
  11984. * Upgrade: Websocket
  11985. *
  11986. * It seems some clients use multiple headers:
  11987. * see https://github.com/civetweb/civetweb/issues/1083
  11988. */
  11989. connection_header_count = get_req_headers(&conn->request_info,
  11990. "Connection",
  11991. connection_headers,
  11992. 8);
  11993. should_upgrade = 0;
  11994. for (i = 0; i < connection_header_count; i++) {
  11995. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  11996. should_upgrade = 1;
  11997. }
  11998. }
  11999. if (!should_upgrade) {
  12000. return PROTOCOL_TYPE_HTTP1;
  12001. }
  12002. upgrade_to = mg_get_header(conn, "Upgrade");
  12003. if (upgrade_to == NULL) {
  12004. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12005. return -1;
  12006. }
  12007. /* Upgrade to ... */
  12008. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12009. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12010. * "Sec-WebSocket-Version" are also required.
  12011. * Don't check them here, since even an unsupported websocket protocol
  12012. * request still IS a websocket request (in contrast to a standard HTTP
  12013. * request). It will fail later in handle_websocket_request.
  12014. */
  12015. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12016. }
  12017. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12018. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12019. }
  12020. /* Upgrade to another protocol */
  12021. return -1;
  12022. }
  12023. static int
  12024. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12025. {
  12026. int n;
  12027. unsigned int a, b, c, d, slash;
  12028. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12029. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12030. // integer value, but function will not report conversion
  12031. // errors; consider using 'strtol' instead
  12032. slash = 32;
  12033. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12034. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12035. // an integer value, but function will not report conversion
  12036. // errors; consider using 'strtol' instead
  12037. n = 0;
  12038. }
  12039. }
  12040. if ((n > 0) && ((size_t)n == vec->len)) {
  12041. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12042. /* IPv4 format */
  12043. if (sa->sa.sa_family == AF_INET) {
  12044. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12045. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12046. | ((uint32_t)c << 8) | (uint32_t)d;
  12047. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12048. return (ip & mask) == net;
  12049. }
  12050. return 0;
  12051. }
  12052. }
  12053. #if defined(USE_IPV6)
  12054. else {
  12055. char ad[50];
  12056. const char *p;
  12057. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12058. slash = 128;
  12059. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12060. n = 0;
  12061. }
  12062. }
  12063. if ((n <= 0) && no_strict) {
  12064. /* no square brackets? */
  12065. p = strchr(vec->ptr, '/');
  12066. if (p && (p < (vec->ptr + vec->len))) {
  12067. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12068. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12069. n += (int)(p - vec->ptr);
  12070. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12071. } else {
  12072. n = 0;
  12073. }
  12074. } else if (vec->len < sizeof(ad)) {
  12075. n = (int)vec->len;
  12076. slash = 128;
  12077. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12078. }
  12079. }
  12080. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12081. p = ad;
  12082. c = 0;
  12083. /* zone indexes are unsupported, at least two colons are needed */
  12084. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12085. if (*(p++) == ':') {
  12086. c++;
  12087. }
  12088. }
  12089. if ((*p == '\0') && (c >= 2)) {
  12090. struct sockaddr_in6 sin6;
  12091. unsigned int i;
  12092. /* for strict validation, an actual IPv6 argument is needed */
  12093. if (sa->sa.sa_family != AF_INET6) {
  12094. return 0;
  12095. }
  12096. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12097. /* IPv6 format */
  12098. for (i = 0; i < 16; i++) {
  12099. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12100. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12101. uint8_t mask = 0;
  12102. if (8 * i + 8 < slash) {
  12103. mask = 0xFFu;
  12104. } else if (8 * i < slash) {
  12105. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12106. }
  12107. if ((ip & mask) != net) {
  12108. return 0;
  12109. }
  12110. }
  12111. return 1;
  12112. }
  12113. }
  12114. }
  12115. }
  12116. #else
  12117. (void)no_strict;
  12118. #endif
  12119. /* malformed */
  12120. return -1;
  12121. }
  12122. static int
  12123. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12124. {
  12125. int throttle = 0;
  12126. struct vec vec, val;
  12127. char mult;
  12128. double v;
  12129. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12130. mult = ',';
  12131. if ((val.ptr == NULL)
  12132. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12133. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12134. // to an integer value, but function will not report
  12135. // conversion errors; consider using 'strtol' instead
  12136. || (v < 0)
  12137. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12138. && (mult != ','))) {
  12139. continue;
  12140. }
  12141. v *= (lowercase(&mult) == 'k')
  12142. ? 1024
  12143. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12144. if (vec.len == 1 && vec.ptr[0] == '*') {
  12145. throttle = (int)v;
  12146. } else {
  12147. int matched = parse_match_net(&vec, rsa, 0);
  12148. if (matched >= 0) {
  12149. /* a valid IP subnet */
  12150. if (matched) {
  12151. throttle = (int)v;
  12152. }
  12153. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12154. throttle = (int)v;
  12155. }
  12156. }
  12157. }
  12158. return throttle;
  12159. }
  12160. /* The mg_upload function is superseded by mg_handle_form_request. */
  12161. #include "handle_form.inl"
  12162. static int
  12163. get_first_ssl_listener_index(const struct mg_context *ctx)
  12164. {
  12165. unsigned int i;
  12166. int idx = -1;
  12167. if (ctx) {
  12168. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12169. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12170. }
  12171. }
  12172. return idx;
  12173. }
  12174. /* Return host (without port) */
  12175. static void
  12176. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12177. {
  12178. const char *host_header =
  12179. get_header(ri->http_headers, ri->num_headers, "Host");
  12180. host->ptr = NULL;
  12181. host->len = 0;
  12182. if (host_header != NULL) {
  12183. const char *pos;
  12184. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12185. * is found. */
  12186. if (*host_header == '[') {
  12187. pos = strchr(host_header, ']');
  12188. if (!pos) {
  12189. /* Malformed hostname starts with '[', but no ']' found */
  12190. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12191. return;
  12192. }
  12193. /* terminate after ']' */
  12194. host->ptr = host_header;
  12195. host->len = (size_t)(pos + 1 - host_header);
  12196. } else {
  12197. /* Otherwise, a ':' separates hostname and port number */
  12198. pos = strchr(host_header, ':');
  12199. if (pos != NULL) {
  12200. host->len = (size_t)(pos - host_header);
  12201. } else {
  12202. host->len = strlen(host_header);
  12203. }
  12204. host->ptr = host_header;
  12205. }
  12206. }
  12207. }
  12208. static int
  12209. switch_domain_context(struct mg_connection *conn)
  12210. {
  12211. struct vec host;
  12212. get_host_from_request_info(&host, &conn->request_info);
  12213. if (host.ptr) {
  12214. if (conn->ssl) {
  12215. /* This is a HTTPS connection, maybe we have a hostname
  12216. * from SNI (set in ssl_servername_callback). */
  12217. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12218. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12219. /* We are not using the default domain */
  12220. if ((strlen(sslhost) != host.len)
  12221. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12222. /* Mismatch between SNI domain and HTTP domain */
  12223. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12224. sslhost,
  12225. (int)host.len,
  12226. host.ptr);
  12227. return 0;
  12228. }
  12229. }
  12230. } else {
  12231. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12232. while (dom) {
  12233. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12234. size_t domNameLen = strlen(domName);
  12235. if ((domNameLen == host.len)
  12236. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12237. /* Found matching domain */
  12238. DEBUG_TRACE("HTTP domain %s found",
  12239. dom->config[AUTHENTICATION_DOMAIN]);
  12240. /* TODO: Check if this is a HTTP or HTTPS domain */
  12241. conn->dom_ctx = dom;
  12242. break;
  12243. }
  12244. mg_lock_context(conn->phys_ctx);
  12245. dom = dom->next;
  12246. mg_unlock_context(conn->phys_ctx);
  12247. }
  12248. }
  12249. DEBUG_TRACE("HTTP%s Host: %.*s",
  12250. conn->ssl ? "S" : "",
  12251. (int)host.len,
  12252. host.ptr);
  12253. } else {
  12254. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12255. return 1;
  12256. }
  12257. return 1;
  12258. }
  12259. static void
  12260. redirect_to_https_port(struct mg_connection *conn, int port)
  12261. {
  12262. char target_url[MG_BUF_LEN];
  12263. int truncated = 0;
  12264. const char *expect_proto =
  12265. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12266. /* Use "308 Permanent Redirect" */
  12267. int redirect_code = 308;
  12268. /* In any case, close the current connection */
  12269. conn->must_close = 1;
  12270. /* Send host, port, uri and (if it exists) ?query_string */
  12271. if (mg_construct_local_link(
  12272. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12273. < 0) {
  12274. truncated = 1;
  12275. } else if (conn->request_info.query_string != NULL) {
  12276. size_t slen1 = strlen(target_url);
  12277. size_t slen2 = strlen(conn->request_info.query_string);
  12278. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12279. target_url[slen1] = '?';
  12280. memcpy(target_url + slen1 + 1,
  12281. conn->request_info.query_string,
  12282. slen2);
  12283. target_url[slen1 + slen2 + 1] = 0;
  12284. } else {
  12285. truncated = 1;
  12286. }
  12287. }
  12288. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12289. * is used as buffer size) */
  12290. if (truncated) {
  12291. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12292. return;
  12293. }
  12294. /* Use redirect helper function */
  12295. mg_send_http_redirect(conn, target_url, redirect_code);
  12296. }
  12297. static void
  12298. mg_set_handler_type(struct mg_context *phys_ctx,
  12299. struct mg_domain_context *dom_ctx,
  12300. const char *uri,
  12301. int handler_type,
  12302. int is_delete_request,
  12303. mg_request_handler handler,
  12304. struct mg_websocket_subprotocols *subprotocols,
  12305. mg_websocket_connect_handler connect_handler,
  12306. mg_websocket_ready_handler ready_handler,
  12307. mg_websocket_data_handler data_handler,
  12308. mg_websocket_close_handler close_handler,
  12309. mg_authorization_handler auth_handler,
  12310. void *cbdata)
  12311. {
  12312. struct mg_handler_info *tmp_rh, **lastref;
  12313. size_t urilen = strlen(uri);
  12314. if (handler_type == WEBSOCKET_HANDLER) {
  12315. DEBUG_ASSERT(handler == NULL);
  12316. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12317. || ready_handler != NULL || data_handler != NULL
  12318. || close_handler != NULL);
  12319. DEBUG_ASSERT(auth_handler == NULL);
  12320. if (handler != NULL) {
  12321. return;
  12322. }
  12323. if (!is_delete_request && (connect_handler == NULL)
  12324. && (ready_handler == NULL) && (data_handler == NULL)
  12325. && (close_handler == NULL)) {
  12326. return;
  12327. }
  12328. if (auth_handler != NULL) {
  12329. return;
  12330. }
  12331. } else if (handler_type == REQUEST_HANDLER) {
  12332. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12333. && data_handler == NULL && close_handler == NULL);
  12334. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12335. DEBUG_ASSERT(auth_handler == NULL);
  12336. if ((connect_handler != NULL) || (ready_handler != NULL)
  12337. || (data_handler != NULL) || (close_handler != NULL)) {
  12338. return;
  12339. }
  12340. if (!is_delete_request && (handler == NULL)) {
  12341. return;
  12342. }
  12343. if (auth_handler != NULL) {
  12344. return;
  12345. }
  12346. } else if (handler_type == AUTH_HANDLER) {
  12347. DEBUG_ASSERT(handler == NULL);
  12348. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12349. && data_handler == NULL && close_handler == NULL);
  12350. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12351. if (handler != NULL) {
  12352. return;
  12353. }
  12354. if ((connect_handler != NULL) || (ready_handler != NULL)
  12355. || (data_handler != NULL) || (close_handler != NULL)) {
  12356. return;
  12357. }
  12358. if (!is_delete_request && (auth_handler == NULL)) {
  12359. return;
  12360. }
  12361. } else {
  12362. /* Unknown handler type. */
  12363. return;
  12364. }
  12365. if (!phys_ctx || !dom_ctx) {
  12366. /* no context available */
  12367. return;
  12368. }
  12369. mg_lock_context(phys_ctx);
  12370. /* first try to find an existing handler */
  12371. do {
  12372. lastref = &(dom_ctx->handlers);
  12373. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12374. tmp_rh = tmp_rh->next) {
  12375. if (tmp_rh->handler_type == handler_type
  12376. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12377. if (!is_delete_request) {
  12378. /* update existing handler */
  12379. if (handler_type == REQUEST_HANDLER) {
  12380. /* Wait for end of use before updating */
  12381. if (tmp_rh->refcount) {
  12382. mg_unlock_context(phys_ctx);
  12383. mg_sleep(1);
  12384. mg_lock_context(phys_ctx);
  12385. /* tmp_rh might have been freed, search again. */
  12386. break;
  12387. }
  12388. /* Ok, the handler is no more use -> Update it */
  12389. tmp_rh->handler = handler;
  12390. } else if (handler_type == WEBSOCKET_HANDLER) {
  12391. tmp_rh->subprotocols = subprotocols;
  12392. tmp_rh->connect_handler = connect_handler;
  12393. tmp_rh->ready_handler = ready_handler;
  12394. tmp_rh->data_handler = data_handler;
  12395. tmp_rh->close_handler = close_handler;
  12396. } else { /* AUTH_HANDLER */
  12397. tmp_rh->auth_handler = auth_handler;
  12398. }
  12399. tmp_rh->cbdata = cbdata;
  12400. } else {
  12401. /* remove existing handler */
  12402. if (handler_type == REQUEST_HANDLER) {
  12403. /* Wait for end of use before removing */
  12404. if (tmp_rh->refcount) {
  12405. tmp_rh->removing = 1;
  12406. mg_unlock_context(phys_ctx);
  12407. mg_sleep(1);
  12408. mg_lock_context(phys_ctx);
  12409. /* tmp_rh might have been freed, search again. */
  12410. break;
  12411. }
  12412. /* Ok, the handler is no more used */
  12413. }
  12414. *lastref = tmp_rh->next;
  12415. mg_free(tmp_rh->uri);
  12416. mg_free(tmp_rh);
  12417. }
  12418. mg_unlock_context(phys_ctx);
  12419. return;
  12420. }
  12421. lastref = &(tmp_rh->next);
  12422. }
  12423. } while (tmp_rh != NULL);
  12424. if (is_delete_request) {
  12425. /* no handler to set, this was a remove request to a non-existing
  12426. * handler */
  12427. mg_unlock_context(phys_ctx);
  12428. return;
  12429. }
  12430. tmp_rh =
  12431. (struct mg_handler_info *)mg_calloc_ctx(1,
  12432. sizeof(struct mg_handler_info),
  12433. phys_ctx);
  12434. if (tmp_rh == NULL) {
  12435. mg_unlock_context(phys_ctx);
  12436. mg_cry_ctx_internal(phys_ctx,
  12437. "%s",
  12438. "Cannot create new request handler struct, OOM");
  12439. return;
  12440. }
  12441. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12442. if (!tmp_rh->uri) {
  12443. mg_unlock_context(phys_ctx);
  12444. mg_free(tmp_rh);
  12445. mg_cry_ctx_internal(phys_ctx,
  12446. "%s",
  12447. "Cannot create new request handler struct, OOM");
  12448. return;
  12449. }
  12450. tmp_rh->uri_len = urilen;
  12451. if (handler_type == REQUEST_HANDLER) {
  12452. tmp_rh->refcount = 0;
  12453. tmp_rh->removing = 0;
  12454. tmp_rh->handler = handler;
  12455. } else if (handler_type == WEBSOCKET_HANDLER) {
  12456. tmp_rh->subprotocols = subprotocols;
  12457. tmp_rh->connect_handler = connect_handler;
  12458. tmp_rh->ready_handler = ready_handler;
  12459. tmp_rh->data_handler = data_handler;
  12460. tmp_rh->close_handler = close_handler;
  12461. } else { /* AUTH_HANDLER */
  12462. tmp_rh->auth_handler = auth_handler;
  12463. }
  12464. tmp_rh->cbdata = cbdata;
  12465. tmp_rh->handler_type = handler_type;
  12466. tmp_rh->next = NULL;
  12467. *lastref = tmp_rh;
  12468. mg_unlock_context(phys_ctx);
  12469. }
  12470. CIVETWEB_API void
  12471. mg_set_request_handler(struct mg_context *ctx,
  12472. const char *uri,
  12473. mg_request_handler handler,
  12474. void *cbdata)
  12475. {
  12476. mg_set_handler_type(ctx,
  12477. &(ctx->dd),
  12478. uri,
  12479. REQUEST_HANDLER,
  12480. handler == NULL,
  12481. handler,
  12482. NULL,
  12483. NULL,
  12484. NULL,
  12485. NULL,
  12486. NULL,
  12487. NULL,
  12488. cbdata);
  12489. }
  12490. CIVETWEB_API void
  12491. mg_set_websocket_handler(struct mg_context *ctx,
  12492. const char *uri,
  12493. mg_websocket_connect_handler connect_handler,
  12494. mg_websocket_ready_handler ready_handler,
  12495. mg_websocket_data_handler data_handler,
  12496. mg_websocket_close_handler close_handler,
  12497. void *cbdata)
  12498. {
  12499. mg_set_websocket_handler_with_subprotocols(ctx,
  12500. uri,
  12501. NULL,
  12502. connect_handler,
  12503. ready_handler,
  12504. data_handler,
  12505. close_handler,
  12506. cbdata);
  12507. }
  12508. CIVETWEB_API void
  12509. mg_set_websocket_handler_with_subprotocols(
  12510. struct mg_context *ctx,
  12511. const char *uri,
  12512. struct mg_websocket_subprotocols *subprotocols,
  12513. mg_websocket_connect_handler connect_handler,
  12514. mg_websocket_ready_handler ready_handler,
  12515. mg_websocket_data_handler data_handler,
  12516. mg_websocket_close_handler close_handler,
  12517. void *cbdata)
  12518. {
  12519. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12520. && (data_handler == NULL)
  12521. && (close_handler == NULL);
  12522. mg_set_handler_type(ctx,
  12523. &(ctx->dd),
  12524. uri,
  12525. WEBSOCKET_HANDLER,
  12526. is_delete_request,
  12527. NULL,
  12528. subprotocols,
  12529. connect_handler,
  12530. ready_handler,
  12531. data_handler,
  12532. close_handler,
  12533. NULL,
  12534. cbdata);
  12535. }
  12536. CIVETWEB_API void
  12537. mg_set_auth_handler(struct mg_context *ctx,
  12538. const char *uri,
  12539. mg_authorization_handler handler,
  12540. void *cbdata)
  12541. {
  12542. mg_set_handler_type(ctx,
  12543. &(ctx->dd),
  12544. uri,
  12545. AUTH_HANDLER,
  12546. handler == NULL,
  12547. NULL,
  12548. NULL,
  12549. NULL,
  12550. NULL,
  12551. NULL,
  12552. NULL,
  12553. handler,
  12554. cbdata);
  12555. }
  12556. static int
  12557. get_request_handler(struct mg_connection *conn,
  12558. int handler_type,
  12559. mg_request_handler *handler,
  12560. struct mg_websocket_subprotocols **subprotocols,
  12561. mg_websocket_connect_handler *connect_handler,
  12562. mg_websocket_ready_handler *ready_handler,
  12563. mg_websocket_data_handler *data_handler,
  12564. mg_websocket_close_handler *close_handler,
  12565. mg_authorization_handler *auth_handler,
  12566. void **cbdata,
  12567. struct mg_handler_info **handler_info)
  12568. {
  12569. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12570. if (request_info) {
  12571. const char *uri = request_info->local_uri;
  12572. size_t urilen = strlen(uri);
  12573. struct mg_handler_info *tmp_rh;
  12574. int step, matched;
  12575. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12576. return 0;
  12577. }
  12578. mg_lock_context(conn->phys_ctx);
  12579. for (step = 0; step < 3; step++) {
  12580. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12581. tmp_rh = tmp_rh->next) {
  12582. if (tmp_rh->handler_type != handler_type) {
  12583. continue;
  12584. }
  12585. if (step == 0) {
  12586. /* first try for an exact match */
  12587. matched = (tmp_rh->uri_len == urilen)
  12588. && (strcmp(tmp_rh->uri, uri) == 0);
  12589. } else if (step == 1) {
  12590. /* next try for a partial match, we will accept
  12591. uri/something */
  12592. matched =
  12593. (tmp_rh->uri_len < urilen)
  12594. && (uri[tmp_rh->uri_len] == '/')
  12595. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12596. } else {
  12597. /* finally try for pattern match */
  12598. matched =
  12599. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12600. }
  12601. if (matched) {
  12602. if (handler_type == WEBSOCKET_HANDLER) {
  12603. *subprotocols = tmp_rh->subprotocols;
  12604. *connect_handler = tmp_rh->connect_handler;
  12605. *ready_handler = tmp_rh->ready_handler;
  12606. *data_handler = tmp_rh->data_handler;
  12607. *close_handler = tmp_rh->close_handler;
  12608. } else if (handler_type == REQUEST_HANDLER) {
  12609. if (tmp_rh->removing) {
  12610. /* Treat as none found */
  12611. step = 2;
  12612. break;
  12613. }
  12614. *handler = tmp_rh->handler;
  12615. /* Acquire handler and give it back */
  12616. tmp_rh->refcount++;
  12617. *handler_info = tmp_rh;
  12618. } else { /* AUTH_HANDLER */
  12619. *auth_handler = tmp_rh->auth_handler;
  12620. }
  12621. *cbdata = tmp_rh->cbdata;
  12622. mg_unlock_context(conn->phys_ctx);
  12623. return 1;
  12624. }
  12625. }
  12626. }
  12627. mg_unlock_context(conn->phys_ctx);
  12628. }
  12629. return 0; /* none found */
  12630. }
  12631. /* Check if the script file is in a path, allowed for script files.
  12632. * This can be used if uploading files is possible not only for the server
  12633. * admin, and the upload mechanism does not check the file extension.
  12634. */
  12635. static int
  12636. is_in_script_path(const struct mg_connection *conn, const char *path)
  12637. {
  12638. /* TODO (Feature): Add config value for allowed script path.
  12639. * Default: All allowed. */
  12640. (void)conn;
  12641. (void)path;
  12642. return 1;
  12643. }
  12644. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12645. static int
  12646. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12647. int bits,
  12648. char *data,
  12649. size_t len,
  12650. void *cbdata)
  12651. {
  12652. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12653. if (pcallbacks->websocket_data) {
  12654. return pcallbacks->websocket_data(conn, bits, data, len);
  12655. }
  12656. /* No handler set - assume "OK" */
  12657. return 1;
  12658. }
  12659. static void
  12660. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12661. void *cbdata)
  12662. {
  12663. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12664. if (pcallbacks->connection_close) {
  12665. pcallbacks->connection_close(conn);
  12666. }
  12667. }
  12668. #endif
  12669. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12670. */
  12671. static void
  12672. release_handler_ref(struct mg_connection *conn,
  12673. struct mg_handler_info *handler_info)
  12674. {
  12675. if (handler_info != NULL) {
  12676. /* Use context lock for ref counter */
  12677. mg_lock_context(conn->phys_ctx);
  12678. handler_info->refcount--;
  12679. mg_unlock_context(conn->phys_ctx);
  12680. }
  12681. }
  12682. /* This is the heart of the Civetweb's logic.
  12683. * This function is called when the request is read, parsed and validated,
  12684. * and Civetweb must decide what action to take: serve a file, or
  12685. * a directory, or call embedded function, etcetera. */
  12686. static void
  12687. handle_request(struct mg_connection *conn)
  12688. {
  12689. struct mg_request_info *ri = &conn->request_info;
  12690. char path[UTF8_PATH_MAX];
  12691. int uri_len, ssl_index;
  12692. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12693. is_put_or_delete_request = 0, is_callback_resource = 0,
  12694. is_template_text_file = 0, is_webdav_request = 0;
  12695. int i;
  12696. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12697. mg_request_handler callback_handler = NULL;
  12698. struct mg_handler_info *handler_info = NULL;
  12699. struct mg_websocket_subprotocols *subprotocols;
  12700. mg_websocket_connect_handler ws_connect_handler = NULL;
  12701. mg_websocket_ready_handler ws_ready_handler = NULL;
  12702. mg_websocket_data_handler ws_data_handler = NULL;
  12703. mg_websocket_close_handler ws_close_handler = NULL;
  12704. void *callback_data = NULL;
  12705. mg_authorization_handler auth_handler = NULL;
  12706. void *auth_callback_data = NULL;
  12707. int handler_type;
  12708. time_t curtime = time(NULL);
  12709. char date[64];
  12710. char *tmp;
  12711. path[0] = 0;
  12712. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12713. conn->request_state = 0;
  12714. /* 1. get the request url */
  12715. /* 1.1. split into url and query string */
  12716. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12717. != NULL) {
  12718. *((char *)conn->request_info.query_string++) = '\0';
  12719. }
  12720. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12721. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12722. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12723. if (ssl_index >= 0) {
  12724. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12725. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12726. redirect_to_https_port(conn, port);
  12727. } else {
  12728. /* A http to https forward port has been specified,
  12729. * but no https port to forward to. */
  12730. mg_send_http_error(conn,
  12731. 503,
  12732. "%s",
  12733. "Error: SSL forward not configured properly");
  12734. mg_cry_internal(conn,
  12735. "%s",
  12736. "Can not redirect to SSL, no SSL port available");
  12737. }
  12738. return;
  12739. }
  12740. uri_len = (int)strlen(ri->local_uri);
  12741. /* 1.3. decode url (if config says so) */
  12742. if (should_decode_url(conn)) {
  12743. url_decode_in_place((char *)ri->local_uri);
  12744. }
  12745. /* URL decode the query-string only if explicitly set in the configuration
  12746. */
  12747. if (conn->request_info.query_string) {
  12748. if (should_decode_query_string(conn)) {
  12749. url_decode_in_place((char *)conn->request_info.query_string);
  12750. }
  12751. }
  12752. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12753. * possible. The fact that we cleaned the URI is stored in that the
  12754. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12755. * ri->local_uri_raw still points to memory allocated in
  12756. * worker_thread_run(). ri->local_uri is private to the request so we
  12757. * don't have to use preallocated memory here. */
  12758. tmp = mg_strdup(ri->local_uri_raw);
  12759. if (!tmp) {
  12760. /* Out of memory. We cannot do anything reasonable here. */
  12761. return;
  12762. }
  12763. remove_dot_segments(tmp);
  12764. ri->local_uri = tmp;
  12765. /* step 1. completed, the url is known now */
  12766. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12767. /* 2. if this ip has limited speed, set it for this connection */
  12768. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12769. &conn->client.rsa,
  12770. ri->local_uri);
  12771. /* 3. call a "handle everything" callback, if registered */
  12772. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12773. /* Note that since V1.7 the "begin_request" function is called
  12774. * before an authorization check. If an authorization check is
  12775. * required, use a request_handler instead. */
  12776. i = conn->phys_ctx->callbacks.begin_request(conn);
  12777. if (i > 0) {
  12778. /* callback already processed the request. Store the
  12779. return value as a status code for the access log. */
  12780. conn->status_code = i;
  12781. if (!conn->must_close) {
  12782. discard_unread_request_data(conn);
  12783. }
  12784. DEBUG_TRACE("%s", "begin_request handled request");
  12785. return;
  12786. } else if (i == 0) {
  12787. /* civetweb should process the request */
  12788. } else {
  12789. /* unspecified - may change with the next version */
  12790. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12791. return;
  12792. }
  12793. }
  12794. /* request not yet handled by a handler or redirect, so the request
  12795. * is processed here */
  12796. /* 4. Check for CORS preflight requests and handle them (if configured).
  12797. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12798. */
  12799. if (!strcmp(ri->request_method, "OPTIONS")) {
  12800. /* Send a response to CORS preflights only if
  12801. * access_control_allow_methods is not NULL and not an empty string.
  12802. * In this case, scripts can still handle CORS. */
  12803. const char *cors_meth_cfg =
  12804. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12805. const char *cors_orig_cfg =
  12806. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12807. const char *cors_origin =
  12808. get_header(ri->http_headers, ri->num_headers, "Origin");
  12809. const char *cors_acrm = get_header(ri->http_headers,
  12810. ri->num_headers,
  12811. "Access-Control-Request-Method");
  12812. /* Todo: check if cors_origin is in cors_orig_cfg.
  12813. * Or, let the client check this. */
  12814. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12815. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12816. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12817. /* This is a valid CORS preflight, and the server is configured
  12818. * to handle it automatically. */
  12819. const char *cors_acrh =
  12820. get_header(ri->http_headers,
  12821. ri->num_headers,
  12822. "Access-Control-Request-Headers");
  12823. gmt_time_string(date, sizeof(date), &curtime);
  12824. mg_printf(conn,
  12825. "HTTP/1.1 200 OK\r\n"
  12826. "Date: %s\r\n"
  12827. "Access-Control-Allow-Origin: %s\r\n"
  12828. "Access-Control-Allow-Methods: %s\r\n"
  12829. "Content-Length: 0\r\n"
  12830. "Connection: %s\r\n",
  12831. date,
  12832. cors_orig_cfg,
  12833. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12834. suggest_connection_header(conn));
  12835. if (cors_acrh != NULL) {
  12836. /* CORS request is asking for additional headers */
  12837. const char *cors_hdr_cfg =
  12838. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12839. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12840. /* Allow only if access_control_allow_headers is
  12841. * not NULL and not an empty string. If this
  12842. * configuration is set to *, allow everything.
  12843. * Otherwise this configuration must be a list
  12844. * of allowed HTTP header names. */
  12845. mg_printf(conn,
  12846. "Access-Control-Allow-Headers: %s\r\n",
  12847. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12848. : cors_hdr_cfg));
  12849. }
  12850. }
  12851. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12852. mg_printf(conn, "\r\n");
  12853. DEBUG_TRACE("%s", "OPTIONS done");
  12854. return;
  12855. }
  12856. }
  12857. /* 5. interpret the url to find out how the request must be handled
  12858. */
  12859. /* 5.1. first test, if the request targets the regular http(s)://
  12860. * protocol namespace or the websocket ws(s):// protocol namespace.
  12861. */
  12862. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12863. #if defined(USE_WEBSOCKET)
  12864. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12865. #else
  12866. handler_type = REQUEST_HANDLER;
  12867. #endif /* defined(USE_WEBSOCKET) */
  12868. if (is_websocket_request) {
  12869. HTTP1_only;
  12870. }
  12871. /* 5.2. check if the request will be handled by a callback */
  12872. if (get_request_handler(conn,
  12873. handler_type,
  12874. &callback_handler,
  12875. &subprotocols,
  12876. &ws_connect_handler,
  12877. &ws_ready_handler,
  12878. &ws_data_handler,
  12879. &ws_close_handler,
  12880. NULL,
  12881. &callback_data,
  12882. &handler_info)) {
  12883. /* 5.2.1. A callback will handle this request. All requests
  12884. * handled by a callback have to be considered as requests
  12885. * to a script resource. */
  12886. is_callback_resource = 1;
  12887. is_script_resource = 1;
  12888. is_put_or_delete_request = is_put_or_delete_method(conn);
  12889. /* Never handle a C callback according to File WebDav rules,
  12890. * even if it is a webdav method */
  12891. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12892. } else {
  12893. no_callback_resource:
  12894. /* 5.2.2. No callback is responsible for this request. The URI
  12895. * addresses a file based resource (static content or Lua/cgi
  12896. * scripts in the file system). */
  12897. is_callback_resource = 0;
  12898. interpret_uri(conn,
  12899. path,
  12900. sizeof(path),
  12901. &file.stat,
  12902. &is_found,
  12903. &is_script_resource,
  12904. &is_websocket_request,
  12905. &is_put_or_delete_request,
  12906. &is_webdav_request,
  12907. &is_template_text_file);
  12908. }
  12909. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12910. if (is_webdav_request) {
  12911. /* TODO: Do we need a config option? */
  12912. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12913. if (webdav_enable[0] != 'y') {
  12914. mg_send_http_error(conn,
  12915. 405,
  12916. "%s method not allowed",
  12917. conn->request_info.request_method);
  12918. DEBUG_TRACE("%s", "webdav rejected");
  12919. return;
  12920. }
  12921. }
  12922. /* 6. authorization check */
  12923. /* 6.1. a custom authorization handler is installed */
  12924. if (get_request_handler(conn,
  12925. AUTH_HANDLER,
  12926. NULL,
  12927. NULL,
  12928. NULL,
  12929. NULL,
  12930. NULL,
  12931. NULL,
  12932. &auth_handler,
  12933. &auth_callback_data,
  12934. NULL)) {
  12935. if (!auth_handler(conn, auth_callback_data)) {
  12936. /* Callback handler will not be used anymore. Release it */
  12937. release_handler_ref(conn, handler_info);
  12938. DEBUG_TRACE("%s", "auth handler rejected request");
  12939. return;
  12940. }
  12941. } else if (is_put_or_delete_request && !is_script_resource
  12942. && !is_callback_resource) {
  12943. HTTP1_only;
  12944. /* 6.2. this request is a PUT/DELETE to a real file */
  12945. /* 6.2.1. thus, the server must have real files */
  12946. #if defined(NO_FILES)
  12947. if (1) {
  12948. #else
  12949. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  12950. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  12951. #endif
  12952. /* This code path will not be called for request handlers */
  12953. DEBUG_ASSERT(handler_info == NULL);
  12954. /* This server does not have any real files, thus the
  12955. * PUT/DELETE methods are not valid. */
  12956. mg_send_http_error(conn,
  12957. 405,
  12958. "%s method not allowed",
  12959. conn->request_info.request_method);
  12960. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  12961. return;
  12962. }
  12963. #if !defined(NO_FILES)
  12964. /* 6.2.2. Check if put authorization for static files is
  12965. * available.
  12966. */
  12967. if (!is_authorized_for_put(conn)) {
  12968. send_authorization_request(conn, NULL);
  12969. DEBUG_TRACE("%s", "file write needs authorization");
  12970. return;
  12971. }
  12972. #endif
  12973. } else {
  12974. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12975. * or it is a PUT or DELETE request to a resource that does not
  12976. * correspond to a file. Check authorization. */
  12977. if (!check_authorization(conn, path)) {
  12978. send_authorization_request(conn, NULL);
  12979. /* Callback handler will not be used anymore. Release it */
  12980. release_handler_ref(conn, handler_info);
  12981. DEBUG_TRACE("%s", "access authorization required");
  12982. return;
  12983. }
  12984. }
  12985. /* request is authorized or does not need authorization */
  12986. /* 7. check if there are request handlers for this uri */
  12987. if (is_callback_resource) {
  12988. HTTP1_only;
  12989. if (!is_websocket_request) {
  12990. i = callback_handler(conn, callback_data);
  12991. /* Callback handler will not be used anymore. Release it */
  12992. release_handler_ref(conn, handler_info);
  12993. if (i > 0) {
  12994. /* Do nothing, callback has served the request. Store
  12995. * then return value as status code for the log and discard
  12996. * all data from the client not used by the callback. */
  12997. conn->status_code = i;
  12998. if (!conn->must_close) {
  12999. discard_unread_request_data(conn);
  13000. }
  13001. } else {
  13002. /* The handler did NOT handle the request. */
  13003. /* Some proper reactions would be:
  13004. * a) close the connections without sending anything
  13005. * b) send a 404 not found
  13006. * c) try if there is a file matching the URI
  13007. * It would be possible to do a, b or c in the callback
  13008. * implementation, and return 1 - we cannot do anything
  13009. * here, that is not possible in the callback.
  13010. *
  13011. * TODO: What would be the best reaction here?
  13012. * (Note: The reaction may change, if there is a better
  13013. * idea.)
  13014. */
  13015. /* For the moment, use option c: We look for a proper file,
  13016. * but since a file request is not always a script resource,
  13017. * the authorization check might be different. */
  13018. callback_handler = NULL;
  13019. /* Here we are at a dead end:
  13020. * According to URI matching, a callback should be
  13021. * responsible for handling the request,
  13022. * we called it, but the callback declared itself
  13023. * not responsible.
  13024. * We use a goto here, to get out of this dead end,
  13025. * and continue with the default handling.
  13026. * A goto here is simpler and better to understand
  13027. * than some curious loop. */
  13028. goto no_callback_resource;
  13029. }
  13030. } else {
  13031. #if defined(USE_WEBSOCKET)
  13032. handle_websocket_request(conn,
  13033. path,
  13034. is_callback_resource,
  13035. subprotocols,
  13036. ws_connect_handler,
  13037. ws_ready_handler,
  13038. ws_data_handler,
  13039. ws_close_handler,
  13040. callback_data);
  13041. #endif
  13042. }
  13043. DEBUG_TRACE("%s", "websocket handling done");
  13044. return;
  13045. }
  13046. /* 8. handle websocket requests */
  13047. #if defined(USE_WEBSOCKET)
  13048. if (is_websocket_request) {
  13049. HTTP1_only;
  13050. if (is_script_resource) {
  13051. if (is_in_script_path(conn, path)) {
  13052. /* Websocket Lua script */
  13053. handle_websocket_request(conn,
  13054. path,
  13055. 0 /* Lua Script */,
  13056. NULL,
  13057. NULL,
  13058. NULL,
  13059. NULL,
  13060. NULL,
  13061. conn->phys_ctx->user_data);
  13062. } else {
  13063. /* Script was in an illegal path */
  13064. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13065. }
  13066. } else {
  13067. mg_send_http_error(conn, 404, "%s", "Not found");
  13068. }
  13069. DEBUG_TRACE("%s", "websocket script done");
  13070. return;
  13071. } else
  13072. #endif
  13073. #if defined(NO_FILES)
  13074. /* 9a. In case the server uses only callbacks, this uri is
  13075. * unknown.
  13076. * Then, all request handling ends here. */
  13077. mg_send_http_error(conn, 404, "%s", "Not Found");
  13078. #else
  13079. /* 9b. This request is either for a static file or resource handled
  13080. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13081. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13082. mg_send_http_error(conn, 404, "%s", "Not Found");
  13083. DEBUG_TRACE("%s", "no document root available");
  13084. return;
  13085. }
  13086. /* 10. Request is handled by a script */
  13087. if (is_script_resource) {
  13088. HTTP1_only;
  13089. handle_file_based_request(conn, path, &file);
  13090. DEBUG_TRACE("%s", "script handling done");
  13091. return;
  13092. }
  13093. /* Request was not handled by a callback or script. It will be
  13094. * handled by a server internal method. */
  13095. /* 11. Handle put/delete/mkcol requests */
  13096. if (is_put_or_delete_request) {
  13097. HTTP1_only;
  13098. /* 11.1. PUT method */
  13099. if (!strcmp(ri->request_method, "PUT")) {
  13100. put_file(conn, path);
  13101. DEBUG_TRACE("handling %s request to %s done",
  13102. ri->request_method,
  13103. path);
  13104. return;
  13105. }
  13106. /* 11.2. DELETE method */
  13107. if (!strcmp(ri->request_method, "DELETE")) {
  13108. delete_file(conn, path);
  13109. DEBUG_TRACE("handling %s request to %s done",
  13110. ri->request_method,
  13111. path);
  13112. return;
  13113. }
  13114. /* 11.3. MKCOL method */
  13115. if (!strcmp(ri->request_method, "MKCOL")) {
  13116. dav_mkcol(conn, path);
  13117. DEBUG_TRACE("handling %s request to %s done",
  13118. ri->request_method,
  13119. path);
  13120. return;
  13121. }
  13122. /* 11.4. MOVE method */
  13123. if (!strcmp(ri->request_method, "MOVE")) {
  13124. dav_move_file(conn, path, 0);
  13125. DEBUG_TRACE("handling %s request to %s done",
  13126. ri->request_method,
  13127. path);
  13128. return;
  13129. }
  13130. if (!strcmp(ri->request_method, "COPY")) {
  13131. dav_move_file(conn, path, 1);
  13132. DEBUG_TRACE("handling %s request to %s done",
  13133. ri->request_method,
  13134. path);
  13135. return;
  13136. }
  13137. /* 11.5. LOCK method */
  13138. if (!strcmp(ri->request_method, "LOCK")) {
  13139. dav_lock_file(conn, path);
  13140. DEBUG_TRACE("handling %s request to %s done",
  13141. ri->request_method,
  13142. path);
  13143. return;
  13144. }
  13145. /* 11.6. UNLOCK method */
  13146. if (!strcmp(ri->request_method, "UNLOCK")) {
  13147. dav_unlock_file(conn, path);
  13148. DEBUG_TRACE("handling %s request to %s done",
  13149. ri->request_method,
  13150. path);
  13151. return;
  13152. }
  13153. /* 11.7. PROPPATCH method */
  13154. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13155. dav_proppatch(conn, path);
  13156. DEBUG_TRACE("handling %s request to %s done",
  13157. ri->request_method,
  13158. path);
  13159. return;
  13160. }
  13161. /* 11.8. Other methods, e.g.: PATCH
  13162. * This method is not supported for static resources,
  13163. * only for scripts (Lua, CGI) and callbacks. */
  13164. mg_send_http_error(conn,
  13165. 405,
  13166. "%s method not allowed",
  13167. conn->request_info.request_method);
  13168. DEBUG_TRACE("method %s on %s is not supported",
  13169. ri->request_method,
  13170. path);
  13171. return;
  13172. }
  13173. /* 11. File does not exist, or it was configured that it should be
  13174. * hidden */
  13175. if (!is_found || (must_hide_file(conn, path))) {
  13176. mg_send_http_error(conn, 404, "%s", "Not found");
  13177. DEBUG_TRACE("handling %s request to %s: file not found",
  13178. ri->request_method,
  13179. path);
  13180. return;
  13181. }
  13182. /* 12. Directory uris should end with a slash */
  13183. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13184. && (ri->local_uri[uri_len - 1] != '/')) {
  13185. /* Path + server root */
  13186. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13187. char *new_path;
  13188. if (ri->query_string) {
  13189. buflen += strlen(ri->query_string);
  13190. }
  13191. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13192. if (!new_path) {
  13193. mg_send_http_error(conn, 500, "out or memory");
  13194. } else {
  13195. mg_get_request_link(conn, new_path, buflen - 1);
  13196. strcat(new_path, "/");
  13197. if (ri->query_string) {
  13198. /* Append ? and query string */
  13199. strcat(new_path, "?");
  13200. strcat(new_path, ri->query_string);
  13201. }
  13202. mg_send_http_redirect(conn, new_path, 301);
  13203. mg_free(new_path);
  13204. }
  13205. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13206. ri->request_method,
  13207. path);
  13208. return;
  13209. }
  13210. /* 13. Handle other methods than GET/HEAD */
  13211. /* 13.1. Handle PROPFIND */
  13212. if (!strcmp(ri->request_method, "PROPFIND")) {
  13213. handle_propfind(conn, path, &file.stat);
  13214. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13215. return;
  13216. }
  13217. /* 13.2. Handle OPTIONS for files */
  13218. if (!strcmp(ri->request_method, "OPTIONS")) {
  13219. /* This standard handler is only used for real files.
  13220. * Scripts should support the OPTIONS method themselves, to allow a
  13221. * maximum flexibility.
  13222. * Lua and CGI scripts may fully support CORS this way (including
  13223. * preflights). */
  13224. send_options(conn);
  13225. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13226. return;
  13227. }
  13228. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13229. if ((0 != strcmp(ri->request_method, "GET"))
  13230. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13231. mg_send_http_error(conn,
  13232. 405,
  13233. "%s method not allowed",
  13234. conn->request_info.request_method);
  13235. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13236. return;
  13237. }
  13238. /* 14. directories */
  13239. if (file.stat.is_directory) {
  13240. /* Substitute files have already been handled above. */
  13241. /* Here we can either generate and send a directory listing,
  13242. * or send an "access denied" error. */
  13243. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13244. "yes")) {
  13245. handle_directory_request(conn, path);
  13246. } else {
  13247. mg_send_http_error(conn,
  13248. 403,
  13249. "%s",
  13250. "Error: Directory listing denied");
  13251. }
  13252. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13253. return;
  13254. }
  13255. /* 15. Files with search/replace patterns: LSP and SSI */
  13256. if (is_template_text_file) {
  13257. HTTP1_only;
  13258. handle_file_based_request(conn, path, &file);
  13259. DEBUG_TRACE("handling %s request to %s done (template)",
  13260. ri->request_method,
  13261. path);
  13262. return;
  13263. }
  13264. /* 16. Static file - maybe cached */
  13265. #if !defined(NO_CACHING)
  13266. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13267. /* Send 304 "Not Modified" - this must not send any body data */
  13268. handle_not_modified_static_file_request(conn, &file);
  13269. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13270. ri->request_method,
  13271. path);
  13272. return;
  13273. }
  13274. #endif /* !NO_CACHING */
  13275. /* 17. Static file - not cached */
  13276. handle_static_file_request(conn, path, &file, NULL, NULL);
  13277. DEBUG_TRACE("handling %s request to %s done (static)",
  13278. ri->request_method,
  13279. path);
  13280. #endif /* !defined(NO_FILES) */
  13281. }
  13282. #if !defined(NO_FILESYSTEMS)
  13283. static void
  13284. handle_file_based_request(struct mg_connection *conn,
  13285. const char *path,
  13286. struct mg_file *file)
  13287. {
  13288. #if !defined(NO_CGI)
  13289. int cgi_config_idx, inc, max;
  13290. #endif
  13291. if (!conn || !conn->dom_ctx) {
  13292. return;
  13293. }
  13294. #if defined(USE_LUA)
  13295. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13296. path)
  13297. > 0) {
  13298. if (is_in_script_path(conn, path)) {
  13299. /* Lua server page: an SSI like page containing mostly plain
  13300. * html code plus some tags with server generated contents. */
  13301. handle_lsp_request(conn, path, file, NULL);
  13302. } else {
  13303. /* Script was in an illegal path */
  13304. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13305. }
  13306. return;
  13307. }
  13308. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13309. > 0) {
  13310. if (is_in_script_path(conn, path)) {
  13311. /* Lua in-server module script: a CGI like script used to
  13312. * generate the entire reply. */
  13313. mg_exec_lua_script(conn, path, NULL);
  13314. } else {
  13315. /* Script was in an illegal path */
  13316. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13317. }
  13318. return;
  13319. }
  13320. #endif
  13321. #if defined(USE_DUKTAPE)
  13322. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13323. path)
  13324. > 0) {
  13325. if (is_in_script_path(conn, path)) {
  13326. /* Call duktape to generate the page */
  13327. mg_exec_duktape_script(conn, path);
  13328. } else {
  13329. /* Script was in an illegal path */
  13330. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13331. }
  13332. return;
  13333. }
  13334. #endif
  13335. #if !defined(NO_CGI)
  13336. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13337. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13338. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13339. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13340. if (match_prefix_strlen(
  13341. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13342. path)
  13343. > 0) {
  13344. if (is_in_script_path(conn, path)) {
  13345. /* CGI scripts may support all HTTP methods */
  13346. handle_cgi_request(conn, path, cgi_config_idx);
  13347. } else {
  13348. /* Script was in an illegal path */
  13349. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13350. }
  13351. return;
  13352. }
  13353. }
  13354. }
  13355. #endif /* !NO_CGI */
  13356. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13357. if (is_in_script_path(conn, path)) {
  13358. handle_ssi_file_request(conn, path, file);
  13359. } else {
  13360. /* Script was in an illegal path */
  13361. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13362. }
  13363. return;
  13364. }
  13365. #if !defined(NO_CACHING)
  13366. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13367. /* Send 304 "Not Modified" - this must not send any body data */
  13368. handle_not_modified_static_file_request(conn, file);
  13369. return;
  13370. }
  13371. #endif /* !NO_CACHING */
  13372. handle_static_file_request(conn, path, file, NULL, NULL);
  13373. }
  13374. #endif /* NO_FILESYSTEMS */
  13375. static void
  13376. close_all_listening_sockets(struct mg_context *ctx)
  13377. {
  13378. unsigned int i;
  13379. if (!ctx) {
  13380. return;
  13381. }
  13382. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13383. closesocket(ctx->listening_sockets[i].sock);
  13384. #if defined(USE_X_DOM_SOCKET)
  13385. /* For unix domain sockets, the socket name represents a file that has
  13386. * to be deleted. */
  13387. /* See
  13388. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13389. */
  13390. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13391. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13392. IGNORE_UNUSED_RESULT(
  13393. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13394. }
  13395. #endif
  13396. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13397. }
  13398. mg_free(ctx->listening_sockets);
  13399. ctx->listening_sockets = NULL;
  13400. mg_free(ctx->listening_socket_fds);
  13401. ctx->listening_socket_fds = NULL;
  13402. }
  13403. /* Valid listening port specification is: [ip_address:]port[s]
  13404. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13405. * Examples for IPv6: [::]:80, [::1]:80,
  13406. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13407. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13408. * In order to bind to both, IPv4 and IPv6, you can either add
  13409. * both ports using 8080,[::]:8080, or the short form +8080.
  13410. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13411. * one only accepting IPv4 the other only IPv6. +8080 creates
  13412. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13413. * environment, they might work differently, or might not work
  13414. * at all - it must be tested what options work best in the
  13415. * relevant network environment.
  13416. */
  13417. static int
  13418. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13419. {
  13420. unsigned int a, b, c, d;
  13421. unsigned port;
  13422. unsigned long portUL;
  13423. int ch, len;
  13424. const char *cb;
  13425. char *endptr;
  13426. #if defined(USE_IPV6)
  13427. char buf[100] = {0};
  13428. #endif
  13429. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13430. * Also, all-zeroes in the socket address means binding to all addresses
  13431. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13432. memset(so, 0, sizeof(*so));
  13433. so->lsa.sin.sin_family = AF_INET;
  13434. *ip_version = 0;
  13435. /* Initialize len as invalid. */
  13436. port = 0;
  13437. len = 0;
  13438. /* Test for different ways to format this string */
  13439. if (sscanf(vec->ptr,
  13440. "%u.%u.%u.%u:%u%n",
  13441. &a,
  13442. &b,
  13443. &c,
  13444. &d,
  13445. &port,
  13446. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13447. // to an integer value, but function will not report
  13448. // conversion errors; consider using 'strtol' instead
  13449. == 5) {
  13450. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13451. so->lsa.sin.sin_addr.s_addr =
  13452. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13453. so->lsa.sin.sin_port = htons((uint16_t)port);
  13454. *ip_version = 4;
  13455. #if defined(USE_IPV6)
  13456. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13457. && ((size_t)len <= vec->len)
  13458. && mg_inet_pton(
  13459. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13460. /* IPv6 address, examples: see above */
  13461. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13462. */
  13463. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13464. *ip_version = 6;
  13465. #endif
  13466. } else if ((vec->ptr[0] == '+')
  13467. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13468. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13469. // string to an integer value, but function will not
  13470. // report conversion errors; consider using 'strtol'
  13471. // instead
  13472. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13473. /* Add 1 to len for the + character we skipped before */
  13474. len++;
  13475. #if defined(USE_IPV6)
  13476. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13477. so->lsa.sin6.sin6_family = AF_INET6;
  13478. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13479. *ip_version = 4 + 6;
  13480. #else
  13481. /* Bind to IPv4 only, since IPv6 is not built in. */
  13482. so->lsa.sin.sin_port = htons((uint16_t)port);
  13483. *ip_version = 4;
  13484. #endif
  13485. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13486. && (vec->ptr != endptr)) {
  13487. len = (int)(endptr - vec->ptr);
  13488. port = (uint16_t)portUL;
  13489. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13490. so->lsa.sin.sin_port = htons((uint16_t)port);
  13491. *ip_version = 4;
  13492. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13493. /* String could be a hostname. This check algorithm
  13494. * will only work for RFC 952 compliant hostnames,
  13495. * starting with a letter, containing only letters,
  13496. * digits and hyphen ('-'). Newer specs may allow
  13497. * more, but this is not guaranteed here, since it
  13498. * may interfere with rules for port option lists. */
  13499. /* According to RFC 1035, hostnames are restricted to 255 characters
  13500. * in total (63 between two dots). */
  13501. char hostname[256];
  13502. size_t hostnlen = (size_t)(cb - vec->ptr);
  13503. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13504. /* This would be invalid in any case */
  13505. *ip_version = 0;
  13506. return 0;
  13507. }
  13508. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13509. if (mg_inet_pton(
  13510. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13511. if (sscanf(cb + 1, "%u%n", &port, &len)
  13512. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13513. // string to an integer value, but function will not
  13514. // report conversion errors; consider using 'strtol'
  13515. // instead
  13516. *ip_version = 4;
  13517. so->lsa.sin.sin_port = htons((uint16_t)port);
  13518. len += (int)(hostnlen + 1);
  13519. } else {
  13520. len = 0;
  13521. }
  13522. #if defined(USE_IPV6)
  13523. } else if (mg_inet_pton(AF_INET6,
  13524. hostname,
  13525. &so->lsa.sin6,
  13526. sizeof(so->lsa.sin6),
  13527. 1)) {
  13528. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13529. *ip_version = 6;
  13530. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13531. len += (int)(hostnlen + 1);
  13532. } else {
  13533. len = 0;
  13534. }
  13535. #endif
  13536. } else {
  13537. len = 0;
  13538. }
  13539. #if defined(USE_X_DOM_SOCKET)
  13540. } else if (vec->ptr[0] == 'x') {
  13541. /* unix (linux) domain socket */
  13542. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13543. len = vec->len;
  13544. so->lsa.sun.sun_family = AF_UNIX;
  13545. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13546. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13547. port = 0;
  13548. *ip_version = 99;
  13549. } else {
  13550. /* String too long */
  13551. len = 0;
  13552. }
  13553. #endif
  13554. } else {
  13555. /* Parsing failure. */
  13556. len = 0;
  13557. }
  13558. /* sscanf and the option splitting code ensure the following condition
  13559. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13560. if ((len > 0) && is_valid_port(port)
  13561. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13562. /* Next character after the port number */
  13563. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13564. so->is_ssl = (ch == 's');
  13565. so->ssl_redir = (ch == 'r');
  13566. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13567. return 1;
  13568. }
  13569. }
  13570. /* Reset ip_version to 0 if there is an error */
  13571. *ip_version = 0;
  13572. return 0;
  13573. }
  13574. /* Is there any SSL port in use? */
  13575. static int
  13576. is_ssl_port_used(const char *ports)
  13577. {
  13578. if (ports) {
  13579. /* There are several different allowed syntax variants:
  13580. * - "80" for a single port using every network interface
  13581. * - "localhost:80" for a single port using only localhost
  13582. * - "80,localhost:8080" for two ports, one bound to localhost
  13583. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13584. * to IPv4 localhost, one to IPv6 localhost
  13585. * - "+80" use port 80 for IPv4 and IPv6
  13586. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13587. * for both: IPv4 and IPv4
  13588. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13589. * additionally port 8080 bound to localhost connections
  13590. *
  13591. * If we just look for 's' anywhere in the string, "localhost:80"
  13592. * will be detected as SSL (false positive).
  13593. * Looking for 's' after a digit may cause false positives in
  13594. * "my24service:8080".
  13595. * Looking from 's' backward if there are only ':' and numbers
  13596. * before will not work for "24service:8080" (non SSL, port 8080)
  13597. * or "24s" (SSL, port 24).
  13598. *
  13599. * Remark: Initially hostnames were not allowed to start with a
  13600. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13601. * Section 2.1).
  13602. *
  13603. * To get this correct, the entire string must be parsed as a whole,
  13604. * reading it as a list element for element and parsing with an
  13605. * algorithm equivalent to parse_port_string.
  13606. *
  13607. * In fact, we use local interface names here, not arbitrary
  13608. * hostnames, so in most cases the only name will be "localhost".
  13609. *
  13610. * So, for now, we use this simple algorithm, that may still return
  13611. * a false positive in bizarre cases.
  13612. */
  13613. int i;
  13614. int portslen = (int)strlen(ports);
  13615. char prevIsNumber = 0;
  13616. for (i = 0; i < portslen; i++) {
  13617. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13618. return 1;
  13619. }
  13620. if (ports[i] >= '0' && ports[i] <= '9') {
  13621. prevIsNumber = 1;
  13622. } else {
  13623. prevIsNumber = 0;
  13624. }
  13625. }
  13626. }
  13627. return 0;
  13628. }
  13629. static int
  13630. set_ports_option(struct mg_context *phys_ctx)
  13631. {
  13632. const char *list;
  13633. int on = 1;
  13634. #if defined(USE_IPV6)
  13635. int off = 0;
  13636. #endif
  13637. struct vec vec;
  13638. struct socket so, *ptr;
  13639. struct mg_pollfd *pfd;
  13640. union usa usa;
  13641. socklen_t len;
  13642. int ip_version;
  13643. int portsTotal = 0;
  13644. int portsOk = 0;
  13645. const char *opt_txt;
  13646. long opt_listen_backlog;
  13647. if (!phys_ctx) {
  13648. return 0;
  13649. }
  13650. memset(&so, 0, sizeof(so));
  13651. memset(&usa, 0, sizeof(usa));
  13652. len = sizeof(usa);
  13653. list = phys_ctx->dd.config[LISTENING_PORTS];
  13654. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13655. portsTotal++;
  13656. if (!parse_port_string(&vec, &so, &ip_version)) {
  13657. mg_cry_ctx_internal(
  13658. phys_ctx,
  13659. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13660. (int)vec.len,
  13661. vec.ptr,
  13662. portsTotal,
  13663. "[IP_ADDRESS:]PORT[s|r]");
  13664. continue;
  13665. }
  13666. #if !defined(NO_SSL)
  13667. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13668. mg_cry_ctx_internal(phys_ctx,
  13669. "Cannot add SSL socket (entry %i)",
  13670. portsTotal);
  13671. continue;
  13672. }
  13673. #endif
  13674. /* Create socket. */
  13675. /* For a list of protocol numbers (e.g., TCP==6) see:
  13676. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13677. */
  13678. if ((so.sock =
  13679. socket(so.lsa.sa.sa_family,
  13680. SOCK_STREAM,
  13681. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13682. == INVALID_SOCKET) {
  13683. mg_cry_ctx_internal(phys_ctx,
  13684. "cannot create socket (entry %i)",
  13685. portsTotal);
  13686. continue;
  13687. }
  13688. #if defined(_WIN32)
  13689. /* Windows SO_REUSEADDR lets many procs binds to a
  13690. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13691. * if someone already has the socket -- DTL */
  13692. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13693. * Windows might need a few seconds before
  13694. * the same port can be used again in the
  13695. * same process, so a short Sleep may be
  13696. * required between mg_stop and mg_start.
  13697. */
  13698. if (setsockopt(so.sock,
  13699. SOL_SOCKET,
  13700. SO_EXCLUSIVEADDRUSE,
  13701. (SOCK_OPT_TYPE)&on,
  13702. sizeof(on))
  13703. != 0) {
  13704. /* Set reuse option, but don't abort on errors. */
  13705. mg_cry_ctx_internal(
  13706. phys_ctx,
  13707. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13708. portsTotal);
  13709. }
  13710. #else
  13711. if (setsockopt(so.sock,
  13712. SOL_SOCKET,
  13713. SO_REUSEADDR,
  13714. (SOCK_OPT_TYPE)&on,
  13715. sizeof(on))
  13716. != 0) {
  13717. /* Set reuse option, but don't abort on errors. */
  13718. mg_cry_ctx_internal(
  13719. phys_ctx,
  13720. "cannot set socket option SO_REUSEADDR (entry %i)",
  13721. portsTotal);
  13722. }
  13723. #endif
  13724. #if defined(USE_X_DOM_SOCKET)
  13725. if (ip_version == 99) {
  13726. /* Unix domain socket */
  13727. } else
  13728. #endif
  13729. if (ip_version > 4) {
  13730. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13731. #if defined(USE_IPV6)
  13732. if (ip_version > 6) {
  13733. if (so.lsa.sa.sa_family == AF_INET6
  13734. && setsockopt(so.sock,
  13735. IPPROTO_IPV6,
  13736. IPV6_V6ONLY,
  13737. (void *)&off,
  13738. sizeof(off))
  13739. != 0) {
  13740. /* Set IPv6 only option, but don't abort on errors. */
  13741. mg_cry_ctx_internal(phys_ctx,
  13742. "cannot set socket option "
  13743. "IPV6_V6ONLY=off (entry %i)",
  13744. portsTotal);
  13745. }
  13746. } else {
  13747. if (so.lsa.sa.sa_family == AF_INET6
  13748. && setsockopt(so.sock,
  13749. IPPROTO_IPV6,
  13750. IPV6_V6ONLY,
  13751. (void *)&on,
  13752. sizeof(on))
  13753. != 0) {
  13754. /* Set IPv6 only option, but don't abort on errors. */
  13755. mg_cry_ctx_internal(phys_ctx,
  13756. "cannot set socket option "
  13757. "IPV6_V6ONLY=on (entry %i)",
  13758. portsTotal);
  13759. }
  13760. }
  13761. #else
  13762. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13763. closesocket(so.sock);
  13764. so.sock = INVALID_SOCKET;
  13765. continue;
  13766. #endif
  13767. }
  13768. if (so.lsa.sa.sa_family == AF_INET) {
  13769. len = sizeof(so.lsa.sin);
  13770. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13771. mg_cry_ctx_internal(phys_ctx,
  13772. "cannot bind to %.*s: %d (%s)",
  13773. (int)vec.len,
  13774. vec.ptr,
  13775. (int)ERRNO,
  13776. strerror(errno));
  13777. closesocket(so.sock);
  13778. so.sock = INVALID_SOCKET;
  13779. continue;
  13780. }
  13781. }
  13782. #if defined(USE_IPV6)
  13783. else if (so.lsa.sa.sa_family == AF_INET6) {
  13784. len = sizeof(so.lsa.sin6);
  13785. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13786. mg_cry_ctx_internal(phys_ctx,
  13787. "cannot bind to IPv6 %.*s: %d (%s)",
  13788. (int)vec.len,
  13789. vec.ptr,
  13790. (int)ERRNO,
  13791. strerror(errno));
  13792. closesocket(so.sock);
  13793. so.sock = INVALID_SOCKET;
  13794. continue;
  13795. }
  13796. }
  13797. #endif
  13798. #if defined(USE_X_DOM_SOCKET)
  13799. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13800. len = sizeof(so.lsa.sun);
  13801. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13802. mg_cry_ctx_internal(phys_ctx,
  13803. "cannot bind to unix socket %s: %d (%s)",
  13804. so.lsa.sun.sun_path,
  13805. (int)ERRNO,
  13806. strerror(errno));
  13807. closesocket(so.sock);
  13808. so.sock = INVALID_SOCKET;
  13809. continue;
  13810. }
  13811. }
  13812. #endif
  13813. else {
  13814. mg_cry_ctx_internal(
  13815. phys_ctx,
  13816. "cannot bind: address family not supported (entry %i)",
  13817. portsTotal);
  13818. closesocket(so.sock);
  13819. so.sock = INVALID_SOCKET;
  13820. continue;
  13821. }
  13822. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13823. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13824. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13825. mg_cry_ctx_internal(phys_ctx,
  13826. "%s value \"%s\" is invalid",
  13827. config_options[LISTEN_BACKLOG_SIZE].name,
  13828. opt_txt);
  13829. closesocket(so.sock);
  13830. so.sock = INVALID_SOCKET;
  13831. continue;
  13832. }
  13833. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13834. mg_cry_ctx_internal(phys_ctx,
  13835. "cannot listen to %.*s: %d (%s)",
  13836. (int)vec.len,
  13837. vec.ptr,
  13838. (int)ERRNO,
  13839. strerror(errno));
  13840. closesocket(so.sock);
  13841. so.sock = INVALID_SOCKET;
  13842. continue;
  13843. }
  13844. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13845. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13846. int err = (int)ERRNO;
  13847. mg_cry_ctx_internal(phys_ctx,
  13848. "call to getsockname failed %.*s: %d (%s)",
  13849. (int)vec.len,
  13850. vec.ptr,
  13851. err,
  13852. strerror(errno));
  13853. closesocket(so.sock);
  13854. so.sock = INVALID_SOCKET;
  13855. continue;
  13856. }
  13857. /* Update lsa port in case of random free ports */
  13858. #if defined(USE_IPV6)
  13859. if (so.lsa.sa.sa_family == AF_INET6) {
  13860. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13861. } else
  13862. #endif
  13863. {
  13864. so.lsa.sin.sin_port = usa.sin.sin_port;
  13865. }
  13866. if ((ptr = (struct socket *)
  13867. mg_realloc_ctx(phys_ctx->listening_sockets,
  13868. (phys_ctx->num_listening_sockets + 1)
  13869. * sizeof(phys_ctx->listening_sockets[0]),
  13870. phys_ctx))
  13871. == NULL) {
  13872. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13873. closesocket(so.sock);
  13874. so.sock = INVALID_SOCKET;
  13875. continue;
  13876. }
  13877. if ((pfd = (struct mg_pollfd *)
  13878. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13879. (phys_ctx->num_listening_sockets + 1)
  13880. * sizeof(phys_ctx->listening_socket_fds[0]),
  13881. phys_ctx))
  13882. == NULL) {
  13883. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13884. closesocket(so.sock);
  13885. so.sock = INVALID_SOCKET;
  13886. mg_free(ptr);
  13887. continue;
  13888. }
  13889. set_close_on_exec(so.sock, NULL, phys_ctx);
  13890. phys_ctx->listening_sockets = ptr;
  13891. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13892. phys_ctx->listening_socket_fds = pfd;
  13893. phys_ctx->num_listening_sockets++;
  13894. portsOk++;
  13895. }
  13896. if (portsOk != portsTotal) {
  13897. close_all_listening_sockets(phys_ctx);
  13898. portsOk = 0;
  13899. }
  13900. return portsOk;
  13901. }
  13902. static const char *
  13903. header_val(const struct mg_connection *conn, const char *header)
  13904. {
  13905. const char *header_value;
  13906. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13907. return "-";
  13908. } else {
  13909. return header_value;
  13910. }
  13911. }
  13912. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13913. #include "external_log_access.inl"
  13914. #elif !defined(NO_FILESYSTEMS)
  13915. static void
  13916. log_access(const struct mg_connection *conn)
  13917. {
  13918. const struct mg_request_info *ri;
  13919. struct mg_file fi;
  13920. char date[64], src_addr[IP_ADDR_STR_LEN];
  13921. #if defined(REENTRANT_TIME)
  13922. struct tm _tm;
  13923. struct tm *tm = &_tm;
  13924. #else
  13925. struct tm *tm;
  13926. #endif
  13927. const char *referer;
  13928. const char *user_agent;
  13929. char log_buf[4096];
  13930. if (!conn || !conn->dom_ctx) {
  13931. return;
  13932. }
  13933. /* Set log message to "empty" */
  13934. log_buf[0] = 0;
  13935. #if defined(USE_LUA)
  13936. if (conn->phys_ctx->lua_bg_log_available) {
  13937. int ret;
  13938. struct mg_context *ctx = conn->phys_ctx;
  13939. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13940. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13941. /* call "log()" in Lua */
  13942. lua_getglobal(lstate, "log");
  13943. prepare_lua_request_info_inner(conn, lstate);
  13944. push_lua_response_log_data(conn, lstate);
  13945. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13946. if (ret == 0) {
  13947. int t = lua_type(lstate, -1);
  13948. if (t == LUA_TBOOLEAN) {
  13949. if (lua_toboolean(lstate, -1) == 0) {
  13950. /* log() returned false: do not log */
  13951. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13952. return;
  13953. }
  13954. /* log returned true: continue logging */
  13955. } else if (t == LUA_TSTRING) {
  13956. size_t len;
  13957. const char *txt = lua_tolstring(lstate, -1, &len);
  13958. if ((len == 0) || (*txt == 0)) {
  13959. /* log() returned empty string: do not log */
  13960. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13961. return;
  13962. }
  13963. /* Copy test from Lua into log_buf */
  13964. if (len >= sizeof(log_buf)) {
  13965. len = sizeof(log_buf) - 1;
  13966. }
  13967. memcpy(log_buf, txt, len);
  13968. log_buf[len] = 0;
  13969. }
  13970. } else {
  13971. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13972. }
  13973. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13974. }
  13975. #endif
  13976. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13977. if (mg_fopen(conn,
  13978. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13979. MG_FOPEN_MODE_APPEND,
  13980. &fi)
  13981. == 0) {
  13982. fi.access.fp = NULL;
  13983. }
  13984. } else {
  13985. fi.access.fp = NULL;
  13986. }
  13987. /* Log is written to a file and/or a callback. If both are not set,
  13988. * executing the rest of the function is pointless. */
  13989. if ((fi.access.fp == NULL)
  13990. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13991. return;
  13992. }
  13993. /* If we did not get a log message from Lua, create it here. */
  13994. if (!log_buf[0]) {
  13995. #if defined(REENTRANT_TIME)
  13996. localtime_r(&conn->conn_birth_time, tm);
  13997. #else
  13998. tm = localtime(&conn->conn_birth_time);
  13999. #endif
  14000. if (tm != NULL) {
  14001. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14002. } else {
  14003. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14004. }
  14005. ri = &conn->request_info;
  14006. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14007. referer = header_val(conn, "Referer");
  14008. user_agent = header_val(conn, "User-Agent");
  14009. mg_snprintf(conn,
  14010. NULL, /* Ignore truncation in access log */
  14011. log_buf,
  14012. sizeof(log_buf),
  14013. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14014. " %s %s",
  14015. src_addr,
  14016. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14017. date,
  14018. ri->request_method ? ri->request_method : "-",
  14019. ri->request_uri ? ri->request_uri : "-",
  14020. ri->query_string ? "?" : "",
  14021. ri->query_string ? ri->query_string : "",
  14022. ri->http_version,
  14023. conn->status_code,
  14024. conn->num_bytes_sent,
  14025. referer,
  14026. user_agent);
  14027. }
  14028. /* Here we have a log message in log_buf. Call the callback */
  14029. if (conn->phys_ctx->callbacks.log_access) {
  14030. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14031. /* do not log if callback returns non-zero */
  14032. if (fi.access.fp) {
  14033. mg_fclose(&fi.access);
  14034. }
  14035. return;
  14036. }
  14037. }
  14038. /* Store in file */
  14039. if (fi.access.fp) {
  14040. int ok = 1;
  14041. flockfile(fi.access.fp);
  14042. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14043. ok = 0;
  14044. }
  14045. if (fflush(fi.access.fp) != 0) {
  14046. ok = 0;
  14047. }
  14048. funlockfile(fi.access.fp);
  14049. if (mg_fclose(&fi.access) != 0) {
  14050. ok = 0;
  14051. }
  14052. if (!ok) {
  14053. mg_cry_internal(conn,
  14054. "Error writing log file %s",
  14055. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14056. }
  14057. }
  14058. }
  14059. #else
  14060. #error "Either enable filesystems or provide a custom log_access implementation"
  14061. #endif /* Externally provided function */
  14062. /* Verify given socket address against the ACL.
  14063. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14064. */
  14065. static int
  14066. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14067. {
  14068. int allowed, flag, matched;
  14069. struct vec vec;
  14070. if (phys_ctx) {
  14071. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14072. /* If any ACL is set, deny by default */
  14073. allowed = (list == NULL) ? '+' : '-';
  14074. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14075. flag = vec.ptr[0];
  14076. matched = -1;
  14077. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14078. vec.ptr++;
  14079. vec.len--;
  14080. matched = parse_match_net(&vec, sa, 1);
  14081. }
  14082. if (matched < 0) {
  14083. mg_cry_ctx_internal(phys_ctx,
  14084. "%s: subnet must be [+|-]IP-addr[/x]",
  14085. __func__);
  14086. return -1;
  14087. }
  14088. if (matched) {
  14089. allowed = flag;
  14090. }
  14091. }
  14092. return allowed == '+';
  14093. }
  14094. return -1;
  14095. }
  14096. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14097. static int
  14098. set_uid_option(struct mg_context *phys_ctx)
  14099. {
  14100. int success = 0;
  14101. if (phys_ctx) {
  14102. /* We are currently running as curr_uid. */
  14103. const uid_t curr_uid = getuid();
  14104. /* If set, we want to run as run_as_user. */
  14105. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14106. const struct passwd *to_pw = NULL;
  14107. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14108. /* run_as_user does not exist on the system. We can't proceed
  14109. * further. */
  14110. mg_cry_ctx_internal(phys_ctx,
  14111. "%s: unknown user [%s]",
  14112. __func__,
  14113. run_as_user);
  14114. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14115. /* There was either no request to change user, or we're already
  14116. * running as run_as_user. Nothing else to do.
  14117. */
  14118. success = 1;
  14119. } else {
  14120. /* Valid change request. */
  14121. if (setgid(to_pw->pw_gid) == -1) {
  14122. mg_cry_ctx_internal(phys_ctx,
  14123. "%s: setgid(%s): %s",
  14124. __func__,
  14125. run_as_user,
  14126. strerror(errno));
  14127. } else if (setgroups(0, NULL) == -1) {
  14128. mg_cry_ctx_internal(phys_ctx,
  14129. "%s: setgroups(): %s",
  14130. __func__,
  14131. strerror(errno));
  14132. } else if (setuid(to_pw->pw_uid) == -1) {
  14133. mg_cry_ctx_internal(phys_ctx,
  14134. "%s: setuid(%s): %s",
  14135. __func__,
  14136. run_as_user,
  14137. strerror(errno));
  14138. } else {
  14139. success = 1;
  14140. }
  14141. }
  14142. }
  14143. return success;
  14144. }
  14145. #endif /* !_WIN32 */
  14146. static void
  14147. tls_dtor(void *key)
  14148. {
  14149. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14150. /* key == pthread_getspecific(sTlsKey); */
  14151. if (tls) {
  14152. if (tls->is_master == 2) {
  14153. tls->is_master = -3; /* Mark memory as dead */
  14154. mg_free(tls);
  14155. }
  14156. }
  14157. pthread_setspecific(sTlsKey, NULL);
  14158. }
  14159. #if defined(USE_MBEDTLS)
  14160. /* Check if SSL is required.
  14161. * If so, set up ctx->ssl_ctx pointer. */
  14162. static int
  14163. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14164. {
  14165. if (!phys_ctx) {
  14166. return 0;
  14167. }
  14168. if (!dom_ctx) {
  14169. dom_ctx = &(phys_ctx->dd);
  14170. }
  14171. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14172. /* No SSL port is set. No need to setup SSL. */
  14173. return 1;
  14174. }
  14175. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14176. if (dom_ctx->ssl_ctx == NULL) {
  14177. fprintf(stderr, "ssl_ctx malloc failed\n");
  14178. return 0;
  14179. }
  14180. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14181. == 0
  14182. ? 1
  14183. : 0;
  14184. }
  14185. #elif !defined(NO_SSL)
  14186. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14187. struct mg_domain_context *dom_ctx,
  14188. const char *pem,
  14189. const char *chain);
  14190. static const char *ssl_error(void);
  14191. static int
  14192. refresh_trust(struct mg_connection *conn)
  14193. {
  14194. struct stat cert_buf;
  14195. int64_t t = 0;
  14196. const char *pem;
  14197. const char *chain;
  14198. int should_verify_peer;
  14199. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14200. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14201. * refresh_trust still can not work. */
  14202. return 0;
  14203. }
  14204. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14205. if (chain == NULL) {
  14206. /* pem is not NULL here */
  14207. chain = pem;
  14208. }
  14209. if (*chain == 0) {
  14210. chain = NULL;
  14211. }
  14212. if (stat(pem, &cert_buf) != -1) {
  14213. t = (int64_t)cert_buf.st_mtime;
  14214. }
  14215. mg_lock_context(conn->phys_ctx);
  14216. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14217. conn->dom_ctx->ssl_cert_last_mtime = t;
  14218. should_verify_peer = 0;
  14219. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14220. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14221. == 0) {
  14222. should_verify_peer = 1;
  14223. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14224. "optional")
  14225. == 0) {
  14226. should_verify_peer = 1;
  14227. }
  14228. }
  14229. if (should_verify_peer) {
  14230. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14231. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14232. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14233. ca_file,
  14234. ca_path)
  14235. != 1) {
  14236. mg_unlock_context(conn->phys_ctx);
  14237. mg_cry_ctx_internal(
  14238. conn->phys_ctx,
  14239. "SSL_CTX_load_verify_locations error: %s "
  14240. "ssl_verify_peer requires setting "
  14241. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14242. "present in "
  14243. "the .conf file?",
  14244. ssl_error());
  14245. return 0;
  14246. }
  14247. }
  14248. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14249. mg_unlock_context(conn->phys_ctx);
  14250. return 0;
  14251. }
  14252. }
  14253. mg_unlock_context(conn->phys_ctx);
  14254. return 1;
  14255. }
  14256. #if defined(OPENSSL_API_1_1)
  14257. #else
  14258. static pthread_mutex_t *ssl_mutexes;
  14259. #endif /* OPENSSL_API_1_1 */
  14260. static int
  14261. sslize(struct mg_connection *conn,
  14262. int (*func)(SSL *),
  14263. const struct mg_client_options *client_options)
  14264. {
  14265. int ret, err;
  14266. int short_trust;
  14267. unsigned timeout = 1024;
  14268. unsigned i;
  14269. if (!conn) {
  14270. return 0;
  14271. }
  14272. short_trust =
  14273. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14274. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14275. if (short_trust) {
  14276. int trust_ret = refresh_trust(conn);
  14277. if (!trust_ret) {
  14278. return trust_ret;
  14279. }
  14280. }
  14281. mg_lock_context(conn->phys_ctx);
  14282. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14283. mg_unlock_context(conn->phys_ctx);
  14284. if (conn->ssl == NULL) {
  14285. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14286. OPENSSL_REMOVE_THREAD_STATE();
  14287. return 0;
  14288. }
  14289. SSL_set_app_data(conn->ssl, (char *)conn);
  14290. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14291. if (ret != 1) {
  14292. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14293. SSL_free(conn->ssl);
  14294. conn->ssl = NULL;
  14295. OPENSSL_REMOVE_THREAD_STATE();
  14296. return 0;
  14297. }
  14298. if (client_options) {
  14299. if (client_options->host_name) {
  14300. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14301. }
  14302. }
  14303. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14304. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14305. /* NOTE: The loop below acts as a back-off, so we can end
  14306. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14307. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14308. if (to >= 0) {
  14309. timeout = (unsigned)to;
  14310. }
  14311. }
  14312. /* SSL functions may fail and require to be called again:
  14313. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14314. * Here "func" could be SSL_connect or SSL_accept. */
  14315. for (i = 0; i <= timeout; i += 50) {
  14316. ERR_clear_error();
  14317. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14318. ret = func(conn->ssl);
  14319. if (ret != 1) {
  14320. err = SSL_get_error(conn->ssl, ret);
  14321. if ((err == SSL_ERROR_WANT_CONNECT)
  14322. || (err == SSL_ERROR_WANT_ACCEPT)
  14323. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14324. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14325. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14326. /* Don't wait if the server is going to be stopped. */
  14327. break;
  14328. }
  14329. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14330. /* Simply retry the function call. */
  14331. mg_sleep(50);
  14332. } else {
  14333. /* Need to retry the function call "later".
  14334. * See https://linux.die.net/man/3/ssl_get_error
  14335. * This is typical for non-blocking sockets. */
  14336. struct mg_pollfd pfd;
  14337. int pollres;
  14338. pfd.fd = conn->client.sock;
  14339. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14340. || (err == SSL_ERROR_WANT_WRITE))
  14341. ? POLLOUT
  14342. : POLLIN;
  14343. pollres =
  14344. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14345. if (pollres < 0) {
  14346. /* Break if error occurred (-1)
  14347. * or server shutdown (-2) */
  14348. break;
  14349. }
  14350. }
  14351. } else if (err == SSL_ERROR_SYSCALL) {
  14352. /* This is an IO error. Look at errno. */
  14353. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14354. break;
  14355. } else {
  14356. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14357. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14358. break;
  14359. }
  14360. } else {
  14361. /* success */
  14362. break;
  14363. }
  14364. }
  14365. ERR_clear_error();
  14366. if (ret != 1) {
  14367. SSL_free(conn->ssl);
  14368. conn->ssl = NULL;
  14369. OPENSSL_REMOVE_THREAD_STATE();
  14370. return 0;
  14371. }
  14372. return 1;
  14373. }
  14374. /* Return OpenSSL error message (from CRYPTO lib) */
  14375. static const char *
  14376. ssl_error(void)
  14377. {
  14378. unsigned long err;
  14379. err = ERR_get_error();
  14380. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14381. }
  14382. static int
  14383. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14384. {
  14385. int i;
  14386. const char hexdigit[] = "0123456789abcdef";
  14387. if ((memlen <= 0) || (buflen <= 0)) {
  14388. return 0;
  14389. }
  14390. if (buflen < (3 * memlen)) {
  14391. return 0;
  14392. }
  14393. for (i = 0; i < memlen; i++) {
  14394. if (i > 0) {
  14395. buf[3 * i - 1] = ' ';
  14396. }
  14397. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14398. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14399. }
  14400. buf[3 * memlen - 1] = 0;
  14401. return 1;
  14402. }
  14403. static int
  14404. ssl_get_client_cert_info(const struct mg_connection *conn,
  14405. struct mg_client_cert *client_cert)
  14406. {
  14407. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14408. if (cert) {
  14409. char str_buf[1024];
  14410. unsigned char buf[256];
  14411. char *str_serial = NULL;
  14412. unsigned int ulen;
  14413. int ilen;
  14414. unsigned char *tmp_buf;
  14415. unsigned char *tmp_p;
  14416. /* Handle to algorithm used for fingerprint */
  14417. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14418. /* Get Subject and issuer */
  14419. X509_NAME *subj = X509_get_subject_name(cert);
  14420. X509_NAME *iss = X509_get_issuer_name(cert);
  14421. /* Get serial number */
  14422. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14423. /* Translate serial number to a hex string */
  14424. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14425. if (serial_bn) {
  14426. str_serial = BN_bn2hex(serial_bn);
  14427. BN_free(serial_bn);
  14428. }
  14429. client_cert->serial =
  14430. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14431. /* Translate subject and issuer to a string */
  14432. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14433. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14434. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14435. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14436. /* Calculate SHA1 fingerprint and store as a hex string */
  14437. ulen = 0;
  14438. /* ASN1_digest is deprecated. Do the calculation manually,
  14439. * using EVP_Digest. */
  14440. ilen = i2d_X509(cert, NULL);
  14441. tmp_buf = (ilen > 0)
  14442. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14443. conn->phys_ctx)
  14444. : NULL;
  14445. if (tmp_buf) {
  14446. tmp_p = tmp_buf;
  14447. (void)i2d_X509(cert, &tmp_p);
  14448. if (!EVP_Digest(
  14449. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14450. ulen = 0;
  14451. }
  14452. mg_free(tmp_buf);
  14453. }
  14454. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14455. *str_buf = 0;
  14456. }
  14457. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14458. client_cert->peer_cert = (void *)cert;
  14459. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14460. * see https://linux.die.net/man/3/bn_bn2hex */
  14461. OPENSSL_free(str_serial);
  14462. return 1;
  14463. }
  14464. return 0;
  14465. }
  14466. #if defined(OPENSSL_API_1_1)
  14467. #else
  14468. static void
  14469. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14470. {
  14471. (void)line;
  14472. (void)file;
  14473. if (mode & 1) {
  14474. /* 1 is CRYPTO_LOCK */
  14475. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14476. } else {
  14477. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14478. }
  14479. }
  14480. #endif /* OPENSSL_API_1_1 */
  14481. #if !defined(NO_SSL_DL)
  14482. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14483. static void *
  14484. load_tls_dll(char *ebuf,
  14485. size_t ebuf_len,
  14486. const char *dll_name,
  14487. struct ssl_func *sw,
  14488. int *feature_missing)
  14489. {
  14490. union {
  14491. void *p;
  14492. void (*fp)(void);
  14493. } u;
  14494. void *dll_handle;
  14495. struct ssl_func *fp;
  14496. int ok;
  14497. int truncated = 0;
  14498. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14499. mg_snprintf(NULL,
  14500. NULL, /* No truncation check for ebuf */
  14501. ebuf,
  14502. ebuf_len,
  14503. "%s: cannot load %s",
  14504. __func__,
  14505. dll_name);
  14506. return NULL;
  14507. }
  14508. ok = 1;
  14509. for (fp = sw; fp->name != NULL; fp++) {
  14510. #if defined(_WIN32)
  14511. /* GetProcAddress() returns pointer to function */
  14512. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14513. #else
  14514. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14515. * pointers to function pointers. We need to use a union to make a
  14516. * cast. */
  14517. u.p = dlsym(dll_handle, fp->name);
  14518. #endif /* _WIN32 */
  14519. /* Set pointer (might be NULL) */
  14520. fp->ptr = u.fp;
  14521. if (u.fp == NULL) {
  14522. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14523. if (feature_missing) {
  14524. feature_missing[fp->required]++;
  14525. }
  14526. if (fp->required == TLS_Mandatory) {
  14527. /* Mandatory function is missing */
  14528. if (ok) {
  14529. /* This is the first missing function.
  14530. * Create a new error message. */
  14531. mg_snprintf(NULL,
  14532. &truncated,
  14533. ebuf,
  14534. ebuf_len,
  14535. "%s: %s: cannot find %s",
  14536. __func__,
  14537. dll_name,
  14538. fp->name);
  14539. ok = 0;
  14540. } else {
  14541. /* This is yet anothermissing function.
  14542. * Append existing error message. */
  14543. size_t cur_len = strlen(ebuf);
  14544. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14545. mg_snprintf(NULL,
  14546. &truncated,
  14547. ebuf + cur_len,
  14548. ebuf_len - cur_len - 3,
  14549. ", %s",
  14550. fp->name);
  14551. if (truncated) {
  14552. /* If truncated, add "..." */
  14553. strcat(ebuf, "...");
  14554. }
  14555. }
  14556. }
  14557. }
  14558. }
  14559. }
  14560. if (!ok) {
  14561. (void)dlclose(dll_handle);
  14562. return NULL;
  14563. }
  14564. return dll_handle;
  14565. }
  14566. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14567. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14568. #endif /* NO_SSL_DL */
  14569. #if defined(SSL_ALREADY_INITIALIZED)
  14570. static volatile ptrdiff_t cryptolib_users =
  14571. 1; /* Reference counter for crypto library. */
  14572. #else
  14573. static volatile ptrdiff_t cryptolib_users =
  14574. 0; /* Reference counter for crypto library. */
  14575. #endif
  14576. static int
  14577. initialize_openssl(char *ebuf, size_t ebuf_len)
  14578. {
  14579. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14580. int i, num_locks;
  14581. size_t size;
  14582. #endif
  14583. if (ebuf_len > 0) {
  14584. ebuf[0] = 0;
  14585. }
  14586. #if !defined(NO_SSL_DL)
  14587. if (!cryptolib_dll_handle) {
  14588. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14589. cryptolib_dll_handle = load_tls_dll(
  14590. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14591. if (!cryptolib_dll_handle) {
  14592. mg_snprintf(NULL,
  14593. NULL, /* No truncation check for ebuf */
  14594. ebuf,
  14595. ebuf_len,
  14596. "%s: error loading library %s",
  14597. __func__,
  14598. CRYPTO_LIB);
  14599. DEBUG_TRACE("%s", ebuf);
  14600. return 0;
  14601. }
  14602. }
  14603. #endif /* NO_SSL_DL */
  14604. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14605. return 1;
  14606. }
  14607. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14608. /* Initialize locking callbacks, needed for thread safety.
  14609. * http://www.openssl.org/support/faq.html#PROG1
  14610. */
  14611. num_locks = CRYPTO_num_locks();
  14612. if (num_locks < 0) {
  14613. num_locks = 0;
  14614. }
  14615. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14616. /* allocate mutex array, if required */
  14617. if (num_locks == 0) {
  14618. /* No mutex array required */
  14619. ssl_mutexes = NULL;
  14620. } else {
  14621. /* Mutex array required - allocate it */
  14622. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14623. /* Check OOM */
  14624. if (ssl_mutexes == NULL) {
  14625. mg_snprintf(NULL,
  14626. NULL, /* No truncation check for ebuf */
  14627. ebuf,
  14628. ebuf_len,
  14629. "%s: cannot allocate mutexes: %s",
  14630. __func__,
  14631. ssl_error());
  14632. DEBUG_TRACE("%s", ebuf);
  14633. return 0;
  14634. }
  14635. /* initialize mutex array */
  14636. for (i = 0; i < num_locks; i++) {
  14637. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14638. mg_snprintf(NULL,
  14639. NULL, /* No truncation check for ebuf */
  14640. ebuf,
  14641. ebuf_len,
  14642. "%s: error initializing mutex %i of %i",
  14643. __func__,
  14644. i,
  14645. num_locks);
  14646. DEBUG_TRACE("%s", ebuf);
  14647. mg_free(ssl_mutexes);
  14648. return 0;
  14649. }
  14650. }
  14651. }
  14652. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14653. CRYPTO_set_id_callback(&mg_current_thread_id);
  14654. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14655. #if !defined(NO_SSL_DL)
  14656. if (!ssllib_dll_handle) {
  14657. ssllib_dll_handle =
  14658. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14659. if (!ssllib_dll_handle) {
  14660. #if !defined(OPENSSL_API_1_1)
  14661. mg_free(ssl_mutexes);
  14662. #endif
  14663. DEBUG_TRACE("%s", ebuf);
  14664. return 0;
  14665. }
  14666. }
  14667. #endif /* NO_SSL_DL */
  14668. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14669. && !defined(NO_SSL_DL)
  14670. /* Initialize SSL library */
  14671. OPENSSL_init_ssl(0, NULL);
  14672. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14673. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14674. NULL);
  14675. #else
  14676. /* Initialize SSL library */
  14677. SSL_library_init();
  14678. SSL_load_error_strings();
  14679. #endif
  14680. return 1;
  14681. }
  14682. static int
  14683. ssl_use_pem_file(struct mg_context *phys_ctx,
  14684. struct mg_domain_context *dom_ctx,
  14685. const char *pem,
  14686. const char *chain)
  14687. {
  14688. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14689. mg_cry_ctx_internal(phys_ctx,
  14690. "%s: cannot open certificate file %s: %s",
  14691. __func__,
  14692. pem,
  14693. ssl_error());
  14694. return 0;
  14695. }
  14696. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14697. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14698. mg_cry_ctx_internal(phys_ctx,
  14699. "%s: cannot open private key file %s: %s",
  14700. __func__,
  14701. pem,
  14702. ssl_error());
  14703. return 0;
  14704. }
  14705. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14706. mg_cry_ctx_internal(phys_ctx,
  14707. "%s: certificate and private key do not match: %s",
  14708. __func__,
  14709. pem);
  14710. return 0;
  14711. }
  14712. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14713. * chain files that contain private keys and certificates in
  14714. * SSL_CTX_use_certificate_chain_file.
  14715. * The CivetWeb-Server used pem-Files that contained both information.
  14716. * In order to make wolfSSL work, it is split in two files.
  14717. * One file that contains key and certificate used by the server and
  14718. * an optional chain file for the ssl stack.
  14719. */
  14720. if (chain) {
  14721. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14722. mg_cry_ctx_internal(phys_ctx,
  14723. "%s: cannot use certificate chain file %s: %s",
  14724. __func__,
  14725. chain,
  14726. ssl_error());
  14727. return 0;
  14728. }
  14729. }
  14730. return 1;
  14731. }
  14732. #if defined(OPENSSL_API_1_1)
  14733. static unsigned long
  14734. ssl_get_protocol(int version_id)
  14735. {
  14736. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14737. if (version_id > 0)
  14738. ret |= SSL_OP_NO_SSLv2;
  14739. if (version_id > 1)
  14740. ret |= SSL_OP_NO_SSLv3;
  14741. if (version_id > 2)
  14742. ret |= SSL_OP_NO_TLSv1;
  14743. if (version_id > 3)
  14744. ret |= SSL_OP_NO_TLSv1_1;
  14745. if (version_id > 4)
  14746. ret |= SSL_OP_NO_TLSv1_2;
  14747. #if defined(SSL_OP_NO_TLSv1_3)
  14748. if (version_id > 5)
  14749. ret |= SSL_OP_NO_TLSv1_3;
  14750. #endif
  14751. return ret;
  14752. }
  14753. #else
  14754. static long
  14755. ssl_get_protocol(int version_id)
  14756. {
  14757. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14758. if (version_id > 0)
  14759. ret |= SSL_OP_NO_SSLv2;
  14760. if (version_id > 1)
  14761. ret |= SSL_OP_NO_SSLv3;
  14762. if (version_id > 2)
  14763. ret |= SSL_OP_NO_TLSv1;
  14764. if (version_id > 3)
  14765. ret |= SSL_OP_NO_TLSv1_1;
  14766. if (version_id > 4)
  14767. ret |= SSL_OP_NO_TLSv1_2;
  14768. #if defined(SSL_OP_NO_TLSv1_3)
  14769. if (version_id > 5)
  14770. ret |= SSL_OP_NO_TLSv1_3;
  14771. #endif
  14772. return (long)ret;
  14773. }
  14774. #endif /* OPENSSL_API_1_1 */
  14775. /* SSL callback documentation:
  14776. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14777. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14778. * https://linux.die.net/man/3/ssl_set_info_callback */
  14779. /* Note: There is no "const" for the first argument in the documentation
  14780. * examples, however some (maybe most, but not all) headers of OpenSSL
  14781. * versions / OpenSSL compatibility layers have it. Having a different
  14782. * definition will cause a warning in C and an error in C++. Use "const SSL
  14783. * *", while automatic conversion from "SSL *" works for all compilers,
  14784. * but not other way around */
  14785. static void
  14786. ssl_info_callback(const SSL *ssl, int what, int ret)
  14787. {
  14788. (void)ret;
  14789. if (what & SSL_CB_HANDSHAKE_START) {
  14790. SSL_get_app_data(ssl);
  14791. }
  14792. if (what & SSL_CB_HANDSHAKE_DONE) {
  14793. /* TODO: check for openSSL 1.1 */
  14794. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14795. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14796. }
  14797. }
  14798. static int
  14799. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14800. {
  14801. #if defined(GCC_DIAGNOSTIC)
  14802. #pragma GCC diagnostic push
  14803. #pragma GCC diagnostic ignored "-Wcast-align"
  14804. #endif /* defined(GCC_DIAGNOSTIC) */
  14805. /* We used an aligned pointer in SSL_set_app_data */
  14806. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14807. #if defined(GCC_DIAGNOSTIC)
  14808. #pragma GCC diagnostic pop
  14809. #endif /* defined(GCC_DIAGNOSTIC) */
  14810. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14811. (void)ad;
  14812. (void)arg;
  14813. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14814. DEBUG_ASSERT(0);
  14815. return SSL_TLSEXT_ERR_NOACK;
  14816. }
  14817. conn->dom_ctx = &(conn->phys_ctx->dd);
  14818. /* Old clients (Win XP) will not support SNI. Then, there
  14819. * is no server name available in the request - we can
  14820. * only work with the default certificate.
  14821. * Multiple HTTPS hosts on one IP+port are only possible
  14822. * with a certificate containing all alternative names.
  14823. */
  14824. if ((servername == NULL) || (*servername == 0)) {
  14825. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14826. mg_lock_context(conn->phys_ctx);
  14827. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14828. mg_unlock_context(conn->phys_ctx);
  14829. return SSL_TLSEXT_ERR_NOACK;
  14830. }
  14831. DEBUG_TRACE("TLS connection to host %s", servername);
  14832. while (conn->dom_ctx) {
  14833. if (!mg_strcasecmp(servername,
  14834. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14835. /* Found matching domain */
  14836. DEBUG_TRACE("TLS domain %s found",
  14837. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14838. break;
  14839. }
  14840. mg_lock_context(conn->phys_ctx);
  14841. conn->dom_ctx = conn->dom_ctx->next;
  14842. mg_unlock_context(conn->phys_ctx);
  14843. }
  14844. if (conn->dom_ctx == NULL) {
  14845. /* Default domain */
  14846. DEBUG_TRACE("TLS default domain %s used",
  14847. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14848. conn->dom_ctx = &(conn->phys_ctx->dd);
  14849. }
  14850. mg_lock_context(conn->phys_ctx);
  14851. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14852. mg_unlock_context(conn->phys_ctx);
  14853. return SSL_TLSEXT_ERR_OK;
  14854. }
  14855. #if defined(USE_ALPN)
  14856. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14857. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14858. alpn_proto_list + 3 + 8,
  14859. NULL};
  14860. #if defined(USE_HTTP2)
  14861. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14862. alpn_proto_list + 3,
  14863. alpn_proto_list + 3 + 8,
  14864. NULL};
  14865. #endif
  14866. static int
  14867. alpn_select_cb(SSL *ssl,
  14868. const unsigned char **out,
  14869. unsigned char *outlen,
  14870. const unsigned char *in,
  14871. unsigned int inlen,
  14872. void *arg)
  14873. {
  14874. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14875. unsigned int i, j, enable_http2 = 0;
  14876. const char **alpn_proto_order = alpn_proto_order_http1;
  14877. struct mg_workerTLS *tls =
  14878. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14879. (void)ssl;
  14880. if (tls == NULL) {
  14881. /* Need to store protocol in Thread Local Storage */
  14882. /* If there is no Thread Local Storage, don't use ALPN */
  14883. return SSL_TLSEXT_ERR_NOACK;
  14884. }
  14885. #if defined(USE_HTTP2)
  14886. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14887. if (enable_http2) {
  14888. alpn_proto_order = alpn_proto_order_http2;
  14889. }
  14890. #endif
  14891. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14892. /* check all accepted protocols in this order */
  14893. const char *alpn_proto = alpn_proto_order[j];
  14894. /* search input for matching protocol */
  14895. for (i = 0; i < inlen; i++) {
  14896. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14897. *out = in + i + 1;
  14898. *outlen = in[i];
  14899. tls->alpn_proto = alpn_proto;
  14900. return SSL_TLSEXT_ERR_OK;
  14901. }
  14902. }
  14903. }
  14904. /* Nothing found */
  14905. return SSL_TLSEXT_ERR_NOACK;
  14906. }
  14907. static int
  14908. next_protos_advertised_cb(SSL *ssl,
  14909. const unsigned char **data,
  14910. unsigned int *len,
  14911. void *arg)
  14912. {
  14913. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14914. *data = (const unsigned char *)alpn_proto_list;
  14915. *len = (unsigned int)strlen((const char *)data);
  14916. (void)ssl;
  14917. (void)dom_ctx;
  14918. return SSL_TLSEXT_ERR_OK;
  14919. }
  14920. static int
  14921. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14922. {
  14923. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14924. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14925. (const unsigned char *)alpn_proto_list,
  14926. alpn_len);
  14927. if (ret != 0) {
  14928. mg_cry_ctx_internal(phys_ctx,
  14929. "SSL_CTX_set_alpn_protos error: %s",
  14930. ssl_error());
  14931. }
  14932. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14933. alpn_select_cb,
  14934. (void *)dom_ctx);
  14935. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14936. next_protos_advertised_cb,
  14937. (void *)dom_ctx);
  14938. return ret;
  14939. }
  14940. #endif
  14941. /* Setup SSL CTX as required by CivetWeb */
  14942. static int
  14943. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14944. struct mg_domain_context *dom_ctx,
  14945. const char *pem,
  14946. const char *chain)
  14947. {
  14948. int callback_ret;
  14949. int should_verify_peer;
  14950. int peer_certificate_optional;
  14951. const char *ca_path;
  14952. const char *ca_file;
  14953. int use_default_verify_paths;
  14954. int verify_depth;
  14955. struct timespec now_mt;
  14956. md5_byte_t ssl_context_id[16];
  14957. md5_state_t md5state;
  14958. int protocol_ver;
  14959. int ssl_cache_timeout;
  14960. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14961. && !defined(NO_SSL_DL)
  14962. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14963. mg_cry_ctx_internal(phys_ctx,
  14964. "SSL_CTX_new (server) error: %s",
  14965. ssl_error());
  14966. return 0;
  14967. }
  14968. #else
  14969. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_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. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14976. #if defined(SSL_OP_NO_TLSv1_3)
  14977. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14978. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14979. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14980. | SSL_OP_NO_TLSv1_3);
  14981. #else
  14982. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14983. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14984. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14985. #endif
  14986. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14987. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14988. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14989. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14990. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14991. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14992. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14993. #if defined(SSL_OP_NO_RENEGOTIATION)
  14994. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14995. #endif
  14996. #if !defined(NO_SSL_DL)
  14997. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14998. #endif /* NO_SSL_DL */
  14999. /* In SSL documentation examples callback defined without const
  15000. * specifier 'void (*)(SSL *, int, int)' See:
  15001. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15002. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15003. * But in the source code const SSL is used:
  15004. * 'void (*)(const SSL *, int, int)' See:
  15005. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15006. * Problem about wrong documentation described, but not resolved:
  15007. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15008. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15009. * But when compiled with modern C++ compiler, correct const should be
  15010. * provided
  15011. */
  15012. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15013. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15014. ssl_servername_callback);
  15015. /* If a callback has been specified, call it. */
  15016. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15017. ? 0
  15018. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15019. phys_ctx->user_data));
  15020. /* If callback returns 0, civetweb sets up the SSL certificate.
  15021. * If it returns 1, civetweb assumes the callback already did this.
  15022. * If it returns -1, initializing ssl fails. */
  15023. if (callback_ret < 0) {
  15024. mg_cry_ctx_internal(phys_ctx,
  15025. "SSL callback returned error: %i",
  15026. callback_ret);
  15027. return 0;
  15028. }
  15029. if (callback_ret > 0) {
  15030. /* Callback did everything. */
  15031. return 1;
  15032. }
  15033. /* If a domain callback has been specified, call it. */
  15034. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15035. ? 0
  15036. : (phys_ctx->callbacks.init_ssl_domain(
  15037. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15038. dom_ctx->ssl_ctx,
  15039. phys_ctx->user_data));
  15040. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15041. * If it returns 1, civetweb assumes the callback already did this.
  15042. * If it returns -1, initializing ssl fails. */
  15043. if (callback_ret < 0) {
  15044. mg_cry_ctx_internal(phys_ctx,
  15045. "Domain SSL callback returned error: %i",
  15046. callback_ret);
  15047. return 0;
  15048. }
  15049. if (callback_ret > 0) {
  15050. /* Domain callback did everything. */
  15051. return 1;
  15052. }
  15053. /* Use some combination of start time, domain and port as a SSL
  15054. * context ID. This should be unique on the current machine. */
  15055. md5_init(&md5state);
  15056. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15057. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15058. md5_append(&md5state,
  15059. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15060. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15061. md5_append(&md5state,
  15062. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15063. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15064. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15065. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15066. md5_finish(&md5state, ssl_context_id);
  15067. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15068. (unsigned char *)ssl_context_id,
  15069. sizeof(ssl_context_id));
  15070. if (pem != NULL) {
  15071. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15072. return 0;
  15073. }
  15074. }
  15075. /* Should we support client certificates? */
  15076. /* Default is "no". */
  15077. should_verify_peer = 0;
  15078. peer_certificate_optional = 0;
  15079. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15080. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15081. /* Yes, they are mandatory */
  15082. should_verify_peer = 1;
  15083. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15084. "optional")
  15085. == 0) {
  15086. /* Yes, they are optional */
  15087. should_verify_peer = 1;
  15088. peer_certificate_optional = 1;
  15089. }
  15090. }
  15091. use_default_verify_paths =
  15092. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15093. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15094. == 0);
  15095. if (should_verify_peer) {
  15096. ca_path = dom_ctx->config[SSL_CA_PATH];
  15097. ca_file = dom_ctx->config[SSL_CA_FILE];
  15098. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15099. != 1) {
  15100. mg_cry_ctx_internal(phys_ctx,
  15101. "SSL_CTX_load_verify_locations error: %s "
  15102. "ssl_verify_peer requires setting "
  15103. "either ssl_ca_path or ssl_ca_file. "
  15104. "Is any of them present in the "
  15105. ".conf file?",
  15106. ssl_error());
  15107. return 0;
  15108. }
  15109. if (peer_certificate_optional) {
  15110. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15111. } else {
  15112. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15113. SSL_VERIFY_PEER
  15114. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15115. NULL);
  15116. }
  15117. if (use_default_verify_paths
  15118. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15119. mg_cry_ctx_internal(phys_ctx,
  15120. "SSL_CTX_set_default_verify_paths error: %s",
  15121. ssl_error());
  15122. return 0;
  15123. }
  15124. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15125. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15126. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15127. }
  15128. }
  15129. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15130. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15131. dom_ctx->config[SSL_CIPHER_LIST])
  15132. != 1) {
  15133. mg_cry_ctx_internal(phys_ctx,
  15134. "SSL_CTX_set_cipher_list error: %s",
  15135. ssl_error());
  15136. }
  15137. }
  15138. /* SSL session caching */
  15139. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15140. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15141. : 0);
  15142. if (ssl_cache_timeout > 0) {
  15143. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15144. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15145. * default */
  15146. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15147. }
  15148. #if defined(USE_ALPN)
  15149. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15150. #if !defined(NO_SSL_DL)
  15151. if (!tls_feature_missing[TLS_ALPN])
  15152. #endif
  15153. {
  15154. init_alpn(phys_ctx, dom_ctx);
  15155. }
  15156. #endif
  15157. return 1;
  15158. }
  15159. /* Check if SSL is required.
  15160. * If so, dynamically load SSL library
  15161. * and set up ctx->ssl_ctx pointer. */
  15162. static int
  15163. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15164. {
  15165. void *ssl_ctx = 0;
  15166. int callback_ret;
  15167. const char *pem;
  15168. const char *chain;
  15169. char ebuf[128];
  15170. if (!phys_ctx) {
  15171. return 0;
  15172. }
  15173. if (!dom_ctx) {
  15174. dom_ctx = &(phys_ctx->dd);
  15175. }
  15176. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15177. /* No SSL port is set. No need to setup SSL. */
  15178. return 1;
  15179. }
  15180. /* Check for external SSL_CTX */
  15181. callback_ret =
  15182. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15183. ? 0
  15184. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15185. phys_ctx->user_data));
  15186. if (callback_ret < 0) {
  15187. /* Callback exists and returns <0: Initializing failed. */
  15188. mg_cry_ctx_internal(phys_ctx,
  15189. "external_ssl_ctx callback returned error: %i",
  15190. callback_ret);
  15191. return 0;
  15192. } else if (callback_ret > 0) {
  15193. /* Callback exists and returns >0: Initializing complete,
  15194. * civetweb should not modify the SSL context. */
  15195. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15196. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15197. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15198. return 0;
  15199. }
  15200. return 1;
  15201. }
  15202. /* If the callback does not exist or return 0, civetweb must initialize
  15203. * the SSL context. Handle "domain" callback next. */
  15204. /* Check for external domain SSL_CTX callback. */
  15205. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15206. ? 0
  15207. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15208. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15209. &ssl_ctx,
  15210. phys_ctx->user_data));
  15211. if (callback_ret < 0) {
  15212. /* Callback < 0: Error. Abort init. */
  15213. mg_cry_ctx_internal(
  15214. phys_ctx,
  15215. "external_ssl_ctx_domain callback returned error: %i",
  15216. callback_ret);
  15217. return 0;
  15218. } else if (callback_ret > 0) {
  15219. /* Callback > 0: Consider init done. */
  15220. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15221. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15222. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15223. return 0;
  15224. }
  15225. return 1;
  15226. }
  15227. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15228. * 0, CivetWeb should continue initializing SSL */
  15229. /* If PEM file is not specified and the init_ssl callbacks
  15230. * are not specified, setup will fail. */
  15231. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15232. && (phys_ctx->callbacks.init_ssl == NULL)
  15233. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15234. /* No certificate and no init_ssl callbacks:
  15235. * Essential data to set up TLS is missing.
  15236. */
  15237. mg_cry_ctx_internal(phys_ctx,
  15238. "Initializing SSL failed: -%s is not set",
  15239. config_options[SSL_CERTIFICATE].name);
  15240. return 0;
  15241. }
  15242. /* If a certificate chain is configured, use it. */
  15243. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15244. if (chain == NULL) {
  15245. /* Default: certificate chain in PEM file */
  15246. chain = pem;
  15247. }
  15248. if ((chain != NULL) && (*chain == 0)) {
  15249. /* If the chain is an empty string, don't use it. */
  15250. chain = NULL;
  15251. }
  15252. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15253. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15254. return 0;
  15255. }
  15256. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15257. }
  15258. static void
  15259. uninitialize_openssl(void)
  15260. {
  15261. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15262. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15263. /* Shutdown according to
  15264. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15265. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15266. */
  15267. CONF_modules_unload(1);
  15268. #else
  15269. int i;
  15270. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15271. /* Shutdown according to
  15272. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15273. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15274. */
  15275. CRYPTO_set_locking_callback(NULL);
  15276. CRYPTO_set_id_callback(NULL);
  15277. ENGINE_cleanup();
  15278. CONF_modules_unload(1);
  15279. ERR_free_strings();
  15280. EVP_cleanup();
  15281. CRYPTO_cleanup_all_ex_data();
  15282. OPENSSL_REMOVE_THREAD_STATE();
  15283. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15284. pthread_mutex_destroy(&ssl_mutexes[i]);
  15285. }
  15286. mg_free(ssl_mutexes);
  15287. ssl_mutexes = NULL;
  15288. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15289. }
  15290. }
  15291. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15292. #if !defined(NO_FILESYSTEMS)
  15293. static int
  15294. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15295. {
  15296. if (phys_ctx) {
  15297. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15298. const char *path;
  15299. struct mg_connection fc;
  15300. if (!dom_ctx) {
  15301. dom_ctx = &(phys_ctx->dd);
  15302. }
  15303. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15304. if ((path != NULL)
  15305. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15306. mg_cry_ctx_internal(phys_ctx,
  15307. "Cannot open %s: %s",
  15308. path,
  15309. strerror(ERRNO));
  15310. return 0;
  15311. }
  15312. return 1;
  15313. }
  15314. return 0;
  15315. }
  15316. #endif /* NO_FILESYSTEMS */
  15317. static int
  15318. set_acl_option(struct mg_context *phys_ctx)
  15319. {
  15320. union usa sa;
  15321. memset(&sa, 0, sizeof(sa));
  15322. #if defined(USE_IPV6)
  15323. sa.sin6.sin6_family = AF_INET6;
  15324. #else
  15325. sa.sin.sin_family = AF_INET;
  15326. #endif
  15327. return check_acl(phys_ctx, &sa) != -1;
  15328. }
  15329. static void
  15330. reset_per_request_attributes(struct mg_connection *conn)
  15331. {
  15332. if (!conn) {
  15333. return;
  15334. }
  15335. conn->num_bytes_sent = conn->consumed_content = 0;
  15336. conn->path_info = NULL;
  15337. conn->status_code = -1;
  15338. conn->content_len = -1;
  15339. conn->is_chunked = 0;
  15340. conn->must_close = 0;
  15341. conn->request_len = 0;
  15342. conn->request_state = 0;
  15343. conn->throttle = 0;
  15344. conn->accept_gzip = 0;
  15345. conn->response_info.content_length = conn->request_info.content_length = -1;
  15346. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15347. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15348. conn->response_info.status_text = NULL;
  15349. conn->response_info.status_code = 0;
  15350. conn->request_info.remote_user = NULL;
  15351. conn->request_info.request_method = NULL;
  15352. conn->request_info.request_uri = NULL;
  15353. /* Free cleaned local URI (if any) */
  15354. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15355. mg_free((void *)conn->request_info.local_uri);
  15356. conn->request_info.local_uri = NULL;
  15357. }
  15358. conn->request_info.local_uri = NULL;
  15359. #if defined(USE_SERVER_STATS)
  15360. conn->processing_time = 0;
  15361. #endif
  15362. }
  15363. static int
  15364. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15365. {
  15366. if ((so->lsa.sa.sa_family == AF_INET)
  15367. || (so->lsa.sa.sa_family == AF_INET6)) {
  15368. /* Only for TCP sockets */
  15369. if (setsockopt(so->sock,
  15370. IPPROTO_TCP,
  15371. TCP_NODELAY,
  15372. (SOCK_OPT_TYPE)&nodelay_on,
  15373. sizeof(nodelay_on))
  15374. != 0) {
  15375. /* Error */
  15376. return 1;
  15377. }
  15378. }
  15379. /* OK */
  15380. return 0;
  15381. }
  15382. #if !defined(__ZEPHYR__)
  15383. static void
  15384. close_socket_gracefully(struct mg_connection *conn)
  15385. {
  15386. #if defined(_WIN32)
  15387. char buf[MG_BUF_LEN];
  15388. int n;
  15389. #endif
  15390. struct linger linger;
  15391. int error_code = 0;
  15392. int linger_timeout = -2;
  15393. socklen_t opt_len = sizeof(error_code);
  15394. if (!conn) {
  15395. return;
  15396. }
  15397. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15398. * "Note that enabling a nonzero timeout on a nonblocking socket
  15399. * is not recommended.", so set it to blocking now */
  15400. set_blocking_mode(conn->client.sock);
  15401. /* Send FIN to the client */
  15402. shutdown(conn->client.sock, SHUTDOWN_WR);
  15403. #if defined(_WIN32)
  15404. /* Read and discard pending incoming data. If we do not do that and
  15405. * close
  15406. * the socket, the data in the send buffer may be discarded. This
  15407. * behaviour is seen on Windows, when client keeps sending data
  15408. * when server decides to close the connection; then when client
  15409. * does recv() it gets no data back. */
  15410. do {
  15411. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15412. } while (n > 0);
  15413. #endif
  15414. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15415. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15416. }
  15417. /* Set linger option according to configuration */
  15418. if (linger_timeout >= 0) {
  15419. /* Set linger option to avoid socket hanging out after close. This
  15420. * prevent ephemeral port exhaust problem under high QPS. */
  15421. linger.l_onoff = 1;
  15422. #if defined(_MSC_VER)
  15423. #pragma warning(push)
  15424. #pragma warning(disable : 4244)
  15425. #endif
  15426. #if defined(GCC_DIAGNOSTIC)
  15427. #pragma GCC diagnostic push
  15428. #pragma GCC diagnostic ignored "-Wconversion"
  15429. #endif
  15430. /* Data type of linger structure elements may differ,
  15431. * so we don't know what cast we need here.
  15432. * Disable type conversion warnings. */
  15433. linger.l_linger = (linger_timeout + 999) / 1000;
  15434. #if defined(GCC_DIAGNOSTIC)
  15435. #pragma GCC diagnostic pop
  15436. #endif
  15437. #if defined(_MSC_VER)
  15438. #pragma warning(pop)
  15439. #endif
  15440. } else {
  15441. linger.l_onoff = 0;
  15442. linger.l_linger = 0;
  15443. }
  15444. if (linger_timeout < -1) {
  15445. /* Default: don't configure any linger */
  15446. } else if (getsockopt(conn->client.sock,
  15447. SOL_SOCKET,
  15448. SO_ERROR,
  15449. #if defined(_WIN32) /* WinSock uses different data type here */
  15450. (char *)&error_code,
  15451. #else
  15452. &error_code,
  15453. #endif
  15454. &opt_len)
  15455. != 0) {
  15456. /* Cannot determine if socket is already closed. This should
  15457. * not occur and never did in a test. Log an error message
  15458. * and continue. */
  15459. mg_cry_internal(conn,
  15460. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15461. __func__,
  15462. strerror(ERRNO));
  15463. #if defined(_WIN32)
  15464. } else if (error_code == WSAECONNRESET) {
  15465. #else
  15466. } else if (error_code == ECONNRESET) {
  15467. #endif
  15468. /* Socket already closed by client/peer, close socket without linger
  15469. */
  15470. } else {
  15471. /* Set linger timeout */
  15472. if (setsockopt(conn->client.sock,
  15473. SOL_SOCKET,
  15474. SO_LINGER,
  15475. (char *)&linger,
  15476. sizeof(linger))
  15477. != 0) {
  15478. mg_cry_internal(
  15479. conn,
  15480. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15481. __func__,
  15482. linger.l_onoff,
  15483. linger.l_linger,
  15484. strerror(ERRNO));
  15485. }
  15486. }
  15487. /* Now we know that our FIN is ACK-ed, safe to close */
  15488. closesocket(conn->client.sock);
  15489. conn->client.sock = INVALID_SOCKET;
  15490. }
  15491. #endif
  15492. static void
  15493. close_connection(struct mg_connection *conn)
  15494. {
  15495. #if defined(USE_SERVER_STATS)
  15496. conn->conn_state = 6; /* to close */
  15497. #endif
  15498. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15499. if (conn->lua_websocket_state) {
  15500. lua_websocket_close(conn, conn->lua_websocket_state);
  15501. conn->lua_websocket_state = NULL;
  15502. }
  15503. #endif
  15504. mg_lock_connection(conn);
  15505. /* Set close flag, so keep-alive loops will stop */
  15506. conn->must_close = 1;
  15507. /* call the connection_close callback if assigned */
  15508. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15509. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15510. conn->phys_ctx->callbacks.connection_close(conn);
  15511. }
  15512. }
  15513. /* Reset user data, after close callback is called.
  15514. * Do not reuse it. If the user needs a destructor,
  15515. * it must be done in the connection_close callback. */
  15516. mg_set_user_connection_data(conn, NULL);
  15517. #if defined(USE_SERVER_STATS)
  15518. conn->conn_state = 7; /* closing */
  15519. #endif
  15520. #if defined(USE_MBEDTLS)
  15521. if (conn->ssl != NULL) {
  15522. mbed_ssl_close(conn->ssl);
  15523. conn->ssl = NULL;
  15524. }
  15525. #elif !defined(NO_SSL)
  15526. if (conn->ssl != NULL) {
  15527. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15528. */
  15529. SSL_shutdown(conn->ssl);
  15530. SSL_free(conn->ssl);
  15531. OPENSSL_REMOVE_THREAD_STATE();
  15532. conn->ssl = NULL;
  15533. }
  15534. #endif
  15535. if (conn->client.sock != INVALID_SOCKET) {
  15536. #if defined(__ZEPHYR__)
  15537. closesocket(conn->client.sock);
  15538. #else
  15539. close_socket_gracefully(conn);
  15540. #endif
  15541. conn->client.sock = INVALID_SOCKET;
  15542. }
  15543. /* call the connection_closed callback if assigned */
  15544. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15545. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15546. conn->phys_ctx->callbacks.connection_closed(conn);
  15547. }
  15548. }
  15549. mg_unlock_connection(conn);
  15550. #if defined(USE_SERVER_STATS)
  15551. conn->conn_state = 8; /* closed */
  15552. #endif
  15553. }
  15554. CIVETWEB_API void
  15555. mg_close_connection(struct mg_connection *conn)
  15556. {
  15557. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15558. return;
  15559. }
  15560. #if defined(USE_WEBSOCKET)
  15561. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15562. if (conn->in_websocket_handling) {
  15563. /* Set close flag, so the server thread can exit. */
  15564. conn->must_close = 1;
  15565. return;
  15566. }
  15567. }
  15568. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15569. unsigned int i;
  15570. /* client context: loops must end */
  15571. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15572. conn->must_close = 1;
  15573. /* We need to get the client thread out of the select/recv call
  15574. * here. */
  15575. /* Since we use a sleep quantum of some seconds to check for recv
  15576. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15577. /* join worker thread */
  15578. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15579. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15580. }
  15581. }
  15582. #endif /* defined(USE_WEBSOCKET) */
  15583. close_connection(conn);
  15584. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15585. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15586. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15587. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15588. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15589. }
  15590. #endif
  15591. #if defined(USE_WEBSOCKET)
  15592. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15593. mg_free(conn->phys_ctx->worker_threadids);
  15594. (void)pthread_mutex_destroy(&conn->mutex);
  15595. mg_free(conn);
  15596. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15597. (void)pthread_mutex_destroy(&conn->mutex);
  15598. mg_free(conn);
  15599. }
  15600. #else
  15601. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15602. (void)pthread_mutex_destroy(&conn->mutex);
  15603. mg_free(conn);
  15604. }
  15605. #endif /* defined(USE_WEBSOCKET) */
  15606. }
  15607. static struct mg_connection *
  15608. mg_connect_client_impl(const struct mg_client_options *client_options,
  15609. int use_ssl,
  15610. struct mg_init_data *init,
  15611. struct mg_error_data *error)
  15612. {
  15613. struct mg_connection *conn = NULL;
  15614. SOCKET sock;
  15615. union usa sa;
  15616. struct sockaddr *psa;
  15617. socklen_t len;
  15618. unsigned max_req_size =
  15619. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15620. /* Size of structures, aligned to 8 bytes */
  15621. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15622. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15623. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15624. (void)init; /* TODO: Implement required options */
  15625. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15626. if (error != NULL) {
  15627. error->code = MG_ERROR_DATA_CODE_OK;
  15628. error->code_sub = 0;
  15629. if (error->text_buffer_size > 0) {
  15630. error->text[0] = 0;
  15631. }
  15632. }
  15633. if (conn == NULL) {
  15634. if (error != NULL) {
  15635. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15636. error->code_sub = (unsigned)alloc_size;
  15637. mg_snprintf(NULL,
  15638. NULL, /* No truncation check for ebuf */
  15639. error->text,
  15640. error->text_buffer_size,
  15641. "calloc(): %s",
  15642. strerror(ERRNO));
  15643. }
  15644. return NULL;
  15645. }
  15646. #if defined(GCC_DIAGNOSTIC)
  15647. #pragma GCC diagnostic push
  15648. #pragma GCC diagnostic ignored "-Wcast-align"
  15649. #endif /* defined(GCC_DIAGNOSTIC) */
  15650. /* conn_size is aligned to 8 bytes */
  15651. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15652. #if defined(GCC_DIAGNOSTIC)
  15653. #pragma GCC diagnostic pop
  15654. #endif /* defined(GCC_DIAGNOSTIC) */
  15655. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15656. conn->buf_size = (int)max_req_size;
  15657. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15658. conn->dom_ctx = &(conn->phys_ctx->dd);
  15659. if (!connect_socket(conn->phys_ctx,
  15660. client_options->host,
  15661. client_options->port,
  15662. use_ssl,
  15663. error,
  15664. &sock,
  15665. &sa)) {
  15666. /* "error" will be set by connect_socket. */
  15667. /* free all memory and return NULL; */
  15668. mg_free(conn);
  15669. return NULL;
  15670. }
  15671. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15672. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15673. && !defined(NO_SSL_DL)
  15674. if (use_ssl
  15675. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15676. == NULL) {
  15677. if (error != NULL) {
  15678. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15679. mg_snprintf(NULL,
  15680. NULL, /* No truncation check for ebuf */
  15681. error->text,
  15682. error->text_buffer_size,
  15683. "SSL_CTX_new error: %s",
  15684. ssl_error());
  15685. }
  15686. closesocket(sock);
  15687. mg_free(conn);
  15688. return NULL;
  15689. }
  15690. #else
  15691. if (use_ssl
  15692. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15693. == NULL) {
  15694. if (error != NULL) {
  15695. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15696. mg_snprintf(NULL,
  15697. NULL, /* No truncation check for ebuf */
  15698. error->text,
  15699. error->text_buffer_size,
  15700. "SSL_CTX_new error: %s",
  15701. ssl_error());
  15702. }
  15703. closesocket(sock);
  15704. mg_free(conn);
  15705. return NULL;
  15706. }
  15707. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15708. #endif /* NO_SSL */
  15709. #if defined(USE_IPV6)
  15710. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15711. : sizeof(conn->client.rsa.sin6);
  15712. psa = (sa.sa.sa_family == AF_INET)
  15713. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15714. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15715. #else
  15716. len = sizeof(conn->client.rsa.sin);
  15717. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15718. #endif
  15719. conn->client.sock = sock;
  15720. conn->client.lsa = sa;
  15721. if (getsockname(sock, psa, &len) != 0) {
  15722. mg_cry_internal(conn,
  15723. "%s: getsockname() failed: %s",
  15724. __func__,
  15725. strerror(ERRNO));
  15726. }
  15727. conn->client.is_ssl = use_ssl ? 1 : 0;
  15728. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15729. if (error != NULL) {
  15730. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15731. error->code_sub = (unsigned)ERRNO;
  15732. mg_snprintf(NULL,
  15733. NULL, /* No truncation check for ebuf */
  15734. error->text,
  15735. error->text_buffer_size,
  15736. "Can not create mutex");
  15737. }
  15738. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15739. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15740. #endif
  15741. closesocket(sock);
  15742. mg_free(conn);
  15743. return NULL;
  15744. }
  15745. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15746. if (use_ssl) {
  15747. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15748. * SSL_CTX_set_verify call is needed to switch off server
  15749. * certificate checking, which is off by default in OpenSSL and
  15750. * on in yaSSL. */
  15751. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15752. * SSL_VERIFY_PEER, verify_ssl_server); */
  15753. if (client_options->client_cert) {
  15754. if (!ssl_use_pem_file(conn->phys_ctx,
  15755. conn->dom_ctx,
  15756. client_options->client_cert,
  15757. NULL)) {
  15758. if (error != NULL) {
  15759. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15760. mg_snprintf(NULL,
  15761. NULL, /* No truncation check for ebuf */
  15762. error->text,
  15763. error->text_buffer_size,
  15764. "Can not use SSL client certificate");
  15765. }
  15766. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15767. closesocket(sock);
  15768. mg_free(conn);
  15769. return NULL;
  15770. }
  15771. }
  15772. if (client_options->server_cert) {
  15773. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15774. client_options->server_cert,
  15775. NULL)
  15776. != 1) {
  15777. if (error != NULL) {
  15778. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15779. mg_snprintf(NULL,
  15780. NULL, /* No truncation check for ebuf */
  15781. error->text,
  15782. error->text_buffer_size,
  15783. "SSL_CTX_load_verify_locations error: %s",
  15784. ssl_error());
  15785. }
  15786. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15787. closesocket(sock);
  15788. mg_free(conn);
  15789. return NULL;
  15790. }
  15791. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15792. } else {
  15793. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15794. }
  15795. if (!sslize(conn, SSL_connect, client_options)) {
  15796. if (error != NULL) {
  15797. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15798. mg_snprintf(NULL,
  15799. NULL, /* No truncation check for ebuf */
  15800. error->text,
  15801. error->text_buffer_size,
  15802. "SSL connection error");
  15803. }
  15804. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15805. closesocket(sock);
  15806. mg_free(conn);
  15807. return NULL;
  15808. }
  15809. }
  15810. #endif
  15811. return conn;
  15812. }
  15813. CIVETWEB_API struct mg_connection *
  15814. mg_connect_client_secure(const struct mg_client_options *client_options,
  15815. char *error_buffer,
  15816. size_t error_buffer_size)
  15817. {
  15818. struct mg_init_data init;
  15819. struct mg_error_data error;
  15820. memset(&init, 0, sizeof(init));
  15821. memset(&error, 0, sizeof(error));
  15822. error.text_buffer_size = error_buffer_size;
  15823. error.text = error_buffer;
  15824. return mg_connect_client_impl(client_options, 1, &init, &error);
  15825. }
  15826. CIVETWEB_API struct mg_connection *
  15827. mg_connect_client(const char *host,
  15828. int port,
  15829. int use_ssl,
  15830. char *error_buffer,
  15831. size_t error_buffer_size)
  15832. {
  15833. struct mg_client_options opts;
  15834. struct mg_init_data init;
  15835. struct mg_error_data error;
  15836. memset(&init, 0, sizeof(init));
  15837. memset(&error, 0, sizeof(error));
  15838. error.text_buffer_size = error_buffer_size;
  15839. error.text = error_buffer;
  15840. memset(&opts, 0, sizeof(opts));
  15841. opts.host = host;
  15842. opts.port = port;
  15843. if (use_ssl) {
  15844. opts.host_name = host;
  15845. }
  15846. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15847. }
  15848. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15849. CIVETWEB_API struct mg_connection *
  15850. mg_connect_client2(const char *host,
  15851. const char *protocol,
  15852. int port,
  15853. const char *path,
  15854. struct mg_init_data *init,
  15855. struct mg_error_data *error)
  15856. {
  15857. (void)path;
  15858. int is_ssl, is_ws;
  15859. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15860. if (error != NULL) {
  15861. error->code = MG_ERROR_DATA_CODE_OK;
  15862. error->code_sub = 0;
  15863. if (error->text_buffer_size > 0) {
  15864. *error->text = 0;
  15865. }
  15866. }
  15867. if ((host == NULL) || (protocol == NULL)) {
  15868. if (error != NULL) {
  15869. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15870. mg_snprintf(NULL,
  15871. NULL, /* No truncation check for error buffers */
  15872. error->text,
  15873. error->text_buffer_size,
  15874. "%s",
  15875. "Invalid parameters");
  15876. }
  15877. return NULL;
  15878. }
  15879. /* check all known protocols */
  15880. if (!mg_strcasecmp(protocol, "http")) {
  15881. is_ssl = 0;
  15882. is_ws = 0;
  15883. } else if (!mg_strcasecmp(protocol, "https")) {
  15884. is_ssl = 1;
  15885. is_ws = 0;
  15886. #if defined(USE_WEBSOCKET)
  15887. } else if (!mg_strcasecmp(protocol, "ws")) {
  15888. is_ssl = 0;
  15889. is_ws = 1;
  15890. } else if (!mg_strcasecmp(protocol, "wss")) {
  15891. is_ssl = 1;
  15892. is_ws = 1;
  15893. #endif
  15894. } else {
  15895. if (error != NULL) {
  15896. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15897. mg_snprintf(NULL,
  15898. NULL, /* No truncation check for error buffers */
  15899. error->text,
  15900. error->text_buffer_size,
  15901. "Protocol %s not supported",
  15902. protocol);
  15903. }
  15904. return NULL;
  15905. }
  15906. /* TODO: The current implementation here just calls the old
  15907. * implementations, without using any new options. This is just a first
  15908. * step to test the new interfaces. */
  15909. #if defined(USE_WEBSOCKET)
  15910. if (is_ws) {
  15911. /* TODO: implement all options */
  15912. return mg_connect_websocket_client(
  15913. host,
  15914. port,
  15915. is_ssl,
  15916. ((error != NULL) ? error->text : NULL),
  15917. ((error != NULL) ? error->text_buffer_size : 0),
  15918. (path ? path : ""),
  15919. NULL /* TODO: origin */,
  15920. experimental_websocket_client_data_wrapper,
  15921. experimental_websocket_client_close_wrapper,
  15922. (void *)init->callbacks);
  15923. }
  15924. #else
  15925. (void)is_ws;
  15926. #endif
  15927. /* TODO: all additional options */
  15928. struct mg_client_options opts;
  15929. memset(&opts, 0, sizeof(opts));
  15930. opts.host = host;
  15931. opts.port = port;
  15932. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15933. }
  15934. #endif
  15935. static const struct {
  15936. const char *proto;
  15937. size_t proto_len;
  15938. unsigned default_port;
  15939. } abs_uri_protocols[] = {{"http://", 7, 80},
  15940. {"https://", 8, 443},
  15941. {"ws://", 5, 80},
  15942. {"wss://", 6, 443},
  15943. {NULL, 0, 0}};
  15944. /* Check if the uri is valid.
  15945. * return 0 for invalid uri,
  15946. * return 1 for *,
  15947. * return 2 for relative uri,
  15948. * return 3 for absolute uri without port,
  15949. * return 4 for absolute uri with port */
  15950. static int
  15951. get_uri_type(const char *uri)
  15952. {
  15953. int i;
  15954. const char *hostend, *portbegin;
  15955. char *portend;
  15956. unsigned long port;
  15957. /* According to the HTTP standard
  15958. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15959. * URI can be an asterisk (*) or should start with slash (relative uri),
  15960. * or it should start with the protocol (absolute uri). */
  15961. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15962. /* asterisk */
  15963. return 1;
  15964. }
  15965. /* Valid URIs according to RFC 3986
  15966. * (https://www.ietf.org/rfc/rfc3986.txt)
  15967. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15968. * and unreserved characters A-Z a-z 0-9 and -._~
  15969. * and % encoded symbols.
  15970. */
  15971. for (i = 0; uri[i] != 0; i++) {
  15972. if (uri[i] < 33) {
  15973. /* control characters and spaces are invalid */
  15974. return 0;
  15975. }
  15976. /* Allow everything else here (See #894) */
  15977. }
  15978. /* A relative uri starts with a / character */
  15979. if (uri[0] == '/') {
  15980. /* relative uri */
  15981. return 2;
  15982. }
  15983. /* It could be an absolute uri: */
  15984. /* This function only checks if the uri is valid, not if it is
  15985. * addressing the current server. So civetweb can also be used
  15986. * as a proxy server. */
  15987. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15988. if (mg_strncasecmp(uri,
  15989. abs_uri_protocols[i].proto,
  15990. abs_uri_protocols[i].proto_len)
  15991. == 0) {
  15992. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15993. if (!hostend) {
  15994. return 0;
  15995. }
  15996. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15997. if (!portbegin) {
  15998. return 3;
  15999. }
  16000. port = strtoul(portbegin + 1, &portend, 10);
  16001. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16002. return 0;
  16003. }
  16004. return 4;
  16005. }
  16006. }
  16007. return 0;
  16008. }
  16009. /* Return NULL or the relative uri at the current server */
  16010. static const char *
  16011. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16012. {
  16013. const char *server_domain;
  16014. size_t server_domain_len;
  16015. size_t request_domain_len = 0;
  16016. unsigned long port = 0;
  16017. int i, auth_domain_check_enabled;
  16018. const char *hostbegin = NULL;
  16019. const char *hostend = NULL;
  16020. const char *portbegin;
  16021. char *portend;
  16022. auth_domain_check_enabled =
  16023. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16024. /* DNS is case insensitive, so use case insensitive string compare here
  16025. */
  16026. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16027. if (mg_strncasecmp(uri,
  16028. abs_uri_protocols[i].proto,
  16029. abs_uri_protocols[i].proto_len)
  16030. == 0) {
  16031. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16032. hostend = strchr(hostbegin, '/');
  16033. if (!hostend) {
  16034. return 0;
  16035. }
  16036. portbegin = strchr(hostbegin, ':');
  16037. if ((!portbegin) || (portbegin > hostend)) {
  16038. port = abs_uri_protocols[i].default_port;
  16039. request_domain_len = (size_t)(hostend - hostbegin);
  16040. } else {
  16041. port = strtoul(portbegin + 1, &portend, 10);
  16042. if ((portend != hostend) || (port <= 0)
  16043. || !is_valid_port(port)) {
  16044. return 0;
  16045. }
  16046. request_domain_len = (size_t)(portbegin - hostbegin);
  16047. }
  16048. /* protocol found, port set */
  16049. break;
  16050. }
  16051. }
  16052. if (!port) {
  16053. /* port remains 0 if the protocol is not found */
  16054. return 0;
  16055. }
  16056. /* Check if the request is directed to a different server. */
  16057. /* First check if the port is the same. */
  16058. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16059. /* Request is directed to a different port */
  16060. return 0;
  16061. }
  16062. /* Finally check if the server corresponds to the authentication
  16063. * domain of the server (the server domain).
  16064. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16065. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16066. * but do not allow substrings (like
  16067. * http://notmydomain.com/path/file.ext
  16068. * or http://mydomain.com.fake/path/file.ext).
  16069. */
  16070. if (auth_domain_check_enabled) {
  16071. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16072. server_domain_len = strlen(server_domain);
  16073. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16074. return 0;
  16075. }
  16076. if ((request_domain_len == server_domain_len)
  16077. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16078. /* Request is directed to this server - full name match. */
  16079. } else {
  16080. if (request_domain_len < (server_domain_len + 2)) {
  16081. /* Request is directed to another server: The server name
  16082. * is longer than the request name.
  16083. * Drop this case here to avoid overflows in the
  16084. * following checks. */
  16085. return 0;
  16086. }
  16087. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16088. /* Request is directed to another server: It could be a
  16089. * substring
  16090. * like notmyserver.com */
  16091. return 0;
  16092. }
  16093. if (0
  16094. != memcmp(server_domain,
  16095. hostbegin + request_domain_len - server_domain_len,
  16096. server_domain_len)) {
  16097. /* Request is directed to another server:
  16098. * The server name is different. */
  16099. return 0;
  16100. }
  16101. }
  16102. }
  16103. return hostend;
  16104. }
  16105. static int
  16106. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16107. {
  16108. if (ebuf_len > 0) {
  16109. ebuf[0] = '\0';
  16110. }
  16111. *err = 0;
  16112. reset_per_request_attributes(conn);
  16113. if (!conn) {
  16114. mg_snprintf(conn,
  16115. NULL, /* No truncation check for ebuf */
  16116. ebuf,
  16117. ebuf_len,
  16118. "%s",
  16119. "Internal error");
  16120. *err = 500;
  16121. return 0;
  16122. }
  16123. /* Set the time the request was received. This value should be used for
  16124. * timeouts. */
  16125. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16126. conn->request_len =
  16127. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16128. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16129. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16130. mg_snprintf(conn,
  16131. NULL, /* No truncation check for ebuf */
  16132. ebuf,
  16133. ebuf_len,
  16134. "%s",
  16135. "Invalid message size");
  16136. *err = 500;
  16137. return 0;
  16138. }
  16139. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16140. mg_snprintf(conn,
  16141. NULL, /* No truncation check for ebuf */
  16142. ebuf,
  16143. ebuf_len,
  16144. "%s",
  16145. "Message too large");
  16146. *err = 413;
  16147. return 0;
  16148. }
  16149. if (conn->request_len <= 0) {
  16150. if (conn->data_len > 0) {
  16151. mg_snprintf(conn,
  16152. NULL, /* No truncation check for ebuf */
  16153. ebuf,
  16154. ebuf_len,
  16155. "%s",
  16156. "Malformed message");
  16157. *err = 400;
  16158. } else {
  16159. /* Server did not recv anything -> just close the connection */
  16160. conn->must_close = 1;
  16161. mg_snprintf(conn,
  16162. NULL, /* No truncation check for ebuf */
  16163. ebuf,
  16164. ebuf_len,
  16165. "%s",
  16166. "No data received");
  16167. *err = 0;
  16168. }
  16169. return 0;
  16170. }
  16171. return 1;
  16172. }
  16173. static int
  16174. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16175. {
  16176. const char *cl;
  16177. conn->connection_type =
  16178. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16179. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16180. return 0;
  16181. }
  16182. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16183. <= 0) {
  16184. mg_snprintf(conn,
  16185. NULL, /* No truncation check for ebuf */
  16186. ebuf,
  16187. ebuf_len,
  16188. "%s",
  16189. "Bad request");
  16190. *err = 400;
  16191. return 0;
  16192. }
  16193. /* Message is a valid request */
  16194. if (!switch_domain_context(conn)) {
  16195. mg_snprintf(conn,
  16196. NULL, /* No truncation check for ebuf */
  16197. ebuf,
  16198. ebuf_len,
  16199. "%s",
  16200. "Bad request: Host mismatch");
  16201. *err = 400;
  16202. return 0;
  16203. }
  16204. #if USE_ZLIB
  16205. if (((cl = get_header(conn->request_info.http_headers,
  16206. conn->request_info.num_headers,
  16207. "Accept-Encoding"))
  16208. != NULL)
  16209. && strstr(cl, "gzip")) {
  16210. conn->accept_gzip = 1;
  16211. }
  16212. #endif
  16213. if (((cl = get_header(conn->request_info.http_headers,
  16214. conn->request_info.num_headers,
  16215. "Transfer-Encoding"))
  16216. != NULL)
  16217. && mg_strcasecmp(cl, "identity")) {
  16218. if (mg_strcasecmp(cl, "chunked")) {
  16219. mg_snprintf(conn,
  16220. NULL, /* No truncation check for ebuf */
  16221. ebuf,
  16222. ebuf_len,
  16223. "%s",
  16224. "Bad request");
  16225. *err = 400;
  16226. return 0;
  16227. }
  16228. conn->is_chunked = 1;
  16229. conn->content_len = 0; /* not yet read */
  16230. } else if ((cl = get_header(conn->request_info.http_headers,
  16231. conn->request_info.num_headers,
  16232. "Content-Length"))
  16233. != NULL) {
  16234. /* Request has content length set */
  16235. char *endptr = NULL;
  16236. conn->content_len = strtoll(cl, &endptr, 10);
  16237. if ((endptr == cl) || (conn->content_len < 0)) {
  16238. mg_snprintf(conn,
  16239. NULL, /* No truncation check for ebuf */
  16240. ebuf,
  16241. ebuf_len,
  16242. "%s",
  16243. "Bad request");
  16244. *err = 411;
  16245. return 0;
  16246. }
  16247. /* Publish the content length back to the request info. */
  16248. conn->request_info.content_length = conn->content_len;
  16249. } else {
  16250. /* There is no exception, see RFC7230. */
  16251. conn->content_len = 0;
  16252. }
  16253. return 1;
  16254. }
  16255. /* conn is assumed to be valid in this internal function */
  16256. static int
  16257. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16258. {
  16259. const char *cl;
  16260. conn->connection_type =
  16261. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16262. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16263. return 0;
  16264. }
  16265. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16266. <= 0) {
  16267. mg_snprintf(conn,
  16268. NULL, /* No truncation check for ebuf */
  16269. ebuf,
  16270. ebuf_len,
  16271. "%s",
  16272. "Bad response");
  16273. *err = 400;
  16274. return 0;
  16275. }
  16276. /* Message is a valid response */
  16277. if (((cl = get_header(conn->response_info.http_headers,
  16278. conn->response_info.num_headers,
  16279. "Transfer-Encoding"))
  16280. != NULL)
  16281. && mg_strcasecmp(cl, "identity")) {
  16282. if (mg_strcasecmp(cl, "chunked")) {
  16283. mg_snprintf(conn,
  16284. NULL, /* No truncation check for ebuf */
  16285. ebuf,
  16286. ebuf_len,
  16287. "%s",
  16288. "Bad request");
  16289. *err = 400;
  16290. return 0;
  16291. }
  16292. conn->is_chunked = 1;
  16293. conn->content_len = 0; /* not yet read */
  16294. } else if ((cl = get_header(conn->response_info.http_headers,
  16295. conn->response_info.num_headers,
  16296. "Content-Length"))
  16297. != NULL) {
  16298. char *endptr = NULL;
  16299. conn->content_len = strtoll(cl, &endptr, 10);
  16300. if ((endptr == cl) || (conn->content_len < 0)) {
  16301. mg_snprintf(conn,
  16302. NULL, /* No truncation check for ebuf */
  16303. ebuf,
  16304. ebuf_len,
  16305. "%s",
  16306. "Bad request");
  16307. *err = 411;
  16308. return 0;
  16309. }
  16310. /* Publish the content length back to the response info. */
  16311. conn->response_info.content_length = conn->content_len;
  16312. /* TODO: check if it is still used in response_info */
  16313. conn->request_info.content_length = conn->content_len;
  16314. /* TODO: we should also consider HEAD method */
  16315. if (conn->response_info.status_code == 304) {
  16316. conn->content_len = 0;
  16317. }
  16318. } else {
  16319. /* TODO: we should also consider HEAD method */
  16320. if (((conn->response_info.status_code >= 100)
  16321. && (conn->response_info.status_code <= 199))
  16322. || (conn->response_info.status_code == 204)
  16323. || (conn->response_info.status_code == 304)) {
  16324. conn->content_len = 0;
  16325. } else {
  16326. conn->content_len = -1; /* unknown content length */
  16327. }
  16328. }
  16329. return 1;
  16330. }
  16331. CIVETWEB_API int
  16332. mg_get_response(struct mg_connection *conn,
  16333. char *ebuf,
  16334. size_t ebuf_len,
  16335. int timeout)
  16336. {
  16337. int err, ret;
  16338. char txt[32]; /* will not overflow */
  16339. char *save_timeout;
  16340. char *new_timeout;
  16341. if (ebuf_len > 0) {
  16342. ebuf[0] = '\0';
  16343. }
  16344. if (!conn) {
  16345. mg_snprintf(conn,
  16346. NULL, /* No truncation check for ebuf */
  16347. ebuf,
  16348. ebuf_len,
  16349. "%s",
  16350. "Parameter error");
  16351. return -1;
  16352. }
  16353. /* Reset the previous responses */
  16354. conn->data_len = 0;
  16355. /* Implementation of API function for HTTP clients */
  16356. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16357. if (timeout >= 0) {
  16358. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16359. new_timeout = txt;
  16360. } else {
  16361. new_timeout = NULL;
  16362. }
  16363. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16364. ret = get_response(conn, ebuf, ebuf_len, &err);
  16365. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16366. /* TODO: here, the URI is the http response code */
  16367. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16368. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16369. /* TODO (mid): Define proper return values - maybe return length?
  16370. * For the first test use <0 for error and >0 for OK */
  16371. return (ret == 0) ? -1 : +1;
  16372. }
  16373. CIVETWEB_API struct mg_connection *
  16374. mg_download(const char *host,
  16375. int port,
  16376. int use_ssl,
  16377. char *ebuf,
  16378. size_t ebuf_len,
  16379. const char *fmt,
  16380. ...)
  16381. {
  16382. struct mg_connection *conn;
  16383. va_list ap;
  16384. int i;
  16385. int reqerr;
  16386. if (ebuf_len > 0) {
  16387. ebuf[0] = '\0';
  16388. }
  16389. va_start(ap, fmt);
  16390. /* open a connection */
  16391. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16392. if (conn != NULL) {
  16393. i = mg_vprintf(conn, fmt, ap);
  16394. if (i <= 0) {
  16395. mg_snprintf(conn,
  16396. NULL, /* No truncation check for ebuf */
  16397. ebuf,
  16398. ebuf_len,
  16399. "%s",
  16400. "Error sending request");
  16401. } else {
  16402. /* make sure the buffer is clear */
  16403. conn->data_len = 0;
  16404. get_response(conn, ebuf, ebuf_len, &reqerr);
  16405. /* TODO: here, the URI is the http response code */
  16406. conn->request_info.local_uri = conn->request_info.request_uri;
  16407. }
  16408. }
  16409. /* if an error occurred, close the connection */
  16410. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16411. mg_close_connection(conn);
  16412. conn = NULL;
  16413. }
  16414. va_end(ap);
  16415. return conn;
  16416. }
  16417. struct websocket_client_thread_data {
  16418. struct mg_connection *conn;
  16419. mg_websocket_data_handler data_handler;
  16420. mg_websocket_close_handler close_handler;
  16421. void *callback_data;
  16422. };
  16423. #if defined(USE_WEBSOCKET)
  16424. #if defined(_WIN32)
  16425. static unsigned __stdcall websocket_client_thread(void *data)
  16426. #else
  16427. static void *
  16428. websocket_client_thread(void *data)
  16429. #endif
  16430. {
  16431. struct websocket_client_thread_data *cdata =
  16432. (struct websocket_client_thread_data *)data;
  16433. void *user_thread_ptr = NULL;
  16434. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16435. struct sigaction sa;
  16436. /* Ignore SIGPIPE */
  16437. memset(&sa, 0, sizeof(sa));
  16438. sa.sa_handler = SIG_IGN;
  16439. sigaction(SIGPIPE, &sa, NULL);
  16440. #endif
  16441. mg_set_thread_name("ws-clnt");
  16442. if (cdata->conn->phys_ctx) {
  16443. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16444. /* 3 indicates a websocket client thread */
  16445. /* TODO: check if conn->phys_ctx can be set */
  16446. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16447. cdata->conn->phys_ctx, 3);
  16448. }
  16449. }
  16450. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16451. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16452. if (cdata->close_handler != NULL) {
  16453. cdata->close_handler(cdata->conn, cdata->callback_data);
  16454. }
  16455. /* The websocket_client context has only this thread. If it runs out,
  16456. set the stop_flag to 2 (= "stopped"). */
  16457. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16458. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16459. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16460. 3,
  16461. user_thread_ptr);
  16462. }
  16463. mg_free((void *)cdata);
  16464. #if defined(_WIN32)
  16465. return 0;
  16466. #else
  16467. return NULL;
  16468. #endif
  16469. }
  16470. #endif
  16471. static struct mg_connection *
  16472. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16473. int use_ssl,
  16474. char *error_buffer,
  16475. size_t error_buffer_size,
  16476. const char *path,
  16477. const char *origin,
  16478. const char *extensions,
  16479. mg_websocket_data_handler data_func,
  16480. mg_websocket_close_handler close_func,
  16481. void *user_data)
  16482. {
  16483. struct mg_connection *conn = NULL;
  16484. #if defined(USE_WEBSOCKET)
  16485. struct websocket_client_thread_data *thread_data;
  16486. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16487. const char *host = client_options->host;
  16488. int i;
  16489. struct mg_init_data init;
  16490. struct mg_error_data error;
  16491. memset(&init, 0, sizeof(init));
  16492. memset(&error, 0, sizeof(error));
  16493. error.text_buffer_size = error_buffer_size;
  16494. error.text = error_buffer;
  16495. #if defined(__clang__)
  16496. #pragma clang diagnostic push
  16497. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16498. #endif
  16499. /* Establish the client connection and request upgrade */
  16500. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16501. /* Connection object will be null if something goes wrong */
  16502. if (conn == NULL) {
  16503. /* error_buffer should be already filled ... */
  16504. if (!error_buffer[0]) {
  16505. /* ... if not add an error message */
  16506. mg_snprintf(conn,
  16507. NULL, /* No truncation check for ebuf */
  16508. error_buffer,
  16509. error_buffer_size,
  16510. "Unexpected error");
  16511. }
  16512. return NULL;
  16513. }
  16514. if (origin != NULL) {
  16515. if (extensions != NULL) {
  16516. i = mg_printf(conn,
  16517. "GET %s HTTP/1.1\r\n"
  16518. "Host: %s\r\n"
  16519. "Upgrade: websocket\r\n"
  16520. "Connection: Upgrade\r\n"
  16521. "Sec-WebSocket-Key: %s\r\n"
  16522. "Sec-WebSocket-Version: 13\r\n"
  16523. "Sec-WebSocket-Extensions: %s\r\n"
  16524. "Origin: %s\r\n"
  16525. "\r\n",
  16526. path,
  16527. host,
  16528. magic,
  16529. extensions,
  16530. origin);
  16531. } else {
  16532. i = mg_printf(conn,
  16533. "GET %s HTTP/1.1\r\n"
  16534. "Host: %s\r\n"
  16535. "Upgrade: websocket\r\n"
  16536. "Connection: Upgrade\r\n"
  16537. "Sec-WebSocket-Key: %s\r\n"
  16538. "Sec-WebSocket-Version: 13\r\n"
  16539. "Origin: %s\r\n"
  16540. "\r\n",
  16541. path,
  16542. host,
  16543. magic,
  16544. origin);
  16545. }
  16546. } else {
  16547. if (extensions != NULL) {
  16548. i = mg_printf(conn,
  16549. "GET %s HTTP/1.1\r\n"
  16550. "Host: %s\r\n"
  16551. "Upgrade: websocket\r\n"
  16552. "Connection: Upgrade\r\n"
  16553. "Sec-WebSocket-Key: %s\r\n"
  16554. "Sec-WebSocket-Version: 13\r\n"
  16555. "Sec-WebSocket-Extensions: %s\r\n"
  16556. "\r\n",
  16557. path,
  16558. host,
  16559. magic,
  16560. extensions);
  16561. } else {
  16562. i = mg_printf(conn,
  16563. "GET %s HTTP/1.1\r\n"
  16564. "Host: %s\r\n"
  16565. "Upgrade: websocket\r\n"
  16566. "Connection: Upgrade\r\n"
  16567. "Sec-WebSocket-Key: %s\r\n"
  16568. "Sec-WebSocket-Version: 13\r\n"
  16569. "\r\n",
  16570. path,
  16571. host,
  16572. magic);
  16573. }
  16574. }
  16575. if (i <= 0) {
  16576. mg_snprintf(conn,
  16577. NULL, /* No truncation check for ebuf */
  16578. error_buffer,
  16579. error_buffer_size,
  16580. "%s",
  16581. "Error sending request");
  16582. mg_close_connection(conn);
  16583. return NULL;
  16584. }
  16585. conn->data_len = 0;
  16586. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16587. mg_close_connection(conn);
  16588. return NULL;
  16589. }
  16590. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16591. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16592. #if defined(__clang__)
  16593. #pragma clang diagnostic pop
  16594. #endif
  16595. if (conn->response_info.status_code != 101) {
  16596. /* We sent an "upgrade" request. For a correct websocket
  16597. * protocol handshake, we expect a "101 Continue" response.
  16598. * Otherwise it is a protocol violation. Maybe the HTTP
  16599. * Server does not know websockets. */
  16600. if (!*error_buffer) {
  16601. /* set an error, if not yet set */
  16602. mg_snprintf(conn,
  16603. NULL, /* No truncation check for ebuf */
  16604. error_buffer,
  16605. error_buffer_size,
  16606. "Unexpected server reply");
  16607. }
  16608. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16609. mg_close_connection(conn);
  16610. return NULL;
  16611. }
  16612. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16613. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16614. if (!thread_data) {
  16615. DEBUG_TRACE("%s\r\n", "Out of memory");
  16616. mg_close_connection(conn);
  16617. return NULL;
  16618. }
  16619. thread_data->conn = conn;
  16620. thread_data->data_handler = data_func;
  16621. thread_data->close_handler = close_func;
  16622. thread_data->callback_data = user_data;
  16623. conn->phys_ctx->worker_threadids =
  16624. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16625. if (!conn->phys_ctx->worker_threadids) {
  16626. DEBUG_TRACE("%s\r\n", "Out of memory");
  16627. mg_free(thread_data);
  16628. mg_close_connection(conn);
  16629. return NULL;
  16630. }
  16631. /* Now upgrade to ws/wss client context */
  16632. conn->phys_ctx->user_data = user_data;
  16633. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16634. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16635. /* Start a thread to read the websocket client connection
  16636. * This thread will automatically stop when mg_disconnect is
  16637. * called on the client connection */
  16638. if (mg_start_thread_with_id(websocket_client_thread,
  16639. thread_data,
  16640. conn->phys_ctx->worker_threadids)
  16641. != 0) {
  16642. conn->phys_ctx->cfg_worker_threads = 0;
  16643. mg_free(thread_data);
  16644. mg_close_connection(conn);
  16645. conn = NULL;
  16646. DEBUG_TRACE("%s",
  16647. "Websocket client connect thread could not be started\r\n");
  16648. }
  16649. #else
  16650. /* Appease "unused parameter" warnings */
  16651. (void)client_options;
  16652. (void)use_ssl;
  16653. (void)error_buffer;
  16654. (void)error_buffer_size;
  16655. (void)path;
  16656. (void)origin;
  16657. (void)extensions;
  16658. (void)user_data;
  16659. (void)data_func;
  16660. (void)close_func;
  16661. #endif
  16662. return conn;
  16663. }
  16664. CIVETWEB_API struct mg_connection *
  16665. mg_connect_websocket_client(const char *host,
  16666. int port,
  16667. int use_ssl,
  16668. char *error_buffer,
  16669. size_t error_buffer_size,
  16670. const char *path,
  16671. const char *origin,
  16672. mg_websocket_data_handler data_func,
  16673. mg_websocket_close_handler close_func,
  16674. void *user_data)
  16675. {
  16676. struct mg_client_options client_options;
  16677. memset(&client_options, 0, sizeof(client_options));
  16678. client_options.host = host;
  16679. client_options.port = port;
  16680. return mg_connect_websocket_client_impl(&client_options,
  16681. use_ssl,
  16682. error_buffer,
  16683. error_buffer_size,
  16684. path,
  16685. origin,
  16686. NULL,
  16687. data_func,
  16688. close_func,
  16689. user_data);
  16690. }
  16691. CIVETWEB_API struct mg_connection *
  16692. mg_connect_websocket_client_secure(
  16693. const struct mg_client_options *client_options,
  16694. char *error_buffer,
  16695. size_t error_buffer_size,
  16696. const char *path,
  16697. const char *origin,
  16698. mg_websocket_data_handler data_func,
  16699. mg_websocket_close_handler close_func,
  16700. void *user_data)
  16701. {
  16702. if (!client_options) {
  16703. return NULL;
  16704. }
  16705. return mg_connect_websocket_client_impl(client_options,
  16706. 1,
  16707. error_buffer,
  16708. error_buffer_size,
  16709. path,
  16710. origin,
  16711. NULL,
  16712. data_func,
  16713. close_func,
  16714. user_data);
  16715. }
  16716. CIVETWEB_API struct mg_connection *
  16717. mg_connect_websocket_client_extensions(const char *host,
  16718. int port,
  16719. int use_ssl,
  16720. char *error_buffer,
  16721. size_t error_buffer_size,
  16722. const char *path,
  16723. const char *origin,
  16724. const char *extensions,
  16725. mg_websocket_data_handler data_func,
  16726. mg_websocket_close_handler close_func,
  16727. void *user_data)
  16728. {
  16729. struct mg_client_options client_options;
  16730. memset(&client_options, 0, sizeof(client_options));
  16731. client_options.host = host;
  16732. client_options.port = port;
  16733. return mg_connect_websocket_client_impl(&client_options,
  16734. use_ssl,
  16735. error_buffer,
  16736. error_buffer_size,
  16737. path,
  16738. origin,
  16739. extensions,
  16740. data_func,
  16741. close_func,
  16742. user_data);
  16743. }
  16744. CIVETWEB_API struct mg_connection *
  16745. mg_connect_websocket_client_secure_extensions(
  16746. const struct mg_client_options *client_options,
  16747. char *error_buffer,
  16748. size_t error_buffer_size,
  16749. const char *path,
  16750. const char *origin,
  16751. const char *extensions,
  16752. mg_websocket_data_handler data_func,
  16753. mg_websocket_close_handler close_func,
  16754. void *user_data)
  16755. {
  16756. if (!client_options) {
  16757. return NULL;
  16758. }
  16759. return mg_connect_websocket_client_impl(client_options,
  16760. 1,
  16761. error_buffer,
  16762. error_buffer_size,
  16763. path,
  16764. origin,
  16765. extensions,
  16766. data_func,
  16767. close_func,
  16768. user_data);
  16769. }
  16770. /* Prepare connection data structure */
  16771. static void
  16772. init_connection(struct mg_connection *conn)
  16773. {
  16774. /* Is keep alive allowed by the server */
  16775. int keep_alive_enabled =
  16776. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16777. if (!keep_alive_enabled) {
  16778. conn->must_close = 1;
  16779. }
  16780. /* Important: on new connection, reset the receiving buffer. Credit
  16781. * goes to crule42. */
  16782. conn->data_len = 0;
  16783. conn->handled_requests = 0;
  16784. conn->connection_type = CONNECTION_TYPE_INVALID;
  16785. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16786. mg_set_user_connection_data(conn, NULL);
  16787. #if defined(USE_SERVER_STATS)
  16788. conn->conn_state = 2; /* init */
  16789. #endif
  16790. /* call the init_connection callback if assigned */
  16791. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16792. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16793. void *conn_data = NULL;
  16794. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16795. mg_set_user_connection_data(conn, conn_data);
  16796. }
  16797. }
  16798. }
  16799. /* Process a connection - may handle multiple requests
  16800. * using the same connection.
  16801. * Must be called with a valid connection (conn and
  16802. * conn->phys_ctx must be valid).
  16803. */
  16804. static void
  16805. process_new_connection(struct mg_connection *conn)
  16806. {
  16807. struct mg_request_info *ri = &conn->request_info;
  16808. int keep_alive, discard_len;
  16809. char ebuf[100];
  16810. const char *hostend;
  16811. int reqerr, uri_type;
  16812. #if defined(USE_SERVER_STATS)
  16813. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16814. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16815. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16816. #endif
  16817. DEBUG_TRACE("Start processing connection from %s",
  16818. conn->request_info.remote_addr);
  16819. /* Loop over multiple requests sent using the same connection
  16820. * (while "keep alive"). */
  16821. do {
  16822. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16823. conn->handled_requests + 1);
  16824. #if defined(USE_SERVER_STATS)
  16825. conn->conn_state = 3; /* ready */
  16826. #endif
  16827. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16828. /* The request sent by the client could not be understood by
  16829. * the server, or it was incomplete or a timeout. Send an
  16830. * error message and close the connection. */
  16831. if (reqerr > 0) {
  16832. DEBUG_ASSERT(ebuf[0] != '\0');
  16833. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16834. }
  16835. } else if (strcmp(ri->http_version, "1.0")
  16836. && strcmp(ri->http_version, "1.1")) {
  16837. /* HTTP/2 is not allowed here */
  16838. mg_snprintf(conn,
  16839. NULL, /* No truncation check for ebuf */
  16840. ebuf,
  16841. sizeof(ebuf),
  16842. "Bad HTTP version: [%s]",
  16843. ri->http_version);
  16844. mg_send_http_error(conn, 505, "%s", ebuf);
  16845. }
  16846. if (ebuf[0] == '\0') {
  16847. uri_type = get_uri_type(conn->request_info.request_uri);
  16848. switch (uri_type) {
  16849. case 1:
  16850. /* Asterisk */
  16851. conn->request_info.local_uri_raw = 0;
  16852. /* TODO: Deal with '*'. */
  16853. break;
  16854. case 2:
  16855. /* relative uri */
  16856. conn->request_info.local_uri_raw =
  16857. conn->request_info.request_uri;
  16858. break;
  16859. case 3:
  16860. case 4:
  16861. /* absolute uri (with/without port) */
  16862. hostend = get_rel_url_at_current_server(
  16863. conn->request_info.request_uri, conn);
  16864. if (hostend) {
  16865. conn->request_info.local_uri_raw = hostend;
  16866. } else {
  16867. conn->request_info.local_uri_raw = NULL;
  16868. }
  16869. break;
  16870. default:
  16871. mg_snprintf(conn,
  16872. NULL, /* No truncation check for ebuf */
  16873. ebuf,
  16874. sizeof(ebuf),
  16875. "Invalid URI");
  16876. mg_send_http_error(conn, 400, "%s", ebuf);
  16877. conn->request_info.local_uri_raw = NULL;
  16878. break;
  16879. }
  16880. conn->request_info.local_uri =
  16881. (char *)conn->request_info.local_uri_raw;
  16882. }
  16883. if (ebuf[0] != '\0') {
  16884. conn->protocol_type = -1;
  16885. } else {
  16886. /* HTTP/1 allows protocol upgrade */
  16887. conn->protocol_type = should_switch_to_protocol(conn);
  16888. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16889. /* This will occur, if a HTTP/1.1 request should be upgraded
  16890. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16891. * Since most (all?) major browsers only support HTTP/2 using
  16892. * ALPN, this is hard to test and very low priority.
  16893. * Deactivate it (at least for now).
  16894. */
  16895. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16896. }
  16897. }
  16898. DEBUG_TRACE("http: %s, error: %s",
  16899. (ri->http_version ? ri->http_version : "none"),
  16900. (ebuf[0] ? ebuf : "none"));
  16901. if (ebuf[0] == '\0') {
  16902. if (conn->request_info.local_uri) {
  16903. /* handle request to local server */
  16904. handle_request_stat_log(conn);
  16905. } else {
  16906. /* TODO: handle non-local request (PROXY) */
  16907. conn->must_close = 1;
  16908. }
  16909. } else {
  16910. conn->must_close = 1;
  16911. }
  16912. /* Response complete. Free header buffer */
  16913. free_buffered_response_header_list(conn);
  16914. if (ri->remote_user != NULL) {
  16915. mg_free((void *)ri->remote_user);
  16916. /* Important! When having connections with and without auth
  16917. * would cause double free and then crash */
  16918. ri->remote_user = NULL;
  16919. }
  16920. /* NOTE(lsm): order is important here. should_keep_alive() call
  16921. * is using parsed request, which will be invalid after
  16922. * memmove's below.
  16923. * Therefore, memorize should_keep_alive() result now for later
  16924. * use in loop exit condition. */
  16925. /* Enable it only if this request is completely discardable. */
  16926. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16927. && should_keep_alive(conn) && (conn->content_len >= 0)
  16928. && (conn->request_len > 0)
  16929. && ((conn->is_chunked == 4)
  16930. || (!conn->is_chunked
  16931. && ((conn->consumed_content == conn->content_len)
  16932. || ((conn->request_len + conn->content_len)
  16933. <= conn->data_len))))
  16934. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16935. if (keep_alive) {
  16936. /* Discard all buffered data for this request */
  16937. discard_len =
  16938. ((conn->request_len + conn->content_len) < conn->data_len)
  16939. ? (int)(conn->request_len + conn->content_len)
  16940. : conn->data_len;
  16941. conn->data_len -= discard_len;
  16942. if (conn->data_len > 0) {
  16943. DEBUG_TRACE("discard_len = %d", discard_len);
  16944. memmove(conn->buf,
  16945. conn->buf + discard_len,
  16946. (size_t)conn->data_len);
  16947. }
  16948. }
  16949. DEBUG_ASSERT(conn->data_len >= 0);
  16950. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16951. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16952. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16953. (long int)conn->data_len,
  16954. (long int)conn->buf_size);
  16955. break;
  16956. }
  16957. conn->handled_requests++;
  16958. } while (keep_alive);
  16959. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16960. conn->request_info.remote_addr,
  16961. difftime(time(NULL), conn->conn_birth_time));
  16962. close_connection(conn);
  16963. #if defined(USE_SERVER_STATS)
  16964. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16965. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16966. #endif
  16967. }
  16968. #if defined(ALTERNATIVE_QUEUE)
  16969. static void
  16970. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16971. {
  16972. unsigned int i;
  16973. while (!ctx->stop_flag) {
  16974. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16975. /* find a free worker slot and signal it */
  16976. if (ctx->client_socks[i].in_use == 2) {
  16977. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16978. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16979. ctx->client_socks[i] = *sp;
  16980. ctx->client_socks[i].in_use = 1;
  16981. /* socket has been moved to the consumer */
  16982. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16983. (void)event_signal(ctx->client_wait_events[i]);
  16984. return;
  16985. }
  16986. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16987. }
  16988. }
  16989. /* queue is full */
  16990. mg_sleep(1);
  16991. }
  16992. /* must consume */
  16993. set_blocking_mode(sp->sock);
  16994. closesocket(sp->sock);
  16995. }
  16996. static int
  16997. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16998. {
  16999. DEBUG_TRACE("%s", "going idle");
  17000. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17001. ctx->client_socks[thread_index].in_use = 2;
  17002. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17003. event_wait(ctx->client_wait_events[thread_index]);
  17004. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17005. *sp = ctx->client_socks[thread_index];
  17006. if (ctx->stop_flag) {
  17007. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17008. if (sp->in_use == 1) {
  17009. /* must consume */
  17010. set_blocking_mode(sp->sock);
  17011. closesocket(sp->sock);
  17012. }
  17013. return 0;
  17014. }
  17015. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17016. if (sp->in_use == 1) {
  17017. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17018. return 1;
  17019. }
  17020. /* must not reach here */
  17021. DEBUG_ASSERT(0);
  17022. return 0;
  17023. }
  17024. #else /* ALTERNATIVE_QUEUE */
  17025. /* Worker threads take accepted socket from the queue */
  17026. static int
  17027. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  17028. {
  17029. (void)thread_index;
  17030. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17031. DEBUG_TRACE("%s", "going idle");
  17032. /* If the queue is empty, wait. We're idle at this point. */
  17033. while ((ctx->sq_head == ctx->sq_tail)
  17034. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17035. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17036. }
  17037. /* If we're stopping, sq_head may be equal to sq_tail. */
  17038. if (ctx->sq_head > ctx->sq_tail) {
  17039. /* Copy socket from the queue and increment tail */
  17040. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17041. ctx->sq_tail++;
  17042. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17043. /* Wrap pointers if needed */
  17044. while (ctx->sq_tail > ctx->sq_size) {
  17045. ctx->sq_tail -= ctx->sq_size;
  17046. ctx->sq_head -= ctx->sq_size;
  17047. }
  17048. }
  17049. (void)pthread_cond_signal(&ctx->sq_empty);
  17050. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17051. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17052. }
  17053. /* Master thread adds accepted socket to a queue */
  17054. static void
  17055. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17056. {
  17057. int queue_filled;
  17058. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17059. queue_filled = ctx->sq_head - ctx->sq_tail;
  17060. /* If the queue is full, wait */
  17061. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17062. && (queue_filled >= ctx->sq_size)) {
  17063. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17064. #if defined(USE_SERVER_STATS)
  17065. if (queue_filled > ctx->sq_max_fill) {
  17066. ctx->sq_max_fill = queue_filled;
  17067. }
  17068. #endif
  17069. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17070. ctx->sq_blocked = 0; /* Not blocked now */
  17071. queue_filled = ctx->sq_head - ctx->sq_tail;
  17072. }
  17073. if (queue_filled < ctx->sq_size) {
  17074. /* Copy socket to the queue and increment head */
  17075. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17076. ctx->sq_head++;
  17077. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17078. }
  17079. queue_filled = ctx->sq_head - ctx->sq_tail;
  17080. #if defined(USE_SERVER_STATS)
  17081. if (queue_filled > ctx->sq_max_fill) {
  17082. ctx->sq_max_fill = queue_filled;
  17083. }
  17084. #endif
  17085. (void)pthread_cond_signal(&ctx->sq_full);
  17086. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17087. }
  17088. #endif /* ALTERNATIVE_QUEUE */
  17089. static void
  17090. worker_thread_run(struct mg_connection *conn)
  17091. {
  17092. struct mg_context *ctx = conn->phys_ctx;
  17093. int thread_index;
  17094. struct mg_workerTLS tls;
  17095. mg_set_thread_name("worker");
  17096. tls.is_master = 0;
  17097. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17098. #if defined(_WIN32)
  17099. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17100. #endif
  17101. /* Initialize thread local storage before calling any callback */
  17102. pthread_setspecific(sTlsKey, &tls);
  17103. /* Check if there is a user callback */
  17104. if (ctx->callbacks.init_thread) {
  17105. /* call init_thread for a worker thread (type 1), and store the
  17106. * return value */
  17107. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17108. } else {
  17109. /* No callback: set user pointer to NULL */
  17110. tls.user_ptr = NULL;
  17111. }
  17112. /* Connection structure has been pre-allocated */
  17113. thread_index = (int)(conn - ctx->worker_connections);
  17114. if ((thread_index < 0)
  17115. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  17116. mg_cry_ctx_internal(ctx,
  17117. "Internal error: Invalid worker index %i",
  17118. thread_index);
  17119. return;
  17120. }
  17121. /* Request buffers are not pre-allocated. They are private to the
  17122. * request and do not contain any state information that might be
  17123. * of interest to anyone observing a server status. */
  17124. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17125. if (conn->buf == NULL) {
  17126. mg_cry_ctx_internal(
  17127. ctx,
  17128. "Out of memory: Cannot allocate buffer for worker %i",
  17129. thread_index);
  17130. return;
  17131. }
  17132. conn->buf_size = (int)ctx->max_request_size;
  17133. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17134. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17135. conn->request_info.user_data = ctx->user_data;
  17136. /* Allocate a mutex for this connection to allow communication both
  17137. * within the request handler and from elsewhere in the application
  17138. */
  17139. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17140. mg_free(conn->buf);
  17141. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17142. return;
  17143. }
  17144. #if defined(USE_SERVER_STATS)
  17145. conn->conn_state = 1; /* not consumed */
  17146. #endif
  17147. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17148. * signal sq_empty condvar to wake up the master waiting in
  17149. * produce_socket() */
  17150. while (consume_socket(ctx, &conn->client, thread_index)) {
  17151. /* New connections must start with new protocol negotiation */
  17152. tls.alpn_proto = NULL;
  17153. #if defined(USE_SERVER_STATS)
  17154. conn->conn_close_time = 0;
  17155. #endif
  17156. conn->conn_birth_time = time(NULL);
  17157. /* Fill in IP, port info early so even if SSL setup below fails,
  17158. * error handler would have the corresponding info.
  17159. * Thanks to Johannes Winkelmann for the patch.
  17160. */
  17161. conn->request_info.remote_port =
  17162. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17163. conn->request_info.server_port =
  17164. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17165. sockaddr_to_string(conn->request_info.remote_addr,
  17166. sizeof(conn->request_info.remote_addr),
  17167. &conn->client.rsa);
  17168. DEBUG_TRACE("Incoming %sconnection from %s",
  17169. (conn->client.is_ssl ? "SSL " : ""),
  17170. conn->request_info.remote_addr);
  17171. conn->request_info.is_ssl = conn->client.is_ssl;
  17172. if (conn->client.is_ssl) {
  17173. #if defined(USE_MBEDTLS)
  17174. /* HTTPS connection */
  17175. if (mbed_ssl_accept(&(conn->ssl),
  17176. conn->dom_ctx->ssl_ctx,
  17177. (int *)&(conn->client.sock),
  17178. conn->phys_ctx)
  17179. == 0) {
  17180. /* conn->dom_ctx is set in get_request */
  17181. /* process HTTPS connection */
  17182. init_connection(conn);
  17183. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17184. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17185. process_new_connection(conn);
  17186. } else {
  17187. /* make sure the connection is cleaned up on SSL failure */
  17188. close_connection(conn);
  17189. }
  17190. #elif !defined(NO_SSL)
  17191. /* HTTPS connection */
  17192. if (sslize(conn, SSL_accept, NULL)) {
  17193. /* conn->dom_ctx is set in get_request */
  17194. /* Get SSL client certificate information (if set) */
  17195. struct mg_client_cert client_cert;
  17196. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17197. conn->request_info.client_cert = &client_cert;
  17198. }
  17199. /* process HTTPS connection */
  17200. #if defined(USE_HTTP2)
  17201. if ((tls.alpn_proto != NULL)
  17202. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17203. /* process HTTPS/2 connection */
  17204. init_connection(conn);
  17205. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17206. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17207. conn->content_len =
  17208. -1; /* content length is not predefined */
  17209. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17210. process_new_http2_connection(conn);
  17211. } else
  17212. #endif
  17213. {
  17214. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17215. init_connection(conn);
  17216. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17217. /* Start with HTTP, WS will be an "upgrade" request later */
  17218. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17219. process_new_connection(conn);
  17220. }
  17221. /* Free client certificate info */
  17222. if (conn->request_info.client_cert) {
  17223. mg_free((void *)(conn->request_info.client_cert->subject));
  17224. mg_free((void *)(conn->request_info.client_cert->issuer));
  17225. mg_free((void *)(conn->request_info.client_cert->serial));
  17226. mg_free((void *)(conn->request_info.client_cert->finger));
  17227. /* Free certificate memory */
  17228. X509_free(
  17229. (X509 *)conn->request_info.client_cert->peer_cert);
  17230. conn->request_info.client_cert->peer_cert = 0;
  17231. conn->request_info.client_cert->subject = 0;
  17232. conn->request_info.client_cert->issuer = 0;
  17233. conn->request_info.client_cert->serial = 0;
  17234. conn->request_info.client_cert->finger = 0;
  17235. conn->request_info.client_cert = 0;
  17236. }
  17237. } else {
  17238. /* make sure the connection is cleaned up on SSL failure */
  17239. close_connection(conn);
  17240. }
  17241. #endif
  17242. } else {
  17243. /* process HTTP connection */
  17244. init_connection(conn);
  17245. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17246. /* Start with HTTP, WS will be an "upgrade" request later */
  17247. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17248. process_new_connection(conn);
  17249. }
  17250. DEBUG_TRACE("%s", "Connection closed");
  17251. #if defined(USE_SERVER_STATS)
  17252. conn->conn_close_time = time(NULL);
  17253. #endif
  17254. }
  17255. /* Call exit thread user callback */
  17256. if (ctx->callbacks.exit_thread) {
  17257. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17258. }
  17259. /* delete thread local storage objects */
  17260. pthread_setspecific(sTlsKey, NULL);
  17261. #if defined(_WIN32)
  17262. CloseHandle(tls.pthread_cond_helper_mutex);
  17263. #endif
  17264. pthread_mutex_destroy(&conn->mutex);
  17265. /* Free the request buffer. */
  17266. conn->buf_size = 0;
  17267. mg_free(conn->buf);
  17268. conn->buf = NULL;
  17269. /* Free cleaned URI (if any) */
  17270. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17271. mg_free((void *)conn->request_info.local_uri);
  17272. conn->request_info.local_uri = NULL;
  17273. }
  17274. #if defined(USE_SERVER_STATS)
  17275. conn->conn_state = 9; /* done */
  17276. #endif
  17277. DEBUG_TRACE("%s", "exiting");
  17278. }
  17279. /* Threads have different return types on Windows and Unix. */
  17280. #if defined(_WIN32)
  17281. static unsigned __stdcall worker_thread(void *thread_func_param)
  17282. {
  17283. worker_thread_run((struct mg_connection *)thread_func_param);
  17284. return 0;
  17285. }
  17286. #else
  17287. static void *
  17288. worker_thread(void *thread_func_param)
  17289. {
  17290. #if !defined(__ZEPHYR__)
  17291. struct sigaction sa;
  17292. /* Ignore SIGPIPE */
  17293. memset(&sa, 0, sizeof(sa));
  17294. sa.sa_handler = SIG_IGN;
  17295. sigaction(SIGPIPE, &sa, NULL);
  17296. #endif
  17297. worker_thread_run((struct mg_connection *)thread_func_param);
  17298. return NULL;
  17299. }
  17300. #endif /* _WIN32 */
  17301. /* This is an internal function, thus all arguments are expected to be
  17302. * valid - a NULL check is not required. */
  17303. static void
  17304. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17305. {
  17306. struct socket so;
  17307. char src_addr[IP_ADDR_STR_LEN];
  17308. socklen_t len = sizeof(so.rsa);
  17309. #if !defined(__ZEPHYR__)
  17310. int on = 1;
  17311. #endif
  17312. memset(&so, 0, sizeof(so));
  17313. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17314. == INVALID_SOCKET) {
  17315. } else if (check_acl(ctx, &so.rsa) != 1) {
  17316. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17317. mg_cry_ctx_internal(ctx,
  17318. "%s: %s is not allowed to connect",
  17319. __func__,
  17320. src_addr);
  17321. closesocket(so.sock);
  17322. } else {
  17323. /* Put so socket structure into the queue */
  17324. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17325. set_close_on_exec(so.sock, NULL, ctx);
  17326. so.is_ssl = listener->is_ssl;
  17327. so.ssl_redir = listener->ssl_redir;
  17328. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17329. mg_cry_ctx_internal(ctx,
  17330. "%s: getsockname() failed: %s",
  17331. __func__,
  17332. strerror(ERRNO));
  17333. }
  17334. #if !defined(__ZEPHYR__)
  17335. if ((so.lsa.sa.sa_family == AF_INET)
  17336. || (so.lsa.sa.sa_family == AF_INET6)) {
  17337. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17338. * This is needed because if HTTP-level keep-alive
  17339. * is enabled, and client resets the connection, server won't get
  17340. * TCP FIN or RST and will keep the connection open forever. With
  17341. * TCP keep-alive, next keep-alive handshake will figure out that
  17342. * the client is down and will close the server end.
  17343. * Thanks to Igor Klopov who suggested the patch. */
  17344. if (setsockopt(so.sock,
  17345. SOL_SOCKET,
  17346. SO_KEEPALIVE,
  17347. (SOCK_OPT_TYPE)&on,
  17348. sizeof(on))
  17349. != 0) {
  17350. mg_cry_ctx_internal(
  17351. ctx,
  17352. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17353. __func__,
  17354. strerror(ERRNO));
  17355. }
  17356. }
  17357. #endif
  17358. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17359. * to effectively fill up the underlying IP packet payload and
  17360. * reduce the overhead of sending lots of small buffers. However
  17361. * this hurts the server's throughput (ie. operations per second)
  17362. * when HTTP 1.1 persistent connections are used and the responses
  17363. * are relatively small (eg. less than 1400 bytes).
  17364. */
  17365. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17366. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17367. if (set_tcp_nodelay(&so, 1) != 0) {
  17368. mg_cry_ctx_internal(
  17369. ctx,
  17370. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17371. __func__,
  17372. strerror(ERRNO));
  17373. }
  17374. }
  17375. /* The "non blocking" property should already be
  17376. * inherited from the parent socket. Set it for
  17377. * non-compliant socket implementations. */
  17378. set_non_blocking_mode(so.sock);
  17379. so.in_use = 0;
  17380. produce_socket(ctx, &so);
  17381. }
  17382. }
  17383. static void
  17384. master_thread_run(struct mg_context *ctx)
  17385. {
  17386. struct mg_workerTLS tls;
  17387. struct mg_pollfd *pfd;
  17388. unsigned int i;
  17389. unsigned int workerthreadcount;
  17390. if (!ctx) {
  17391. return;
  17392. }
  17393. mg_set_thread_name("master");
  17394. /* Increase priority of the master thread */
  17395. #if defined(_WIN32)
  17396. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17397. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17398. int min_prio = sched_get_priority_min(SCHED_RR);
  17399. int max_prio = sched_get_priority_max(SCHED_RR);
  17400. if ((min_prio >= 0) && (max_prio >= 0)
  17401. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17402. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17403. struct sched_param sched_param = {0};
  17404. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17405. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17406. }
  17407. #endif
  17408. /* Initialize thread local storage */
  17409. #if defined(_WIN32)
  17410. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17411. #endif
  17412. tls.is_master = 1;
  17413. pthread_setspecific(sTlsKey, &tls);
  17414. if (ctx->callbacks.init_thread) {
  17415. /* Callback for the master thread (type 0) */
  17416. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17417. } else {
  17418. tls.user_ptr = NULL;
  17419. }
  17420. /* Lua background script "start" event */
  17421. #if defined(USE_LUA)
  17422. if (ctx->lua_background_state) {
  17423. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17424. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17425. /* call "start()" in Lua */
  17426. lua_getglobal(lstate, "start");
  17427. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17428. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17429. if (ret != 0) {
  17430. struct mg_connection fc;
  17431. lua_cry(fake_connection(&fc, ctx),
  17432. ret,
  17433. lstate,
  17434. "lua_background_script",
  17435. "start");
  17436. }
  17437. } else {
  17438. lua_pop(lstate, 1);
  17439. }
  17440. /* determine if there is a "log()" function in Lua background script */
  17441. lua_getglobal(lstate, "log");
  17442. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17443. ctx->lua_bg_log_available = 1;
  17444. }
  17445. lua_pop(lstate, 1);
  17446. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17447. }
  17448. #endif
  17449. /* Server starts *now* */
  17450. ctx->start_time = time(NULL);
  17451. /* Server accept loop */
  17452. pfd = ctx->listening_socket_fds;
  17453. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17454. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17455. pfd[i].fd = ctx->listening_sockets[i].sock;
  17456. pfd[i].events = POLLIN;
  17457. }
  17458. if (mg_poll(pfd,
  17459. ctx->num_listening_sockets,
  17460. SOCKET_TIMEOUT_QUANTUM,
  17461. &(ctx->stop_flag))
  17462. > 0) {
  17463. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17464. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17465. * successful poll, and POLLIN is defined as
  17466. * (POLLRDNORM | POLLRDBAND)
  17467. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17468. * pfd[i].revents == POLLIN. */
  17469. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17470. && (pfd[i].revents & POLLIN)) {
  17471. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17472. }
  17473. }
  17474. }
  17475. }
  17476. /* Here stop_flag is 1 - Initiate shutdown. */
  17477. DEBUG_TRACE("%s", "stopping workers");
  17478. /* Stop signal received: somebody called mg_stop. Quit. */
  17479. close_all_listening_sockets(ctx);
  17480. /* Wakeup workers that are waiting for connections to handle. */
  17481. #if defined(ALTERNATIVE_QUEUE)
  17482. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17483. event_signal(ctx->client_wait_events[i]);
  17484. }
  17485. #else
  17486. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17487. pthread_cond_broadcast(&ctx->sq_full);
  17488. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17489. #endif
  17490. /* Join all worker threads to avoid leaking threads. */
  17491. workerthreadcount = ctx->cfg_worker_threads;
  17492. for (i = 0; i < workerthreadcount; i++) {
  17493. if (ctx->worker_threadids[i] != 0) {
  17494. mg_join_thread(ctx->worker_threadids[i]);
  17495. }
  17496. }
  17497. #if defined(USE_LUA)
  17498. /* Free Lua state of lua background task */
  17499. if (ctx->lua_background_state) {
  17500. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17501. ctx->lua_bg_log_available = 0;
  17502. /* call "stop()" in Lua */
  17503. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17504. lua_getglobal(lstate, "stop");
  17505. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17506. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17507. if (ret != 0) {
  17508. struct mg_connection fc;
  17509. lua_cry(fake_connection(&fc, ctx),
  17510. ret,
  17511. lstate,
  17512. "lua_background_script",
  17513. "stop");
  17514. }
  17515. }
  17516. DEBUG_TRACE("Close Lua background state %p", lstate);
  17517. lua_close(lstate);
  17518. ctx->lua_background_state = 0;
  17519. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17520. }
  17521. #endif
  17522. DEBUG_TRACE("%s", "exiting");
  17523. /* call exit thread callback */
  17524. if (ctx->callbacks.exit_thread) {
  17525. /* Callback for the master thread (type 0) */
  17526. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17527. }
  17528. #if defined(_WIN32)
  17529. CloseHandle(tls.pthread_cond_helper_mutex);
  17530. #endif
  17531. pthread_setspecific(sTlsKey, NULL);
  17532. /* Signal mg_stop() that we're done.
  17533. * WARNING: This must be the very last thing this
  17534. * thread does, as ctx becomes invalid after this line. */
  17535. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17536. }
  17537. /* Threads have different return types on Windows and Unix. */
  17538. #if defined(_WIN32)
  17539. static unsigned __stdcall master_thread(void *thread_func_param)
  17540. {
  17541. master_thread_run((struct mg_context *)thread_func_param);
  17542. return 0;
  17543. }
  17544. #else
  17545. static void *
  17546. master_thread(void *thread_func_param)
  17547. {
  17548. #if !defined(__ZEPHYR__)
  17549. struct sigaction sa;
  17550. /* Ignore SIGPIPE */
  17551. memset(&sa, 0, sizeof(sa));
  17552. sa.sa_handler = SIG_IGN;
  17553. sigaction(SIGPIPE, &sa, NULL);
  17554. #endif
  17555. master_thread_run((struct mg_context *)thread_func_param);
  17556. return NULL;
  17557. }
  17558. #endif /* _WIN32 */
  17559. static void
  17560. free_context(struct mg_context *ctx)
  17561. {
  17562. int i;
  17563. struct mg_handler_info *tmp_rh;
  17564. if (ctx == NULL) {
  17565. return;
  17566. }
  17567. /* Call user callback */
  17568. if (ctx->callbacks.exit_context) {
  17569. ctx->callbacks.exit_context(ctx);
  17570. }
  17571. /* All threads exited, no sync is needed. Destroy thread mutex and
  17572. * condvars
  17573. */
  17574. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17575. #if defined(ALTERNATIVE_QUEUE)
  17576. mg_free(ctx->client_socks);
  17577. if (ctx->client_wait_events != NULL) {
  17578. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17579. event_destroy(ctx->client_wait_events[i]);
  17580. }
  17581. mg_free(ctx->client_wait_events);
  17582. }
  17583. #else
  17584. (void)pthread_cond_destroy(&ctx->sq_empty);
  17585. (void)pthread_cond_destroy(&ctx->sq_full);
  17586. mg_free(ctx->squeue);
  17587. #endif
  17588. /* Destroy other context global data structures mutex */
  17589. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17590. #if defined(USE_LUA)
  17591. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17592. #endif
  17593. /* Deallocate config parameters */
  17594. for (i = 0; i < NUM_OPTIONS; i++) {
  17595. if (ctx->dd.config[i] != NULL) {
  17596. #if defined(_MSC_VER)
  17597. #pragma warning(suppress : 6001)
  17598. #endif
  17599. mg_free(ctx->dd.config[i]);
  17600. }
  17601. }
  17602. /* Deallocate request handlers */
  17603. while (ctx->dd.handlers) {
  17604. tmp_rh = ctx->dd.handlers;
  17605. ctx->dd.handlers = tmp_rh->next;
  17606. mg_free(tmp_rh->uri);
  17607. mg_free(tmp_rh);
  17608. }
  17609. #if defined(USE_MBEDTLS)
  17610. if (ctx->dd.ssl_ctx != NULL) {
  17611. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17612. mg_free(ctx->dd.ssl_ctx);
  17613. ctx->dd.ssl_ctx = NULL;
  17614. }
  17615. #elif !defined(NO_SSL)
  17616. /* Deallocate SSL context */
  17617. if (ctx->dd.ssl_ctx != NULL) {
  17618. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17619. int callback_ret =
  17620. (ctx->callbacks.external_ssl_ctx == NULL)
  17621. ? 0
  17622. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17623. if (callback_ret == 0) {
  17624. SSL_CTX_free(ctx->dd.ssl_ctx);
  17625. }
  17626. /* else: ignore error and omit SSL_CTX_free in case
  17627. * callback_ret is 1 */
  17628. }
  17629. #endif /* !NO_SSL */
  17630. /* Deallocate worker thread ID array */
  17631. mg_free(ctx->worker_threadids);
  17632. /* Deallocate worker thread ID array */
  17633. mg_free(ctx->worker_connections);
  17634. /* deallocate system name string */
  17635. mg_free(ctx->systemName);
  17636. /* Deallocate context itself */
  17637. mg_free(ctx);
  17638. }
  17639. CIVETWEB_API void
  17640. mg_stop(struct mg_context *ctx)
  17641. {
  17642. pthread_t mt;
  17643. if (!ctx) {
  17644. return;
  17645. }
  17646. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17647. * two threads is not allowed. */
  17648. mt = ctx->masterthreadid;
  17649. if (mt == 0) {
  17650. return;
  17651. }
  17652. ctx->masterthreadid = 0;
  17653. /* Set stop flag, so all threads know they have to exit. */
  17654. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17655. /* Join timer thread */
  17656. #if defined(USE_TIMERS)
  17657. timers_exit(ctx);
  17658. #endif
  17659. /* Wait until everything has stopped. */
  17660. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17661. (void)mg_sleep(10);
  17662. }
  17663. /* Wait to stop master thread */
  17664. mg_join_thread(mt);
  17665. /* Close remaining Lua states */
  17666. #if defined(USE_LUA)
  17667. lua_ctx_exit(ctx);
  17668. #endif
  17669. /* Free memory */
  17670. free_context(ctx);
  17671. }
  17672. static void
  17673. get_system_name(char **sysName)
  17674. {
  17675. #if defined(_WIN32)
  17676. char name[128];
  17677. DWORD dwVersion = 0;
  17678. DWORD dwMajorVersion = 0;
  17679. DWORD dwMinorVersion = 0;
  17680. DWORD dwBuild = 0;
  17681. BOOL wowRet, isWoW = FALSE;
  17682. #if defined(_MSC_VER)
  17683. #pragma warning(push)
  17684. /* GetVersion was declared deprecated */
  17685. #pragma warning(disable : 4996)
  17686. #endif
  17687. dwVersion = GetVersion();
  17688. #if defined(_MSC_VER)
  17689. #pragma warning(pop)
  17690. #endif
  17691. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17692. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17693. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17694. (void)dwBuild;
  17695. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17696. sprintf(name,
  17697. "Windows %u.%u%s",
  17698. (unsigned)dwMajorVersion,
  17699. (unsigned)dwMinorVersion,
  17700. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17701. *sysName = mg_strdup(name);
  17702. #elif defined(__ZEPHYR__)
  17703. *sysName = mg_strdup("Zephyr OS");
  17704. #else
  17705. struct utsname name;
  17706. memset(&name, 0, sizeof(name));
  17707. uname(&name);
  17708. *sysName = mg_strdup(name.sysname);
  17709. #endif
  17710. }
  17711. static void
  17712. legacy_init(const char **options)
  17713. {
  17714. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17715. if (options) {
  17716. const char **run_options = options;
  17717. const char *optname = config_options[LISTENING_PORTS].name;
  17718. /* Try to find the "listening_ports" option */
  17719. while (*run_options) {
  17720. if (!strcmp(*run_options, optname)) {
  17721. ports_option = run_options[1];
  17722. }
  17723. run_options += 2;
  17724. }
  17725. }
  17726. if (is_ssl_port_used(ports_option)) {
  17727. /* Initialize with SSL support */
  17728. mg_init_library(MG_FEATURES_TLS);
  17729. } else {
  17730. /* Initialize without SSL support */
  17731. mg_init_library(MG_FEATURES_DEFAULT);
  17732. }
  17733. }
  17734. CIVETWEB_API struct mg_context *
  17735. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17736. {
  17737. struct mg_context *ctx;
  17738. const char *name, *value, *default_value;
  17739. int idx, ok, workerthreadcount;
  17740. unsigned int i;
  17741. int itmp;
  17742. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17743. const char **options =
  17744. ((init != NULL) ? (init->configuration_options) : (NULL));
  17745. struct mg_workerTLS tls;
  17746. if (error != NULL) {
  17747. error->code = MG_ERROR_DATA_CODE_OK;
  17748. error->code_sub = 0;
  17749. if (error->text_buffer_size > 0) {
  17750. *error->text = 0;
  17751. }
  17752. }
  17753. if (mg_init_library_called == 0) {
  17754. /* Legacy INIT, if mg_start is called without mg_init_library.
  17755. * Note: This will cause a memory leak when unloading the library.
  17756. */
  17757. legacy_init(options);
  17758. }
  17759. if (mg_init_library_called == 0) {
  17760. if (error != NULL) {
  17761. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17762. mg_snprintf(NULL,
  17763. NULL, /* No truncation check for error buffers */
  17764. error->text,
  17765. error->text_buffer_size,
  17766. "%s",
  17767. "Library uninitialized");
  17768. }
  17769. return NULL;
  17770. }
  17771. /* Allocate context and initialize reasonable general case defaults. */
  17772. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17773. if (ctx == NULL) {
  17774. if (error != NULL) {
  17775. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17776. error->code_sub = (unsigned)sizeof(*ctx);
  17777. mg_snprintf(NULL,
  17778. NULL, /* No truncation check for error buffers */
  17779. error->text,
  17780. error->text_buffer_size,
  17781. "%s",
  17782. "Out of memory");
  17783. }
  17784. return NULL;
  17785. }
  17786. /* Random number generator will initialize at the first call */
  17787. ctx->dd.auth_nonce_mask =
  17788. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17789. /* Save started thread index to reuse in other external API calls
  17790. * For the sake of thread synchronization all non-civetweb threads
  17791. * can be considered as single external thread */
  17792. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17793. tls.is_master = -1; /* Thread calling mg_start */
  17794. tls.thread_idx = ctx->starter_thread_idx;
  17795. #if defined(_WIN32)
  17796. tls.pthread_cond_helper_mutex = NULL;
  17797. #endif
  17798. pthread_setspecific(sTlsKey, &tls);
  17799. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17800. #if !defined(ALTERNATIVE_QUEUE)
  17801. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17802. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17803. ctx->sq_blocked = 0;
  17804. #endif
  17805. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17806. #if defined(USE_LUA)
  17807. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17808. #endif
  17809. if (!ok) {
  17810. unsigned error_id = (unsigned)ERRNO;
  17811. const char *err_msg =
  17812. "Cannot initialize thread synchronization objects";
  17813. /* Fatal error - abort start. However, this situation should never
  17814. * occur in practice. */
  17815. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17816. if (error != NULL) {
  17817. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17818. error->code_sub = error_id;
  17819. mg_snprintf(NULL,
  17820. NULL, /* No truncation check for error buffers */
  17821. error->text,
  17822. error->text_buffer_size,
  17823. "%s",
  17824. err_msg);
  17825. }
  17826. mg_free(ctx);
  17827. pthread_setspecific(sTlsKey, NULL);
  17828. return NULL;
  17829. }
  17830. if ((init != NULL) && (init->callbacks != NULL)) {
  17831. /* Set all callbacks except exit_context. */
  17832. ctx->callbacks = *init->callbacks;
  17833. exit_callback = init->callbacks->exit_context;
  17834. /* The exit callback is activated once the context is successfully
  17835. * created. It should not be called, if an incomplete context object
  17836. * is deleted during a failed initialization. */
  17837. ctx->callbacks.exit_context = 0;
  17838. }
  17839. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17840. ctx->dd.handlers = NULL;
  17841. ctx->dd.next = NULL;
  17842. #if defined(USE_LUA)
  17843. lua_ctx_init(ctx);
  17844. #endif
  17845. /* Store options */
  17846. while (options && (name = *options++) != NULL) {
  17847. idx = get_option_index(name);
  17848. if (idx == -1) {
  17849. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17850. if (error != NULL) {
  17851. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17852. error->code_sub = (unsigned)-1;
  17853. mg_snprintf(NULL,
  17854. NULL, /* No truncation check for error buffers */
  17855. error->text,
  17856. error->text_buffer_size,
  17857. "Invalid configuration option: %s",
  17858. name);
  17859. }
  17860. free_context(ctx);
  17861. pthread_setspecific(sTlsKey, NULL);
  17862. return NULL;
  17863. } else if ((value = *options++) == NULL) {
  17864. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17865. if (error != NULL) {
  17866. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17867. error->code_sub = (unsigned)idx;
  17868. mg_snprintf(NULL,
  17869. NULL, /* No truncation check for error buffers */
  17870. error->text,
  17871. error->text_buffer_size,
  17872. "Invalid configuration option value: %s",
  17873. name);
  17874. }
  17875. free_context(ctx);
  17876. pthread_setspecific(sTlsKey, NULL);
  17877. return NULL;
  17878. }
  17879. if (ctx->dd.config[idx] != NULL) {
  17880. /* A duplicate configuration option is not an error - the last
  17881. * option value will be used. */
  17882. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17883. mg_free(ctx->dd.config[idx]);
  17884. }
  17885. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17886. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17887. }
  17888. /* Set default value if needed */
  17889. for (i = 0; config_options[i].name != NULL; i++) {
  17890. default_value = config_options[i].default_value;
  17891. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17892. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17893. }
  17894. }
  17895. /* Request size option */
  17896. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17897. if (itmp < 1024) {
  17898. mg_cry_ctx_internal(ctx,
  17899. "%s too small",
  17900. config_options[MAX_REQUEST_SIZE].name);
  17901. if (error != NULL) {
  17902. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17903. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17904. mg_snprintf(NULL,
  17905. NULL, /* No truncation check for error buffers */
  17906. error->text,
  17907. error->text_buffer_size,
  17908. "Invalid configuration option value: %s",
  17909. config_options[MAX_REQUEST_SIZE].name);
  17910. }
  17911. free_context(ctx);
  17912. pthread_setspecific(sTlsKey, NULL);
  17913. return NULL;
  17914. }
  17915. ctx->max_request_size = (unsigned)itmp;
  17916. /* Queue length */
  17917. #if !defined(ALTERNATIVE_QUEUE)
  17918. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17919. if (itmp < 1) {
  17920. mg_cry_ctx_internal(ctx,
  17921. "%s too small",
  17922. config_options[CONNECTION_QUEUE_SIZE].name);
  17923. if (error != NULL) {
  17924. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17925. error->code_sub = CONNECTION_QUEUE_SIZE;
  17926. mg_snprintf(NULL,
  17927. NULL, /* No truncation check for error buffers */
  17928. error->text,
  17929. error->text_buffer_size,
  17930. "Invalid configuration option value: %s",
  17931. config_options[CONNECTION_QUEUE_SIZE].name);
  17932. }
  17933. free_context(ctx);
  17934. pthread_setspecific(sTlsKey, NULL);
  17935. return NULL;
  17936. }
  17937. ctx->squeue =
  17938. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17939. if (ctx->squeue == NULL) {
  17940. mg_cry_ctx_internal(ctx,
  17941. "Out of memory: Cannot allocate %s",
  17942. config_options[CONNECTION_QUEUE_SIZE].name);
  17943. if (error != NULL) {
  17944. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17945. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17946. mg_snprintf(NULL,
  17947. NULL, /* No truncation check for error buffers */
  17948. error->text,
  17949. error->text_buffer_size,
  17950. "Out of memory: Cannot allocate %s",
  17951. config_options[CONNECTION_QUEUE_SIZE].name);
  17952. }
  17953. free_context(ctx);
  17954. pthread_setspecific(sTlsKey, NULL);
  17955. return NULL;
  17956. }
  17957. ctx->sq_size = itmp;
  17958. #endif
  17959. /* Worker thread count option */
  17960. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17961. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17962. if (workerthreadcount <= 0) {
  17963. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17964. } else {
  17965. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17966. }
  17967. if (error != NULL) {
  17968. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17969. error->code_sub = NUM_THREADS;
  17970. mg_snprintf(NULL,
  17971. NULL, /* No truncation check for error buffers */
  17972. error->text,
  17973. error->text_buffer_size,
  17974. "Invalid configuration option value: %s",
  17975. config_options[NUM_THREADS].name);
  17976. }
  17977. free_context(ctx);
  17978. pthread_setspecific(sTlsKey, NULL);
  17979. return NULL;
  17980. }
  17981. /* Document root */
  17982. #if defined(NO_FILES)
  17983. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17984. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17985. if (error != NULL) {
  17986. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17987. error->code_sub = (unsigned)DOCUMENT_ROOT;
  17988. mg_snprintf(NULL,
  17989. NULL, /* No truncation check for error buffers */
  17990. error->text,
  17991. error->text_buffer_size,
  17992. "Invalid configuration option value: %s",
  17993. config_options[DOCUMENT_ROOT].name);
  17994. }
  17995. free_context(ctx);
  17996. pthread_setspecific(sTlsKey, NULL);
  17997. return NULL;
  17998. }
  17999. #endif
  18000. get_system_name(&ctx->systemName);
  18001. #if defined(USE_LUA)
  18002. /* If a Lua background script has been configured, start it. */
  18003. ctx->lua_bg_log_available = 0;
  18004. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18005. char ebuf[256];
  18006. struct vec opt_vec;
  18007. struct vec eq_vec;
  18008. const char *sparams;
  18009. memset(ebuf, 0, sizeof(ebuf));
  18010. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18011. /* Create a Lua state, load all standard libraries and the mg table */
  18012. lua_State *state = mg_lua_context_script_prepare(
  18013. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18014. if (!state) {
  18015. mg_cry_ctx_internal(ctx,
  18016. "lua_background_script load error: %s",
  18017. ebuf);
  18018. if (error != NULL) {
  18019. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18020. mg_snprintf(NULL,
  18021. NULL, /* No truncation check for error buffers */
  18022. error->text,
  18023. error->text_buffer_size,
  18024. "Error in script %s: %s",
  18025. config_options[LUA_BACKGROUND_SCRIPT].name,
  18026. ebuf);
  18027. }
  18028. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18029. free_context(ctx);
  18030. pthread_setspecific(sTlsKey, NULL);
  18031. return NULL;
  18032. }
  18033. /* Add a table with parameters into mg.params */
  18034. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18035. if (sparams && sparams[0]) {
  18036. lua_getglobal(state, "mg");
  18037. lua_pushstring(state, "params");
  18038. lua_newtable(state);
  18039. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18040. != NULL) {
  18041. reg_llstring(
  18042. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18043. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18044. break;
  18045. }
  18046. lua_rawset(state, -3);
  18047. lua_pop(state, 1);
  18048. }
  18049. /* Call script */
  18050. state = mg_lua_context_script_run(state,
  18051. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18052. ctx,
  18053. ebuf,
  18054. sizeof(ebuf));
  18055. if (!state) {
  18056. mg_cry_ctx_internal(ctx,
  18057. "lua_background_script start error: %s",
  18058. ebuf);
  18059. if (error != NULL) {
  18060. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18061. mg_snprintf(NULL,
  18062. NULL, /* No truncation check for error buffers */
  18063. error->text,
  18064. error->text_buffer_size,
  18065. "Error in script %s: %s",
  18066. config_options[DOCUMENT_ROOT].name,
  18067. ebuf);
  18068. }
  18069. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18070. free_context(ctx);
  18071. pthread_setspecific(sTlsKey, NULL);
  18072. return NULL;
  18073. }
  18074. /* state remains valid */
  18075. ctx->lua_background_state = (void *)state;
  18076. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18077. } else {
  18078. ctx->lua_background_state = 0;
  18079. }
  18080. #endif
  18081. /* Step by step initialization of ctx - depending on build options */
  18082. #if !defined(NO_FILESYSTEMS)
  18083. if (!set_gpass_option(ctx, NULL)) {
  18084. const char *err_msg = "Invalid global password file";
  18085. /* Fatal error - abort start. */
  18086. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18087. if (error != NULL) {
  18088. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18089. mg_snprintf(NULL,
  18090. NULL, /* No truncation check for error buffers */
  18091. error->text,
  18092. error->text_buffer_size,
  18093. "%s",
  18094. err_msg);
  18095. }
  18096. free_context(ctx);
  18097. pthread_setspecific(sTlsKey, NULL);
  18098. return NULL;
  18099. }
  18100. #endif
  18101. #if defined(USE_MBEDTLS)
  18102. if (!mg_sslctx_init(ctx, NULL)) {
  18103. const char *err_msg = "Error initializing SSL context";
  18104. /* Fatal error - abort start. */
  18105. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18106. if (error != NULL) {
  18107. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18108. mg_snprintf(NULL,
  18109. NULL, /* No truncation check for error buffers */
  18110. error->text,
  18111. error->text_buffer_size,
  18112. "%s",
  18113. err_msg);
  18114. }
  18115. free_context(ctx);
  18116. pthread_setspecific(sTlsKey, NULL);
  18117. return NULL;
  18118. }
  18119. #elif !defined(NO_SSL)
  18120. if (!init_ssl_ctx(ctx, NULL)) {
  18121. const char *err_msg = "Error initializing SSL context";
  18122. /* Fatal error - abort start. */
  18123. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18124. if (error != NULL) {
  18125. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18126. mg_snprintf(NULL,
  18127. NULL, /* No truncation check for error buffers */
  18128. error->text,
  18129. error->text_buffer_size,
  18130. "%s",
  18131. err_msg);
  18132. }
  18133. free_context(ctx);
  18134. pthread_setspecific(sTlsKey, NULL);
  18135. return NULL;
  18136. }
  18137. #endif
  18138. if (!set_ports_option(ctx)) {
  18139. const char *err_msg = "Failed to setup server ports";
  18140. /* Fatal error - abort start. */
  18141. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18142. if (error != NULL) {
  18143. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18144. mg_snprintf(NULL,
  18145. NULL, /* No truncation check for error buffers */
  18146. error->text,
  18147. error->text_buffer_size,
  18148. "%s",
  18149. err_msg);
  18150. }
  18151. free_context(ctx);
  18152. pthread_setspecific(sTlsKey, NULL);
  18153. return NULL;
  18154. }
  18155. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18156. if (!set_uid_option(ctx)) {
  18157. const char *err_msg = "Failed to run as configured user";
  18158. /* Fatal error - abort start. */
  18159. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18160. if (error != NULL) {
  18161. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18162. mg_snprintf(NULL,
  18163. NULL, /* No truncation check for error buffers */
  18164. error->text,
  18165. error->text_buffer_size,
  18166. "%s",
  18167. err_msg);
  18168. }
  18169. free_context(ctx);
  18170. pthread_setspecific(sTlsKey, NULL);
  18171. return NULL;
  18172. }
  18173. #endif
  18174. if (!set_acl_option(ctx)) {
  18175. const char *err_msg = "Failed to setup access control list";
  18176. /* Fatal error - abort start. */
  18177. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18178. if (error != NULL) {
  18179. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18180. mg_snprintf(NULL,
  18181. NULL, /* No truncation check for error buffers */
  18182. error->text,
  18183. error->text_buffer_size,
  18184. "%s",
  18185. err_msg);
  18186. }
  18187. free_context(ctx);
  18188. pthread_setspecific(sTlsKey, NULL);
  18189. return NULL;
  18190. }
  18191. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18192. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18193. sizeof(pthread_t),
  18194. ctx);
  18195. if (ctx->worker_threadids == NULL) {
  18196. const char *err_msg = "Not enough memory for worker thread ID array";
  18197. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18198. if (error != NULL) {
  18199. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18200. error->code_sub =
  18201. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
  18202. mg_snprintf(NULL,
  18203. NULL, /* No truncation check for error buffers */
  18204. error->text,
  18205. error->text_buffer_size,
  18206. "%s",
  18207. err_msg);
  18208. }
  18209. free_context(ctx);
  18210. pthread_setspecific(sTlsKey, NULL);
  18211. return NULL;
  18212. }
  18213. ctx->worker_connections =
  18214. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18215. sizeof(struct mg_connection),
  18216. ctx);
  18217. if (ctx->worker_connections == NULL) {
  18218. const char *err_msg =
  18219. "Not enough memory for worker thread connection array";
  18220. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18221. if (error != NULL) {
  18222. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18223. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18224. * (unsigned)sizeof(struct mg_connection);
  18225. mg_snprintf(NULL,
  18226. NULL, /* No truncation check for error buffers */
  18227. error->text,
  18228. error->text_buffer_size,
  18229. "%s",
  18230. err_msg);
  18231. }
  18232. free_context(ctx);
  18233. pthread_setspecific(sTlsKey, NULL);
  18234. return NULL;
  18235. }
  18236. #if defined(ALTERNATIVE_QUEUE)
  18237. ctx->client_wait_events =
  18238. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18239. sizeof(ctx->client_wait_events[0]),
  18240. ctx);
  18241. if (ctx->client_wait_events == NULL) {
  18242. const char *err_msg = "Not enough memory for worker event array";
  18243. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18244. mg_free(ctx->worker_threadids);
  18245. if (error != NULL) {
  18246. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18247. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18248. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18249. mg_snprintf(NULL,
  18250. NULL, /* No truncation check for error buffers */
  18251. error->text,
  18252. error->text_buffer_size,
  18253. "%s",
  18254. err_msg);
  18255. }
  18256. free_context(ctx);
  18257. pthread_setspecific(sTlsKey, NULL);
  18258. return NULL;
  18259. }
  18260. ctx->client_socks =
  18261. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18262. sizeof(ctx->client_socks[0]),
  18263. ctx);
  18264. if (ctx->client_socks == NULL) {
  18265. const char *err_msg = "Not enough memory for worker socket array";
  18266. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18267. mg_free(ctx->client_wait_events);
  18268. mg_free(ctx->worker_threadids);
  18269. if (error != NULL) {
  18270. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18271. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18272. * (unsigned)sizeof(ctx->client_socks[0]);
  18273. mg_snprintf(NULL,
  18274. NULL, /* No truncation check for error buffers */
  18275. error->text,
  18276. error->text_buffer_size,
  18277. "%s",
  18278. err_msg);
  18279. }
  18280. free_context(ctx);
  18281. pthread_setspecific(sTlsKey, NULL);
  18282. return NULL;
  18283. }
  18284. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18285. ctx->client_wait_events[i] = event_create();
  18286. if (ctx->client_wait_events[i] == 0) {
  18287. const char *err_msg = "Error creating worker event %i";
  18288. mg_cry_ctx_internal(ctx, err_msg, i);
  18289. while (i > 0) {
  18290. i--;
  18291. event_destroy(ctx->client_wait_events[i]);
  18292. }
  18293. mg_free(ctx->client_socks);
  18294. mg_free(ctx->client_wait_events);
  18295. mg_free(ctx->worker_threadids);
  18296. if (error != NULL) {
  18297. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18298. error->code_sub = (unsigned)ERRNO;
  18299. mg_snprintf(NULL,
  18300. NULL, /* No truncation check for error buffers */
  18301. error->text,
  18302. error->text_buffer_size,
  18303. err_msg,
  18304. i);
  18305. }
  18306. free_context(ctx);
  18307. pthread_setspecific(sTlsKey, NULL);
  18308. return NULL;
  18309. }
  18310. }
  18311. #endif
  18312. #if defined(USE_TIMERS)
  18313. if (timers_init(ctx) != 0) {
  18314. const char *err_msg = "Error creating timers";
  18315. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18316. if (error != NULL) {
  18317. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18318. error->code_sub = (unsigned)ERRNO;
  18319. mg_snprintf(NULL,
  18320. NULL, /* No truncation check for error buffers */
  18321. error->text,
  18322. error->text_buffer_size,
  18323. "%s",
  18324. err_msg);
  18325. }
  18326. free_context(ctx);
  18327. pthread_setspecific(sTlsKey, NULL);
  18328. return NULL;
  18329. }
  18330. #endif
  18331. /* Context has been created - init user libraries */
  18332. if (ctx->callbacks.init_context) {
  18333. ctx->callbacks.init_context(ctx);
  18334. }
  18335. /* From now, the context is successfully created.
  18336. * When it is destroyed, the exit callback should be called. */
  18337. ctx->callbacks.exit_context = exit_callback;
  18338. ctx->context_type = CONTEXT_SERVER; /* server context */
  18339. /* Start worker threads */
  18340. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18341. /* worker_thread sets up the other fields */
  18342. ctx->worker_connections[i].phys_ctx = ctx;
  18343. if (mg_start_thread_with_id(worker_thread,
  18344. &ctx->worker_connections[i],
  18345. &ctx->worker_threadids[i])
  18346. != 0) {
  18347. long error_no = (long)ERRNO;
  18348. /* thread was not created */
  18349. if (i > 0) {
  18350. /* If the second, third, ... thread cannot be created, set a
  18351. * warning, but keep running. */
  18352. mg_cry_ctx_internal(ctx,
  18353. "Cannot start worker thread %i: error %ld",
  18354. i + 1,
  18355. error_no);
  18356. /* If the server initialization should stop here, all
  18357. * threads that have already been created must be stopped
  18358. * first, before any free_context(ctx) call.
  18359. */
  18360. } else {
  18361. /* If the first worker thread cannot be created, stop
  18362. * initialization and free the entire server context. */
  18363. mg_cry_ctx_internal(ctx,
  18364. "Cannot create threads: error %ld",
  18365. error_no);
  18366. if (error != NULL) {
  18367. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18368. error->code_sub = (unsigned)error_no;
  18369. mg_snprintf(
  18370. NULL,
  18371. NULL, /* No truncation check for error buffers */
  18372. error->text,
  18373. error->text_buffer_size,
  18374. "Cannot create first worker thread: error %ld",
  18375. error_no);
  18376. }
  18377. free_context(ctx);
  18378. pthread_setspecific(sTlsKey, NULL);
  18379. return NULL;
  18380. }
  18381. break;
  18382. }
  18383. }
  18384. /* Start master (listening) thread */
  18385. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18386. pthread_setspecific(sTlsKey, NULL);
  18387. return ctx;
  18388. }
  18389. CIVETWEB_API struct mg_context *
  18390. mg_start(const struct mg_callbacks *callbacks,
  18391. void *user_data,
  18392. const char **options)
  18393. {
  18394. struct mg_init_data init = {0};
  18395. init.callbacks = callbacks;
  18396. init.user_data = user_data;
  18397. init.configuration_options = options;
  18398. return mg_start2(&init, NULL);
  18399. }
  18400. /* Add an additional domain to an already running web server. */
  18401. CIVETWEB_API int
  18402. mg_start_domain2(struct mg_context *ctx,
  18403. const char **options,
  18404. struct mg_error_data *error)
  18405. {
  18406. const char *name;
  18407. const char *value;
  18408. const char *default_value;
  18409. struct mg_domain_context *new_dom;
  18410. struct mg_domain_context *dom;
  18411. int idx, i;
  18412. if (error != NULL) {
  18413. error->code = MG_ERROR_DATA_CODE_OK;
  18414. error->code_sub = 0;
  18415. if (error->text_buffer_size > 0) {
  18416. *error->text = 0;
  18417. }
  18418. }
  18419. if ((ctx == NULL) || (options == NULL)) {
  18420. if (error != NULL) {
  18421. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18422. mg_snprintf(NULL,
  18423. NULL, /* No truncation check for error buffers */
  18424. error->text,
  18425. error->text_buffer_size,
  18426. "%s",
  18427. "Invalid parameters");
  18428. }
  18429. return -1;
  18430. }
  18431. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18432. if (error != NULL) {
  18433. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18434. mg_snprintf(NULL,
  18435. NULL, /* No truncation check for error buffers */
  18436. error->text,
  18437. error->text_buffer_size,
  18438. "%s",
  18439. "Server already stopped");
  18440. }
  18441. return -7;
  18442. }
  18443. new_dom = (struct mg_domain_context *)
  18444. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18445. if (!new_dom) {
  18446. /* Out of memory */
  18447. if (error != NULL) {
  18448. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18449. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18450. mg_snprintf(NULL,
  18451. NULL, /* No truncation check for error buffers */
  18452. error->text,
  18453. error->text_buffer_size,
  18454. "%s",
  18455. "Out or memory");
  18456. }
  18457. return -6;
  18458. }
  18459. /* Store options - TODO: unite duplicate code */
  18460. while (options && (name = *options++) != NULL) {
  18461. idx = get_option_index(name);
  18462. if (idx == -1) {
  18463. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18464. if (error != NULL) {
  18465. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18466. error->code_sub = (unsigned)-1;
  18467. mg_snprintf(NULL,
  18468. NULL, /* No truncation check for error buffers */
  18469. error->text,
  18470. error->text_buffer_size,
  18471. "Invalid option: %s",
  18472. name);
  18473. }
  18474. mg_free(new_dom);
  18475. return -2;
  18476. } else if ((value = *options++) == NULL) {
  18477. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18478. if (error != NULL) {
  18479. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18480. error->code_sub = (unsigned)idx;
  18481. mg_snprintf(NULL,
  18482. NULL, /* No truncation check for error buffers */
  18483. error->text,
  18484. error->text_buffer_size,
  18485. "Invalid option value: %s",
  18486. name);
  18487. }
  18488. mg_free(new_dom);
  18489. return -2;
  18490. }
  18491. if (new_dom->config[idx] != NULL) {
  18492. /* Duplicate option: Later values overwrite earlier ones. */
  18493. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18494. mg_free(new_dom->config[idx]);
  18495. }
  18496. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18497. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18498. }
  18499. /* Authentication domain is mandatory */
  18500. /* TODO: Maybe use a new option hostname? */
  18501. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18502. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18503. if (error != NULL) {
  18504. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18505. error->code_sub = AUTHENTICATION_DOMAIN;
  18506. mg_snprintf(NULL,
  18507. NULL, /* No truncation check for error buffers */
  18508. error->text,
  18509. error->text_buffer_size,
  18510. "Mandatory option %s missing",
  18511. config_options[AUTHENTICATION_DOMAIN].name);
  18512. }
  18513. mg_free(new_dom);
  18514. return -4;
  18515. }
  18516. /* Set default value if needed. Take the config value from
  18517. * ctx as a default value. */
  18518. for (i = 0; config_options[i].name != NULL; i++) {
  18519. default_value = ctx->dd.config[i];
  18520. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18521. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18522. }
  18523. }
  18524. new_dom->handlers = NULL;
  18525. new_dom->next = NULL;
  18526. new_dom->nonce_count = 0;
  18527. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18528. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18529. new_dom->shared_lua_websockets = NULL;
  18530. #endif
  18531. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18532. if (!init_ssl_ctx(ctx, new_dom)) {
  18533. /* Init SSL failed */
  18534. if (error != NULL) {
  18535. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18536. mg_snprintf(NULL,
  18537. NULL, /* No truncation check for error buffers */
  18538. error->text,
  18539. error->text_buffer_size,
  18540. "%s",
  18541. "Initializing SSL context failed");
  18542. }
  18543. mg_free(new_dom);
  18544. return -3;
  18545. }
  18546. #endif
  18547. /* Add element to linked list. */
  18548. mg_lock_context(ctx);
  18549. idx = 0;
  18550. dom = &(ctx->dd);
  18551. for (;;) {
  18552. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18553. dom->config[AUTHENTICATION_DOMAIN])) {
  18554. /* Domain collision */
  18555. mg_cry_ctx_internal(ctx,
  18556. "domain %s already in use",
  18557. new_dom->config[AUTHENTICATION_DOMAIN]);
  18558. if (error != NULL) {
  18559. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18560. mg_snprintf(NULL,
  18561. NULL, /* No truncation check for error buffers */
  18562. error->text,
  18563. error->text_buffer_size,
  18564. "Domain %s specified by %s is already in use",
  18565. new_dom->config[AUTHENTICATION_DOMAIN],
  18566. config_options[AUTHENTICATION_DOMAIN].name);
  18567. }
  18568. mg_free(new_dom);
  18569. mg_unlock_context(ctx);
  18570. return -5;
  18571. }
  18572. /* Count number of domains */
  18573. idx++;
  18574. if (dom->next == NULL) {
  18575. dom->next = new_dom;
  18576. break;
  18577. }
  18578. dom = dom->next;
  18579. }
  18580. mg_unlock_context(ctx);
  18581. /* Return domain number */
  18582. return idx;
  18583. }
  18584. CIVETWEB_API int
  18585. mg_start_domain(struct mg_context *ctx, const char **options)
  18586. {
  18587. return mg_start_domain2(ctx, options, NULL);
  18588. }
  18589. /* Feature check API function */
  18590. CIVETWEB_API unsigned
  18591. mg_check_feature(unsigned feature)
  18592. {
  18593. static const unsigned feature_set = 0
  18594. /* Set bits for available features according to API documentation.
  18595. * This bit mask is created at compile time, according to the active
  18596. * preprocessor defines. It is a single const value at runtime. */
  18597. #if !defined(NO_FILES)
  18598. | MG_FEATURES_FILES
  18599. #endif
  18600. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18601. | MG_FEATURES_SSL
  18602. #endif
  18603. #if !defined(NO_CGI)
  18604. | MG_FEATURES_CGI
  18605. #endif
  18606. #if defined(USE_IPV6)
  18607. | MG_FEATURES_IPV6
  18608. #endif
  18609. #if defined(USE_WEBSOCKET)
  18610. | MG_FEATURES_WEBSOCKET
  18611. #endif
  18612. #if defined(USE_LUA)
  18613. | MG_FEATURES_LUA
  18614. #endif
  18615. #if defined(USE_DUKTAPE)
  18616. | MG_FEATURES_SSJS
  18617. #endif
  18618. #if !defined(NO_CACHING)
  18619. | MG_FEATURES_CACHE
  18620. #endif
  18621. #if defined(USE_SERVER_STATS)
  18622. | MG_FEATURES_STATS
  18623. #endif
  18624. #if defined(USE_ZLIB)
  18625. | MG_FEATURES_COMPRESSION
  18626. #endif
  18627. #if defined(USE_HTTP2)
  18628. | MG_FEATURES_HTTP2
  18629. #endif
  18630. #if defined(USE_X_DOM_SOCKET)
  18631. | MG_FEATURES_X_DOMAIN_SOCKET
  18632. #endif
  18633. /* Set some extra bits not defined in the API documentation.
  18634. * These bits may change without further notice. */
  18635. #if defined(MG_LEGACY_INTERFACE)
  18636. | 0x80000000u
  18637. #endif
  18638. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18639. | 0x40000000u
  18640. #endif
  18641. #if !defined(NO_RESPONSE_BUFFERING)
  18642. | 0x20000000u
  18643. #endif
  18644. #if defined(MEMORY_DEBUGGING)
  18645. | 0x10000000u
  18646. #endif
  18647. ;
  18648. return (feature & feature_set);
  18649. }
  18650. static size_t
  18651. mg_str_append(char **dst, char *end, const char *src)
  18652. {
  18653. size_t len = strlen(src);
  18654. if (*dst != end) {
  18655. /* Append src if enough space, or close dst. */
  18656. if ((size_t)(end - *dst) > len) {
  18657. strcpy(*dst, src);
  18658. *dst += len;
  18659. } else {
  18660. *dst = end;
  18661. }
  18662. }
  18663. return len;
  18664. }
  18665. /* Get system information. It can be printed or stored by the caller.
  18666. * Return the size of available information. */
  18667. CIVETWEB_API int
  18668. mg_get_system_info(char *buffer, int buflen)
  18669. {
  18670. char *end, *append_eoobj = NULL, block[256];
  18671. size_t system_info_length = 0;
  18672. #if defined(_WIN32)
  18673. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18674. #else
  18675. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18676. #endif
  18677. if ((buffer == NULL) || (buflen < 1)) {
  18678. buflen = 0;
  18679. end = buffer;
  18680. } else {
  18681. *buffer = 0;
  18682. end = buffer + buflen;
  18683. }
  18684. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18685. /* has enough space to append eoobj */
  18686. append_eoobj = buffer;
  18687. if (end) {
  18688. end -= sizeof(eoobj) - 1;
  18689. }
  18690. }
  18691. system_info_length += mg_str_append(&buffer, end, "{");
  18692. /* Server version */
  18693. {
  18694. const char *version = mg_version();
  18695. mg_snprintf(NULL,
  18696. NULL,
  18697. block,
  18698. sizeof(block),
  18699. "%s\"version\" : \"%s\"",
  18700. eol,
  18701. version);
  18702. system_info_length += mg_str_append(&buffer, end, block);
  18703. }
  18704. /* System info */
  18705. {
  18706. #if defined(_WIN32)
  18707. DWORD dwVersion = 0;
  18708. DWORD dwMajorVersion = 0;
  18709. DWORD dwMinorVersion = 0;
  18710. SYSTEM_INFO si;
  18711. GetSystemInfo(&si);
  18712. #if defined(_MSC_VER)
  18713. #pragma warning(push)
  18714. /* GetVersion was declared deprecated */
  18715. #pragma warning(disable : 4996)
  18716. #endif
  18717. dwVersion = GetVersion();
  18718. #if defined(_MSC_VER)
  18719. #pragma warning(pop)
  18720. #endif
  18721. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18722. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18723. mg_snprintf(NULL,
  18724. NULL,
  18725. block,
  18726. sizeof(block),
  18727. ",%s\"os\" : \"Windows %u.%u\"",
  18728. eol,
  18729. (unsigned)dwMajorVersion,
  18730. (unsigned)dwMinorVersion);
  18731. system_info_length += mg_str_append(&buffer, end, block);
  18732. mg_snprintf(NULL,
  18733. NULL,
  18734. block,
  18735. sizeof(block),
  18736. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18737. eol,
  18738. (unsigned)si.wProcessorArchitecture,
  18739. (unsigned)si.dwNumberOfProcessors,
  18740. (unsigned)si.dwActiveProcessorMask);
  18741. system_info_length += mg_str_append(&buffer, end, block);
  18742. #elif defined(__ZEPHYR__)
  18743. mg_snprintf(NULL,
  18744. NULL,
  18745. block,
  18746. sizeof(block),
  18747. ",%s\"os\" : \"%s %s\"",
  18748. eol,
  18749. "Zephyr OS",
  18750. ZEPHYR_VERSION);
  18751. system_info_length += mg_str_append(&buffer, end, block);
  18752. #else
  18753. struct utsname name;
  18754. memset(&name, 0, sizeof(name));
  18755. uname(&name);
  18756. mg_snprintf(NULL,
  18757. NULL,
  18758. block,
  18759. sizeof(block),
  18760. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18761. eol,
  18762. name.sysname,
  18763. name.version,
  18764. name.release,
  18765. name.machine);
  18766. system_info_length += mg_str_append(&buffer, end, block);
  18767. #endif
  18768. }
  18769. /* Features */
  18770. {
  18771. mg_snprintf(NULL,
  18772. NULL,
  18773. block,
  18774. sizeof(block),
  18775. ",%s\"features\" : %lu"
  18776. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18777. eol,
  18778. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18779. eol,
  18780. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18781. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18782. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18783. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18784. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18785. : "",
  18786. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18787. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18788. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18789. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18790. system_info_length += mg_str_append(&buffer, end, block);
  18791. #if defined(USE_LUA)
  18792. mg_snprintf(NULL,
  18793. NULL,
  18794. block,
  18795. sizeof(block),
  18796. ",%s\"lua_version\" : \"%u (%s)\"",
  18797. eol,
  18798. (unsigned)LUA_VERSION_NUM,
  18799. LUA_RELEASE);
  18800. system_info_length += mg_str_append(&buffer, end, block);
  18801. #endif
  18802. #if defined(USE_DUKTAPE)
  18803. mg_snprintf(NULL,
  18804. NULL,
  18805. block,
  18806. sizeof(block),
  18807. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18808. eol,
  18809. (unsigned)DUK_VERSION / 10000,
  18810. ((unsigned)DUK_VERSION / 100) % 100,
  18811. (unsigned)DUK_VERSION % 100);
  18812. system_info_length += mg_str_append(&buffer, end, block);
  18813. #endif
  18814. }
  18815. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18816. {
  18817. #if defined(BUILD_DATE)
  18818. const char *bd = BUILD_DATE;
  18819. #else
  18820. #if defined(GCC_DIAGNOSTIC)
  18821. #if GCC_VERSION >= 40900
  18822. #pragma GCC diagnostic push
  18823. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18824. * does not work in some versions. If "BUILD_DATE" is defined to some
  18825. * string, it is used instead of __DATE__. */
  18826. #pragma GCC diagnostic ignored "-Wdate-time"
  18827. #endif
  18828. #endif
  18829. const char *bd = __DATE__;
  18830. #if defined(GCC_DIAGNOSTIC)
  18831. #if GCC_VERSION >= 40900
  18832. #pragma GCC diagnostic pop
  18833. #endif
  18834. #endif
  18835. #endif
  18836. mg_snprintf(
  18837. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18838. system_info_length += mg_str_append(&buffer, end, block);
  18839. }
  18840. /* Compiler information */
  18841. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18842. {
  18843. #if defined(_MSC_VER)
  18844. mg_snprintf(NULL,
  18845. NULL,
  18846. block,
  18847. sizeof(block),
  18848. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18849. eol,
  18850. (unsigned)_MSC_VER,
  18851. (unsigned)_MSC_FULL_VER);
  18852. system_info_length += mg_str_append(&buffer, end, block);
  18853. #elif defined(__MINGW64__)
  18854. mg_snprintf(NULL,
  18855. NULL,
  18856. block,
  18857. sizeof(block),
  18858. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18859. eol,
  18860. (unsigned)__MINGW64_VERSION_MAJOR,
  18861. (unsigned)__MINGW64_VERSION_MINOR);
  18862. system_info_length += mg_str_append(&buffer, end, block);
  18863. mg_snprintf(NULL,
  18864. NULL,
  18865. block,
  18866. sizeof(block),
  18867. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18868. eol,
  18869. (unsigned)__MINGW32_MAJOR_VERSION,
  18870. (unsigned)__MINGW32_MINOR_VERSION);
  18871. system_info_length += mg_str_append(&buffer, end, block);
  18872. #elif defined(__MINGW32__)
  18873. mg_snprintf(NULL,
  18874. NULL,
  18875. block,
  18876. sizeof(block),
  18877. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18878. eol,
  18879. (unsigned)__MINGW32_MAJOR_VERSION,
  18880. (unsigned)__MINGW32_MINOR_VERSION);
  18881. system_info_length += mg_str_append(&buffer, end, block);
  18882. #elif defined(__clang__)
  18883. mg_snprintf(NULL,
  18884. NULL,
  18885. block,
  18886. sizeof(block),
  18887. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18888. eol,
  18889. __clang_major__,
  18890. __clang_minor__,
  18891. __clang_patchlevel__,
  18892. __clang_version__);
  18893. system_info_length += mg_str_append(&buffer, end, block);
  18894. #elif defined(__GNUC__)
  18895. mg_snprintf(NULL,
  18896. NULL,
  18897. block,
  18898. sizeof(block),
  18899. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18900. eol,
  18901. (unsigned)__GNUC__,
  18902. (unsigned)__GNUC_MINOR__,
  18903. (unsigned)__GNUC_PATCHLEVEL__);
  18904. system_info_length += mg_str_append(&buffer, end, block);
  18905. #elif defined(__INTEL_COMPILER)
  18906. mg_snprintf(NULL,
  18907. NULL,
  18908. block,
  18909. sizeof(block),
  18910. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18911. eol,
  18912. (unsigned)__INTEL_COMPILER);
  18913. system_info_length += mg_str_append(&buffer, end, block);
  18914. #elif defined(__BORLANDC__)
  18915. mg_snprintf(NULL,
  18916. NULL,
  18917. block,
  18918. sizeof(block),
  18919. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18920. eol,
  18921. (unsigned)__BORLANDC__);
  18922. system_info_length += mg_str_append(&buffer, end, block);
  18923. #elif defined(__SUNPRO_C)
  18924. mg_snprintf(NULL,
  18925. NULL,
  18926. block,
  18927. sizeof(block),
  18928. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18929. eol,
  18930. (unsigned)__SUNPRO_C);
  18931. system_info_length += mg_str_append(&buffer, end, block);
  18932. #else
  18933. mg_snprintf(NULL,
  18934. NULL,
  18935. block,
  18936. sizeof(block),
  18937. ",%s\"compiler\" : \"other\"",
  18938. eol);
  18939. system_info_length += mg_str_append(&buffer, end, block);
  18940. #endif
  18941. }
  18942. /* Determine 32/64 bit data mode.
  18943. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18944. {
  18945. mg_snprintf(NULL,
  18946. NULL,
  18947. block,
  18948. sizeof(block),
  18949. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18950. "char:%u/%u, "
  18951. "ptr:%u, size:%u, time:%u\"",
  18952. eol,
  18953. (unsigned)sizeof(short),
  18954. (unsigned)sizeof(int),
  18955. (unsigned)sizeof(long),
  18956. (unsigned)sizeof(long long),
  18957. (unsigned)sizeof(float),
  18958. (unsigned)sizeof(double),
  18959. (unsigned)sizeof(long double),
  18960. (unsigned)sizeof(char),
  18961. (unsigned)sizeof(wchar_t),
  18962. (unsigned)sizeof(void *),
  18963. (unsigned)sizeof(size_t),
  18964. (unsigned)sizeof(time_t));
  18965. system_info_length += mg_str_append(&buffer, end, block);
  18966. }
  18967. /* Terminate string */
  18968. if (append_eoobj) {
  18969. strcat(append_eoobj, eoobj);
  18970. }
  18971. system_info_length += sizeof(eoobj) - 1;
  18972. return (int)system_info_length;
  18973. }
  18974. /* Get context information. It can be printed or stored by the caller.
  18975. * Return the size of available information. */
  18976. CIVETWEB_API int
  18977. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18978. {
  18979. #if defined(USE_SERVER_STATS)
  18980. char *end, *append_eoobj = NULL, block[256];
  18981. size_t context_info_length = 0;
  18982. #if defined(_WIN32)
  18983. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18984. #else
  18985. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18986. #endif
  18987. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18988. if ((buffer == NULL) || (buflen < 1)) {
  18989. buflen = 0;
  18990. end = buffer;
  18991. } else {
  18992. *buffer = 0;
  18993. end = buffer + buflen;
  18994. }
  18995. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18996. /* has enough space to append eoobj */
  18997. append_eoobj = buffer;
  18998. end -= sizeof(eoobj) - 1;
  18999. }
  19000. context_info_length += mg_str_append(&buffer, end, "{");
  19001. if (ms) { /* <-- should be always true */
  19002. /* Memory information */
  19003. int blockCount = (int)ms->blockCount;
  19004. int64_t totalMemUsed = ms->totalMemUsed;
  19005. int64_t maxMemUsed = ms->maxMemUsed;
  19006. if (totalMemUsed > maxMemUsed) {
  19007. maxMemUsed = totalMemUsed;
  19008. }
  19009. mg_snprintf(NULL,
  19010. NULL,
  19011. block,
  19012. sizeof(block),
  19013. "%s\"memory\" : {%s"
  19014. "\"blocks\" : %i,%s"
  19015. "\"used\" : %" INT64_FMT ",%s"
  19016. "\"maxUsed\" : %" INT64_FMT "%s"
  19017. "}",
  19018. eol,
  19019. eol,
  19020. blockCount,
  19021. eol,
  19022. totalMemUsed,
  19023. eol,
  19024. maxMemUsed,
  19025. eol);
  19026. context_info_length += mg_str_append(&buffer, end, block);
  19027. }
  19028. if (ctx) {
  19029. /* Declare all variables at begin of the block, to comply
  19030. * with old C standards. */
  19031. char start_time_str[64] = {0};
  19032. char now_str[64] = {0};
  19033. time_t start_time = ctx->start_time;
  19034. time_t now = time(NULL);
  19035. int64_t total_data_read, total_data_written;
  19036. int active_connections = (int)ctx->active_connections;
  19037. int max_active_connections = (int)ctx->max_active_connections;
  19038. int total_connections = (int)ctx->total_connections;
  19039. if (active_connections > max_active_connections) {
  19040. max_active_connections = active_connections;
  19041. }
  19042. if (active_connections > total_connections) {
  19043. total_connections = active_connections;
  19044. }
  19045. /* Connections information */
  19046. mg_snprintf(NULL,
  19047. NULL,
  19048. block,
  19049. sizeof(block),
  19050. ",%s\"connections\" : {%s"
  19051. "\"active\" : %i,%s"
  19052. "\"maxActive\" : %i,%s"
  19053. "\"total\" : %i%s"
  19054. "}",
  19055. eol,
  19056. eol,
  19057. active_connections,
  19058. eol,
  19059. max_active_connections,
  19060. eol,
  19061. total_connections,
  19062. eol);
  19063. context_info_length += mg_str_append(&buffer, end, block);
  19064. /* Queue information */
  19065. #if !defined(ALTERNATIVE_QUEUE)
  19066. mg_snprintf(NULL,
  19067. NULL,
  19068. block,
  19069. sizeof(block),
  19070. ",%s\"queue\" : {%s"
  19071. "\"length\" : %i,%s"
  19072. "\"filled\" : %i,%s"
  19073. "\"maxFilled\" : %i,%s"
  19074. "\"full\" : %s%s"
  19075. "}",
  19076. eol,
  19077. eol,
  19078. ctx->sq_size,
  19079. eol,
  19080. ctx->sq_head - ctx->sq_tail,
  19081. eol,
  19082. ctx->sq_max_fill,
  19083. eol,
  19084. (ctx->sq_blocked ? "true" : "false"),
  19085. eol);
  19086. context_info_length += mg_str_append(&buffer, end, block);
  19087. #endif
  19088. /* Requests information */
  19089. mg_snprintf(NULL,
  19090. NULL,
  19091. block,
  19092. sizeof(block),
  19093. ",%s\"requests\" : {%s"
  19094. "\"total\" : %lu%s"
  19095. "}",
  19096. eol,
  19097. eol,
  19098. (unsigned long)ctx->total_requests,
  19099. eol);
  19100. context_info_length += mg_str_append(&buffer, end, block);
  19101. /* Data information */
  19102. total_data_read =
  19103. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19104. total_data_written =
  19105. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19106. mg_snprintf(NULL,
  19107. NULL,
  19108. block,
  19109. sizeof(block),
  19110. ",%s\"data\" : {%s"
  19111. "\"read\" : %" INT64_FMT ",%s"
  19112. "\"written\" : %" INT64_FMT "%s"
  19113. "}",
  19114. eol,
  19115. eol,
  19116. total_data_read,
  19117. eol,
  19118. total_data_written,
  19119. eol);
  19120. context_info_length += mg_str_append(&buffer, end, block);
  19121. /* Execution time information */
  19122. gmt_time_string(start_time_str,
  19123. sizeof(start_time_str) - 1,
  19124. &start_time);
  19125. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19126. mg_snprintf(NULL,
  19127. NULL,
  19128. block,
  19129. sizeof(block),
  19130. ",%s\"time\" : {%s"
  19131. "\"uptime\" : %.0f,%s"
  19132. "\"start\" : \"%s\",%s"
  19133. "\"now\" : \"%s\"%s"
  19134. "}",
  19135. eol,
  19136. eol,
  19137. difftime(now, start_time),
  19138. eol,
  19139. start_time_str,
  19140. eol,
  19141. now_str,
  19142. eol);
  19143. context_info_length += mg_str_append(&buffer, end, block);
  19144. }
  19145. /* Terminate string */
  19146. if (append_eoobj) {
  19147. strcat(append_eoobj, eoobj);
  19148. }
  19149. context_info_length += sizeof(eoobj) - 1;
  19150. return (int)context_info_length;
  19151. #else
  19152. (void)ctx;
  19153. if ((buffer != NULL) && (buflen > 0)) {
  19154. *buffer = 0;
  19155. }
  19156. return 0;
  19157. #endif
  19158. }
  19159. CIVETWEB_API void
  19160. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19161. {
  19162. /* https://github.com/civetweb/civetweb/issues/727 */
  19163. if (conn != NULL) {
  19164. conn->must_close = 1;
  19165. }
  19166. }
  19167. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19168. /* Get connection information. It can be printed or stored by the caller.
  19169. * Return the size of available information. */
  19170. CIVETWEB_API int
  19171. mg_get_connection_info(const struct mg_context *ctx,
  19172. int idx,
  19173. char *buffer,
  19174. int buflen)
  19175. {
  19176. const struct mg_connection *conn;
  19177. const struct mg_request_info *ri;
  19178. char *end, *append_eoobj = NULL, block[256];
  19179. size_t connection_info_length = 0;
  19180. int state = 0;
  19181. const char *state_str = "unknown";
  19182. #if defined(_WIN32)
  19183. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19184. #else
  19185. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19186. #endif
  19187. if ((buffer == NULL) || (buflen < 1)) {
  19188. buflen = 0;
  19189. end = buffer;
  19190. } else {
  19191. *buffer = 0;
  19192. end = buffer + buflen;
  19193. }
  19194. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19195. /* has enough space to append eoobj */
  19196. append_eoobj = buffer;
  19197. end -= sizeof(eoobj) - 1;
  19198. }
  19199. if ((ctx == NULL) || (idx < 0)) {
  19200. /* Parameter error */
  19201. return 0;
  19202. }
  19203. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19204. /* Out of range */
  19205. return 0;
  19206. }
  19207. /* Take connection [idx]. This connection is not locked in
  19208. * any way, so some other thread might use it. */
  19209. conn = (ctx->worker_connections) + idx;
  19210. /* Initialize output string */
  19211. connection_info_length += mg_str_append(&buffer, end, "{");
  19212. /* Init variables */
  19213. ri = &(conn->request_info);
  19214. #if defined(USE_SERVER_STATS)
  19215. state = conn->conn_state;
  19216. /* State as string */
  19217. switch (state) {
  19218. case 0:
  19219. state_str = "undefined";
  19220. break;
  19221. case 1:
  19222. state_str = "not used";
  19223. break;
  19224. case 2:
  19225. state_str = "init";
  19226. break;
  19227. case 3:
  19228. state_str = "ready";
  19229. break;
  19230. case 4:
  19231. state_str = "processing";
  19232. break;
  19233. case 5:
  19234. state_str = "processed";
  19235. break;
  19236. case 6:
  19237. state_str = "to close";
  19238. break;
  19239. case 7:
  19240. state_str = "closing";
  19241. break;
  19242. case 8:
  19243. state_str = "closed";
  19244. break;
  19245. case 9:
  19246. state_str = "done";
  19247. break;
  19248. }
  19249. #endif
  19250. /* Connection info */
  19251. if ((state >= 3) && (state < 9)) {
  19252. mg_snprintf(NULL,
  19253. NULL,
  19254. block,
  19255. sizeof(block),
  19256. "%s\"connection\" : {%s"
  19257. "\"remote\" : {%s"
  19258. "\"protocol\" : \"%s\",%s"
  19259. "\"addr\" : \"%s\",%s"
  19260. "\"port\" : %u%s"
  19261. "},%s"
  19262. "\"handled_requests\" : %u%s"
  19263. "}",
  19264. eol,
  19265. eol,
  19266. eol,
  19267. get_proto_name(conn),
  19268. eol,
  19269. ri->remote_addr,
  19270. eol,
  19271. ri->remote_port,
  19272. eol,
  19273. eol,
  19274. conn->handled_requests,
  19275. eol);
  19276. connection_info_length += mg_str_append(&buffer, end, block);
  19277. }
  19278. /* Request info */
  19279. if ((state >= 4) && (state < 6)) {
  19280. mg_snprintf(NULL,
  19281. NULL,
  19282. block,
  19283. sizeof(block),
  19284. "%s%s\"request_info\" : {%s"
  19285. "\"method\" : \"%s\",%s"
  19286. "\"uri\" : \"%s\",%s"
  19287. "\"query\" : %s%s%s%s"
  19288. "}",
  19289. (connection_info_length > 1 ? "," : ""),
  19290. eol,
  19291. eol,
  19292. ri->request_method,
  19293. eol,
  19294. ri->request_uri,
  19295. eol,
  19296. ri->query_string ? "\"" : "",
  19297. ri->query_string ? ri->query_string : "null",
  19298. ri->query_string ? "\"" : "",
  19299. eol);
  19300. connection_info_length += mg_str_append(&buffer, end, block);
  19301. }
  19302. /* Execution time information */
  19303. if ((state >= 2) && (state < 9)) {
  19304. char start_time_str[64] = {0};
  19305. char close_time_str[64] = {0};
  19306. time_t start_time = conn->conn_birth_time;
  19307. time_t close_time = 0;
  19308. double time_diff;
  19309. gmt_time_string(start_time_str,
  19310. sizeof(start_time_str) - 1,
  19311. &start_time);
  19312. #if defined(USE_SERVER_STATS)
  19313. close_time = conn->conn_close_time;
  19314. #endif
  19315. if (close_time != 0) {
  19316. time_diff = difftime(close_time, start_time);
  19317. gmt_time_string(close_time_str,
  19318. sizeof(close_time_str) - 1,
  19319. &close_time);
  19320. } else {
  19321. time_t now = time(NULL);
  19322. time_diff = difftime(now, start_time);
  19323. close_time_str[0] = 0; /* or use "now" ? */
  19324. }
  19325. mg_snprintf(NULL,
  19326. NULL,
  19327. block,
  19328. sizeof(block),
  19329. "%s%s\"time\" : {%s"
  19330. "\"uptime\" : %.0f,%s"
  19331. "\"start\" : \"%s\",%s"
  19332. "\"closed\" : \"%s\"%s"
  19333. "}",
  19334. (connection_info_length > 1 ? "," : ""),
  19335. eol,
  19336. eol,
  19337. time_diff,
  19338. eol,
  19339. start_time_str,
  19340. eol,
  19341. close_time_str,
  19342. eol);
  19343. connection_info_length += mg_str_append(&buffer, end, block);
  19344. }
  19345. /* Remote user name */
  19346. if ((ri->remote_user) && (state < 9)) {
  19347. mg_snprintf(NULL,
  19348. NULL,
  19349. block,
  19350. sizeof(block),
  19351. "%s%s\"user\" : {%s"
  19352. "\"name\" : \"%s\",%s"
  19353. "}",
  19354. (connection_info_length > 1 ? "," : ""),
  19355. eol,
  19356. eol,
  19357. ri->remote_user,
  19358. eol);
  19359. connection_info_length += mg_str_append(&buffer, end, block);
  19360. }
  19361. /* Data block */
  19362. if (state >= 3) {
  19363. mg_snprintf(NULL,
  19364. NULL,
  19365. block,
  19366. sizeof(block),
  19367. "%s%s\"data\" : {%s"
  19368. "\"read\" : %" INT64_FMT ",%s"
  19369. "\"written\" : %" INT64_FMT "%s"
  19370. "}",
  19371. (connection_info_length > 1 ? "," : ""),
  19372. eol,
  19373. eol,
  19374. conn->consumed_content,
  19375. eol,
  19376. conn->num_bytes_sent,
  19377. eol);
  19378. connection_info_length += mg_str_append(&buffer, end, block);
  19379. }
  19380. /* State */
  19381. mg_snprintf(NULL,
  19382. NULL,
  19383. block,
  19384. sizeof(block),
  19385. "%s%s\"state\" : \"%s\"",
  19386. (connection_info_length > 1 ? "," : ""),
  19387. eol,
  19388. state_str);
  19389. connection_info_length += mg_str_append(&buffer, end, block);
  19390. /* Terminate string */
  19391. if (append_eoobj) {
  19392. strcat(append_eoobj, eoobj);
  19393. }
  19394. connection_info_length += sizeof(eoobj) - 1;
  19395. return (int)connection_info_length;
  19396. }
  19397. #if 0
  19398. /* Get handler information. Not fully implemented. Is it required? */
  19399. CIVETWEB_API int
  19400. mg_get_handler_info(struct mg_context *ctx,
  19401. char *buffer,
  19402. int buflen)
  19403. {
  19404. int handler_info_len = 0;
  19405. struct mg_handler_info *tmp_rh;
  19406. mg_lock_context(ctx);
  19407. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19408. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19409. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19410. }
  19411. handler_info_len += tmp_rh->uri_len;
  19412. switch (tmp_rh->handler_type) {
  19413. case REQUEST_HANDLER:
  19414. (void)tmp_rh->handler;
  19415. break;
  19416. case WEBSOCKET_HANDLER:
  19417. (void)tmp_rh->connect_handler;
  19418. (void)tmp_rh->ready_handler;
  19419. (void)tmp_rh->data_handler;
  19420. (void)tmp_rh->close_handler;
  19421. break;
  19422. case AUTH_HANDLER:
  19423. (void)tmp_rh->auth_handler;
  19424. break;
  19425. }
  19426. (void)cbdata;
  19427. }
  19428. mg_unlock_context(ctx);
  19429. return handler_info_len;
  19430. }
  19431. #endif
  19432. #endif
  19433. /* Initialize this library. This function does not need to be thread safe.
  19434. */
  19435. CIVETWEB_API unsigned
  19436. mg_init_library(unsigned features)
  19437. {
  19438. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19439. unsigned features_inited = features_to_init;
  19440. if (mg_init_library_called <= 0) {
  19441. /* Not initialized yet */
  19442. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19443. return 0;
  19444. }
  19445. }
  19446. mg_global_lock();
  19447. if (mg_init_library_called <= 0) {
  19448. int i;
  19449. size_t len;
  19450. #if defined(_WIN32)
  19451. int file_mutex_init = 1;
  19452. int wsa = 1;
  19453. #else
  19454. int mutexattr_init = 1;
  19455. #endif
  19456. int failed = 1;
  19457. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19458. if (key_create == 0) {
  19459. #if defined(_WIN32)
  19460. file_mutex_init =
  19461. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19462. if (file_mutex_init == 0) {
  19463. /* Start WinSock */
  19464. WSADATA data;
  19465. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19466. }
  19467. #else
  19468. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19469. if (mutexattr_init == 0) {
  19470. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19471. PTHREAD_MUTEX_RECURSIVE);
  19472. }
  19473. #endif
  19474. }
  19475. if (failed) {
  19476. #if defined(_WIN32)
  19477. if (wsa == 0) {
  19478. (void)WSACleanup();
  19479. }
  19480. if (file_mutex_init == 0) {
  19481. (void)pthread_mutex_destroy(&global_log_file_lock);
  19482. }
  19483. #else
  19484. if (mutexattr_init == 0) {
  19485. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19486. }
  19487. #endif
  19488. if (key_create == 0) {
  19489. (void)pthread_key_delete(sTlsKey);
  19490. }
  19491. mg_global_unlock();
  19492. (void)pthread_mutex_destroy(&global_lock_mutex);
  19493. return 0;
  19494. }
  19495. len = 1;
  19496. for (i = 0; http_methods[i].name != NULL; i++) {
  19497. size_t sl = strlen(http_methods[i].name);
  19498. len += sl;
  19499. if (i > 0) {
  19500. len += 2;
  19501. }
  19502. }
  19503. all_methods = (char *)mg_malloc(len);
  19504. if (!all_methods) {
  19505. /* Must never happen */
  19506. mg_global_unlock();
  19507. (void)pthread_mutex_destroy(&global_lock_mutex);
  19508. return 0;
  19509. }
  19510. all_methods[0] = 0;
  19511. for (i = 0; http_methods[i].name != NULL; i++) {
  19512. if (i > 0) {
  19513. strcat(all_methods, ", ");
  19514. strcat(all_methods, http_methods[i].name);
  19515. } else {
  19516. strcpy(all_methods, http_methods[i].name);
  19517. }
  19518. }
  19519. }
  19520. #if defined(USE_LUA)
  19521. lua_init_optional_libraries();
  19522. #endif
  19523. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19524. || defined(OPENSSL_API_3_0)) \
  19525. && !defined(NO_SSL)
  19526. if (features_to_init & MG_FEATURES_SSL) {
  19527. if (!mg_openssl_initialized) {
  19528. char ebuf[128];
  19529. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19530. mg_openssl_initialized = 1;
  19531. } else {
  19532. (void)ebuf;
  19533. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19534. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19535. }
  19536. } else {
  19537. /* ssl already initialized */
  19538. }
  19539. }
  19540. #endif
  19541. if (mg_init_library_called <= 0) {
  19542. mg_init_library_called = 1;
  19543. } else {
  19544. mg_init_library_called++;
  19545. }
  19546. mg_global_unlock();
  19547. return features_inited;
  19548. }
  19549. /* Un-initialize this library. */
  19550. CIVETWEB_API unsigned
  19551. mg_exit_library(void)
  19552. {
  19553. if (mg_init_library_called <= 0) {
  19554. return 0;
  19555. }
  19556. mg_global_lock();
  19557. mg_init_library_called--;
  19558. if (mg_init_library_called == 0) {
  19559. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19560. if (mg_openssl_initialized) {
  19561. uninitialize_openssl();
  19562. mg_openssl_initialized = 0;
  19563. }
  19564. #endif
  19565. #if defined(_WIN32)
  19566. (void)WSACleanup();
  19567. (void)pthread_mutex_destroy(&global_log_file_lock);
  19568. #else
  19569. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19570. #endif
  19571. (void)pthread_key_delete(sTlsKey);
  19572. #if defined(USE_LUA)
  19573. lua_exit_optional_libraries();
  19574. #endif
  19575. mg_free(all_methods);
  19576. all_methods = NULL;
  19577. mg_global_unlock();
  19578. (void)pthread_mutex_destroy(&global_lock_mutex);
  19579. return 1;
  19580. }
  19581. mg_global_unlock();
  19582. return 1;
  19583. }
  19584. /* End of civetweb.c */