civetweb.c 594 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364
  1. /* Copyright (c) 2013-2021 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. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0502
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__) || defined(__sun)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Select queue implementation. Diagnosis features originally only implemented
  123. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  124. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  125. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  126. * implementation, since the queue length is independent from the number of
  127. * worker threads there, while the new queue is one element per worker thread.
  128. *
  129. */
  130. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  131. /* The queues are exclusive or - only one can be used. */
  132. #error \
  133. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  134. #endif
  135. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  136. /* Use a default implementation */
  137. #define NO_ALTERNATIVE_QUEUE
  138. #endif
  139. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  140. /* File system access:
  141. * NO_FILES = do not serve any files from the file system automatically.
  142. * However, with NO_FILES CivetWeb may still write log files, read access
  143. * control files, default error page files or use API functions like
  144. * mg_send_file in callbacks to send files from the server local
  145. * file system.
  146. * NO_FILES only disables the automatic mapping between URLs and local
  147. * file names.
  148. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  149. * devices without file system. Logging to files in not available
  150. * (use callbacks instead) and API functions like mg_send_file are not
  151. * available.
  152. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  153. */
  154. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  155. #endif
  156. /* DTL -- including winsock2.h works better if lean and mean */
  157. #if !defined(WIN32_LEAN_AND_MEAN)
  158. #define WIN32_LEAN_AND_MEAN
  159. #endif
  160. #if defined(__SYMBIAN32__)
  161. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  162. * Symbian is no longer maintained since 2014-01-01.
  163. * Support for Symbian has been removed from CivetWeb
  164. */
  165. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  166. #endif /* __SYMBIAN32__ */
  167. #if defined(__ZEPHYR__)
  168. #include <time.h>
  169. #include <ctype.h>
  170. #include <net/socket.h>
  171. #include <posix/pthread.h>
  172. #include <posix/time.h>
  173. #include <stdio.h>
  174. #include <stdlib.h>
  175. #include <string.h>
  176. #include <zephyr.h>
  177. #include <fcntl.h>
  178. #include <libc_extensions.h>
  179. /* Max worker threads is the max of pthreads minus the main application thread
  180. * and minus the main civetweb thread, thus -2
  181. */
  182. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  183. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  184. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  185. #else
  186. #define ZEPHYR_STACK_SIZE (1024 * 16)
  187. #endif
  188. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  189. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  190. MAX_WORKER_THREADS,
  191. ZEPHYR_STACK_SIZE);
  192. static int zephyr_worker_stack_index;
  193. #endif
  194. #if !defined(CIVETWEB_HEADER_INCLUDED)
  195. /* Include the header file here, so the CivetWeb interface is defined for the
  196. * entire implementation, including the following forward definitions. */
  197. #include "civetweb.h"
  198. #endif
  199. #if !defined(DEBUG_TRACE)
  200. #if defined(DEBUG)
  201. static void DEBUG_TRACE_FUNC(const char *func,
  202. unsigned line,
  203. PRINTF_FORMAT_STRING(const char *fmt),
  204. ...) PRINTF_ARGS(3, 4);
  205. #define DEBUG_TRACE(fmt, ...) \
  206. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  207. #define NEED_DEBUG_TRACE_FUNC
  208. #if !defined(DEBUG_TRACE_STREAM)
  209. #define DEBUG_TRACE_STREAM stdout
  210. #endif
  211. #else
  212. #define DEBUG_TRACE(fmt, ...) \
  213. do { \
  214. } while (0)
  215. #endif /* DEBUG */
  216. #endif /* DEBUG_TRACE */
  217. #if !defined(DEBUG_ASSERT)
  218. #if defined(DEBUG)
  219. #include <stdlib.h>
  220. #define DEBUG_ASSERT(cond) \
  221. do { \
  222. if (!(cond)) { \
  223. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  224. exit(2); /* Exit with error */ \
  225. } \
  226. } while (0)
  227. #else
  228. #define DEBUG_ASSERT(cond)
  229. #endif /* DEBUG */
  230. #endif
  231. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  232. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  233. __attribute__((no_instrument_function));
  234. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void
  237. __cyg_profile_func_enter(void *this_fn, void *call_site)
  238. {
  239. if ((void *)this_fn != (void *)printf) {
  240. printf("E %p %p\n", this_fn, call_site);
  241. }
  242. }
  243. void
  244. __cyg_profile_func_exit(void *this_fn, void *call_site)
  245. {
  246. if ((void *)this_fn != (void *)printf) {
  247. printf("X %p %p\n", this_fn, call_site);
  248. }
  249. }
  250. #endif
  251. #if !defined(IGNORE_UNUSED_RESULT)
  252. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  253. #endif
  254. #if defined(__GNUC__) || defined(__MINGW32__)
  255. /* GCC unused function attribute seems fundamentally broken.
  256. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  257. * OR UNUSED" for individual functions failed.
  258. * Either the compiler creates an "unused-function" warning if a
  259. * function is not marked with __attribute__((unused)).
  260. * On the other hand, if the function is marked with this attribute,
  261. * but is used, the compiler raises a completely idiotic
  262. * "used-but-marked-unused" warning - and
  263. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  264. * raises error: unknown option after "#pragma GCC diagnostic".
  265. * Disable this warning completely, until the GCC guys sober up
  266. * again.
  267. */
  268. #pragma GCC diagnostic ignored "-Wunused-function"
  269. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  270. #else
  271. #define FUNCTION_MAY_BE_UNUSED
  272. #endif
  273. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  274. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  275. #include <errno.h>
  276. #include <fcntl.h>
  277. #include <signal.h>
  278. #include <stdlib.h>
  279. #include <sys/stat.h>
  280. #include <sys/types.h>
  281. #endif /* !_WIN32_WCE */
  282. #if defined(__clang__)
  283. /* When using -Weverything, clang does not accept it's own headers
  284. * in a release build configuration. Disable what is too much in
  285. * -Weverything. */
  286. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  287. #endif
  288. #if defined(__GNUC__) || defined(__MINGW32__)
  289. /* Who on earth came to the conclusion, using __DATE__ should rise
  290. * an "expansion of date or time macro is not reproducible"
  291. * warning. That's exactly what was intended by using this macro.
  292. * Just disable this nonsense warning. */
  293. /* And disabling them does not work either:
  294. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  295. * #pragma clang diagnostic ignored "-Wdate-time"
  296. * So we just have to disable ALL warnings for some lines
  297. * of code.
  298. * This seems to be a known GCC bug, not resolved since 2012:
  299. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  300. */
  301. #endif
  302. #if defined(__MACH__) /* Apple OSX section */
  303. #if defined(__clang__)
  304. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  305. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  306. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  307. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  308. #endif
  309. #endif
  310. #ifndef CLOCK_MONOTONIC
  311. #define CLOCK_MONOTONIC (1)
  312. #endif
  313. #ifndef CLOCK_REALTIME
  314. #define CLOCK_REALTIME (2)
  315. #endif
  316. #include <mach/clock.h>
  317. #include <mach/mach.h>
  318. #include <mach/mach_time.h>
  319. #include <sys/errno.h>
  320. #include <sys/time.h>
  321. /* clock_gettime is not implemented on OSX prior to 10.12 */
  322. static int
  323. _civet_clock_gettime(int clk_id, struct timespec *t)
  324. {
  325. memset(t, 0, sizeof(*t));
  326. if (clk_id == CLOCK_REALTIME) {
  327. struct timeval now;
  328. int rv = gettimeofday(&now, NULL);
  329. if (rv) {
  330. return rv;
  331. }
  332. t->tv_sec = now.tv_sec;
  333. t->tv_nsec = now.tv_usec * 1000;
  334. return 0;
  335. } else if (clk_id == CLOCK_MONOTONIC) {
  336. static uint64_t clock_start_time = 0;
  337. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  338. uint64_t now = mach_absolute_time();
  339. if (clock_start_time == 0) {
  340. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  341. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  342. /* appease "unused variable" warning for release builds */
  343. (void)mach_status;
  344. clock_start_time = now;
  345. }
  346. now = (uint64_t)((double)(now - clock_start_time)
  347. * (double)timebase_ifo.numer
  348. / (double)timebase_ifo.denom);
  349. t->tv_sec = now / 1000000000;
  350. t->tv_nsec = now % 1000000000;
  351. return 0;
  352. }
  353. return -1; /* EINVAL - Clock ID is unknown */
  354. }
  355. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  356. #if defined(__CLOCK_AVAILABILITY)
  357. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  358. * declared but it may be NULL at runtime. So we need to check before using
  359. * it. */
  360. static int
  361. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  362. {
  363. if (clock_gettime) {
  364. return clock_gettime(clk_id, t);
  365. }
  366. return _civet_clock_gettime(clk_id, t);
  367. }
  368. #define clock_gettime _civet_safe_clock_gettime
  369. #else
  370. #define clock_gettime _civet_clock_gettime
  371. #endif
  372. #endif
  373. #if !defined(_WIN32)
  374. /* Unix might return different error codes indicating to try again.
  375. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  376. * decades ago, but better check both and let the compile optimize it. */
  377. #define ERROR_TRY_AGAIN(err) \
  378. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  379. #endif
  380. #if defined(USE_ZLIB)
  381. #include "zconf.h"
  382. #include "zlib.h"
  383. #endif
  384. /********************************************************************/
  385. /* CivetWeb configuration defines */
  386. /********************************************************************/
  387. /* Maximum number of threads that can be configured.
  388. * The number of threads actually created depends on the "num_threads"
  389. * configuration parameter, but this is the upper limit. */
  390. #if !defined(MAX_WORKER_THREADS)
  391. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  392. #endif
  393. /* Timeout interval for select/poll calls.
  394. * The timeouts depend on "*_timeout_ms" configuration values, but long
  395. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  396. * This reduces the time required to stop the server. */
  397. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  398. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  399. #endif
  400. /* Do not try to compress files smaller than this limit. */
  401. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  402. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  403. #endif
  404. #if !defined(PASSWORDS_FILE_NAME)
  405. #define PASSWORDS_FILE_NAME ".htpasswd"
  406. #endif
  407. /* Initial buffer size for all CGI environment variables. In case there is
  408. * not enough space, another block is allocated. */
  409. #if !defined(CGI_ENVIRONMENT_SIZE)
  410. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  411. #endif
  412. /* Maximum number of environment variables. */
  413. #if !defined(MAX_CGI_ENVIR_VARS)
  414. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  415. #endif
  416. /* General purpose buffer size. */
  417. #if !defined(MG_BUF_LEN) /* in bytes */
  418. #define MG_BUF_LEN (1024 * 8)
  419. #endif
  420. /********************************************************************/
  421. /* Helper makros */
  422. #if !defined(ARRAY_SIZE)
  423. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  424. #endif
  425. #include <stdint.h>
  426. /* Standard defines */
  427. #if !defined(INT64_MAX)
  428. #define INT64_MAX (9223372036854775807)
  429. #endif
  430. #define SHUTDOWN_RD (0)
  431. #define SHUTDOWN_WR (1)
  432. #define SHUTDOWN_BOTH (2)
  433. mg_static_assert(MAX_WORKER_THREADS >= 1,
  434. "worker threads must be a positive number");
  435. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  436. "size_t data type size check");
  437. #if defined(_WIN32) /* WINDOWS include block */
  438. #include <malloc.h> /* *alloc( */
  439. #include <stdlib.h> /* *alloc( */
  440. #include <time.h> /* struct timespec */
  441. #include <windows.h>
  442. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  443. #include <ws2tcpip.h>
  444. typedef const char *SOCK_OPT_TYPE;
  445. /* For a detailed description of these *_PATH_MAX defines, see
  446. * https://github.com/civetweb/civetweb/issues/937. */
  447. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  448. * null termination, rounded up to the next 4 bytes boundary */
  449. #define UTF8_PATH_MAX (3 * 260)
  450. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  451. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  452. #define UTF16_PATH_MAX (260)
  453. #if !defined(_IN_PORT_T)
  454. #if !defined(in_port_t)
  455. #define in_port_t u_short
  456. #endif
  457. #endif
  458. #if defined(_WIN32_WCE)
  459. #error "WinCE support has ended"
  460. #endif
  461. #include <direct.h>
  462. #include <io.h>
  463. #include <process.h>
  464. #define MAKEUQUAD(lo, hi) \
  465. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  466. #define RATE_DIFF (10000000) /* 100 nsecs */
  467. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  468. #define SYS2UNIX_TIME(lo, hi) \
  469. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  470. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  471. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  472. * Also use _strtoui64 on modern M$ compilers */
  473. #if defined(_MSC_VER)
  474. #if (_MSC_VER < 1300)
  475. #define STRX(x) #x
  476. #define STR(x) STRX(x)
  477. #define __func__ __FILE__ ":" STR(__LINE__)
  478. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  479. #define strtoll(x, y, z) (_atoi64(x))
  480. #else
  481. #define __func__ __FUNCTION__
  482. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  483. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  484. #endif
  485. #endif /* _MSC_VER */
  486. #define ERRNO ((int)(GetLastError()))
  487. #define NO_SOCKLEN_T
  488. #if defined(_WIN64) || defined(__MINGW64__)
  489. #if !defined(SSL_LIB)
  490. #if defined(OPENSSL_API_3_0)
  491. #define SSL_LIB "libssl-3-x64.dll"
  492. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  493. #endif
  494. #if defined(OPENSSL_API_1_1)
  495. #define SSL_LIB "libssl-1_1-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  497. #endif /* OPENSSL_API_1_1 */
  498. #if defined(OPENSSL_API_1_0)
  499. #define SSL_LIB "ssleay64.dll"
  500. #define CRYPTO_LIB "libeay64.dll"
  501. #endif /* OPENSSL_API_1_0 */
  502. #endif
  503. #else /* defined(_WIN64) || defined(__MINGW64__) */
  504. #if !defined(SSL_LIB)
  505. #if defined(OPENSSL_API_3_0)
  506. #define SSL_LIB "libssl-3.dll"
  507. #define CRYPTO_LIB "libcrypto-3.dll"
  508. #endif
  509. #if defined(OPENSSL_API_1_1)
  510. #define SSL_LIB "libssl-1_1.dll"
  511. #define CRYPTO_LIB "libcrypto-1_1.dll"
  512. #endif /* OPENSSL_API_1_1 */
  513. #if defined(OPENSSL_API_1_0)
  514. #define SSL_LIB "ssleay32.dll"
  515. #define CRYPTO_LIB "libeay32.dll"
  516. #endif /* OPENSSL_API_1_0 */
  517. #endif /* SSL_LIB */
  518. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  519. #define O_NONBLOCK (0)
  520. #if !defined(W_OK)
  521. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  522. #endif
  523. #define _POSIX_
  524. #define INT64_FMT "I64d"
  525. #define UINT64_FMT "I64u"
  526. #define WINCDECL __cdecl
  527. #define vsnprintf_impl _vsnprintf
  528. #define access _access
  529. #define mg_sleep(x) (Sleep(x))
  530. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  531. #if !defined(popen)
  532. #define popen(x, y) (_popen(x, y))
  533. #endif
  534. #if !defined(pclose)
  535. #define pclose(x) (_pclose(x))
  536. #endif
  537. #define close(x) (_close(x))
  538. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  539. #define RTLD_LAZY (0)
  540. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  541. #define fdopen(x, y) (_fdopen((x), (y)))
  542. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  543. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  544. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  545. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  546. #define sleep(x) (Sleep((x)*1000))
  547. #define rmdir(x) (_rmdir(x))
  548. #if defined(_WIN64) || !defined(__MINGW32__)
  549. /* Only MinGW 32 bit is missing this function */
  550. #define timegm(x) (_mkgmtime(x))
  551. #else
  552. time_t timegm(struct tm *tm);
  553. #define NEED_TIMEGM
  554. #endif
  555. #if !defined(fileno)
  556. #define fileno(x) (_fileno(x))
  557. #endif /* !fileno MINGW #defines fileno */
  558. typedef struct {
  559. CRITICAL_SECTION sec; /* Immovable */
  560. } pthread_mutex_t;
  561. typedef DWORD pthread_key_t;
  562. typedef HANDLE pthread_t;
  563. typedef struct {
  564. pthread_mutex_t threadIdSec;
  565. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  566. } pthread_cond_t;
  567. #if !defined(__clockid_t_defined)
  568. typedef DWORD clockid_t;
  569. #endif
  570. #if !defined(CLOCK_MONOTONIC)
  571. #define CLOCK_MONOTONIC (1)
  572. #endif
  573. #if !defined(CLOCK_REALTIME)
  574. #define CLOCK_REALTIME (2)
  575. #endif
  576. #if !defined(CLOCK_THREAD)
  577. #define CLOCK_THREAD (3)
  578. #endif
  579. #if !defined(CLOCK_PROCESS)
  580. #define CLOCK_PROCESS (4)
  581. #endif
  582. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  583. #define _TIMESPEC_DEFINED
  584. #endif
  585. #if !defined(_TIMESPEC_DEFINED)
  586. struct timespec {
  587. time_t tv_sec; /* seconds */
  588. long tv_nsec; /* nanoseconds */
  589. };
  590. #endif
  591. #if !defined(WIN_PTHREADS_TIME_H)
  592. #define MUST_IMPLEMENT_CLOCK_GETTIME
  593. #endif
  594. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  595. #define clock_gettime mg_clock_gettime
  596. static int
  597. clock_gettime(clockid_t clk_id, struct timespec *tp)
  598. {
  599. FILETIME ft;
  600. ULARGE_INTEGER li, li2;
  601. BOOL ok = FALSE;
  602. double d;
  603. static double perfcnt_per_sec = 0.0;
  604. static BOOL initialized = FALSE;
  605. if (!initialized) {
  606. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  607. perfcnt_per_sec = 1.0 / li.QuadPart;
  608. initialized = TRUE;
  609. }
  610. if (tp) {
  611. memset(tp, 0, sizeof(*tp));
  612. if (clk_id == CLOCK_REALTIME) {
  613. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  614. GetSystemTimeAsFileTime(&ft);
  615. li.LowPart = ft.dwLowDateTime;
  616. li.HighPart = ft.dwHighDateTime;
  617. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  618. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  619. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  620. ok = TRUE;
  621. /* END: CLOCK_REALTIME */
  622. } else if (clk_id == CLOCK_MONOTONIC) {
  623. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  624. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  625. d = li.QuadPart * perfcnt_per_sec;
  626. tp->tv_sec = (time_t)d;
  627. d -= (double)tp->tv_sec;
  628. tp->tv_nsec = (long)(d * 1.0E9);
  629. ok = TRUE;
  630. /* END: CLOCK_MONOTONIC */
  631. } else if (clk_id == CLOCK_THREAD) {
  632. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  633. FILETIME t_create, t_exit, t_kernel, t_user;
  634. if (GetThreadTimes(GetCurrentThread(),
  635. &t_create,
  636. &t_exit,
  637. &t_kernel,
  638. &t_user)) {
  639. li.LowPart = t_user.dwLowDateTime;
  640. li.HighPart = t_user.dwHighDateTime;
  641. li2.LowPart = t_kernel.dwLowDateTime;
  642. li2.HighPart = t_kernel.dwHighDateTime;
  643. li.QuadPart += li2.QuadPart;
  644. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  645. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  646. ok = TRUE;
  647. }
  648. /* END: CLOCK_THREAD */
  649. } else if (clk_id == CLOCK_PROCESS) {
  650. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  651. FILETIME t_create, t_exit, t_kernel, t_user;
  652. if (GetProcessTimes(GetCurrentProcess(),
  653. &t_create,
  654. &t_exit,
  655. &t_kernel,
  656. &t_user)) {
  657. li.LowPart = t_user.dwLowDateTime;
  658. li.HighPart = t_user.dwHighDateTime;
  659. li2.LowPart = t_kernel.dwLowDateTime;
  660. li2.HighPart = t_kernel.dwHighDateTime;
  661. li.QuadPart += li2.QuadPart;
  662. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  663. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  664. ok = TRUE;
  665. }
  666. /* END: CLOCK_PROCESS */
  667. } else {
  668. /* BEGIN: unknown clock */
  669. /* ok = FALSE; already set by init */
  670. /* END: unknown clock */
  671. }
  672. }
  673. return ok ? 0 : -1;
  674. }
  675. #endif
  676. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  677. static int pthread_mutex_lock(pthread_mutex_t *);
  678. static int pthread_mutex_unlock(pthread_mutex_t *);
  679. static void path_to_unicode(const struct mg_connection *conn,
  680. const char *path,
  681. wchar_t *wbuf,
  682. size_t wbuf_len);
  683. /* All file operations need to be rewritten to solve #246. */
  684. struct mg_file;
  685. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  686. /* POSIX dirent interface */
  687. struct dirent {
  688. char d_name[UTF8_PATH_MAX];
  689. };
  690. typedef struct DIR {
  691. HANDLE handle;
  692. WIN32_FIND_DATAW info;
  693. struct dirent result;
  694. } DIR;
  695. #if defined(HAVE_POLL)
  696. #define mg_pollfd pollfd
  697. #else
  698. struct mg_pollfd {
  699. SOCKET fd;
  700. short events;
  701. short revents;
  702. };
  703. #endif
  704. /* Mark required libraries */
  705. #if defined(_MSC_VER)
  706. #pragma comment(lib, "Ws2_32.lib")
  707. #endif
  708. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  709. #include <inttypes.h>
  710. /* Linux & co. internally use UTF8 */
  711. #define UTF8_PATH_MAX (PATH_MAX)
  712. typedef const void *SOCK_OPT_TYPE;
  713. #if defined(ANDROID)
  714. typedef unsigned short int in_port_t;
  715. #endif
  716. #if !defined(__ZEPHYR__)
  717. #include <arpa/inet.h>
  718. #include <ctype.h>
  719. #include <dirent.h>
  720. #include <grp.h>
  721. #include <limits.h>
  722. #include <netdb.h>
  723. #include <netinet/in.h>
  724. #include <netinet/tcp.h>
  725. #include <pthread.h>
  726. #include <pwd.h>
  727. #include <stdarg.h>
  728. #include <stddef.h>
  729. #include <stdio.h>
  730. #include <stdlib.h>
  731. #include <string.h>
  732. #include <sys/poll.h>
  733. #include <sys/socket.h>
  734. #include <sys/time.h>
  735. #include <sys/utsname.h>
  736. #include <sys/wait.h>
  737. #include <time.h>
  738. #include <unistd.h>
  739. #if defined(USE_X_DOM_SOCKET)
  740. #include <sys/un.h>
  741. #endif
  742. #endif
  743. #define vsnprintf_impl vsnprintf
  744. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  745. #include <dlfcn.h>
  746. #endif
  747. #if defined(__MACH__)
  748. #define SSL_LIB "libssl.dylib"
  749. #define CRYPTO_LIB "libcrypto.dylib"
  750. #else
  751. #if !defined(SSL_LIB)
  752. #define SSL_LIB "libssl.so"
  753. #endif
  754. #if !defined(CRYPTO_LIB)
  755. #define CRYPTO_LIB "libcrypto.so"
  756. #endif
  757. #endif
  758. #if !defined(O_BINARY)
  759. #define O_BINARY (0)
  760. #endif /* O_BINARY */
  761. #define closesocket(a) (close(a))
  762. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  763. #define mg_remove(conn, x) (remove(x))
  764. #define mg_sleep(x) (usleep((x)*1000))
  765. #define mg_opendir(conn, x) (opendir(x))
  766. #define mg_closedir(x) (closedir(x))
  767. #define mg_readdir(x) (readdir(x))
  768. #define ERRNO (errno)
  769. #define INVALID_SOCKET (-1)
  770. #define INT64_FMT PRId64
  771. #define UINT64_FMT PRIu64
  772. typedef int SOCKET;
  773. #define WINCDECL
  774. #if defined(__hpux)
  775. /* HPUX 11 does not have monotonic, fall back to realtime */
  776. #if !defined(CLOCK_MONOTONIC)
  777. #define CLOCK_MONOTONIC CLOCK_REALTIME
  778. #endif
  779. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  780. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  781. * the prototypes use int* rather than socklen_t* which matches the
  782. * actual library expectation. When called with the wrong size arg
  783. * accept() returns a zero client inet addr and check_acl() always
  784. * fails. Since socklen_t is widely used below, just force replace
  785. * their typedef with int. - DTL
  786. */
  787. #define socklen_t int
  788. #endif /* hpux */
  789. #define mg_pollfd pollfd
  790. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  791. /* In case our C library is missing "timegm", provide an implementation */
  792. #if defined(NEED_TIMEGM)
  793. static inline int
  794. is_leap(int y)
  795. {
  796. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  797. }
  798. static inline int
  799. count_leap(int y)
  800. {
  801. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  802. }
  803. time_t
  804. timegm(struct tm *tm)
  805. {
  806. static const unsigned short ydays[] = {
  807. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  808. int year = tm->tm_year + 1900;
  809. int mon = tm->tm_mon;
  810. int mday = tm->tm_mday - 1;
  811. int hour = tm->tm_hour;
  812. int min = tm->tm_min;
  813. int sec = tm->tm_sec;
  814. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  815. || (mday >= ydays[mon + 1] - ydays[mon]
  816. + (mon == 1 && is_leap(year) ? 1 : 0))
  817. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  818. return -1;
  819. time_t res = year - 1970;
  820. res *= 365;
  821. res += mday;
  822. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  823. res += count_leap(year);
  824. res *= 24;
  825. res += hour;
  826. res *= 60;
  827. res += min;
  828. res *= 60;
  829. res += sec;
  830. return res;
  831. }
  832. #endif /* NEED_TIMEGM */
  833. /* va_copy should always be a macro, C99 and C++11 - DTL */
  834. #if !defined(va_copy)
  835. #define va_copy(x, y) ((x) = (y))
  836. #endif
  837. #if defined(_WIN32)
  838. /* Create substitutes for POSIX functions in Win32. */
  839. #if defined(GCC_DIAGNOSTIC)
  840. /* Show no warning in case system functions are not used. */
  841. #pragma GCC diagnostic push
  842. #pragma GCC diagnostic ignored "-Wunused-function"
  843. #endif
  844. static pthread_mutex_t global_log_file_lock;
  845. FUNCTION_MAY_BE_UNUSED
  846. static DWORD
  847. pthread_self(void)
  848. {
  849. return GetCurrentThreadId();
  850. }
  851. FUNCTION_MAY_BE_UNUSED
  852. static int
  853. pthread_key_create(
  854. pthread_key_t *key,
  855. void (*_ignored)(void *) /* destructor not supported for Windows */
  856. )
  857. {
  858. (void)_ignored;
  859. if ((key != 0)) {
  860. *key = TlsAlloc();
  861. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  862. }
  863. return -2;
  864. }
  865. FUNCTION_MAY_BE_UNUSED
  866. static int
  867. pthread_key_delete(pthread_key_t key)
  868. {
  869. return TlsFree(key) ? 0 : 1;
  870. }
  871. FUNCTION_MAY_BE_UNUSED
  872. static int
  873. pthread_setspecific(pthread_key_t key, void *value)
  874. {
  875. return TlsSetValue(key, value) ? 0 : 1;
  876. }
  877. FUNCTION_MAY_BE_UNUSED
  878. static void *
  879. pthread_getspecific(pthread_key_t key)
  880. {
  881. return TlsGetValue(key);
  882. }
  883. #if defined(GCC_DIAGNOSTIC)
  884. /* Enable unused function warning again */
  885. #pragma GCC diagnostic pop
  886. #endif
  887. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  888. #else
  889. static pthread_mutexattr_t pthread_mutex_attr;
  890. #endif /* _WIN32 */
  891. #if defined(GCC_DIAGNOSTIC)
  892. /* Show no warning in case system functions are not used. */
  893. #pragma GCC diagnostic push
  894. #pragma GCC diagnostic ignored "-Wunused-function"
  895. #endif /* defined(GCC_DIAGNOSTIC) */
  896. #if defined(__clang__)
  897. /* Show no warning in case system functions are not used. */
  898. #pragma clang diagnostic push
  899. #pragma clang diagnostic ignored "-Wunused-function"
  900. #endif
  901. static pthread_mutex_t global_lock_mutex;
  902. FUNCTION_MAY_BE_UNUSED
  903. static void
  904. mg_global_lock(void)
  905. {
  906. (void)pthread_mutex_lock(&global_lock_mutex);
  907. }
  908. FUNCTION_MAY_BE_UNUSED
  909. static void
  910. mg_global_unlock(void)
  911. {
  912. (void)pthread_mutex_unlock(&global_lock_mutex);
  913. }
  914. #if defined(_WIN64)
  915. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  916. #elif defined(_WIN32)
  917. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  918. #endif
  919. /* Atomic functions working on ptrdiff_t ("signed size_t").
  920. * Operations: Increment, Decrement, Add, Maximum.
  921. * Up to size_t, they do not an atomic "load" operation.
  922. */
  923. FUNCTION_MAY_BE_UNUSED
  924. static ptrdiff_t
  925. mg_atomic_inc(volatile ptrdiff_t *addr)
  926. {
  927. ptrdiff_t ret;
  928. #if defined(_WIN64) && !defined(NO_ATOMICS)
  929. ret = InterlockedIncrement64(addr);
  930. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  931. ret = InterlockedIncrement(addr);
  932. #elif defined(__GNUC__) \
  933. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  934. && !defined(NO_ATOMICS)
  935. ret = __sync_add_and_fetch(addr, 1);
  936. #else
  937. mg_global_lock();
  938. ret = (++(*addr));
  939. mg_global_unlock();
  940. #endif
  941. return ret;
  942. }
  943. FUNCTION_MAY_BE_UNUSED
  944. static ptrdiff_t
  945. mg_atomic_dec(volatile ptrdiff_t *addr)
  946. {
  947. ptrdiff_t ret;
  948. #if defined(_WIN64) && !defined(NO_ATOMICS)
  949. ret = InterlockedDecrement64(addr);
  950. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  951. ret = InterlockedDecrement(addr);
  952. #elif defined(__GNUC__) \
  953. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  954. && !defined(NO_ATOMICS)
  955. ret = __sync_sub_and_fetch(addr, 1);
  956. #else
  957. mg_global_lock();
  958. ret = (--(*addr));
  959. mg_global_unlock();
  960. #endif
  961. return ret;
  962. }
  963. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  964. static ptrdiff_t
  965. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  966. {
  967. ptrdiff_t ret;
  968. #if defined(_WIN64) && !defined(NO_ATOMICS)
  969. ret = InterlockedAdd64(addr, value);
  970. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  971. ret = InterlockedExchangeAdd(addr, value) + value;
  972. #elif defined(__GNUC__) \
  973. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  974. && !defined(NO_ATOMICS)
  975. ret = __sync_add_and_fetch(addr, value);
  976. #else
  977. mg_global_lock();
  978. *addr += value;
  979. ret = (*addr);
  980. mg_global_unlock();
  981. #endif
  982. return ret;
  983. }
  984. FUNCTION_MAY_BE_UNUSED
  985. static ptrdiff_t
  986. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  987. ptrdiff_t oldval,
  988. ptrdiff_t newval)
  989. {
  990. ptrdiff_t ret;
  991. #if defined(_WIN64) && !defined(NO_ATOMICS)
  992. ret = InterlockedCompareExchange64(addr, newval, oldval);
  993. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  994. ret = InterlockedCompareExchange(addr, newval, oldval);
  995. #elif defined(__GNUC__) \
  996. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  997. && !defined(NO_ATOMICS)
  998. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  999. #else
  1000. mg_global_lock();
  1001. ret = *addr;
  1002. if ((ret != newval) && (ret == oldval)) {
  1003. *addr = newval;
  1004. }
  1005. mg_global_unlock();
  1006. #endif
  1007. return ret;
  1008. }
  1009. static void
  1010. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1011. {
  1012. register ptrdiff_t tmp = *addr;
  1013. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1014. while (tmp < value) {
  1015. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1016. }
  1017. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1018. while (tmp < value) {
  1019. tmp = InterlockedCompareExchange(addr, value, tmp);
  1020. }
  1021. #elif defined(__GNUC__) \
  1022. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1023. && !defined(NO_ATOMICS)
  1024. while (tmp < value) {
  1025. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1026. }
  1027. #else
  1028. mg_global_lock();
  1029. if (*addr < value) {
  1030. *addr = value;
  1031. }
  1032. mg_global_unlock();
  1033. #endif
  1034. }
  1035. static int64_t
  1036. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1037. {
  1038. int64_t ret;
  1039. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1040. ret = InterlockedAdd64(addr, value);
  1041. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1042. ret = InterlockedExchangeAdd64(addr, value) + value;
  1043. #elif defined(__GNUC__) \
  1044. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1045. && !defined(NO_ATOMICS)
  1046. ret = __sync_add_and_fetch(addr, value);
  1047. #else
  1048. mg_global_lock();
  1049. *addr += value;
  1050. ret = (*addr);
  1051. mg_global_unlock();
  1052. #endif
  1053. return ret;
  1054. }
  1055. #endif
  1056. #if defined(GCC_DIAGNOSTIC)
  1057. /* Show no warning in case system functions are not used. */
  1058. #pragma GCC diagnostic pop
  1059. #endif /* defined(GCC_DIAGNOSTIC) */
  1060. #if defined(__clang__)
  1061. /* Show no warning in case system functions are not used. */
  1062. #pragma clang diagnostic pop
  1063. #endif
  1064. #if defined(USE_SERVER_STATS)
  1065. struct mg_memory_stat {
  1066. volatile ptrdiff_t totalMemUsed;
  1067. volatile ptrdiff_t maxMemUsed;
  1068. volatile ptrdiff_t blockCount;
  1069. };
  1070. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1071. static void *
  1072. mg_malloc_ex(size_t size,
  1073. struct mg_context *ctx,
  1074. const char *file,
  1075. unsigned line)
  1076. {
  1077. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1078. void *memory = 0;
  1079. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1080. #if defined(MEMORY_DEBUGGING)
  1081. char mallocStr[256];
  1082. #else
  1083. (void)file;
  1084. (void)line;
  1085. #endif
  1086. if (data) {
  1087. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1088. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1089. mg_atomic_inc(&mstat->blockCount);
  1090. ((uintptr_t *)data)[0] = size;
  1091. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1092. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1093. }
  1094. #if defined(MEMORY_DEBUGGING)
  1095. sprintf(mallocStr,
  1096. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1097. memory,
  1098. (unsigned long)size,
  1099. (unsigned long)mstat->totalMemUsed,
  1100. (unsigned long)mstat->blockCount,
  1101. file,
  1102. line);
  1103. DEBUG_TRACE("%s", mallocStr);
  1104. #endif
  1105. return memory;
  1106. }
  1107. static void *
  1108. mg_calloc_ex(size_t count,
  1109. size_t size,
  1110. struct mg_context *ctx,
  1111. const char *file,
  1112. unsigned line)
  1113. {
  1114. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1115. if (data) {
  1116. memset(data, 0, size * count);
  1117. }
  1118. return data;
  1119. }
  1120. static void
  1121. mg_free_ex(void *memory, const char *file, unsigned line)
  1122. {
  1123. #if defined(MEMORY_DEBUGGING)
  1124. char mallocStr[256];
  1125. #else
  1126. (void)file;
  1127. (void)line;
  1128. #endif
  1129. if (memory) {
  1130. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1131. uintptr_t size = ((uintptr_t *)data)[0];
  1132. struct mg_memory_stat *mstat =
  1133. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1134. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1135. mg_atomic_dec(&mstat->blockCount);
  1136. #if defined(MEMORY_DEBUGGING)
  1137. sprintf(mallocStr,
  1138. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1139. memory,
  1140. (unsigned long)size,
  1141. (unsigned long)mstat->totalMemUsed,
  1142. (unsigned long)mstat->blockCount,
  1143. file,
  1144. line);
  1145. DEBUG_TRACE("%s", mallocStr);
  1146. #endif
  1147. free(data);
  1148. }
  1149. }
  1150. static void *
  1151. mg_realloc_ex(void *memory,
  1152. size_t newsize,
  1153. struct mg_context *ctx,
  1154. const char *file,
  1155. unsigned line)
  1156. {
  1157. void *data;
  1158. void *_realloc;
  1159. uintptr_t oldsize;
  1160. #if defined(MEMORY_DEBUGGING)
  1161. char mallocStr[256];
  1162. #else
  1163. (void)file;
  1164. (void)line;
  1165. #endif
  1166. if (newsize) {
  1167. if (memory) {
  1168. /* Reallocate existing block */
  1169. struct mg_memory_stat *mstat;
  1170. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1171. oldsize = ((uintptr_t *)data)[0];
  1172. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1173. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1174. if (_realloc) {
  1175. data = _realloc;
  1176. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1177. #if defined(MEMORY_DEBUGGING)
  1178. sprintf(mallocStr,
  1179. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1180. memory,
  1181. (unsigned long)oldsize,
  1182. (unsigned long)mstat->totalMemUsed,
  1183. (unsigned long)mstat->blockCount,
  1184. file,
  1185. line);
  1186. DEBUG_TRACE("%s", mallocStr);
  1187. #endif
  1188. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1189. #if defined(MEMORY_DEBUGGING)
  1190. sprintf(mallocStr,
  1191. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1192. memory,
  1193. (unsigned long)newsize,
  1194. (unsigned long)mstat->totalMemUsed,
  1195. (unsigned long)mstat->blockCount,
  1196. file,
  1197. line);
  1198. DEBUG_TRACE("%s", mallocStr);
  1199. #endif
  1200. *(uintptr_t *)data = newsize;
  1201. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1202. } else {
  1203. #if defined(MEMORY_DEBUGGING)
  1204. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1205. #endif
  1206. return _realloc;
  1207. }
  1208. } else {
  1209. /* Allocate new block */
  1210. data = mg_malloc_ex(newsize, ctx, file, line);
  1211. }
  1212. } else {
  1213. /* Free existing block */
  1214. data = 0;
  1215. mg_free_ex(memory, file, line);
  1216. }
  1217. return data;
  1218. }
  1219. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1220. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1222. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1223. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1224. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1226. #else /* USE_SERVER_STATS */
  1227. static __inline void *
  1228. mg_malloc(size_t a)
  1229. {
  1230. return malloc(a);
  1231. }
  1232. static __inline void *
  1233. mg_calloc(size_t a, size_t b)
  1234. {
  1235. return calloc(a, b);
  1236. }
  1237. static __inline void *
  1238. mg_realloc(void *a, size_t b)
  1239. {
  1240. return realloc(a, b);
  1241. }
  1242. static __inline void
  1243. mg_free(void *a)
  1244. {
  1245. free(a);
  1246. }
  1247. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1248. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1249. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1250. #define mg_free_ctx(a, c) mg_free(a)
  1251. #endif /* USE_SERVER_STATS */
  1252. static void mg_vsnprintf(const struct mg_connection *conn,
  1253. int *truncated,
  1254. char *buf,
  1255. size_t buflen,
  1256. const char *fmt,
  1257. va_list ap);
  1258. static void mg_snprintf(const struct mg_connection *conn,
  1259. int *truncated,
  1260. char *buf,
  1261. size_t buflen,
  1262. PRINTF_FORMAT_STRING(const char *fmt),
  1263. ...) PRINTF_ARGS(5, 6);
  1264. /* This following lines are just meant as a reminder to use the mg-functions
  1265. * for memory management */
  1266. #if defined(malloc)
  1267. #undef malloc
  1268. #endif
  1269. #if defined(calloc)
  1270. #undef calloc
  1271. #endif
  1272. #if defined(realloc)
  1273. #undef realloc
  1274. #endif
  1275. #if defined(free)
  1276. #undef free
  1277. #endif
  1278. #if defined(snprintf)
  1279. #undef snprintf
  1280. #endif
  1281. #if defined(vsnprintf)
  1282. #undef vsnprintf
  1283. #endif
  1284. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1285. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1286. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1287. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1288. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1289. #if defined(_WIN32)
  1290. /* vsnprintf must not be used in any system,
  1291. * but this define only works well for Windows. */
  1292. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1293. #endif
  1294. /* mg_init_library counter */
  1295. static int mg_init_library_called = 0;
  1296. #if !defined(NO_SSL)
  1297. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1298. || defined(OPENSSL_API_3_0)
  1299. static int mg_openssl_initialized = 0;
  1300. #endif
  1301. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1302. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1303. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1304. #endif
  1305. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1306. && defined(OPENSSL_API_3_0)
  1307. #error "Multiple OPENSSL_API versions defined"
  1308. #endif
  1309. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1310. || defined(OPENSSL_API_3_0)) \
  1311. && defined(USE_MBEDTLS)
  1312. #error "Multiple SSL libraries defined"
  1313. #endif
  1314. #endif
  1315. static pthread_key_t sTlsKey; /* Thread local storage index */
  1316. static volatile ptrdiff_t thread_idx_max = 0;
  1317. #if defined(MG_LEGACY_INTERFACE)
  1318. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1319. #endif
  1320. struct mg_workerTLS {
  1321. int is_master;
  1322. unsigned long thread_idx;
  1323. void *user_ptr;
  1324. #if defined(_WIN32)
  1325. HANDLE pthread_cond_helper_mutex;
  1326. struct mg_workerTLS *next_waiting_thread;
  1327. #endif
  1328. const char *alpn_proto;
  1329. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1330. char txtbuf[4];
  1331. #endif
  1332. };
  1333. #if defined(GCC_DIAGNOSTIC)
  1334. /* Show no warning in case system functions are not used. */
  1335. #pragma GCC diagnostic push
  1336. #pragma GCC diagnostic ignored "-Wunused-function"
  1337. #endif /* defined(GCC_DIAGNOSTIC) */
  1338. #if defined(__clang__)
  1339. /* Show no warning in case system functions are not used. */
  1340. #pragma clang diagnostic push
  1341. #pragma clang diagnostic ignored "-Wunused-function"
  1342. #endif
  1343. /* Get a unique thread ID as unsigned long, independent from the data type
  1344. * of thread IDs defined by the operating system API.
  1345. * If two calls to mg_current_thread_id return the same value, they calls
  1346. * are done from the same thread. If they return different values, they are
  1347. * done from different threads. (Provided this function is used in the same
  1348. * process context and threads are not repeatedly created and deleted, but
  1349. * CivetWeb does not do that).
  1350. * This function must match the signature required for SSL id callbacks:
  1351. * CRYPTO_set_id_callback
  1352. */
  1353. FUNCTION_MAY_BE_UNUSED
  1354. static unsigned long
  1355. mg_current_thread_id(void)
  1356. {
  1357. #if defined(_WIN32)
  1358. return GetCurrentThreadId();
  1359. #else
  1360. #if defined(__clang__)
  1361. #pragma clang diagnostic push
  1362. #pragma clang diagnostic ignored "-Wunreachable-code"
  1363. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1364. * or not, so one of the two conditions will be unreachable by construction.
  1365. * Unfortunately the C standard does not define a way to check this at
  1366. * compile time, since the #if preprocessor conditions can not use the
  1367. * sizeof operator as an argument. */
  1368. #endif
  1369. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1370. /* This is the problematic case for CRYPTO_set_id_callback:
  1371. * The OS pthread_t can not be cast to unsigned long. */
  1372. struct mg_workerTLS *tls =
  1373. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1374. if (tls == NULL) {
  1375. /* SSL called from an unknown thread: Create some thread index.
  1376. */
  1377. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1378. tls->is_master = -2; /* -2 means "3rd party thread" */
  1379. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1380. pthread_setspecific(sTlsKey, tls);
  1381. }
  1382. return tls->thread_idx;
  1383. } else {
  1384. /* pthread_t may be any data type, so a simple cast to unsigned long
  1385. * can rise a warning/error, depending on the platform.
  1386. * Here memcpy is used as an anything-to-anything cast. */
  1387. unsigned long ret = 0;
  1388. pthread_t t = pthread_self();
  1389. memcpy(&ret, &t, sizeof(pthread_t));
  1390. return ret;
  1391. }
  1392. #if defined(__clang__)
  1393. #pragma clang diagnostic pop
  1394. #endif
  1395. #endif
  1396. }
  1397. FUNCTION_MAY_BE_UNUSED
  1398. static uint64_t
  1399. mg_get_current_time_ns(void)
  1400. {
  1401. struct timespec tsnow;
  1402. clock_gettime(CLOCK_REALTIME, &tsnow);
  1403. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1404. }
  1405. #if defined(GCC_DIAGNOSTIC)
  1406. /* Show no warning in case system functions are not used. */
  1407. #pragma GCC diagnostic pop
  1408. #endif /* defined(GCC_DIAGNOSTIC) */
  1409. #if defined(__clang__)
  1410. /* Show no warning in case system functions are not used. */
  1411. #pragma clang diagnostic pop
  1412. #endif
  1413. #if defined(NEED_DEBUG_TRACE_FUNC)
  1414. static void
  1415. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1416. {
  1417. va_list args;
  1418. struct timespec tsnow;
  1419. /* Get some operating system independent thread id */
  1420. unsigned long thread_id = mg_current_thread_id();
  1421. clock_gettime(CLOCK_REALTIME, &tsnow);
  1422. flockfile(DEBUG_TRACE_STREAM);
  1423. fprintf(DEBUG_TRACE_STREAM,
  1424. "*** %lu.%09lu %lu %s:%u: ",
  1425. (unsigned long)tsnow.tv_sec,
  1426. (unsigned long)tsnow.tv_nsec,
  1427. thread_id,
  1428. func,
  1429. line);
  1430. va_start(args, fmt);
  1431. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1432. va_end(args);
  1433. putc('\n', DEBUG_TRACE_STREAM);
  1434. fflush(DEBUG_TRACE_STREAM);
  1435. funlockfile(DEBUG_TRACE_STREAM);
  1436. }
  1437. #endif /* NEED_DEBUG_TRACE_FUNC */
  1438. #define MD5_STATIC static
  1439. #include "md5.inl"
  1440. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1441. #if defined(NO_SOCKLEN_T)
  1442. typedef int socklen_t;
  1443. #endif /* NO_SOCKLEN_T */
  1444. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1445. #if !defined(MSG_NOSIGNAL)
  1446. #define MSG_NOSIGNAL (0)
  1447. #endif
  1448. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1449. #if defined(USE_MBEDTLS)
  1450. /* mbedTLS */
  1451. #include "mod_mbedtls.inl"
  1452. #elif defined(NO_SSL)
  1453. /* no SSL */
  1454. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1455. typedef struct SSL_CTX SSL_CTX;
  1456. #elif defined(NO_SSL_DL)
  1457. /* OpenSSL without dynamic loading */
  1458. #include <openssl/bn.h>
  1459. #include <openssl/conf.h>
  1460. #include <openssl/crypto.h>
  1461. #include <openssl/dh.h>
  1462. #include <openssl/engine.h>
  1463. #include <openssl/err.h>
  1464. #include <openssl/opensslv.h>
  1465. #include <openssl/pem.h>
  1466. #include <openssl/ssl.h>
  1467. #include <openssl/tls1.h>
  1468. #include <openssl/x509.h>
  1469. #if defined(WOLFSSL_VERSION)
  1470. /* Additional defines for WolfSSL, see
  1471. * https://github.com/civetweb/civetweb/issues/583 */
  1472. #include "wolfssl_extras.inl"
  1473. #endif
  1474. #if defined(OPENSSL_IS_BORINGSSL)
  1475. /* From boringssl/src/include/openssl/mem.h:
  1476. *
  1477. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1478. * However, that was written in a time before Valgrind and ASAN. Since we now
  1479. * have those tools, the OpenSSL allocation functions are simply macros around
  1480. * the standard memory functions.
  1481. *
  1482. * #define OPENSSL_free free */
  1483. #define free free
  1484. // disable for boringssl
  1485. #define CONF_modules_unload(a) ((void)0)
  1486. #define ENGINE_cleanup() ((void)0)
  1487. #endif
  1488. /* If OpenSSL headers are included, automatically select the API version */
  1489. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1490. #if !defined(OPENSSL_API_3_0)
  1491. #define OPENSSL_API_3_0
  1492. #endif
  1493. #define OPENSSL_REMOVE_THREAD_STATE()
  1494. #else
  1495. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1496. #if !defined(OPENSSL_API_1_1)
  1497. #define OPENSSL_API_1_1
  1498. #endif
  1499. #define OPENSSL_REMOVE_THREAD_STATE()
  1500. #else
  1501. #if !defined(OPENSSL_API_1_0)
  1502. #define OPENSSL_API_1_0
  1503. #endif
  1504. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1505. #endif
  1506. #endif
  1507. #else
  1508. /* SSL loaded dynamically from DLL / shared object */
  1509. /* Add all prototypes here, to be independent from OpenSSL source
  1510. * installation. */
  1511. #include "openssl_dl.inl"
  1512. #endif /* Various SSL bindings */
  1513. #if !defined(NO_CACHING)
  1514. static const char month_names[][4] = {"Jan",
  1515. "Feb",
  1516. "Mar",
  1517. "Apr",
  1518. "May",
  1519. "Jun",
  1520. "Jul",
  1521. "Aug",
  1522. "Sep",
  1523. "Oct",
  1524. "Nov",
  1525. "Dec"};
  1526. #endif /* !NO_CACHING */
  1527. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1528. * the union u. */
  1529. union usa {
  1530. struct sockaddr sa;
  1531. struct sockaddr_in sin;
  1532. #if defined(USE_IPV6)
  1533. struct sockaddr_in6 sin6;
  1534. #endif
  1535. #if defined(USE_X_DOM_SOCKET)
  1536. struct sockaddr_un sun;
  1537. #endif
  1538. };
  1539. #if defined(USE_X_DOM_SOCKET)
  1540. static unsigned short
  1541. USA_IN_PORT_UNSAFE(union usa *s)
  1542. {
  1543. if (s->sa.sa_family == AF_INET)
  1544. return s->sin.sin_port;
  1545. #if defined(USE_IPV6)
  1546. if (s->sa.sa_family == AF_INET6)
  1547. return s->sin6.sin6_port;
  1548. #endif
  1549. return 0;
  1550. }
  1551. #endif
  1552. #if defined(USE_IPV6)
  1553. #define USA_IN_PORT_UNSAFE(s) \
  1554. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1555. #else
  1556. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1557. #endif
  1558. /* Describes a string (chunk of memory). */
  1559. struct vec {
  1560. const char *ptr;
  1561. size_t len;
  1562. };
  1563. struct mg_file_stat {
  1564. /* File properties filled by mg_stat: */
  1565. uint64_t size;
  1566. time_t last_modified;
  1567. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1568. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1569. * case we need a "Content-Eencoding: gzip" header */
  1570. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1571. };
  1572. struct mg_file_access {
  1573. /* File properties filled by mg_fopen: */
  1574. FILE *fp;
  1575. };
  1576. struct mg_file {
  1577. struct mg_file_stat stat;
  1578. struct mg_file_access access;
  1579. };
  1580. #define STRUCT_FILE_INITIALIZER \
  1581. { \
  1582. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1583. { \
  1584. (FILE *)NULL \
  1585. } \
  1586. }
  1587. /* Describes listening socket, or socket which was accept()-ed by the master
  1588. * thread and queued for future handling by the worker thread. */
  1589. struct socket {
  1590. SOCKET sock; /* Listening socket */
  1591. union usa lsa; /* Local socket address */
  1592. union usa rsa; /* Remote socket address */
  1593. unsigned char is_ssl; /* Is port SSL-ed */
  1594. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1595. * port */
  1596. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1597. };
  1598. /* Enum const for all options must be in sync with
  1599. * static struct mg_option config_options[]
  1600. * This is tested in the unit test (test/private.c)
  1601. * "Private Config Options"
  1602. */
  1603. enum {
  1604. /* Once for each server */
  1605. LISTENING_PORTS,
  1606. NUM_THREADS,
  1607. RUN_AS_USER,
  1608. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1609. * socket option typedef TCP_NODELAY. */
  1610. MAX_REQUEST_SIZE,
  1611. LINGER_TIMEOUT,
  1612. CONNECTION_QUEUE_SIZE,
  1613. LISTEN_BACKLOG_SIZE,
  1614. #if defined(__linux__)
  1615. ALLOW_SENDFILE_CALL,
  1616. #endif
  1617. #if defined(_WIN32)
  1618. CASE_SENSITIVE_FILES,
  1619. #endif
  1620. THROTTLE,
  1621. ENABLE_KEEP_ALIVE,
  1622. REQUEST_TIMEOUT,
  1623. KEEP_ALIVE_TIMEOUT,
  1624. #if defined(USE_WEBSOCKET)
  1625. WEBSOCKET_TIMEOUT,
  1626. ENABLE_WEBSOCKET_PING_PONG,
  1627. #endif
  1628. DECODE_URL,
  1629. DECODE_QUERY_STRING,
  1630. #if defined(USE_LUA)
  1631. LUA_BACKGROUND_SCRIPT,
  1632. LUA_BACKGROUND_SCRIPT_PARAMS,
  1633. #endif
  1634. #if defined(USE_HTTP2)
  1635. ENABLE_HTTP2,
  1636. #endif
  1637. /* Once for each domain */
  1638. DOCUMENT_ROOT,
  1639. ACCESS_LOG_FILE,
  1640. ERROR_LOG_FILE,
  1641. CGI_EXTENSIONS,
  1642. CGI_ENVIRONMENT,
  1643. CGI_INTERPRETER,
  1644. CGI_INTERPRETER_ARGS,
  1645. #if defined(USE_TIMERS)
  1646. CGI_TIMEOUT,
  1647. #endif
  1648. CGI_BUFFERING,
  1649. CGI2_EXTENSIONS,
  1650. CGI2_ENVIRONMENT,
  1651. CGI2_INTERPRETER,
  1652. CGI2_INTERPRETER_ARGS,
  1653. #if defined(USE_TIMERS)
  1654. CGI2_TIMEOUT,
  1655. #endif
  1656. CGI2_BUFFERING,
  1657. #if defined(USE_4_CGI)
  1658. CGI3_EXTENSIONS,
  1659. CGI3_ENVIRONMENT,
  1660. CGI3_INTERPRETER,
  1661. CGI3_INTERPRETER_ARGS,
  1662. #if defined(USE_TIMERS)
  1663. CGI3_TIMEOUT,
  1664. #endif
  1665. CGI3_BUFFERING,
  1666. CGI4_EXTENSIONS,
  1667. CGI4_ENVIRONMENT,
  1668. CGI4_INTERPRETER,
  1669. CGI4_INTERPRETER_ARGS,
  1670. #if defined(USE_TIMERS)
  1671. CGI4_TIMEOUT,
  1672. #endif
  1673. CGI4_BUFFERING,
  1674. #endif
  1675. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1676. PROTECT_URI,
  1677. AUTHENTICATION_DOMAIN,
  1678. ENABLE_AUTH_DOMAIN_CHECK,
  1679. SSI_EXTENSIONS,
  1680. ENABLE_DIRECTORY_LISTING,
  1681. ENABLE_WEBDAV,
  1682. GLOBAL_PASSWORDS_FILE,
  1683. INDEX_FILES,
  1684. ACCESS_CONTROL_LIST,
  1685. EXTRA_MIME_TYPES,
  1686. SSL_CERTIFICATE,
  1687. SSL_CERTIFICATE_CHAIN,
  1688. URL_REWRITE_PATTERN,
  1689. HIDE_FILES,
  1690. SSL_DO_VERIFY_PEER,
  1691. SSL_CACHE_TIMEOUT,
  1692. SSL_CA_PATH,
  1693. SSL_CA_FILE,
  1694. SSL_VERIFY_DEPTH,
  1695. SSL_DEFAULT_VERIFY_PATHS,
  1696. SSL_CIPHER_LIST,
  1697. SSL_PROTOCOL_VERSION,
  1698. SSL_SHORT_TRUST,
  1699. #if defined(USE_LUA)
  1700. LUA_PRELOAD_FILE,
  1701. LUA_SCRIPT_EXTENSIONS,
  1702. LUA_SERVER_PAGE_EXTENSIONS,
  1703. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1704. LUA_DEBUG_PARAMS,
  1705. #endif
  1706. #endif
  1707. #if defined(USE_DUKTAPE)
  1708. DUKTAPE_SCRIPT_EXTENSIONS,
  1709. #endif
  1710. #if defined(USE_WEBSOCKET)
  1711. WEBSOCKET_ROOT,
  1712. #endif
  1713. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1714. LUA_WEBSOCKET_EXTENSIONS,
  1715. #endif
  1716. ACCESS_CONTROL_ALLOW_ORIGIN,
  1717. ACCESS_CONTROL_ALLOW_METHODS,
  1718. ACCESS_CONTROL_ALLOW_HEADERS,
  1719. ERROR_PAGES,
  1720. #if !defined(NO_CACHING)
  1721. STATIC_FILE_MAX_AGE,
  1722. STATIC_FILE_CACHE_CONTROL,
  1723. #endif
  1724. #if !defined(NO_SSL)
  1725. STRICT_HTTPS_MAX_AGE,
  1726. #endif
  1727. ADDITIONAL_HEADER,
  1728. ALLOW_INDEX_SCRIPT_SUB_RES,
  1729. NUM_OPTIONS
  1730. };
  1731. /* Config option name, config types, default value.
  1732. * Must be in the same order as the enum const above.
  1733. */
  1734. static const struct mg_option config_options[] = {
  1735. /* Once for each server */
  1736. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1737. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1738. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1739. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1740. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1741. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1742. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1743. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1744. #if defined(__linux__)
  1745. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1746. #endif
  1747. #if defined(_WIN32)
  1748. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1749. #endif
  1750. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1751. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1752. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1753. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1754. #if defined(USE_WEBSOCKET)
  1755. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1756. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1757. #endif
  1758. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1759. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1760. #if defined(USE_LUA)
  1761. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1762. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1763. #endif
  1764. #if defined(USE_HTTP2)
  1765. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1766. #endif
  1767. /* Once for each domain */
  1768. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1769. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1770. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1771. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1772. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1773. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1774. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1775. #if defined(USE_TIMERS)
  1776. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1777. #endif
  1778. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1779. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1780. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1781. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1782. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1783. #if defined(USE_TIMERS)
  1784. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1785. #endif
  1786. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1787. #if defined(USE_4_CGI)
  1788. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1789. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1790. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1791. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1792. #if defined(USE_TIMERS)
  1793. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1794. #endif
  1795. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1796. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1797. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1798. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1799. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1800. #if defined(USE_TIMERS)
  1801. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1802. #endif
  1803. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1804. #endif
  1805. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1806. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1808. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1809. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1810. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1811. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1812. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1813. {"index_files",
  1814. MG_CONFIG_TYPE_STRING_LIST,
  1815. #if defined(USE_LUA)
  1816. "index.xhtml,index.html,index.htm,"
  1817. "index.lp,index.lsp,index.lua,index.cgi,"
  1818. "index.shtml,index.php"},
  1819. #else
  1820. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1821. #endif
  1822. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1823. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1824. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1825. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1826. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1827. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1828. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1829. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1830. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1831. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1832. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1833. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1834. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1835. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1836. * as a minimum in 2020 */
  1837. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1838. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1839. #if defined(USE_LUA)
  1840. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1841. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1842. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1843. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1844. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1845. #endif
  1846. #endif
  1847. #if defined(USE_DUKTAPE)
  1848. /* The support for duktape is still in alpha version state.
  1849. * The name of this config option might change. */
  1850. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1851. #endif
  1852. #if defined(USE_WEBSOCKET)
  1853. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1854. #endif
  1855. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1856. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1857. #endif
  1858. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1859. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1860. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1861. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1862. #if !defined(NO_CACHING)
  1863. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1864. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1865. #endif
  1866. #if !defined(NO_SSL)
  1867. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1868. #endif
  1869. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1870. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1871. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1872. /* Check if the config_options and the corresponding enum have compatible
  1873. * sizes. */
  1874. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1875. == (NUM_OPTIONS + 1),
  1876. "config_options and enum not sync");
  1877. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1878. struct mg_handler_info {
  1879. /* Name/Pattern of the URI. */
  1880. char *uri;
  1881. size_t uri_len;
  1882. /* handler type */
  1883. int handler_type;
  1884. /* Handler for http/https or requests. */
  1885. mg_request_handler handler;
  1886. unsigned int refcount;
  1887. int removing;
  1888. /* Handler for ws/wss (websocket) requests. */
  1889. mg_websocket_connect_handler connect_handler;
  1890. mg_websocket_ready_handler ready_handler;
  1891. mg_websocket_data_handler data_handler;
  1892. mg_websocket_close_handler close_handler;
  1893. /* accepted subprotocols for ws/wss requests. */
  1894. struct mg_websocket_subprotocols *subprotocols;
  1895. /* Handler for authorization requests */
  1896. mg_authorization_handler auth_handler;
  1897. /* User supplied argument for the handler function. */
  1898. void *cbdata;
  1899. /* next handler in a linked list */
  1900. struct mg_handler_info *next;
  1901. };
  1902. enum {
  1903. CONTEXT_INVALID,
  1904. CONTEXT_SERVER,
  1905. CONTEXT_HTTP_CLIENT,
  1906. CONTEXT_WS_CLIENT
  1907. };
  1908. struct mg_domain_context {
  1909. SSL_CTX *ssl_ctx; /* SSL context */
  1910. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1911. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1912. int64_t ssl_cert_last_mtime;
  1913. /* Server nonce */
  1914. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1915. unsigned long nonce_count; /* Used nonces, used for authentication */
  1916. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1917. /* linked list of shared lua websockets */
  1918. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1919. #endif
  1920. /* Linked list of domains */
  1921. struct mg_domain_context *next;
  1922. };
  1923. /* Stop flag can be "volatile" or require a lock.
  1924. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1925. * states a read operation for int is always atomic. */
  1926. #if defined(STOP_FLAG_NEEDS_LOCK)
  1927. typedef ptrdiff_t volatile stop_flag_t;
  1928. static int
  1929. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1930. {
  1931. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1932. return (sf == 0);
  1933. }
  1934. static int
  1935. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1936. {
  1937. stop_flag_t sf = mg_atomic_add(f, 0);
  1938. return (sf == 2);
  1939. }
  1940. static void
  1941. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1942. {
  1943. stop_flag_t sf;
  1944. do {
  1945. sf = mg_atomic_compare_and_swap(f, *f, v);
  1946. } while (sf != v);
  1947. }
  1948. #else /* STOP_FLAG_NEEDS_LOCK */
  1949. typedef int volatile stop_flag_t;
  1950. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1951. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1952. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1953. #endif /* STOP_FLAG_NEEDS_LOCK */
  1954. #if !defined(NUM_WEBDAV_LOCKS)
  1955. #define NUM_WEBDAV_LOCKS 10
  1956. #endif
  1957. #if !defined(LOCK_DURATION_S)
  1958. #define LOCK_DURATION_S 60
  1959. #endif
  1960. struct twebdav_lock {
  1961. uint64_t locktime;
  1962. char token[33];
  1963. char path[UTF8_PATH_MAX * 2];
  1964. char user[UTF8_PATH_MAX * 2];
  1965. };
  1966. struct mg_context {
  1967. /* Part 1 - Physical context:
  1968. * This holds threads, ports, timeouts, ...
  1969. * set for the entire server, independent from the
  1970. * addressed hostname.
  1971. */
  1972. /* Connection related */
  1973. int context_type; /* See CONTEXT_* above */
  1974. struct socket *listening_sockets;
  1975. struct mg_pollfd *listening_socket_fds;
  1976. unsigned int num_listening_sockets;
  1977. struct mg_connection *worker_connections; /* The connection struct, pre-
  1978. * allocated for each worker */
  1979. #if defined(USE_SERVER_STATS)
  1980. volatile ptrdiff_t active_connections;
  1981. volatile ptrdiff_t max_active_connections;
  1982. volatile ptrdiff_t total_connections;
  1983. volatile ptrdiff_t total_requests;
  1984. volatile int64_t total_data_read;
  1985. volatile int64_t total_data_written;
  1986. #endif
  1987. /* Thread related */
  1988. stop_flag_t stop_flag; /* Should we stop event loop */
  1989. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1990. pthread_t masterthreadid; /* The master thread ID */
  1991. unsigned int
  1992. cfg_worker_threads; /* The number of configured worker threads. */
  1993. pthread_t *worker_threadids; /* The worker thread IDs */
  1994. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1995. /* Connection to thread dispatching */
  1996. #if defined(ALTERNATIVE_QUEUE)
  1997. struct socket *client_socks;
  1998. void **client_wait_events;
  1999. #else
  2000. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2001. worker thread */
  2002. volatile int sq_head; /* Head of the socket queue */
  2003. volatile int sq_tail; /* Tail of the socket queue */
  2004. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2005. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2006. volatile int sq_blocked; /* Status information: sq is full */
  2007. int sq_size; /* No of elements in socket queue */
  2008. #if defined(USE_SERVER_STATS)
  2009. int sq_max_fill;
  2010. #endif /* USE_SERVER_STATS */
  2011. #endif /* ALTERNATIVE_QUEUE */
  2012. /* Memory related */
  2013. unsigned int max_request_size; /* The max request size */
  2014. #if defined(USE_SERVER_STATS)
  2015. struct mg_memory_stat ctx_memory;
  2016. #endif
  2017. /* WebDAV lock structures */
  2018. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2019. /* Operating system related */
  2020. char *systemName; /* What operating system is running */
  2021. time_t start_time; /* Server start time, used for authentication
  2022. * and for diagnstics. */
  2023. #if defined(USE_TIMERS)
  2024. struct ttimers *timers;
  2025. #endif
  2026. /* Lua specific: Background operations and shared websockets */
  2027. #if defined(USE_LUA)
  2028. void *lua_background_state; /* lua_State (here as void *) */
  2029. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2030. int lua_bg_log_available; /* Use Lua background state for access log */
  2031. #endif
  2032. /* Server nonce */
  2033. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2034. * ssl_cert_last_mtime, nonce_count, and
  2035. * next (linked list) */
  2036. /* Server callbacks */
  2037. struct mg_callbacks callbacks; /* User-defined callback function */
  2038. void *user_data; /* User-defined data */
  2039. /* Part 2 - Logical domain:
  2040. * This holds hostname, TLS certificate, document root, ...
  2041. * set for a domain hosted at the server.
  2042. * There may be multiple domains hosted at one physical server.
  2043. * The default domain "dd" is the first element of a list of
  2044. * domains.
  2045. */
  2046. struct mg_domain_context dd; /* default domain */
  2047. };
  2048. #if defined(USE_SERVER_STATS)
  2049. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2050. static struct mg_memory_stat *
  2051. get_memory_stat(struct mg_context *ctx)
  2052. {
  2053. if (ctx) {
  2054. return &(ctx->ctx_memory);
  2055. }
  2056. return &mg_common_memory;
  2057. }
  2058. #endif
  2059. enum {
  2060. CONNECTION_TYPE_INVALID = 0,
  2061. CONNECTION_TYPE_REQUEST = 1,
  2062. CONNECTION_TYPE_RESPONSE = 2
  2063. };
  2064. enum {
  2065. PROTOCOL_TYPE_HTTP1 = 0,
  2066. PROTOCOL_TYPE_WEBSOCKET = 1,
  2067. PROTOCOL_TYPE_HTTP2 = 2
  2068. };
  2069. #if defined(USE_HTTP2)
  2070. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2071. #define HTTP2_DYN_TABLE_SIZE (256)
  2072. #endif
  2073. struct mg_http2_connection {
  2074. uint32_t stream_id;
  2075. uint32_t dyn_table_size;
  2076. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2077. };
  2078. #endif
  2079. struct mg_connection {
  2080. int connection_type; /* see CONNECTION_TYPE_* above */
  2081. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2082. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2083. fully sent */
  2084. #if defined(USE_HTTP2)
  2085. struct mg_http2_connection http2;
  2086. #endif
  2087. struct mg_request_info request_info;
  2088. struct mg_response_info response_info;
  2089. struct mg_context *phys_ctx;
  2090. struct mg_domain_context *dom_ctx;
  2091. #if defined(USE_SERVER_STATS)
  2092. int conn_state; /* 0 = undef, numerical value may change in different
  2093. * versions. For the current definition, see
  2094. * mg_get_connection_info_impl */
  2095. #endif
  2096. SSL *ssl; /* SSL descriptor */
  2097. struct socket client; /* Connected client */
  2098. time_t conn_birth_time; /* Time (wall clock) when connection was
  2099. * established */
  2100. #if defined(USE_SERVER_STATS)
  2101. time_t conn_close_time; /* Time (wall clock) when connection was
  2102. * closed (or 0 if still open) */
  2103. double processing_time; /* Procesing time for one request. */
  2104. #endif
  2105. struct timespec req_time; /* Time (since system start) when the request
  2106. * was received */
  2107. int64_t num_bytes_sent; /* Total bytes sent to client */
  2108. int64_t content_len; /* How many bytes of content can be read
  2109. * !is_chunked: Content-Length header value
  2110. * or -1 (until connection closed,
  2111. * not allowed for a request)
  2112. * is_chunked: >= 0, appended gradually
  2113. */
  2114. int64_t consumed_content; /* How many bytes of content have been read */
  2115. int is_chunked; /* Transfer-Encoding is chunked:
  2116. * 0 = not chunked,
  2117. * 1 = chunked, not yet, or some data read,
  2118. * 2 = chunked, has error,
  2119. * 3 = chunked, all data read except trailer,
  2120. * 4 = chunked, all data read
  2121. */
  2122. char *buf; /* Buffer for received data */
  2123. char *path_info; /* PATH_INFO part of the URL */
  2124. int must_close; /* 1 if connection must be closed */
  2125. int accept_gzip; /* 1 if gzip encoding is accepted */
  2126. int in_error_handler; /* 1 if in handler for user defined error
  2127. * pages */
  2128. #if defined(USE_WEBSOCKET)
  2129. int in_websocket_handling; /* 1 if in read_websocket */
  2130. #endif
  2131. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2132. && defined(MG_EXPERIMENTAL_INTERFACES)
  2133. /* Parameters for websocket data compression according to rfc7692 */
  2134. int websocket_deflate_server_max_windows_bits;
  2135. int websocket_deflate_client_max_windows_bits;
  2136. int websocket_deflate_server_no_context_takeover;
  2137. int websocket_deflate_client_no_context_takeover;
  2138. int websocket_deflate_initialized;
  2139. int websocket_deflate_flush;
  2140. z_stream websocket_deflate_state;
  2141. z_stream websocket_inflate_state;
  2142. #endif
  2143. int handled_requests; /* Number of requests handled by this connection
  2144. */
  2145. int buf_size; /* Buffer size */
  2146. int request_len; /* Size of the request + headers in a buffer */
  2147. int data_len; /* Total size of data in a buffer */
  2148. int status_code; /* HTTP reply status code, e.g. 200 */
  2149. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2150. * throttle */
  2151. time_t last_throttle_time; /* Last time throttled data was sent */
  2152. int last_throttle_bytes; /* Bytes sent this second */
  2153. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2154. * atomic transmissions for websockets */
  2155. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2156. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2157. #endif
  2158. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2159. * for quick access */
  2160. };
  2161. /* Directory entry */
  2162. struct de {
  2163. char *file_name;
  2164. struct mg_file_stat file;
  2165. };
  2166. #define mg_cry_internal(conn, fmt, ...) \
  2167. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2168. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2169. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2170. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2171. struct mg_context *ctx,
  2172. const char *func,
  2173. unsigned line,
  2174. const char *fmt,
  2175. ...) PRINTF_ARGS(5, 6);
  2176. #if !defined(NO_THREAD_NAME)
  2177. #if defined(_WIN32) && defined(_MSC_VER)
  2178. /* Set the thread name for debugging purposes in Visual Studio
  2179. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2180. */
  2181. #pragma pack(push, 8)
  2182. typedef struct tagTHREADNAME_INFO {
  2183. DWORD dwType; /* Must be 0x1000. */
  2184. LPCSTR szName; /* Pointer to name (in user addr space). */
  2185. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2186. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2187. } THREADNAME_INFO;
  2188. #pragma pack(pop)
  2189. #elif defined(__linux__)
  2190. #include <sys/prctl.h>
  2191. #include <sys/sendfile.h>
  2192. #if defined(ALTERNATIVE_QUEUE)
  2193. #include <sys/eventfd.h>
  2194. #endif /* ALTERNATIVE_QUEUE */
  2195. #if defined(ALTERNATIVE_QUEUE)
  2196. static void *
  2197. event_create(void)
  2198. {
  2199. int evhdl = eventfd(0, EFD_CLOEXEC);
  2200. int *ret;
  2201. if (evhdl == -1) {
  2202. /* Linux uses -1 on error, Windows NULL. */
  2203. /* However, Linux does not return 0 on success either. */
  2204. return 0;
  2205. }
  2206. ret = (int *)mg_malloc(sizeof(int));
  2207. if (ret) {
  2208. *ret = evhdl;
  2209. } else {
  2210. (void)close(evhdl);
  2211. }
  2212. return (void *)ret;
  2213. }
  2214. static int
  2215. event_wait(void *eventhdl)
  2216. {
  2217. uint64_t u;
  2218. int evhdl, s;
  2219. if (!eventhdl) {
  2220. /* error */
  2221. return 0;
  2222. }
  2223. evhdl = *(int *)eventhdl;
  2224. s = (int)read(evhdl, &u, sizeof(u));
  2225. if (s != sizeof(u)) {
  2226. /* error */
  2227. return 0;
  2228. }
  2229. (void)u; /* the value is not required */
  2230. return 1;
  2231. }
  2232. static int
  2233. event_signal(void *eventhdl)
  2234. {
  2235. uint64_t u = 1;
  2236. int evhdl, s;
  2237. if (!eventhdl) {
  2238. /* error */
  2239. return 0;
  2240. }
  2241. evhdl = *(int *)eventhdl;
  2242. s = (int)write(evhdl, &u, sizeof(u));
  2243. if (s != sizeof(u)) {
  2244. /* error */
  2245. return 0;
  2246. }
  2247. return 1;
  2248. }
  2249. static void
  2250. event_destroy(void *eventhdl)
  2251. {
  2252. int evhdl;
  2253. if (!eventhdl) {
  2254. /* error */
  2255. return;
  2256. }
  2257. evhdl = *(int *)eventhdl;
  2258. close(evhdl);
  2259. mg_free(eventhdl);
  2260. }
  2261. #endif
  2262. #endif
  2263. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2264. struct posix_event {
  2265. pthread_mutex_t mutex;
  2266. pthread_cond_t cond;
  2267. int signaled;
  2268. };
  2269. static void *
  2270. event_create(void)
  2271. {
  2272. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2273. if (ret == 0) {
  2274. /* out of memory */
  2275. return 0;
  2276. }
  2277. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2278. /* pthread mutex not available */
  2279. mg_free(ret);
  2280. return 0;
  2281. }
  2282. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2283. /* pthread cond not available */
  2284. pthread_mutex_destroy(&(ret->mutex));
  2285. mg_free(ret);
  2286. return 0;
  2287. }
  2288. ret->signaled = 0;
  2289. return (void *)ret;
  2290. }
  2291. static int
  2292. event_wait(void *eventhdl)
  2293. {
  2294. struct posix_event *ev = (struct posix_event *)eventhdl;
  2295. pthread_mutex_lock(&(ev->mutex));
  2296. while (!ev->signaled) {
  2297. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2298. }
  2299. ev->signaled = 0;
  2300. pthread_mutex_unlock(&(ev->mutex));
  2301. return 1;
  2302. }
  2303. static int
  2304. event_signal(void *eventhdl)
  2305. {
  2306. struct posix_event *ev = (struct posix_event *)eventhdl;
  2307. pthread_mutex_lock(&(ev->mutex));
  2308. pthread_cond_signal(&(ev->cond));
  2309. ev->signaled = 1;
  2310. pthread_mutex_unlock(&(ev->mutex));
  2311. return 1;
  2312. }
  2313. static void
  2314. event_destroy(void *eventhdl)
  2315. {
  2316. struct posix_event *ev = (struct posix_event *)eventhdl;
  2317. pthread_cond_destroy(&(ev->cond));
  2318. pthread_mutex_destroy(&(ev->mutex));
  2319. mg_free(ev);
  2320. }
  2321. #endif
  2322. static void
  2323. mg_set_thread_name(const char *name)
  2324. {
  2325. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2326. mg_snprintf(
  2327. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2328. #if defined(_WIN32)
  2329. #if defined(_MSC_VER)
  2330. /* Windows and Visual Studio Compiler */
  2331. __try {
  2332. THREADNAME_INFO info;
  2333. info.dwType = 0x1000;
  2334. info.szName = threadName;
  2335. info.dwThreadID = ~0U;
  2336. info.dwFlags = 0;
  2337. RaiseException(0x406D1388,
  2338. 0,
  2339. sizeof(info) / sizeof(ULONG_PTR),
  2340. (ULONG_PTR *)&info);
  2341. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2342. }
  2343. #elif defined(__MINGW32__)
  2344. /* No option known to set thread name for MinGW known */
  2345. #endif
  2346. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2347. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2348. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2349. #if defined(__MACH__)
  2350. /* OS X only current thread name can be changed */
  2351. (void)pthread_setname_np(threadName);
  2352. #else
  2353. (void)pthread_setname_np(pthread_self(), threadName);
  2354. #endif
  2355. #elif defined(__linux__)
  2356. /* On Linux we can use the prctl function.
  2357. * When building for Linux Standard Base (LSB) use
  2358. * NO_THREAD_NAME. However, thread names are a big
  2359. * help for debugging, so the stadard is to set them.
  2360. */
  2361. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2362. #endif
  2363. }
  2364. #else /* !defined(NO_THREAD_NAME) */
  2365. static void
  2366. mg_set_thread_name(const char *threadName)
  2367. {
  2368. }
  2369. #endif
  2370. CIVETWEB_API const struct mg_option *
  2371. mg_get_valid_options(void)
  2372. {
  2373. return config_options;
  2374. }
  2375. /* Do not open file (unused) */
  2376. #define MG_FOPEN_MODE_NONE (0)
  2377. /* Open file for read only access */
  2378. #define MG_FOPEN_MODE_READ (1)
  2379. /* Open file for writing, create and overwrite */
  2380. #define MG_FOPEN_MODE_WRITE (2)
  2381. /* Open file for writing, create and append */
  2382. #define MG_FOPEN_MODE_APPEND (4)
  2383. static int
  2384. is_file_opened(const struct mg_file_access *fileacc)
  2385. {
  2386. if (!fileacc) {
  2387. return 0;
  2388. }
  2389. return (fileacc->fp != NULL);
  2390. }
  2391. #if !defined(NO_FILESYSTEMS)
  2392. static int mg_stat(const struct mg_connection *conn,
  2393. const char *path,
  2394. struct mg_file_stat *filep);
  2395. /* Reject files with special characters (for Windows) */
  2396. static int
  2397. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2398. {
  2399. const uint8_t *c = (const uint8_t *)path;
  2400. (void)conn; /* not used */
  2401. if ((c == NULL) || (c[0] == 0)) {
  2402. /* Null pointer or empty path --> suspicious */
  2403. return 1;
  2404. }
  2405. #if defined(_WIN32)
  2406. while (*c) {
  2407. if (*c < 32) {
  2408. /* Control character */
  2409. return 1;
  2410. }
  2411. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2412. /* stdin/stdout redirection character */
  2413. return 1;
  2414. }
  2415. if ((*c == '*') || (*c == '?')) {
  2416. /* Wildcard character */
  2417. return 1;
  2418. }
  2419. if (*c == '"') {
  2420. /* Windows quotation */
  2421. return 1;
  2422. }
  2423. c++;
  2424. }
  2425. #endif
  2426. /* Nothing suspicious found */
  2427. return 0;
  2428. }
  2429. /* mg_fopen will open a file either in memory or on the disk.
  2430. * The input parameter path is a string in UTF-8 encoding.
  2431. * The input parameter mode is MG_FOPEN_MODE_*
  2432. * On success, fp will be set in the output struct mg_file.
  2433. * All status members will also be set.
  2434. * The function returns 1 on success, 0 on error. */
  2435. static int
  2436. mg_fopen(const struct mg_connection *conn,
  2437. const char *path,
  2438. int mode,
  2439. struct mg_file *filep)
  2440. {
  2441. int found;
  2442. if (!filep) {
  2443. return 0;
  2444. }
  2445. filep->access.fp = NULL;
  2446. if (mg_path_suspicious(conn, path)) {
  2447. return 0;
  2448. }
  2449. /* filep is initialized in mg_stat: all fields with memset to,
  2450. * some fields like size and modification date with values */
  2451. found = mg_stat(conn, path, &(filep->stat));
  2452. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2453. /* file does not exist and will not be created */
  2454. return 0;
  2455. }
  2456. #if defined(_WIN32)
  2457. {
  2458. wchar_t wbuf[UTF16_PATH_MAX];
  2459. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2460. switch (mode) {
  2461. case MG_FOPEN_MODE_READ:
  2462. filep->access.fp = _wfopen(wbuf, L"rb");
  2463. break;
  2464. case MG_FOPEN_MODE_WRITE:
  2465. filep->access.fp = _wfopen(wbuf, L"wb");
  2466. break;
  2467. case MG_FOPEN_MODE_APPEND:
  2468. filep->access.fp = _wfopen(wbuf, L"ab");
  2469. break;
  2470. }
  2471. }
  2472. #else
  2473. /* Linux et al already use unicode. No need to convert. */
  2474. switch (mode) {
  2475. case MG_FOPEN_MODE_READ:
  2476. filep->access.fp = fopen(path, "r");
  2477. break;
  2478. case MG_FOPEN_MODE_WRITE:
  2479. filep->access.fp = fopen(path, "w");
  2480. break;
  2481. case MG_FOPEN_MODE_APPEND:
  2482. filep->access.fp = fopen(path, "a");
  2483. break;
  2484. }
  2485. #endif
  2486. if (!found) {
  2487. /* File did not exist before fopen was called.
  2488. * Maybe it has been created now. Get stat info
  2489. * like creation time now. */
  2490. found = mg_stat(conn, path, &(filep->stat));
  2491. (void)found;
  2492. }
  2493. /* return OK if file is opened */
  2494. return (filep->access.fp != NULL);
  2495. }
  2496. /* return 0 on success, just like fclose */
  2497. static int
  2498. mg_fclose(struct mg_file_access *fileacc)
  2499. {
  2500. int ret = -1;
  2501. if (fileacc != NULL) {
  2502. if (fileacc->fp != NULL) {
  2503. ret = fclose(fileacc->fp);
  2504. }
  2505. /* reset all members of fileacc */
  2506. memset(fileacc, 0, sizeof(*fileacc));
  2507. }
  2508. return ret;
  2509. }
  2510. #endif /* NO_FILESYSTEMS */
  2511. static void
  2512. mg_strlcpy(char *dst, const char *src, size_t n)
  2513. {
  2514. for (; *src != '\0' && n > 1; n--) {
  2515. *dst++ = *src++;
  2516. }
  2517. *dst = '\0';
  2518. }
  2519. static int
  2520. lowercase(const char *s)
  2521. {
  2522. return tolower((unsigned char)*s);
  2523. }
  2524. CIVETWEB_API int
  2525. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2526. {
  2527. int diff = 0;
  2528. if (len > 0) {
  2529. do {
  2530. diff = lowercase(s1++) - lowercase(s2++);
  2531. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2532. }
  2533. return diff;
  2534. }
  2535. CIVETWEB_API int
  2536. mg_strcasecmp(const char *s1, const char *s2)
  2537. {
  2538. int diff;
  2539. do {
  2540. diff = lowercase(s1++) - lowercase(s2++);
  2541. } while (diff == 0 && s1[-1] != '\0');
  2542. return diff;
  2543. }
  2544. static char *
  2545. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2546. {
  2547. char *p;
  2548. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2549. * defined */
  2550. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2551. mg_strlcpy(p, ptr, len + 1);
  2552. }
  2553. return p;
  2554. }
  2555. static char *
  2556. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2557. {
  2558. return mg_strndup_ctx(str, strlen(str), ctx);
  2559. }
  2560. static char *
  2561. mg_strdup(const char *str)
  2562. {
  2563. return mg_strndup_ctx(str, strlen(str), NULL);
  2564. }
  2565. static const char *
  2566. mg_strcasestr(const char *big_str, const char *small_str)
  2567. {
  2568. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2569. if (big_len >= small_len) {
  2570. for (i = 0; i <= (big_len - small_len); i++) {
  2571. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2572. return big_str + i;
  2573. }
  2574. }
  2575. }
  2576. return NULL;
  2577. }
  2578. /* Return null terminated string of given maximum length.
  2579. * Report errors if length is exceeded. */
  2580. static void
  2581. mg_vsnprintf(const struct mg_connection *conn,
  2582. int *truncated,
  2583. char *buf,
  2584. size_t buflen,
  2585. const char *fmt,
  2586. va_list ap)
  2587. {
  2588. int n, ok;
  2589. if (buflen == 0) {
  2590. if (truncated) {
  2591. *truncated = 1;
  2592. }
  2593. return;
  2594. }
  2595. #if defined(__clang__)
  2596. #pragma clang diagnostic push
  2597. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2598. /* Using fmt as a non-literal is intended here, since it is mostly called
  2599. * indirectly by mg_snprintf */
  2600. #endif
  2601. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2602. ok = (n >= 0) && ((size_t)n < buflen);
  2603. #if defined(__clang__)
  2604. #pragma clang diagnostic pop
  2605. #endif
  2606. if (ok) {
  2607. if (truncated) {
  2608. *truncated = 0;
  2609. }
  2610. } else {
  2611. if (truncated) {
  2612. *truncated = 1;
  2613. }
  2614. mg_cry_internal(conn,
  2615. "truncating vsnprintf buffer: [%.*s]",
  2616. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2617. buf);
  2618. n = (int)buflen - 1;
  2619. }
  2620. buf[n] = '\0';
  2621. }
  2622. static void
  2623. mg_snprintf(const struct mg_connection *conn,
  2624. int *truncated,
  2625. char *buf,
  2626. size_t buflen,
  2627. const char *fmt,
  2628. ...)
  2629. {
  2630. va_list ap;
  2631. va_start(ap, fmt);
  2632. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2633. va_end(ap);
  2634. }
  2635. static int
  2636. get_option_index(const char *name)
  2637. {
  2638. int i;
  2639. for (i = 0; config_options[i].name != NULL; i++) {
  2640. if (strcmp(config_options[i].name, name) == 0) {
  2641. return i;
  2642. }
  2643. }
  2644. return -1;
  2645. }
  2646. CIVETWEB_API const char *
  2647. mg_get_option(const struct mg_context *ctx, const char *name)
  2648. {
  2649. int i;
  2650. if ((i = get_option_index(name)) == -1) {
  2651. return NULL;
  2652. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2653. return "";
  2654. } else {
  2655. return ctx->dd.config[i];
  2656. }
  2657. }
  2658. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2659. CIVETWEB_API struct mg_context *
  2660. mg_get_context(const struct mg_connection *conn)
  2661. {
  2662. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2663. }
  2664. CIVETWEB_API void *
  2665. mg_get_user_data(const struct mg_context *ctx)
  2666. {
  2667. return (ctx == NULL) ? NULL : ctx->user_data;
  2668. }
  2669. CIVETWEB_API void *
  2670. mg_get_user_context_data(const struct mg_connection *conn)
  2671. {
  2672. return mg_get_user_data(mg_get_context(conn));
  2673. }
  2674. CIVETWEB_API void *
  2675. mg_get_thread_pointer(const struct mg_connection *conn)
  2676. {
  2677. /* both methods should return the same pointer */
  2678. if (conn) {
  2679. /* quick access, in case conn is known */
  2680. return conn->tls_user_ptr;
  2681. } else {
  2682. /* otherwise get pointer from thread local storage (TLS) */
  2683. struct mg_workerTLS *tls =
  2684. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2685. return tls->user_ptr;
  2686. }
  2687. }
  2688. CIVETWEB_API void
  2689. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2690. {
  2691. if (const_conn != NULL) {
  2692. /* Const cast, since "const struct mg_connection *" does not mean
  2693. * the connection object is not modified. Here "const" is used,
  2694. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2695. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2696. conn->request_info.conn_data = data;
  2697. }
  2698. }
  2699. CIVETWEB_API void *
  2700. mg_get_user_connection_data(const struct mg_connection *conn)
  2701. {
  2702. if (conn != NULL) {
  2703. return conn->request_info.conn_data;
  2704. }
  2705. return NULL;
  2706. }
  2707. CIVETWEB_API int
  2708. mg_get_server_ports(const struct mg_context *ctx,
  2709. int size,
  2710. struct mg_server_port *ports)
  2711. {
  2712. int i, cnt = 0;
  2713. if (size <= 0) {
  2714. return -1;
  2715. }
  2716. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2717. if (!ctx) {
  2718. return -1;
  2719. }
  2720. if (!ctx->listening_sockets) {
  2721. return -1;
  2722. }
  2723. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2724. ports[cnt].port =
  2725. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2726. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2727. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2728. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2729. /* IPv4 */
  2730. ports[cnt].protocol = 1;
  2731. cnt++;
  2732. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2733. /* IPv6 */
  2734. ports[cnt].protocol = 3;
  2735. cnt++;
  2736. }
  2737. }
  2738. return cnt;
  2739. }
  2740. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2741. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2742. #endif
  2743. static void
  2744. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2745. {
  2746. buf[0] = '\0';
  2747. if (!usa) {
  2748. return;
  2749. }
  2750. if (usa->sa.sa_family == AF_INET) {
  2751. getnameinfo(&usa->sa,
  2752. sizeof(usa->sin),
  2753. buf,
  2754. (unsigned)len,
  2755. NULL,
  2756. 0,
  2757. NI_NUMERICHOST);
  2758. }
  2759. #if defined(USE_IPV6)
  2760. else if (usa->sa.sa_family == AF_INET6) {
  2761. getnameinfo(&usa->sa,
  2762. sizeof(usa->sin6),
  2763. buf,
  2764. (unsigned)len,
  2765. NULL,
  2766. 0,
  2767. NI_NUMERICHOST);
  2768. }
  2769. #endif
  2770. #if defined(USE_X_DOM_SOCKET)
  2771. else if (usa->sa.sa_family == AF_UNIX) {
  2772. /* TODO: Define a remote address for unix domain sockets.
  2773. * This code will always return "localhost", identical to http+tcp:
  2774. getnameinfo(&usa->sa,
  2775. sizeof(usa->sun),
  2776. buf,
  2777. (unsigned)len,
  2778. NULL,
  2779. 0,
  2780. NI_NUMERICHOST);
  2781. */
  2782. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2783. buf[len] = 0;
  2784. }
  2785. #endif
  2786. }
  2787. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2788. * included in all responses other than 100, 101, 5xx. */
  2789. static void
  2790. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2791. {
  2792. #if !defined(REENTRANT_TIME)
  2793. struct tm *tm;
  2794. tm = ((t != NULL) ? gmtime(t) : NULL);
  2795. if (tm != NULL) {
  2796. #else
  2797. struct tm _tm;
  2798. struct tm *tm = &_tm;
  2799. if (t != NULL) {
  2800. gmtime_r(t, tm);
  2801. #endif
  2802. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2803. } else {
  2804. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2805. buf[buf_len - 1] = '\0';
  2806. }
  2807. }
  2808. /* difftime for struct timespec. Return value is in seconds. */
  2809. static double
  2810. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2811. {
  2812. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2813. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2814. }
  2815. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2816. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2817. const char *func,
  2818. unsigned line,
  2819. const char *fmt,
  2820. va_list ap);
  2821. #include "external_mg_cry_internal_impl.inl"
  2822. #elif !defined(NO_FILESYSTEMS)
  2823. /* Print error message to the opened error log stream. */
  2824. static void
  2825. mg_cry_internal_impl(const struct mg_connection *conn,
  2826. const char *func,
  2827. unsigned line,
  2828. const char *fmt,
  2829. va_list ap)
  2830. {
  2831. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2832. struct mg_file fi;
  2833. time_t timestamp;
  2834. /* Unused, in the RELEASE build */
  2835. (void)func;
  2836. (void)line;
  2837. #if defined(GCC_DIAGNOSTIC)
  2838. #pragma GCC diagnostic push
  2839. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2840. #endif
  2841. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2842. #if defined(GCC_DIAGNOSTIC)
  2843. #pragma GCC diagnostic pop
  2844. #endif
  2845. buf[sizeof(buf) - 1] = 0;
  2846. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2847. if (!conn) {
  2848. puts(buf);
  2849. return;
  2850. }
  2851. /* Do not lock when getting the callback value, here and below.
  2852. * I suppose this is fine, since function cannot disappear in the
  2853. * same way string option can. */
  2854. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2855. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2856. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2857. if (mg_fopen(conn,
  2858. conn->dom_ctx->config[ERROR_LOG_FILE],
  2859. MG_FOPEN_MODE_APPEND,
  2860. &fi)
  2861. == 0) {
  2862. fi.access.fp = NULL;
  2863. }
  2864. } else {
  2865. fi.access.fp = NULL;
  2866. }
  2867. if (fi.access.fp != NULL) {
  2868. flockfile(fi.access.fp);
  2869. timestamp = time(NULL);
  2870. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2871. fprintf(fi.access.fp,
  2872. "[%010lu] [error] [client %s] ",
  2873. (unsigned long)timestamp,
  2874. src_addr);
  2875. if (conn->request_info.request_method != NULL) {
  2876. fprintf(fi.access.fp,
  2877. "%s %s: ",
  2878. conn->request_info.request_method,
  2879. conn->request_info.request_uri
  2880. ? conn->request_info.request_uri
  2881. : "");
  2882. }
  2883. fprintf(fi.access.fp, "%s", buf);
  2884. fputc('\n', fi.access.fp);
  2885. fflush(fi.access.fp);
  2886. funlockfile(fi.access.fp);
  2887. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2888. * mg_cry here anyway ;-) */
  2889. }
  2890. }
  2891. }
  2892. #else
  2893. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2894. #endif /* Externally provided function */
  2895. /* Construct fake connection structure. Used for logging, if connection
  2896. * is not applicable at the moment of logging. */
  2897. static struct mg_connection *
  2898. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2899. {
  2900. static const struct mg_connection conn_zero = {0};
  2901. *fc = conn_zero;
  2902. fc->phys_ctx = ctx;
  2903. fc->dom_ctx = &(ctx->dd);
  2904. return fc;
  2905. }
  2906. static void
  2907. mg_cry_internal_wrap(const struct mg_connection *conn,
  2908. struct mg_context *ctx,
  2909. const char *func,
  2910. unsigned line,
  2911. const char *fmt,
  2912. ...)
  2913. {
  2914. va_list ap;
  2915. va_start(ap, fmt);
  2916. if (!conn && ctx) {
  2917. struct mg_connection fc;
  2918. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2919. } else {
  2920. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2921. }
  2922. va_end(ap);
  2923. }
  2924. CIVETWEB_API void
  2925. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2926. {
  2927. va_list ap;
  2928. va_start(ap, fmt);
  2929. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2930. va_end(ap);
  2931. }
  2932. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2933. CIVETWEB_API const char *
  2934. mg_version(void)
  2935. {
  2936. return CIVETWEB_VERSION;
  2937. }
  2938. CIVETWEB_API const struct mg_request_info *
  2939. mg_get_request_info(const struct mg_connection *conn)
  2940. {
  2941. if (!conn) {
  2942. return NULL;
  2943. }
  2944. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2945. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2946. char txt[16];
  2947. struct mg_workerTLS *tls =
  2948. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2949. sprintf(txt, "%03i", conn->response_info.status_code);
  2950. if (strlen(txt) == 3) {
  2951. memcpy(tls->txtbuf, txt, 4);
  2952. } else {
  2953. strcpy(tls->txtbuf, "ERR");
  2954. }
  2955. ((struct mg_connection *)conn)->request_info.local_uri =
  2956. tls->txtbuf; /* use thread safe buffer */
  2957. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2958. tls->txtbuf; /* use the same thread safe buffer */
  2959. ((struct mg_connection *)conn)->request_info.request_uri =
  2960. tls->txtbuf; /* use the same thread safe buffer */
  2961. ((struct mg_connection *)conn)->request_info.num_headers =
  2962. conn->response_info.num_headers;
  2963. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2964. conn->response_info.http_headers,
  2965. sizeof(conn->response_info.http_headers));
  2966. } else
  2967. #endif
  2968. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2969. return NULL;
  2970. }
  2971. return &conn->request_info;
  2972. }
  2973. CIVETWEB_API const struct mg_response_info *
  2974. mg_get_response_info(const struct mg_connection *conn)
  2975. {
  2976. if (!conn) {
  2977. return NULL;
  2978. }
  2979. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2980. return NULL;
  2981. }
  2982. return &conn->response_info;
  2983. }
  2984. static const char *
  2985. get_proto_name(const struct mg_connection *conn)
  2986. {
  2987. #if defined(__clang__)
  2988. #pragma clang diagnostic push
  2989. #pragma clang diagnostic ignored "-Wunreachable-code"
  2990. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2991. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2992. * unreachable, but splitting into four different #ifdef clauses here is
  2993. * more complicated.
  2994. */
  2995. #endif
  2996. const struct mg_request_info *ri = &conn->request_info;
  2997. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2998. ? (ri->is_ssl ? "wss" : "ws")
  2999. : (ri->is_ssl ? "https" : "http"));
  3000. return proto;
  3001. #if defined(__clang__)
  3002. #pragma clang diagnostic pop
  3003. #endif
  3004. }
  3005. static int
  3006. mg_construct_local_link(const struct mg_connection *conn,
  3007. char *buf,
  3008. size_t buflen,
  3009. const char *define_proto,
  3010. int define_port,
  3011. const char *define_uri)
  3012. {
  3013. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3014. return -1;
  3015. } else {
  3016. int i, j;
  3017. int truncated = 0;
  3018. const struct mg_request_info *ri = &conn->request_info;
  3019. const char *proto =
  3020. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3021. const char *uri =
  3022. (define_uri != NULL)
  3023. ? define_uri
  3024. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3025. int port = (define_port > 0) ? define_port : ri->server_port;
  3026. int default_port = 80;
  3027. char *uri_encoded;
  3028. size_t uri_encoded_len;
  3029. if (uri == NULL) {
  3030. return -1;
  3031. }
  3032. uri_encoded_len = strlen(uri) * 3 + 1;
  3033. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3034. if (uri_encoded == NULL) {
  3035. return -1;
  3036. }
  3037. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3038. /* Directory separator should be preserved. */
  3039. for (i = j = 0; uri_encoded[i]; j++) {
  3040. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3041. uri_encoded[j] = '/';
  3042. i += 3;
  3043. } else {
  3044. uri_encoded[j] = uri_encoded[i++];
  3045. }
  3046. }
  3047. uri_encoded[j] = '\0';
  3048. #if defined(USE_X_DOM_SOCKET)
  3049. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3050. /* TODO: Define and document a link for UNIX domain sockets. */
  3051. /* There seems to be no official standard for this.
  3052. * Common uses seem to be "httpunix://", "http.unix://" or
  3053. * "http+unix://" as a protocol definition string, followed by
  3054. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3055. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3056. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3057. * "" (completely skipping the server name part). In any case, the
  3058. * last part is the server local path. */
  3059. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3060. mg_snprintf(conn,
  3061. &truncated,
  3062. buf,
  3063. buflen,
  3064. "%s.unix://%s%s",
  3065. proto,
  3066. server_name,
  3067. ri->local_uri);
  3068. default_port = 0;
  3069. mg_free(uri_encoded);
  3070. return 0;
  3071. }
  3072. #endif
  3073. if (define_proto) {
  3074. /* If we got a protocol name, use the default port accordingly. */
  3075. if ((0 == strcmp(define_proto, "https"))
  3076. || (0 == strcmp(define_proto, "wss"))) {
  3077. default_port = 443;
  3078. }
  3079. } else if (ri->is_ssl) {
  3080. /* If we did not get a protocol name, use TLS as default if it is
  3081. * already used. */
  3082. default_port = 443;
  3083. }
  3084. {
  3085. #if defined(USE_IPV6)
  3086. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3087. #endif
  3088. int auth_domain_check_enabled =
  3089. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3090. && (!mg_strcasecmp(
  3091. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3092. const char *server_domain =
  3093. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3094. char portstr[16];
  3095. char server_ip[48];
  3096. if (port != default_port) {
  3097. sprintf(portstr, ":%u", (unsigned)port);
  3098. } else {
  3099. portstr[0] = 0;
  3100. }
  3101. if (!auth_domain_check_enabled || !server_domain) {
  3102. sockaddr_to_string(server_ip,
  3103. sizeof(server_ip),
  3104. &conn->client.lsa);
  3105. server_domain = server_ip;
  3106. }
  3107. mg_snprintf(conn,
  3108. &truncated,
  3109. buf,
  3110. buflen,
  3111. #if defined(USE_IPV6)
  3112. "%s://%s%s%s%s%s",
  3113. proto,
  3114. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3115. server_domain,
  3116. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3117. #else
  3118. "%s://%s%s%s",
  3119. proto,
  3120. server_domain,
  3121. #endif
  3122. portstr,
  3123. uri_encoded);
  3124. mg_free(uri_encoded);
  3125. if (truncated) {
  3126. return -1;
  3127. }
  3128. return 0;
  3129. }
  3130. }
  3131. }
  3132. CIVETWEB_API int
  3133. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3134. {
  3135. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3136. }
  3137. /* Skip the characters until one of the delimiters characters found.
  3138. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3139. * Advance pointer to buffer to the next word. Return found 0-terminated
  3140. * word.
  3141. * Delimiters can be quoted with quotechar. */
  3142. static char *
  3143. skip_quoted(char **buf,
  3144. const char *delimiters,
  3145. const char *whitespace,
  3146. char quotechar)
  3147. {
  3148. char *p, *begin_word, *end_word, *end_whitespace;
  3149. begin_word = *buf;
  3150. end_word = begin_word + strcspn(begin_word, delimiters);
  3151. /* Check for quotechar */
  3152. if (end_word > begin_word) {
  3153. p = end_word - 1;
  3154. while (*p == quotechar) {
  3155. /* While the delimiter is quoted, look for the next delimiter.
  3156. */
  3157. /* This happens, e.g., in calls from parse_auth_header,
  3158. * if the user name contains a " character. */
  3159. /* If there is anything beyond end_word, copy it. */
  3160. if (*end_word != '\0') {
  3161. size_t end_off = strcspn(end_word + 1, delimiters);
  3162. memmove(p, end_word, end_off + 1);
  3163. p += end_off; /* p must correspond to end_word - 1 */
  3164. end_word += end_off + 1;
  3165. } else {
  3166. *p = '\0';
  3167. break;
  3168. }
  3169. }
  3170. for (p++; p < end_word; p++) {
  3171. *p = '\0';
  3172. }
  3173. }
  3174. if (*end_word == '\0') {
  3175. *buf = end_word;
  3176. } else {
  3177. #if defined(GCC_DIAGNOSTIC)
  3178. /* Disable spurious conversion warning for GCC */
  3179. #pragma GCC diagnostic push
  3180. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3181. #endif /* defined(GCC_DIAGNOSTIC) */
  3182. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3183. #if defined(GCC_DIAGNOSTIC)
  3184. #pragma GCC diagnostic pop
  3185. #endif /* defined(GCC_DIAGNOSTIC) */
  3186. for (p = end_word; p < end_whitespace; p++) {
  3187. *p = '\0';
  3188. }
  3189. *buf = end_whitespace;
  3190. }
  3191. return begin_word;
  3192. }
  3193. /* Return HTTP header value, or NULL if not found. */
  3194. static const char *
  3195. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3196. {
  3197. int i;
  3198. for (i = 0; i < num_hdr; i++) {
  3199. if (!mg_strcasecmp(name, hdr[i].name)) {
  3200. return hdr[i].value;
  3201. }
  3202. }
  3203. return NULL;
  3204. }
  3205. #if defined(USE_WEBSOCKET)
  3206. /* Retrieve requested HTTP header multiple values, and return the number of
  3207. * found occurrences */
  3208. static int
  3209. get_req_headers(const struct mg_request_info *ri,
  3210. const char *name,
  3211. const char **output,
  3212. int output_max_size)
  3213. {
  3214. int i;
  3215. int cnt = 0;
  3216. if (ri) {
  3217. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3218. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3219. output[cnt++] = ri->http_headers[i].value;
  3220. }
  3221. }
  3222. }
  3223. return cnt;
  3224. }
  3225. #endif
  3226. CIVETWEB_API const char *
  3227. mg_get_header(const struct mg_connection *conn, const char *name)
  3228. {
  3229. if (!conn) {
  3230. return NULL;
  3231. }
  3232. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3233. return get_header(conn->request_info.http_headers,
  3234. conn->request_info.num_headers,
  3235. name);
  3236. }
  3237. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3238. return get_header(conn->response_info.http_headers,
  3239. conn->response_info.num_headers,
  3240. name);
  3241. }
  3242. return NULL;
  3243. }
  3244. static const char *
  3245. get_http_version(const struct mg_connection *conn)
  3246. {
  3247. if (!conn) {
  3248. return NULL;
  3249. }
  3250. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3251. return conn->request_info.http_version;
  3252. }
  3253. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3254. return conn->response_info.http_version;
  3255. }
  3256. return NULL;
  3257. }
  3258. /* A helper function for traversing a comma separated list of values.
  3259. * It returns a list pointer shifted to the next value, or NULL if the end
  3260. * of the list found.
  3261. * Value is stored in val vector. If value has form "x=y", then eq_val
  3262. * vector is initialized to point to the "y" part, and val vector length
  3263. * is adjusted to point only to "x". */
  3264. static const char *
  3265. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3266. {
  3267. int end;
  3268. reparse:
  3269. if (val == NULL || list == NULL || *list == '\0') {
  3270. /* End of the list */
  3271. return NULL;
  3272. }
  3273. /* Skip over leading LWS */
  3274. while (*list == ' ' || *list == '\t')
  3275. list++;
  3276. val->ptr = list;
  3277. if ((list = strchr(val->ptr, ',')) != NULL) {
  3278. /* Comma found. Store length and shift the list ptr */
  3279. val->len = ((size_t)(list - val->ptr));
  3280. list++;
  3281. } else {
  3282. /* This value is the last one */
  3283. list = val->ptr + strlen(val->ptr);
  3284. val->len = ((size_t)(list - val->ptr));
  3285. }
  3286. /* Adjust length for trailing LWS */
  3287. end = (int)val->len - 1;
  3288. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3289. end--;
  3290. val->len = (size_t)(end) + (size_t)(1);
  3291. if (val->len == 0) {
  3292. /* Ignore any empty entries. */
  3293. goto reparse;
  3294. }
  3295. if (eq_val != NULL) {
  3296. /* Value has form "x=y", adjust pointers and lengths
  3297. * so that val points to "x", and eq_val points to "y". */
  3298. eq_val->len = 0;
  3299. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3300. if (eq_val->ptr != NULL) {
  3301. eq_val->ptr++; /* Skip over '=' character */
  3302. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3303. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3304. }
  3305. }
  3306. return list;
  3307. }
  3308. /* A helper function for checking if a comma separated list of values
  3309. * contains
  3310. * the given option (case insensitvely).
  3311. * 'header' can be NULL, in which case false is returned. */
  3312. static int
  3313. header_has_option(const char *header, const char *option)
  3314. {
  3315. struct vec opt_vec;
  3316. struct vec eq_vec;
  3317. DEBUG_ASSERT(option != NULL);
  3318. DEBUG_ASSERT(option[0] != '\0');
  3319. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3320. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3321. return 1;
  3322. }
  3323. return 0;
  3324. }
  3325. /* Sorting function implemented in a separate file */
  3326. #include "sort.inl"
  3327. /* Pattern matching has been reimplemented in a new file */
  3328. #include "match.inl"
  3329. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3330. * This function must tolerate situations when connection info is not
  3331. * set up, for example if request parsing failed. */
  3332. static int
  3333. should_keep_alive(const struct mg_connection *conn)
  3334. {
  3335. const char *http_version;
  3336. const char *header;
  3337. /* First satisfy needs of the server */
  3338. if ((conn == NULL) || conn->must_close) {
  3339. /* Close, if civetweb framework needs to close */
  3340. return 0;
  3341. }
  3342. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3343. /* Close, if keep alive is not enabled */
  3344. return 0;
  3345. }
  3346. /* Check explicit wish of the client */
  3347. header = mg_get_header(conn, "Connection");
  3348. if (header) {
  3349. /* If there is a connection header from the client, obey */
  3350. if (header_has_option(header, "keep-alive")) {
  3351. return 1;
  3352. }
  3353. return 0;
  3354. }
  3355. /* Use default of the standard */
  3356. http_version = get_http_version(conn);
  3357. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3358. /* HTTP 1.1 default is keep alive */
  3359. return 1;
  3360. }
  3361. /* HTTP 1.0 (and earlier) default is to close the connection */
  3362. return 0;
  3363. }
  3364. static int
  3365. should_decode_url(const struct mg_connection *conn)
  3366. {
  3367. if (!conn || !conn->dom_ctx) {
  3368. return 0;
  3369. }
  3370. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3371. }
  3372. static int
  3373. should_decode_query_string(const struct mg_connection *conn)
  3374. {
  3375. if (!conn || !conn->dom_ctx) {
  3376. return 0;
  3377. }
  3378. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3379. == 0);
  3380. }
  3381. static const char *
  3382. suggest_connection_header(const struct mg_connection *conn)
  3383. {
  3384. return should_keep_alive(conn) ? "keep-alive" : "close";
  3385. }
  3386. #include "response.inl"
  3387. static void
  3388. send_no_cache_header(struct mg_connection *conn)
  3389. {
  3390. /* Send all current and obsolete cache opt-out directives. */
  3391. mg_response_header_add(conn,
  3392. "Cache-Control",
  3393. "no-cache, no-store, "
  3394. "must-revalidate, private, max-age=0",
  3395. -1);
  3396. mg_response_header_add(conn, "Expires", "0", -1);
  3397. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3398. /* Obsolete, but still send it for HTTP/1.0 */
  3399. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3400. }
  3401. }
  3402. static void
  3403. send_static_cache_header(struct mg_connection *conn)
  3404. {
  3405. #if !defined(NO_CACHING)
  3406. int max_age;
  3407. char val[64];
  3408. const char *cache_control =
  3409. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3410. /* If there is a full cache-control option configured,0 use it */
  3411. if (cache_control != NULL) {
  3412. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3413. return;
  3414. }
  3415. /* Read the server config to check how long a file may be cached.
  3416. * The configuration is in seconds. */
  3417. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3418. if (max_age <= 0) {
  3419. /* 0 means "do not cache". All values <0 are reserved
  3420. * and may be used differently in the future. */
  3421. /* If a file should not be cached, do not only send
  3422. * max-age=0, but also pragmas and Expires headers. */
  3423. send_no_cache_header(conn);
  3424. return;
  3425. }
  3426. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3427. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3428. /* See also https://www.mnot.net/cache_docs/ */
  3429. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3430. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3431. * leap
  3432. * year to 31622400 seconds. For the moment, we just send whatever has
  3433. * been configured, still the behavior for >1 year should be considered
  3434. * as undefined. */
  3435. mg_snprintf(
  3436. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3437. mg_response_header_add(conn, "Cache-Control", val, -1);
  3438. #else /* NO_CACHING */
  3439. send_no_cache_header(conn);
  3440. #endif /* !NO_CACHING */
  3441. }
  3442. static void
  3443. send_additional_header(struct mg_connection *conn)
  3444. {
  3445. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3446. #if !defined(NO_SSL)
  3447. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3448. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3449. if (max_age >= 0) {
  3450. char val[64];
  3451. mg_snprintf(conn,
  3452. NULL,
  3453. val,
  3454. sizeof(val),
  3455. "max-age=%lu",
  3456. (unsigned long)max_age);
  3457. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3458. }
  3459. }
  3460. #endif
  3461. if (header && header[0]) {
  3462. mg_response_header_add_lines(conn, header);
  3463. }
  3464. }
  3465. static void
  3466. send_cors_header(struct mg_connection *conn)
  3467. {
  3468. const char *origin_hdr = mg_get_header(conn, "Origin");
  3469. const char *cors_orig_cfg =
  3470. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3471. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3472. /* Cross-origin resource sharing (CORS), see
  3473. * http://www.html5rocks.com/en/tutorials/cors/,
  3474. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3475. * CORS preflight is not supported for files. */
  3476. mg_response_header_add(conn,
  3477. "Access-Control-Allow-Origin",
  3478. cors_orig_cfg,
  3479. -1);
  3480. }
  3481. }
  3482. #if !defined(NO_FILESYSTEMS)
  3483. static void handle_file_based_request(struct mg_connection *conn,
  3484. const char *path,
  3485. struct mg_file *filep);
  3486. #endif /* NO_FILESYSTEMS */
  3487. CIVETWEB_API const char *
  3488. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3489. {
  3490. /* See IANA HTTP status code assignment:
  3491. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3492. */
  3493. switch (response_code) {
  3494. /* RFC2616 Section 10.1 - Informational 1xx */
  3495. case 100:
  3496. return "Continue"; /* RFC2616 Section 10.1.1 */
  3497. case 101:
  3498. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3499. case 102:
  3500. return "Processing"; /* RFC2518 Section 10.1 */
  3501. /* RFC2616 Section 10.2 - Successful 2xx */
  3502. case 200:
  3503. return "OK"; /* RFC2616 Section 10.2.1 */
  3504. case 201:
  3505. return "Created"; /* RFC2616 Section 10.2.2 */
  3506. case 202:
  3507. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3508. case 203:
  3509. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3510. case 204:
  3511. return "No Content"; /* RFC2616 Section 10.2.5 */
  3512. case 205:
  3513. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3514. case 206:
  3515. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3516. case 207:
  3517. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3518. */
  3519. case 208:
  3520. return "Already Reported"; /* RFC5842 Section 7.1 */
  3521. case 226:
  3522. return "IM used"; /* RFC3229 Section 10.4.1 */
  3523. /* RFC2616 Section 10.3 - Redirection 3xx */
  3524. case 300:
  3525. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3526. case 301:
  3527. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3528. case 302:
  3529. return "Found"; /* RFC2616 Section 10.3.3 */
  3530. case 303:
  3531. return "See Other"; /* RFC2616 Section 10.3.4 */
  3532. case 304:
  3533. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3534. case 305:
  3535. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3536. case 307:
  3537. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3538. case 308:
  3539. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3540. /* RFC2616 Section 10.4 - Client Error 4xx */
  3541. case 400:
  3542. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3543. case 401:
  3544. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3545. case 402:
  3546. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3547. case 403:
  3548. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3549. case 404:
  3550. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3551. case 405:
  3552. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3553. case 406:
  3554. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3555. case 407:
  3556. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3557. case 408:
  3558. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3559. case 409:
  3560. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3561. case 410:
  3562. return "Gone"; /* RFC2616 Section 10.4.11 */
  3563. case 411:
  3564. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3565. case 412:
  3566. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3567. case 413:
  3568. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3569. case 414:
  3570. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3571. case 415:
  3572. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3573. case 416:
  3574. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3575. */
  3576. case 417:
  3577. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3578. case 421:
  3579. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3580. case 422:
  3581. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3582. * Section 11.2 */
  3583. case 423:
  3584. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3585. case 424:
  3586. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3587. * Section 11.4 */
  3588. case 426:
  3589. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3590. case 428:
  3591. return "Precondition Required"; /* RFC 6585, Section 3 */
  3592. case 429:
  3593. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3594. case 431:
  3595. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3596. case 451:
  3597. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3598. * Section 3 */
  3599. /* RFC2616 Section 10.5 - Server Error 5xx */
  3600. case 500:
  3601. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3602. case 501:
  3603. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3604. case 502:
  3605. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3606. case 503:
  3607. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3608. case 504:
  3609. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3610. case 505:
  3611. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3612. case 506:
  3613. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3614. case 507:
  3615. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3616. * Section 11.5 */
  3617. case 508:
  3618. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3619. case 510:
  3620. return "Not Extended"; /* RFC 2774, Section 7 */
  3621. case 511:
  3622. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3623. /* Other status codes, not shown in the IANA HTTP status code
  3624. * assignment.
  3625. * E.g., "de facto" standards due to common use, ... */
  3626. case 418:
  3627. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3628. case 419:
  3629. return "Authentication Timeout"; /* common use */
  3630. case 420:
  3631. return "Enhance Your Calm"; /* common use */
  3632. case 440:
  3633. return "Login Timeout"; /* common use */
  3634. case 509:
  3635. return "Bandwidth Limit Exceeded"; /* common use */
  3636. default:
  3637. /* This error code is unknown. This should not happen. */
  3638. if (conn) {
  3639. mg_cry_internal(conn,
  3640. "Unknown HTTP response code: %u",
  3641. response_code);
  3642. }
  3643. /* Return at least a category according to RFC 2616 Section 10. */
  3644. if (response_code >= 100 && response_code < 200) {
  3645. /* Unknown informational status code */
  3646. return "Information";
  3647. }
  3648. if (response_code >= 200 && response_code < 300) {
  3649. /* Unknown success code */
  3650. return "Success";
  3651. }
  3652. if (response_code >= 300 && response_code < 400) {
  3653. /* Unknown redirection code */
  3654. return "Redirection";
  3655. }
  3656. if (response_code >= 400 && response_code < 500) {
  3657. /* Unknown request error code */
  3658. return "Client Error";
  3659. }
  3660. if (response_code >= 500 && response_code < 600) {
  3661. /* Unknown server error code */
  3662. return "Server Error";
  3663. }
  3664. /* Response code not even within reasonable range */
  3665. return "";
  3666. }
  3667. }
  3668. static int
  3669. mg_send_http_error_impl(struct mg_connection *conn,
  3670. int status,
  3671. const char *fmt,
  3672. va_list args)
  3673. {
  3674. char errmsg_buf[MG_BUF_LEN];
  3675. va_list ap;
  3676. int has_body;
  3677. #if !defined(NO_FILESYSTEMS)
  3678. char path_buf[UTF8_PATH_MAX];
  3679. int len, i, page_handler_found, scope, truncated;
  3680. const char *error_handler = NULL;
  3681. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3682. const char *error_page_file_ext, *tstr;
  3683. #endif /* NO_FILESYSTEMS */
  3684. int handled_by_callback = 0;
  3685. if ((conn == NULL) || (fmt == NULL)) {
  3686. return -2;
  3687. }
  3688. /* Set status (for log) */
  3689. conn->status_code = status;
  3690. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3691. has_body = ((status > 199) && (status != 204) && (status != 304));
  3692. /* Prepare message in buf, if required */
  3693. if (has_body
  3694. || (!conn->in_error_handler
  3695. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3696. /* Store error message in errmsg_buf */
  3697. va_copy(ap, args);
  3698. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3699. va_end(ap);
  3700. /* In a debug build, print all html errors */
  3701. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3702. }
  3703. /* If there is a http_error callback, call it.
  3704. * But don't do it recursively, if callback calls mg_send_http_error again.
  3705. */
  3706. if (!conn->in_error_handler
  3707. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3708. /* Mark in_error_handler to avoid recursion and call user callback. */
  3709. conn->in_error_handler = 1;
  3710. handled_by_callback =
  3711. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3712. == 0);
  3713. conn->in_error_handler = 0;
  3714. }
  3715. if (!handled_by_callback) {
  3716. /* Check for recursion */
  3717. if (conn->in_error_handler) {
  3718. DEBUG_TRACE(
  3719. "Recursion when handling error %u - fall back to default",
  3720. status);
  3721. #if !defined(NO_FILESYSTEMS)
  3722. } else {
  3723. /* Send user defined error pages, if defined */
  3724. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3725. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3726. page_handler_found = 0;
  3727. if (error_handler != NULL) {
  3728. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3729. switch (scope) {
  3730. case 1: /* Handler for specific error, e.g. 404 error */
  3731. mg_snprintf(conn,
  3732. &truncated,
  3733. path_buf,
  3734. sizeof(path_buf) - 32,
  3735. "%serror%03u.",
  3736. error_handler,
  3737. status);
  3738. break;
  3739. case 2: /* Handler for error group, e.g., 5xx error
  3740. * handler
  3741. * for all server errors (500-599) */
  3742. mg_snprintf(conn,
  3743. &truncated,
  3744. path_buf,
  3745. sizeof(path_buf) - 32,
  3746. "%serror%01uxx.",
  3747. error_handler,
  3748. status / 100);
  3749. break;
  3750. default: /* Handler for all errors */
  3751. mg_snprintf(conn,
  3752. &truncated,
  3753. path_buf,
  3754. sizeof(path_buf) - 32,
  3755. "%serror.",
  3756. error_handler);
  3757. break;
  3758. }
  3759. /* String truncation in buf may only occur if
  3760. * error_handler is too long. This string is
  3761. * from the config, not from a client. */
  3762. (void)truncated;
  3763. /* The following code is redundant, but it should avoid
  3764. * false positives in static source code analyzers and
  3765. * vulnerability scanners.
  3766. */
  3767. path_buf[sizeof(path_buf) - 32] = 0;
  3768. len = (int)strlen(path_buf);
  3769. if (len > (int)sizeof(path_buf) - 32) {
  3770. len = (int)sizeof(path_buf) - 32;
  3771. }
  3772. /* Start with the file extenstion from the configuration. */
  3773. tstr = strchr(error_page_file_ext, '.');
  3774. while (tstr) {
  3775. for (i = 1;
  3776. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3777. i++) {
  3778. /* buffer overrun is not possible here, since
  3779. * (i < 32) && (len < sizeof(path_buf) - 32)
  3780. * ==> (i + len) < sizeof(path_buf) */
  3781. path_buf[len + i - 1] = tstr[i];
  3782. }
  3783. /* buffer overrun is not possible here, since
  3784. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3785. * ==> (i + len) <= sizeof(path_buf) */
  3786. path_buf[len + i - 1] = 0;
  3787. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3788. DEBUG_TRACE("Check error page %s - found",
  3789. path_buf);
  3790. page_handler_found = 1;
  3791. break;
  3792. }
  3793. DEBUG_TRACE("Check error page %s - not found",
  3794. path_buf);
  3795. /* Continue with the next file extenstion from the
  3796. * configuration (if there is a next one). */
  3797. tstr = strchr(tstr + i, '.');
  3798. }
  3799. }
  3800. }
  3801. if (page_handler_found) {
  3802. conn->in_error_handler = 1;
  3803. handle_file_based_request(conn, path_buf, &error_page_file);
  3804. conn->in_error_handler = 0;
  3805. return 0;
  3806. }
  3807. #endif /* NO_FILESYSTEMS */
  3808. }
  3809. /* No custom error page. Send default error page. */
  3810. conn->must_close = 1;
  3811. mg_response_header_start(conn, status);
  3812. send_no_cache_header(conn);
  3813. send_additional_header(conn);
  3814. send_cors_header(conn);
  3815. if (has_body) {
  3816. mg_response_header_add(conn,
  3817. "Content-Type",
  3818. "text/plain; charset=utf-8",
  3819. -1);
  3820. }
  3821. mg_response_header_send(conn);
  3822. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3823. if (has_body) {
  3824. /* For other errors, send a generic error message. */
  3825. const char *status_text = mg_get_response_code_text(conn, status);
  3826. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3827. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3828. } else {
  3829. /* No body allowed. Close the connection. */
  3830. DEBUG_TRACE("Error %i", status);
  3831. }
  3832. }
  3833. return 0;
  3834. }
  3835. CIVETWEB_API int
  3836. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3837. {
  3838. va_list ap;
  3839. int ret;
  3840. va_start(ap, fmt);
  3841. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3842. va_end(ap);
  3843. return ret;
  3844. }
  3845. CIVETWEB_API int
  3846. mg_send_http_ok(struct mg_connection *conn,
  3847. const char *mime_type,
  3848. long long content_length)
  3849. {
  3850. if ((mime_type == NULL) || (*mime_type == 0)) {
  3851. /* No content type defined: default to text/html */
  3852. mime_type = "text/html";
  3853. }
  3854. mg_response_header_start(conn, 200);
  3855. send_no_cache_header(conn);
  3856. send_additional_header(conn);
  3857. send_cors_header(conn);
  3858. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3859. if (content_length < 0) {
  3860. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3861. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3862. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3863. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3864. }
  3865. } else {
  3866. char len[32];
  3867. int trunc = 0;
  3868. mg_snprintf(conn,
  3869. &trunc,
  3870. len,
  3871. sizeof(len),
  3872. "%" UINT64_FMT,
  3873. (uint64_t)content_length);
  3874. if (!trunc) {
  3875. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3876. * !trunc is always true */
  3877. mg_response_header_add(conn, "Content-Length", len, -1);
  3878. }
  3879. }
  3880. mg_response_header_send(conn);
  3881. return 0;
  3882. }
  3883. CIVETWEB_API int
  3884. mg_send_http_redirect(struct mg_connection *conn,
  3885. const char *target_url,
  3886. int redirect_code)
  3887. {
  3888. /* Send a 30x redirect response.
  3889. *
  3890. * Redirect types (status codes):
  3891. *
  3892. * Status | Perm/Temp | Method | Version
  3893. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3894. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3895. * 303 | temporary | always use GET | HTTP/1.1
  3896. * 307 | temporary | always keep method | HTTP/1.1
  3897. * 308 | permanent | always keep method | HTTP/1.1
  3898. */
  3899. #if defined(MG_SEND_REDIRECT_BODY)
  3900. char redirect_body[MG_BUF_LEN];
  3901. size_t content_len = 0;
  3902. char content_len_text[32];
  3903. #endif
  3904. /* In case redirect_code=0, use 307. */
  3905. if (redirect_code == 0) {
  3906. redirect_code = 307;
  3907. }
  3908. /* In case redirect_code is none of the above, return error. */
  3909. if ((redirect_code != 301) && (redirect_code != 302)
  3910. && (redirect_code != 303) && (redirect_code != 307)
  3911. && (redirect_code != 308)) {
  3912. /* Parameter error */
  3913. return -2;
  3914. }
  3915. /* If target_url is not defined, redirect to "/". */
  3916. if ((target_url == NULL) || (*target_url == 0)) {
  3917. target_url = "/";
  3918. }
  3919. #if defined(MG_SEND_REDIRECT_BODY)
  3920. /* TODO: condition name? */
  3921. /* Prepare a response body with a hyperlink.
  3922. *
  3923. * According to RFC2616 (and RFC1945 before):
  3924. * Unless the request method was HEAD, the entity of the
  3925. * response SHOULD contain a short hypertext note with a hyperlink to
  3926. * the new URI(s).
  3927. *
  3928. * However, this response body is not useful in M2M communication.
  3929. * Probably the original reason in the RFC was, clients not supporting
  3930. * a 30x HTTP redirect could still show the HTML page and let the user
  3931. * press the link. Since current browsers support 30x HTTP, the additional
  3932. * HTML body does not seem to make sense anymore.
  3933. *
  3934. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3935. * but it only notes:
  3936. * The server's response payload usually contains a short
  3937. * hypertext note with a hyperlink to the new URI(s).
  3938. *
  3939. * Deactivated by default. If you need the 30x body, set the define.
  3940. */
  3941. mg_snprintf(
  3942. conn,
  3943. NULL /* ignore truncation */,
  3944. redirect_body,
  3945. sizeof(redirect_body),
  3946. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3947. redirect_text,
  3948. target_url,
  3949. target_url);
  3950. content_len = strlen(reply);
  3951. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3952. #endif
  3953. /* Send all required headers */
  3954. mg_response_header_start(conn, redirect_code);
  3955. mg_response_header_add(conn, "Location", target_url, -1);
  3956. if ((redirect_code == 301) || (redirect_code == 308)) {
  3957. /* Permanent redirect */
  3958. send_static_cache_header(conn);
  3959. } else {
  3960. /* Temporary redirect */
  3961. send_no_cache_header(conn);
  3962. }
  3963. send_additional_header(conn);
  3964. send_cors_header(conn);
  3965. #if defined(MG_SEND_REDIRECT_BODY)
  3966. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3967. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3968. #else
  3969. mg_response_header_add(conn, "Content-Length", "0", 1);
  3970. #endif
  3971. mg_response_header_send(conn);
  3972. #if defined(MG_SEND_REDIRECT_BODY)
  3973. /* Send response body */
  3974. /* ... unless it is a HEAD request */
  3975. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3976. ret = mg_write(conn, redirect_body, content_len);
  3977. }
  3978. #endif
  3979. return 1;
  3980. }
  3981. #if defined(_WIN32)
  3982. /* Create substitutes for POSIX functions in Win32. */
  3983. #if defined(GCC_DIAGNOSTIC)
  3984. /* Show no warning in case system functions are not used. */
  3985. #pragma GCC diagnostic push
  3986. #pragma GCC diagnostic ignored "-Wunused-function"
  3987. #endif
  3988. static int
  3989. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3990. {
  3991. (void)unused;
  3992. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3993. InitializeCriticalSection(&mutex->sec);
  3994. return 0;
  3995. }
  3996. static int
  3997. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3998. {
  3999. DeleteCriticalSection(&mutex->sec);
  4000. return 0;
  4001. }
  4002. static int
  4003. pthread_mutex_lock(pthread_mutex_t *mutex)
  4004. {
  4005. EnterCriticalSection(&mutex->sec);
  4006. return 0;
  4007. }
  4008. static int
  4009. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4010. {
  4011. LeaveCriticalSection(&mutex->sec);
  4012. return 0;
  4013. }
  4014. FUNCTION_MAY_BE_UNUSED
  4015. static int
  4016. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4017. {
  4018. (void)unused;
  4019. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4020. cv->waiting_thread = NULL;
  4021. return 0;
  4022. }
  4023. FUNCTION_MAY_BE_UNUSED
  4024. static int
  4025. pthread_cond_timedwait(pthread_cond_t *cv,
  4026. pthread_mutex_t *mutex,
  4027. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4028. {
  4029. struct mg_workerTLS **ptls,
  4030. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4031. int ok;
  4032. uint64_t nsnow, nswaitabs;
  4033. int64_t nswaitrel;
  4034. DWORD mswaitrel;
  4035. pthread_mutex_lock(&cv->threadIdSec);
  4036. /* Add this thread to cv's waiting list */
  4037. ptls = &cv->waiting_thread;
  4038. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4039. ;
  4040. tls->next_waiting_thread = NULL;
  4041. *ptls = tls;
  4042. pthread_mutex_unlock(&cv->threadIdSec);
  4043. if (abstime) {
  4044. nsnow = mg_get_current_time_ns();
  4045. nswaitabs =
  4046. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4047. nswaitrel = nswaitabs - nsnow;
  4048. if (nswaitrel < 0) {
  4049. nswaitrel = 0;
  4050. }
  4051. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4052. } else {
  4053. mswaitrel = (DWORD)INFINITE;
  4054. }
  4055. pthread_mutex_unlock(mutex);
  4056. ok = (WAIT_OBJECT_0
  4057. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4058. if (!ok) {
  4059. ok = 1;
  4060. pthread_mutex_lock(&cv->threadIdSec);
  4061. ptls = &cv->waiting_thread;
  4062. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4063. if (*ptls == tls) {
  4064. *ptls = tls->next_waiting_thread;
  4065. ok = 0;
  4066. break;
  4067. }
  4068. }
  4069. pthread_mutex_unlock(&cv->threadIdSec);
  4070. if (ok) {
  4071. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4072. (DWORD)INFINITE);
  4073. }
  4074. }
  4075. /* This thread has been removed from cv's waiting list */
  4076. pthread_mutex_lock(mutex);
  4077. return ok ? 0 : -1;
  4078. }
  4079. FUNCTION_MAY_BE_UNUSED
  4080. static int
  4081. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4082. {
  4083. return pthread_cond_timedwait(cv, mutex, NULL);
  4084. }
  4085. FUNCTION_MAY_BE_UNUSED
  4086. static int
  4087. pthread_cond_signal(pthread_cond_t *cv)
  4088. {
  4089. HANDLE wkup = NULL;
  4090. BOOL ok = FALSE;
  4091. pthread_mutex_lock(&cv->threadIdSec);
  4092. if (cv->waiting_thread) {
  4093. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4094. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4095. ok = SetEvent(wkup);
  4096. DEBUG_ASSERT(ok);
  4097. }
  4098. pthread_mutex_unlock(&cv->threadIdSec);
  4099. return ok ? 0 : 1;
  4100. }
  4101. FUNCTION_MAY_BE_UNUSED
  4102. static int
  4103. pthread_cond_broadcast(pthread_cond_t *cv)
  4104. {
  4105. pthread_mutex_lock(&cv->threadIdSec);
  4106. while (cv->waiting_thread) {
  4107. pthread_cond_signal(cv);
  4108. }
  4109. pthread_mutex_unlock(&cv->threadIdSec);
  4110. return 0;
  4111. }
  4112. FUNCTION_MAY_BE_UNUSED
  4113. static int
  4114. pthread_cond_destroy(pthread_cond_t *cv)
  4115. {
  4116. pthread_mutex_lock(&cv->threadIdSec);
  4117. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4118. pthread_mutex_unlock(&cv->threadIdSec);
  4119. pthread_mutex_destroy(&cv->threadIdSec);
  4120. return 0;
  4121. }
  4122. #if defined(ALTERNATIVE_QUEUE)
  4123. FUNCTION_MAY_BE_UNUSED
  4124. static void *
  4125. event_create(void)
  4126. {
  4127. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4128. }
  4129. FUNCTION_MAY_BE_UNUSED
  4130. static int
  4131. event_wait(void *eventhdl)
  4132. {
  4133. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4134. return (res == WAIT_OBJECT_0);
  4135. }
  4136. FUNCTION_MAY_BE_UNUSED
  4137. static int
  4138. event_signal(void *eventhdl)
  4139. {
  4140. return (int)SetEvent((HANDLE)eventhdl);
  4141. }
  4142. FUNCTION_MAY_BE_UNUSED
  4143. static void
  4144. event_destroy(void *eventhdl)
  4145. {
  4146. CloseHandle((HANDLE)eventhdl);
  4147. }
  4148. #endif
  4149. #if defined(GCC_DIAGNOSTIC)
  4150. /* Enable unused function warning again */
  4151. #pragma GCC diagnostic pop
  4152. #endif
  4153. /* For Windows, change all slashes to backslashes in path names. */
  4154. static void
  4155. change_slashes_to_backslashes(char *path)
  4156. {
  4157. int i;
  4158. for (i = 0; path[i] != '\0'; i++) {
  4159. if (path[i] == '/') {
  4160. path[i] = '\\';
  4161. }
  4162. /* remove double backslash (check i > 0 to preserve UNC paths,
  4163. * like \\server\file.txt) */
  4164. if ((i > 0) && (path[i] == '\\')) {
  4165. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4166. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4167. }
  4168. }
  4169. }
  4170. }
  4171. static int
  4172. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4173. {
  4174. int diff;
  4175. do {
  4176. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4177. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4178. s1++;
  4179. s2++;
  4180. } while ((diff == 0) && (s1[-1] != L'\0'));
  4181. return diff;
  4182. }
  4183. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4184. * wbuf and wbuf_len is a target buffer and its length. */
  4185. static void
  4186. path_to_unicode(const struct mg_connection *conn,
  4187. const char *path,
  4188. wchar_t *wbuf,
  4189. size_t wbuf_len)
  4190. {
  4191. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4192. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4193. DWORD long_len, err;
  4194. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4195. mg_strlcpy(buf, path, sizeof(buf));
  4196. change_slashes_to_backslashes(buf);
  4197. /* Convert to Unicode and back. If doubly-converted string does not
  4198. * match the original, something is fishy, reject. */
  4199. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4200. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4201. WideCharToMultiByte(
  4202. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4203. if (strcmp(buf, buf2) != 0) {
  4204. wbuf[0] = L'\0';
  4205. }
  4206. /* Windows file systems are not case sensitive, but you can still use
  4207. * uppercase and lowercase letters (on all modern file systems).
  4208. * The server can check if the URI uses the same upper/lowercase
  4209. * letters an the file system, effectively making Windows servers
  4210. * case sensitive (like Linux servers are). It is still not possible
  4211. * to use two files with the same name in different cases on Windows
  4212. * (like /a and /A) - this would be possible in Linux.
  4213. * As a default, Windows is not case sensitive, but the case sensitive
  4214. * file name check can be activated by an additional configuration. */
  4215. if (conn) {
  4216. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4217. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4218. "yes")) {
  4219. /* Use case sensitive compare function */
  4220. fcompare = wcscmp;
  4221. }
  4222. }
  4223. (void)conn; /* conn is currently unused */
  4224. /* Only accept a full file path, not a Windows short (8.3) path. */
  4225. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4226. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4227. if (long_len == 0) {
  4228. err = GetLastError();
  4229. if (err == ERROR_FILE_NOT_FOUND) {
  4230. /* File does not exist. This is not always a problem here. */
  4231. return;
  4232. }
  4233. }
  4234. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4235. /* Short name is used. */
  4236. wbuf[0] = L'\0';
  4237. }
  4238. }
  4239. #if !defined(NO_FILESYSTEMS)
  4240. /* Get file information, return 1 if file exists, 0 if not */
  4241. static int
  4242. mg_stat(const struct mg_connection *conn,
  4243. const char *path,
  4244. struct mg_file_stat *filep)
  4245. {
  4246. wchar_t wbuf[UTF16_PATH_MAX];
  4247. WIN32_FILE_ATTRIBUTE_DATA info;
  4248. time_t creation_time;
  4249. size_t len;
  4250. if (!filep) {
  4251. return 0;
  4252. }
  4253. memset(filep, 0, sizeof(*filep));
  4254. if (mg_path_suspicious(conn, path)) {
  4255. return 0;
  4256. }
  4257. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4258. /* Windows happily opens files with some garbage at the end of file name.
  4259. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4260. * "a.cgi", despite one would expect an error back. */
  4261. len = strlen(path);
  4262. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4263. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4264. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4265. filep->last_modified =
  4266. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4267. info.ftLastWriteTime.dwHighDateTime);
  4268. /* On Windows, the file creation time can be higher than the
  4269. * modification time, e.g. when a file is copied.
  4270. * Since the Last-Modified timestamp is used for caching
  4271. * it should be based on the most recent timestamp. */
  4272. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4273. info.ftCreationTime.dwHighDateTime);
  4274. if (creation_time > filep->last_modified) {
  4275. filep->last_modified = creation_time;
  4276. }
  4277. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4278. return 1;
  4279. }
  4280. return 0;
  4281. }
  4282. #endif
  4283. static int
  4284. mg_remove(const struct mg_connection *conn, const char *path)
  4285. {
  4286. wchar_t wbuf[UTF16_PATH_MAX];
  4287. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4288. return DeleteFileW(wbuf) ? 0 : -1;
  4289. }
  4290. static int
  4291. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4292. {
  4293. wchar_t wbuf[UTF16_PATH_MAX];
  4294. (void)mode;
  4295. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4296. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4297. }
  4298. /* Create substitutes for POSIX functions in Win32. */
  4299. #if defined(GCC_DIAGNOSTIC)
  4300. /* Show no warning in case system functions are not used. */
  4301. #pragma GCC diagnostic push
  4302. #pragma GCC diagnostic ignored "-Wunused-function"
  4303. #endif
  4304. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4305. FUNCTION_MAY_BE_UNUSED
  4306. static DIR *
  4307. mg_opendir(const struct mg_connection *conn, const char *name)
  4308. {
  4309. DIR *dir = NULL;
  4310. wchar_t wpath[UTF16_PATH_MAX];
  4311. DWORD attrs;
  4312. if (name == NULL) {
  4313. SetLastError(ERROR_BAD_ARGUMENTS);
  4314. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4315. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4316. } else {
  4317. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4318. attrs = GetFileAttributesW(wpath);
  4319. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4320. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4321. (void)wcscat(wpath, L"\\*");
  4322. dir->handle = FindFirstFileW(wpath, &dir->info);
  4323. dir->result.d_name[0] = '\0';
  4324. } else {
  4325. mg_free(dir);
  4326. dir = NULL;
  4327. }
  4328. }
  4329. return dir;
  4330. }
  4331. FUNCTION_MAY_BE_UNUSED
  4332. static int
  4333. mg_closedir(DIR *dir)
  4334. {
  4335. int result = 0;
  4336. if (dir != NULL) {
  4337. if (dir->handle != INVALID_HANDLE_VALUE)
  4338. result = FindClose(dir->handle) ? 0 : -1;
  4339. mg_free(dir);
  4340. } else {
  4341. result = -1;
  4342. SetLastError(ERROR_BAD_ARGUMENTS);
  4343. }
  4344. return result;
  4345. }
  4346. FUNCTION_MAY_BE_UNUSED
  4347. static struct dirent *
  4348. mg_readdir(DIR *dir)
  4349. {
  4350. struct dirent *result = 0;
  4351. if (dir) {
  4352. if (dir->handle != INVALID_HANDLE_VALUE) {
  4353. result = &dir->result;
  4354. (void)WideCharToMultiByte(CP_UTF8,
  4355. 0,
  4356. dir->info.cFileName,
  4357. -1,
  4358. result->d_name,
  4359. sizeof(result->d_name),
  4360. NULL,
  4361. NULL);
  4362. if (!FindNextFileW(dir->handle, &dir->info)) {
  4363. (void)FindClose(dir->handle);
  4364. dir->handle = INVALID_HANDLE_VALUE;
  4365. }
  4366. } else {
  4367. SetLastError(ERROR_FILE_NOT_FOUND);
  4368. }
  4369. } else {
  4370. SetLastError(ERROR_BAD_ARGUMENTS);
  4371. }
  4372. return result;
  4373. }
  4374. #if !defined(HAVE_POLL)
  4375. #undef POLLIN
  4376. #undef POLLPRI
  4377. #undef POLLOUT
  4378. #undef POLLERR
  4379. #define POLLIN (1) /* Data ready - read will not block. */
  4380. #define POLLPRI (2) /* Priority data ready. */
  4381. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4382. #define POLLERR (8) /* Error event */
  4383. FUNCTION_MAY_BE_UNUSED
  4384. static int
  4385. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4386. {
  4387. struct timeval tv;
  4388. fd_set rset;
  4389. fd_set wset;
  4390. fd_set eset;
  4391. unsigned int i;
  4392. int result;
  4393. SOCKET maxfd = 0;
  4394. memset(&tv, 0, sizeof(tv));
  4395. tv.tv_sec = milliseconds / 1000;
  4396. tv.tv_usec = (milliseconds % 1000) * 1000;
  4397. FD_ZERO(&rset);
  4398. FD_ZERO(&wset);
  4399. FD_ZERO(&eset);
  4400. for (i = 0; i < n; i++) {
  4401. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4402. if (pfd[i].events & POLLIN) {
  4403. FD_SET(pfd[i].fd, &rset);
  4404. }
  4405. if (pfd[i].events & POLLOUT) {
  4406. FD_SET(pfd[i].fd, &wset);
  4407. }
  4408. /* Check for errors for any FD in the set */
  4409. FD_SET(pfd[i].fd, &eset);
  4410. }
  4411. pfd[i].revents = 0;
  4412. if (pfd[i].fd > maxfd) {
  4413. maxfd = pfd[i].fd;
  4414. }
  4415. }
  4416. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4417. for (i = 0; i < n; i++) {
  4418. if (FD_ISSET(pfd[i].fd, &rset)) {
  4419. pfd[i].revents |= POLLIN;
  4420. }
  4421. if (FD_ISSET(pfd[i].fd, &wset)) {
  4422. pfd[i].revents |= POLLOUT;
  4423. }
  4424. if (FD_ISSET(pfd[i].fd, &eset)) {
  4425. pfd[i].revents |= POLLERR;
  4426. }
  4427. }
  4428. }
  4429. /* We should subtract the time used in select from remaining
  4430. * "milliseconds", in particular if called from mg_poll with a
  4431. * timeout quantum.
  4432. * Unfortunately, the remaining time is not stored in "tv" in all
  4433. * implementations, so the result in "tv" must be considered undefined.
  4434. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4435. return result;
  4436. }
  4437. #endif /* HAVE_POLL */
  4438. #if defined(GCC_DIAGNOSTIC)
  4439. /* Enable unused function warning again */
  4440. #pragma GCC diagnostic pop
  4441. #endif
  4442. static void
  4443. set_close_on_exec(SOCKET sock,
  4444. const struct mg_connection *conn /* may be null */,
  4445. struct mg_context *ctx /* may be null */)
  4446. {
  4447. (void)conn; /* Unused. */
  4448. (void)ctx;
  4449. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4450. }
  4451. CIVETWEB_API int
  4452. mg_start_thread(mg_thread_func_t f, void *p)
  4453. {
  4454. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4455. /* Compile-time option to control stack size, e.g.
  4456. * -DUSE_STACK_SIZE=16384
  4457. */
  4458. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4459. == ((uintptr_t)(-1L)))
  4460. ? -1
  4461. : 0);
  4462. #else
  4463. return (
  4464. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4465. ? -1
  4466. : 0);
  4467. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4468. }
  4469. /* Start a thread storing the thread context. */
  4470. static int
  4471. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4472. void *p,
  4473. pthread_t *threadidptr)
  4474. {
  4475. uintptr_t uip;
  4476. HANDLE threadhandle;
  4477. int result = -1;
  4478. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4479. threadhandle = (HANDLE)uip;
  4480. if ((uip != 0) && (threadidptr != NULL)) {
  4481. *threadidptr = threadhandle;
  4482. result = 0;
  4483. }
  4484. return result;
  4485. }
  4486. /* Wait for a thread to finish. */
  4487. static int
  4488. mg_join_thread(pthread_t threadid)
  4489. {
  4490. int result;
  4491. DWORD dwevent;
  4492. result = -1;
  4493. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4494. if (dwevent == WAIT_FAILED) {
  4495. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4496. } else {
  4497. if (dwevent == WAIT_OBJECT_0) {
  4498. CloseHandle(threadid);
  4499. result = 0;
  4500. }
  4501. }
  4502. return result;
  4503. }
  4504. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4505. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4506. /* Create substitutes for POSIX functions in Win32. */
  4507. #if defined(GCC_DIAGNOSTIC)
  4508. /* Show no warning in case system functions are not used. */
  4509. #pragma GCC diagnostic push
  4510. #pragma GCC diagnostic ignored "-Wunused-function"
  4511. #endif
  4512. FUNCTION_MAY_BE_UNUSED
  4513. static HANDLE
  4514. dlopen(const char *dll_name, int flags)
  4515. {
  4516. wchar_t wbuf[UTF16_PATH_MAX];
  4517. (void)flags;
  4518. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4519. return LoadLibraryW(wbuf);
  4520. }
  4521. FUNCTION_MAY_BE_UNUSED
  4522. static int
  4523. dlclose(void *handle)
  4524. {
  4525. int result;
  4526. if (FreeLibrary((HMODULE)handle) != 0) {
  4527. result = 0;
  4528. } else {
  4529. result = -1;
  4530. }
  4531. return result;
  4532. }
  4533. #if defined(GCC_DIAGNOSTIC)
  4534. /* Enable unused function warning again */
  4535. #pragma GCC diagnostic pop
  4536. #endif
  4537. #endif
  4538. #if !defined(NO_CGI)
  4539. #define SIGKILL (0)
  4540. static int
  4541. kill(pid_t pid, int sig_num)
  4542. {
  4543. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4544. (void)CloseHandle((HANDLE)pid);
  4545. return 0;
  4546. }
  4547. #if !defined(WNOHANG)
  4548. #define WNOHANG (1)
  4549. #endif
  4550. static pid_t
  4551. waitpid(pid_t pid, int *status, int flags)
  4552. {
  4553. DWORD timeout = INFINITE;
  4554. DWORD waitres;
  4555. (void)status; /* Currently not used by any client here */
  4556. if ((flags | WNOHANG) == WNOHANG) {
  4557. timeout = 0;
  4558. }
  4559. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4560. if (waitres == WAIT_OBJECT_0) {
  4561. return pid;
  4562. }
  4563. if (waitres == WAIT_TIMEOUT) {
  4564. return 0;
  4565. }
  4566. return (pid_t)-1;
  4567. }
  4568. static void
  4569. trim_trailing_whitespaces(char *s)
  4570. {
  4571. char *e = s + strlen(s);
  4572. while ((e > s) && isspace((unsigned char)e[-1])) {
  4573. *(--e) = '\0';
  4574. }
  4575. }
  4576. static pid_t
  4577. spawn_process(struct mg_connection *conn,
  4578. const char *prog,
  4579. char *envblk,
  4580. char *envp[],
  4581. int fdin[2],
  4582. int fdout[2],
  4583. int fderr[2],
  4584. const char *dir,
  4585. unsigned char cgi_config_idx)
  4586. {
  4587. HANDLE me;
  4588. char *interp;
  4589. char *interp_arg = 0;
  4590. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4591. int truncated;
  4592. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4593. STARTUPINFOA si;
  4594. PROCESS_INFORMATION pi = {0};
  4595. (void)envp;
  4596. memset(&si, 0, sizeof(si));
  4597. si.cb = sizeof(si);
  4598. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4599. si.wShowWindow = SW_HIDE;
  4600. me = GetCurrentProcess();
  4601. DuplicateHandle(me,
  4602. (HANDLE)_get_osfhandle(fdin[0]),
  4603. me,
  4604. &si.hStdInput,
  4605. 0,
  4606. TRUE,
  4607. DUPLICATE_SAME_ACCESS);
  4608. DuplicateHandle(me,
  4609. (HANDLE)_get_osfhandle(fdout[1]),
  4610. me,
  4611. &si.hStdOutput,
  4612. 0,
  4613. TRUE,
  4614. DUPLICATE_SAME_ACCESS);
  4615. DuplicateHandle(me,
  4616. (HANDLE)_get_osfhandle(fderr[1]),
  4617. me,
  4618. &si.hStdError,
  4619. 0,
  4620. TRUE,
  4621. DUPLICATE_SAME_ACCESS);
  4622. /* Mark handles that should not be inherited. See
  4623. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4624. */
  4625. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4626. HANDLE_FLAG_INHERIT,
  4627. 0);
  4628. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4629. HANDLE_FLAG_INHERIT,
  4630. 0);
  4631. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4632. HANDLE_FLAG_INHERIT,
  4633. 0);
  4634. /* First check, if there is a CGI interpreter configured for all CGI
  4635. * scripts. */
  4636. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4637. if (interp != NULL) {
  4638. /* If there is a configured interpreter, check for additional arguments
  4639. */
  4640. interp_arg =
  4641. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4642. } else {
  4643. /* Otherwise, the interpreter must be stated in the first line of the
  4644. * CGI script file, after a #! (shebang) mark. */
  4645. buf[0] = buf[1] = '\0';
  4646. /* Get the full script path */
  4647. mg_snprintf(
  4648. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4649. if (truncated) {
  4650. pi.hProcess = (pid_t)-1;
  4651. goto spawn_cleanup;
  4652. }
  4653. /* Open the script file, to read the first line */
  4654. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4655. /* Read the first line of the script into the buffer */
  4656. mg_fgets(buf, sizeof(buf), &file);
  4657. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4658. buf[sizeof(buf) - 1] = '\0';
  4659. }
  4660. if ((buf[0] == '#') && (buf[1] == '!')) {
  4661. trim_trailing_whitespaces(buf + 2);
  4662. } else {
  4663. buf[2] = '\0';
  4664. }
  4665. interp = buf + 2;
  4666. }
  4667. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4668. if (interp[0] != '\0') {
  4669. /* This is an interpreted script file. We must call the interpreter. */
  4670. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4671. mg_snprintf(conn,
  4672. &truncated,
  4673. cmdline,
  4674. sizeof(cmdline),
  4675. "\"%s\" %s \"%s\\%s\"",
  4676. interp,
  4677. interp_arg,
  4678. full_dir,
  4679. prog);
  4680. } else {
  4681. mg_snprintf(conn,
  4682. &truncated,
  4683. cmdline,
  4684. sizeof(cmdline),
  4685. "\"%s\" \"%s\\%s\"",
  4686. interp,
  4687. full_dir,
  4688. prog);
  4689. }
  4690. } else {
  4691. /* This is (probably) a compiled program. We call it directly. */
  4692. mg_snprintf(conn,
  4693. &truncated,
  4694. cmdline,
  4695. sizeof(cmdline),
  4696. "\"%s\\%s\"",
  4697. full_dir,
  4698. prog);
  4699. }
  4700. if (truncated) {
  4701. pi.hProcess = (pid_t)-1;
  4702. goto spawn_cleanup;
  4703. }
  4704. DEBUG_TRACE("Running [%s]", cmdline);
  4705. if (CreateProcessA(NULL,
  4706. cmdline,
  4707. NULL,
  4708. NULL,
  4709. TRUE,
  4710. CREATE_NEW_PROCESS_GROUP,
  4711. envblk,
  4712. NULL,
  4713. &si,
  4714. &pi)
  4715. == 0) {
  4716. mg_cry_internal(
  4717. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4718. pi.hProcess = (pid_t)-1;
  4719. /* goto spawn_cleanup; */
  4720. }
  4721. spawn_cleanup:
  4722. (void)CloseHandle(si.hStdOutput);
  4723. (void)CloseHandle(si.hStdError);
  4724. (void)CloseHandle(si.hStdInput);
  4725. if (pi.hThread != NULL) {
  4726. (void)CloseHandle(pi.hThread);
  4727. }
  4728. return (pid_t)pi.hProcess;
  4729. }
  4730. #endif /* !NO_CGI */
  4731. static int
  4732. set_blocking_mode(SOCKET sock)
  4733. {
  4734. unsigned long non_blocking = 0;
  4735. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4736. }
  4737. static int
  4738. set_non_blocking_mode(SOCKET sock)
  4739. {
  4740. unsigned long non_blocking = 1;
  4741. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4742. }
  4743. #else
  4744. #if !defined(NO_FILESYSTEMS)
  4745. static int
  4746. mg_stat(const struct mg_connection *conn,
  4747. const char *path,
  4748. struct mg_file_stat *filep)
  4749. {
  4750. struct stat st;
  4751. if (!filep) {
  4752. return 0;
  4753. }
  4754. memset(filep, 0, sizeof(*filep));
  4755. if (mg_path_suspicious(conn, path)) {
  4756. return 0;
  4757. }
  4758. if (0 == stat(path, &st)) {
  4759. filep->size = (uint64_t)(st.st_size);
  4760. filep->last_modified = st.st_mtime;
  4761. filep->is_directory = S_ISDIR(st.st_mode);
  4762. return 1;
  4763. }
  4764. return 0;
  4765. }
  4766. #endif /* NO_FILESYSTEMS */
  4767. static void
  4768. set_close_on_exec(int fd,
  4769. const struct mg_connection *conn /* may be null */,
  4770. struct mg_context *ctx /* may be null */)
  4771. {
  4772. #if defined(__ZEPHYR__)
  4773. (void)fd;
  4774. (void)conn;
  4775. (void)ctx;
  4776. #else
  4777. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4778. if (conn || ctx) {
  4779. struct mg_connection fc;
  4780. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4781. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4782. __func__,
  4783. strerror(ERRNO));
  4784. }
  4785. }
  4786. #endif
  4787. }
  4788. CIVETWEB_API int
  4789. mg_start_thread(mg_thread_func_t func, void *param)
  4790. {
  4791. pthread_t thread_id;
  4792. pthread_attr_t attr;
  4793. int result;
  4794. (void)pthread_attr_init(&attr);
  4795. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4796. #if defined(__ZEPHYR__)
  4797. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4798. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4799. /* Compile-time option to control stack size,
  4800. * e.g. -DUSE_STACK_SIZE=16384 */
  4801. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4802. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4803. result = pthread_create(&thread_id, &attr, func, param);
  4804. pthread_attr_destroy(&attr);
  4805. return result;
  4806. }
  4807. /* Start a thread storing the thread context. */
  4808. static int
  4809. mg_start_thread_with_id(mg_thread_func_t func,
  4810. void *param,
  4811. pthread_t *threadidptr)
  4812. {
  4813. pthread_t thread_id;
  4814. pthread_attr_t attr;
  4815. int result;
  4816. (void)pthread_attr_init(&attr);
  4817. #if defined(__ZEPHYR__)
  4818. pthread_attr_setstack(&attr,
  4819. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4820. ZEPHYR_STACK_SIZE);
  4821. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4822. /* Compile-time option to control stack size,
  4823. * e.g. -DUSE_STACK_SIZE=16384 */
  4824. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4825. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4826. result = pthread_create(&thread_id, &attr, func, param);
  4827. pthread_attr_destroy(&attr);
  4828. if ((result == 0) && (threadidptr != NULL)) {
  4829. *threadidptr = thread_id;
  4830. }
  4831. return result;
  4832. }
  4833. /* Wait for a thread to finish. */
  4834. static int
  4835. mg_join_thread(pthread_t threadid)
  4836. {
  4837. int result;
  4838. result = pthread_join(threadid, NULL);
  4839. return result;
  4840. }
  4841. #if !defined(NO_CGI)
  4842. static pid_t
  4843. spawn_process(struct mg_connection *conn,
  4844. const char *prog,
  4845. char *envblk,
  4846. char *envp[],
  4847. int fdin[2],
  4848. int fdout[2],
  4849. int fderr[2],
  4850. const char *dir,
  4851. unsigned char cgi_config_idx)
  4852. {
  4853. pid_t pid;
  4854. const char *interp;
  4855. (void)envblk;
  4856. if ((pid = fork()) == -1) {
  4857. /* Parent */
  4858. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4859. } else if (pid != 0) {
  4860. /* Make sure children close parent-side descriptors.
  4861. * The caller will close the child-side immediately. */
  4862. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4863. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4864. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4865. } else {
  4866. /* Child */
  4867. if (chdir(dir) != 0) {
  4868. mg_cry_internal(
  4869. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4870. } else if (dup2(fdin[0], 0) == -1) {
  4871. mg_cry_internal(conn,
  4872. "%s: dup2(%d, 0): %s",
  4873. __func__,
  4874. fdin[0],
  4875. strerror(ERRNO));
  4876. } else if (dup2(fdout[1], 1) == -1) {
  4877. mg_cry_internal(conn,
  4878. "%s: dup2(%d, 1): %s",
  4879. __func__,
  4880. fdout[1],
  4881. strerror(ERRNO));
  4882. } else if (dup2(fderr[1], 2) == -1) {
  4883. mg_cry_internal(conn,
  4884. "%s: dup2(%d, 2): %s",
  4885. __func__,
  4886. fderr[1],
  4887. strerror(ERRNO));
  4888. } else {
  4889. struct sigaction sa;
  4890. /* Keep stderr and stdout in two different pipes.
  4891. * Stdout will be sent back to the client,
  4892. * stderr should go into a server error log. */
  4893. (void)close(fdin[0]);
  4894. (void)close(fdout[1]);
  4895. (void)close(fderr[1]);
  4896. /* Close write end fdin and read end fdout and fderr */
  4897. (void)close(fdin[1]);
  4898. (void)close(fdout[0]);
  4899. (void)close(fderr[0]);
  4900. /* After exec, all signal handlers are restored to their default
  4901. * values, with one exception of SIGCHLD. According to
  4902. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4903. * will leave unchanged after exec if it was set to be ignored.
  4904. * Restore it to default action. */
  4905. memset(&sa, 0, sizeof(sa));
  4906. sa.sa_handler = SIG_DFL;
  4907. sigaction(SIGCHLD, &sa, NULL);
  4908. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4909. if (interp == NULL) {
  4910. /* no interpreter configured, call the programm directly */
  4911. (void)execle(prog, prog, NULL, envp);
  4912. mg_cry_internal(conn,
  4913. "%s: execle(%s): %s",
  4914. __func__,
  4915. prog,
  4916. strerror(ERRNO));
  4917. } else {
  4918. /* call the configured interpreter */
  4919. const char *interp_args =
  4920. conn->dom_ctx
  4921. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4922. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4923. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4924. } else {
  4925. (void)execle(interp, interp, prog, NULL, envp);
  4926. }
  4927. mg_cry_internal(conn,
  4928. "%s: execle(%s %s): %s",
  4929. __func__,
  4930. interp,
  4931. prog,
  4932. strerror(ERRNO));
  4933. }
  4934. }
  4935. exit(EXIT_FAILURE);
  4936. }
  4937. return pid;
  4938. }
  4939. #endif /* !NO_CGI */
  4940. static int
  4941. set_non_blocking_mode(SOCKET sock)
  4942. {
  4943. int flags = fcntl(sock, F_GETFL, 0);
  4944. if (flags < 0) {
  4945. return -1;
  4946. }
  4947. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4948. return -1;
  4949. }
  4950. return 0;
  4951. }
  4952. static int
  4953. set_blocking_mode(SOCKET sock)
  4954. {
  4955. int flags = fcntl(sock, F_GETFL, 0);
  4956. if (flags < 0) {
  4957. return -1;
  4958. }
  4959. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4960. return -1;
  4961. }
  4962. return 0;
  4963. }
  4964. #endif /* _WIN32 / else */
  4965. /* End of initial operating system specific define block. */
  4966. /* Get a random number (independent of C rand function) */
  4967. static uint64_t
  4968. get_random(void)
  4969. {
  4970. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4971. static uint64_t lcg = 0; /* Linear congruential generator */
  4972. uint64_t now = mg_get_current_time_ns();
  4973. if (lfsr == 0) {
  4974. /* lfsr will be only 0 if has not been initialized,
  4975. * so this code is called only once. */
  4976. lfsr = mg_get_current_time_ns();
  4977. lcg = mg_get_current_time_ns();
  4978. } else {
  4979. /* Get the next step of both random number generators. */
  4980. lfsr = (lfsr >> 1)
  4981. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4982. << 63);
  4983. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4984. }
  4985. /* Combining two pseudo-random number generators and a high resolution
  4986. * part
  4987. * of the current server time will make it hard (impossible?) to guess
  4988. * the
  4989. * next number. */
  4990. return (lfsr ^ lcg ^ now);
  4991. }
  4992. static int
  4993. mg_poll(struct mg_pollfd *pfd,
  4994. unsigned int n,
  4995. int milliseconds,
  4996. const stop_flag_t *stop_flag)
  4997. {
  4998. /* Call poll, but only for a maximum time of a few seconds.
  4999. * This will allow to stop the server after some seconds, instead
  5000. * of having to wait for a long socket timeout. */
  5001. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5002. int check_pollerr = 0;
  5003. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5004. /* If we wait for only one file descriptor, wait on error as well */
  5005. pfd[0].events |= POLLERR;
  5006. check_pollerr = 1;
  5007. }
  5008. do {
  5009. int result;
  5010. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5011. /* Shut down signal */
  5012. return -2;
  5013. }
  5014. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5015. ms_now = milliseconds;
  5016. }
  5017. result = poll(pfd, n, ms_now);
  5018. if (result != 0) {
  5019. /* Poll returned either success (1) or error (-1).
  5020. * Forward both to the caller. */
  5021. if ((check_pollerr)
  5022. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5023. == POLLERR)) {
  5024. /* One and only file descriptor returned error */
  5025. return -1;
  5026. }
  5027. return result;
  5028. }
  5029. /* Poll returned timeout (0). */
  5030. if (milliseconds > 0) {
  5031. milliseconds -= ms_now;
  5032. }
  5033. } while (milliseconds > 0);
  5034. /* timeout: return 0 */
  5035. return 0;
  5036. }
  5037. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5038. * descriptor.
  5039. * Return value:
  5040. * >=0 .. number of bytes successfully written
  5041. * -1 .. timeout
  5042. * -2 .. error
  5043. */
  5044. static int
  5045. push_inner(struct mg_context *ctx,
  5046. FILE *fp,
  5047. SOCKET sock,
  5048. SSL *ssl,
  5049. const char *buf,
  5050. int len,
  5051. double timeout)
  5052. {
  5053. uint64_t start = 0, now = 0, timeout_ns = 0;
  5054. int n, err;
  5055. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5056. #if defined(_WIN32)
  5057. typedef int len_t;
  5058. #else
  5059. typedef size_t len_t;
  5060. #endif
  5061. if (timeout > 0) {
  5062. now = mg_get_current_time_ns();
  5063. start = now;
  5064. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5065. }
  5066. if (ctx == NULL) {
  5067. return -2;
  5068. }
  5069. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5070. if (ssl) {
  5071. return -2;
  5072. }
  5073. #endif
  5074. /* Try to read until it succeeds, fails, times out, or the server
  5075. * shuts down. */
  5076. for (;;) {
  5077. #if defined(USE_MBEDTLS)
  5078. if (ssl != NULL) {
  5079. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5080. if (n <= 0) {
  5081. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5082. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5083. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5084. n = 0;
  5085. } else {
  5086. fprintf(stderr, "SSL write failed, error %d\n", n);
  5087. return -2;
  5088. }
  5089. } else {
  5090. err = 0;
  5091. }
  5092. } else
  5093. #elif !defined(NO_SSL)
  5094. if (ssl != NULL) {
  5095. ERR_clear_error();
  5096. n = SSL_write(ssl, buf, len);
  5097. if (n <= 0) {
  5098. err = SSL_get_error(ssl, n);
  5099. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5100. err = ERRNO;
  5101. } else if ((err == SSL_ERROR_WANT_READ)
  5102. || (err == SSL_ERROR_WANT_WRITE)) {
  5103. n = 0;
  5104. } else {
  5105. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5106. ERR_clear_error();
  5107. return -2;
  5108. }
  5109. ERR_clear_error();
  5110. } else {
  5111. err = 0;
  5112. }
  5113. } else
  5114. #endif
  5115. if (fp != NULL) {
  5116. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5117. if (ferror(fp)) {
  5118. n = -1;
  5119. err = ERRNO;
  5120. } else {
  5121. err = 0;
  5122. }
  5123. } else {
  5124. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5125. err = (n < 0) ? ERRNO : 0;
  5126. #if defined(_WIN32)
  5127. if (err == WSAEWOULDBLOCK) {
  5128. err = 0;
  5129. n = 0;
  5130. }
  5131. #else
  5132. if (ERROR_TRY_AGAIN(err)) {
  5133. err = 0;
  5134. n = 0;
  5135. }
  5136. #endif
  5137. if (n < 0) {
  5138. /* shutdown of the socket at client side */
  5139. return -2;
  5140. }
  5141. }
  5142. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5143. return -2;
  5144. }
  5145. if ((n > 0) || ((n == 0) && (len == 0))) {
  5146. /* some data has been read, or no data was requested */
  5147. return n;
  5148. }
  5149. if (n < 0) {
  5150. /* socket error - check errno */
  5151. DEBUG_TRACE("send() failed, error %d", err);
  5152. /* TODO (mid): error handling depending on the error code.
  5153. * These codes are different between Windows and Linux.
  5154. * Currently there is no problem with failing send calls,
  5155. * if there is a reproducible situation, it should be
  5156. * investigated in detail.
  5157. */
  5158. return -2;
  5159. }
  5160. /* Only in case n=0 (timeout), repeat calling the write function */
  5161. /* If send failed, wait before retry */
  5162. if (fp != NULL) {
  5163. /* For files, just wait a fixed time.
  5164. * Maybe it helps, maybe not. */
  5165. mg_sleep(5);
  5166. } else {
  5167. /* For sockets, wait for the socket using poll */
  5168. struct mg_pollfd pfd[1];
  5169. int pollres;
  5170. pfd[0].fd = sock;
  5171. pfd[0].events = POLLOUT;
  5172. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5173. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5174. return -2;
  5175. }
  5176. if (pollres > 0) {
  5177. continue;
  5178. }
  5179. }
  5180. if (timeout > 0) {
  5181. now = mg_get_current_time_ns();
  5182. if ((now - start) > timeout_ns) {
  5183. /* Timeout */
  5184. break;
  5185. }
  5186. }
  5187. }
  5188. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5189. used */
  5190. return -1;
  5191. }
  5192. static int
  5193. push_all(struct mg_context *ctx,
  5194. FILE *fp,
  5195. SOCKET sock,
  5196. SSL *ssl,
  5197. const char *buf,
  5198. int len)
  5199. {
  5200. double timeout = -1.0;
  5201. int n, nwritten = 0;
  5202. if (ctx == NULL) {
  5203. return -1;
  5204. }
  5205. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5206. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5207. }
  5208. if (timeout <= 0.0) {
  5209. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5210. / 1000.0;
  5211. }
  5212. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5213. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5214. if (n < 0) {
  5215. if (nwritten == 0) {
  5216. nwritten = -1; /* Propagate the error */
  5217. }
  5218. break;
  5219. } else if (n == 0) {
  5220. break; /* No more data to write */
  5221. } else {
  5222. nwritten += n;
  5223. len -= n;
  5224. }
  5225. }
  5226. return nwritten;
  5227. }
  5228. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5229. * Return value:
  5230. * >=0 .. number of bytes successfully read
  5231. * -1 .. timeout
  5232. * -2 .. error
  5233. */
  5234. static int
  5235. pull_inner(FILE *fp,
  5236. struct mg_connection *conn,
  5237. char *buf,
  5238. int len,
  5239. double timeout)
  5240. {
  5241. int nread, err = 0;
  5242. #if defined(_WIN32)
  5243. typedef int len_t;
  5244. #else
  5245. typedef size_t len_t;
  5246. #endif
  5247. /* We need an additional wait loop around this, because in some cases
  5248. * with TLSwe may get data from the socket but not from SSL_read.
  5249. * In this case we need to repeat at least once.
  5250. */
  5251. if (fp != NULL) {
  5252. /* Use read() instead of fread(), because if we're reading from the
  5253. * CGI pipe, fread() may block until IO buffer is filled up. We
  5254. * cannot afford to block and must pass all read bytes immediately
  5255. * to the client. */
  5256. nread = (int)read(fileno(fp), buf, (size_t)len);
  5257. err = (nread < 0) ? ERRNO : 0;
  5258. if ((nread == 0) && (len > 0)) {
  5259. /* Should get data, but got EOL */
  5260. return -2;
  5261. }
  5262. #if defined(USE_MBEDTLS)
  5263. } else if (conn->ssl != NULL) {
  5264. struct mg_pollfd pfd[1];
  5265. int to_read;
  5266. int pollres;
  5267. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5268. if (to_read > 0) {
  5269. /* We already know there is no more data buffered in conn->buf
  5270. * but there is more available in the SSL layer. So don't poll
  5271. * conn->client.sock yet. */
  5272. pollres = 1;
  5273. if (to_read > len)
  5274. to_read = len;
  5275. } else {
  5276. pfd[0].fd = conn->client.sock;
  5277. pfd[0].events = POLLIN;
  5278. to_read = len;
  5279. pollres = mg_poll(pfd,
  5280. 1,
  5281. (int)(timeout * 1000.0),
  5282. &(conn->phys_ctx->stop_flag));
  5283. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5284. return -2;
  5285. }
  5286. }
  5287. if (pollres > 0) {
  5288. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5289. if (nread <= 0) {
  5290. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5291. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5292. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5293. nread = 0;
  5294. } else {
  5295. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5296. return -2;
  5297. }
  5298. } else {
  5299. err = 0;
  5300. }
  5301. } else if (pollres < 0) {
  5302. /* Error */
  5303. return -2;
  5304. } else {
  5305. /* pollres = 0 means timeout */
  5306. nread = 0;
  5307. }
  5308. #elif !defined(NO_SSL)
  5309. } else if (conn->ssl != NULL) {
  5310. int ssl_pending;
  5311. struct mg_pollfd pfd[1];
  5312. int pollres;
  5313. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5314. /* We already know there is no more data buffered in conn->buf
  5315. * but there is more available in the SSL layer. So don't poll
  5316. * conn->client.sock yet. */
  5317. if (ssl_pending > len) {
  5318. ssl_pending = len;
  5319. }
  5320. pollres = 1;
  5321. } else {
  5322. pfd[0].fd = conn->client.sock;
  5323. pfd[0].events = POLLIN;
  5324. pollres = mg_poll(pfd,
  5325. 1,
  5326. (int)(timeout * 1000.0),
  5327. &(conn->phys_ctx->stop_flag));
  5328. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5329. return -2;
  5330. }
  5331. }
  5332. if (pollres > 0) {
  5333. ERR_clear_error();
  5334. nread =
  5335. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5336. if (nread <= 0) {
  5337. err = SSL_get_error(conn->ssl, nread);
  5338. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5339. err = ERRNO;
  5340. } else if ((err == SSL_ERROR_WANT_READ)
  5341. || (err == SSL_ERROR_WANT_WRITE)) {
  5342. nread = 0;
  5343. } else {
  5344. /* All errors should return -2 */
  5345. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5346. ERR_clear_error();
  5347. return -2;
  5348. }
  5349. ERR_clear_error();
  5350. } else {
  5351. err = 0;
  5352. }
  5353. } else if (pollres < 0) {
  5354. /* Error */
  5355. return -2;
  5356. } else {
  5357. /* pollres = 0 means timeout */
  5358. nread = 0;
  5359. }
  5360. #endif
  5361. } else {
  5362. struct mg_pollfd pfd[1];
  5363. int pollres;
  5364. pfd[0].fd = conn->client.sock;
  5365. pfd[0].events = POLLIN;
  5366. pollres = mg_poll(pfd,
  5367. 1,
  5368. (int)(timeout * 1000.0),
  5369. &(conn->phys_ctx->stop_flag));
  5370. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5371. return -2;
  5372. }
  5373. if (pollres > 0) {
  5374. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5375. err = (nread < 0) ? ERRNO : 0;
  5376. if (nread <= 0) {
  5377. /* shutdown of the socket at client side */
  5378. return -2;
  5379. }
  5380. } else if (pollres < 0) {
  5381. /* error callint poll */
  5382. return -2;
  5383. } else {
  5384. /* pollres = 0 means timeout */
  5385. nread = 0;
  5386. }
  5387. }
  5388. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5389. return -2;
  5390. }
  5391. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5392. /* some data has been read, or no data was requested */
  5393. return nread;
  5394. }
  5395. if (nread < 0) {
  5396. /* socket error - check errno */
  5397. #if defined(_WIN32)
  5398. if (err == WSAEWOULDBLOCK) {
  5399. /* TODO (low): check if this is still required */
  5400. /* standard case if called from close_socket_gracefully */
  5401. return -2;
  5402. } else if (err == WSAETIMEDOUT) {
  5403. /* TODO (low): check if this is still required */
  5404. /* timeout is handled by the while loop */
  5405. return 0;
  5406. } else if (err == WSAECONNABORTED) {
  5407. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5408. return -2;
  5409. } else {
  5410. DEBUG_TRACE("recv() failed, error %d", err);
  5411. return -2;
  5412. }
  5413. #else
  5414. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5415. * if the timeout is reached and if the socket was set to non-
  5416. * blocking in close_socket_gracefully, so we can not distinguish
  5417. * here. We have to wait for the timeout in both cases for now.
  5418. */
  5419. if (ERROR_TRY_AGAIN(err)) {
  5420. /* TODO (low): check if this is still required */
  5421. /* EAGAIN/EWOULDBLOCK:
  5422. * standard case if called from close_socket_gracefully
  5423. * => should return -1 */
  5424. /* or timeout occurred
  5425. * => the code must stay in the while loop */
  5426. /* EINTR can be generated on a socket with a timeout set even
  5427. * when SA_RESTART is effective for all relevant signals
  5428. * (see signal(7)).
  5429. * => stay in the while loop */
  5430. } else {
  5431. DEBUG_TRACE("recv() failed, error %d", err);
  5432. return -2;
  5433. }
  5434. #endif
  5435. }
  5436. /* Timeout occurred, but no data available. */
  5437. return -1;
  5438. }
  5439. static int
  5440. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5441. {
  5442. int n, nread = 0;
  5443. double timeout = -1.0;
  5444. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5445. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5446. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5447. }
  5448. if (timeout <= 0.0) {
  5449. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5450. / 1000.0;
  5451. }
  5452. start_time = mg_get_current_time_ns();
  5453. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5454. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5455. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5456. if (n == -2) {
  5457. if (nread == 0) {
  5458. nread = -1; /* Propagate the error */
  5459. }
  5460. break;
  5461. } else if (n == -1) {
  5462. /* timeout */
  5463. if (timeout >= 0.0) {
  5464. now = mg_get_current_time_ns();
  5465. if ((now - start_time) <= timeout_ns) {
  5466. continue;
  5467. }
  5468. }
  5469. break;
  5470. } else if (n == 0) {
  5471. break; /* No more data to read */
  5472. } else {
  5473. nread += n;
  5474. len -= n;
  5475. }
  5476. }
  5477. return nread;
  5478. }
  5479. static void
  5480. discard_unread_request_data(struct mg_connection *conn)
  5481. {
  5482. char buf[MG_BUF_LEN];
  5483. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5484. ;
  5485. }
  5486. static int
  5487. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5488. {
  5489. int64_t content_len, n, buffered_len, nread;
  5490. int64_t len64 =
  5491. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5492. * int, we may not read more
  5493. * bytes */
  5494. const char *body;
  5495. if (conn == NULL) {
  5496. return 0;
  5497. }
  5498. /* If Content-Length is not set for a response with body data,
  5499. * we do not know in advance how much data should be read. */
  5500. content_len = conn->content_len;
  5501. if (content_len < 0) {
  5502. /* The body data is completed when the connection is closed. */
  5503. content_len = INT64_MAX;
  5504. }
  5505. nread = 0;
  5506. if (conn->consumed_content < content_len) {
  5507. /* Adjust number of bytes to read. */
  5508. int64_t left_to_read = content_len - conn->consumed_content;
  5509. if (left_to_read < len64) {
  5510. /* Do not read more than the total content length of the
  5511. * request.
  5512. */
  5513. len64 = left_to_read;
  5514. }
  5515. /* Return buffered data */
  5516. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5517. - conn->consumed_content;
  5518. if (buffered_len > 0) {
  5519. if (len64 < buffered_len) {
  5520. buffered_len = len64;
  5521. }
  5522. body = conn->buf + conn->request_len + conn->consumed_content;
  5523. memcpy(buf, body, (size_t)buffered_len);
  5524. len64 -= buffered_len;
  5525. conn->consumed_content += buffered_len;
  5526. nread += buffered_len;
  5527. buf = (char *)buf + buffered_len;
  5528. }
  5529. /* We have returned all buffered data. Read new data from the remote
  5530. * socket.
  5531. */
  5532. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5533. conn->consumed_content += n;
  5534. nread += n;
  5535. } else {
  5536. nread = ((nread > 0) ? nread : n);
  5537. }
  5538. }
  5539. return (int)nread;
  5540. }
  5541. /* Forward declarations */
  5542. static void handle_request(struct mg_connection *);
  5543. static void log_access(const struct mg_connection *);
  5544. /* Handle request, update statistics and call access log */
  5545. static void
  5546. handle_request_stat_log(struct mg_connection *conn)
  5547. {
  5548. #if defined(USE_SERVER_STATS)
  5549. struct timespec tnow;
  5550. conn->conn_state = 4; /* processing */
  5551. #endif
  5552. handle_request(conn);
  5553. #if defined(USE_SERVER_STATS)
  5554. conn->conn_state = 5; /* processed */
  5555. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5556. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5557. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5558. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5559. conn->num_bytes_sent);
  5560. #endif
  5561. DEBUG_TRACE("%s", "handle_request done");
  5562. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5563. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5564. DEBUG_TRACE("%s", "end_request callback done");
  5565. }
  5566. log_access(conn);
  5567. }
  5568. #if defined(USE_HTTP2)
  5569. #if defined(NO_SSL)
  5570. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5571. #endif
  5572. #define USE_ALPN
  5573. #include "http2.inl"
  5574. /* Not supported with HTTP/2 */
  5575. #define HTTP1_only \
  5576. { \
  5577. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5578. http2_must_use_http1(conn); \
  5579. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5580. return; \
  5581. } \
  5582. }
  5583. #else
  5584. #define HTTP1_only
  5585. #endif
  5586. CIVETWEB_API int
  5587. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5588. {
  5589. if (len > INT_MAX) {
  5590. len = INT_MAX;
  5591. }
  5592. if (conn == NULL) {
  5593. return 0;
  5594. }
  5595. if (conn->is_chunked) {
  5596. size_t all_read = 0;
  5597. while (len > 0) {
  5598. if (conn->is_chunked >= 3) {
  5599. /* No more data left to read */
  5600. return 0;
  5601. }
  5602. if (conn->is_chunked != 1) {
  5603. /* Has error */
  5604. return -1;
  5605. }
  5606. if (conn->consumed_content != conn->content_len) {
  5607. /* copy from the current chunk */
  5608. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5609. if (read_ret < 1) {
  5610. /* read error */
  5611. conn->is_chunked = 2;
  5612. return -1;
  5613. }
  5614. all_read += (size_t)read_ret;
  5615. len -= (size_t)read_ret;
  5616. if (conn->consumed_content == conn->content_len) {
  5617. /* Add data bytes in the current chunk have been read,
  5618. * so we are expecting \r\n now. */
  5619. char x[2];
  5620. conn->content_len += 2;
  5621. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5622. || (x[1] != '\n')) {
  5623. /* Protocol violation */
  5624. conn->is_chunked = 2;
  5625. return -1;
  5626. }
  5627. }
  5628. } else {
  5629. /* fetch a new chunk */
  5630. size_t i;
  5631. char lenbuf[64];
  5632. char *end = NULL;
  5633. unsigned long chunkSize = 0;
  5634. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5635. conn->content_len++;
  5636. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5637. lenbuf[i] = 0;
  5638. }
  5639. if ((i > 0) && (lenbuf[i] == '\r')
  5640. && (lenbuf[i - 1] != '\r')) {
  5641. continue;
  5642. }
  5643. if ((i > 1) && (lenbuf[i] == '\n')
  5644. && (lenbuf[i - 1] == '\r')) {
  5645. lenbuf[i + 1] = 0;
  5646. chunkSize = strtoul(lenbuf, &end, 16);
  5647. if (chunkSize == 0) {
  5648. /* regular end of content */
  5649. conn->is_chunked = 3;
  5650. }
  5651. break;
  5652. }
  5653. if (!isxdigit((unsigned char)lenbuf[i])) {
  5654. /* illegal character for chunk length */
  5655. conn->is_chunked = 2;
  5656. return -1;
  5657. }
  5658. }
  5659. if ((end == NULL) || (*end != '\r')) {
  5660. /* chunksize not set correctly */
  5661. conn->is_chunked = 2;
  5662. return -1;
  5663. }
  5664. if (chunkSize == 0) {
  5665. /* try discarding trailer for keep-alive */
  5666. conn->content_len += 2;
  5667. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5668. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5669. conn->is_chunked = 4;
  5670. }
  5671. break;
  5672. }
  5673. /* append a new chunk */
  5674. conn->content_len += (int64_t)chunkSize;
  5675. }
  5676. }
  5677. return (int)all_read;
  5678. }
  5679. return mg_read_inner(conn, buf, len);
  5680. }
  5681. CIVETWEB_API int
  5682. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5683. {
  5684. time_t now;
  5685. int n, total, allowed;
  5686. if (conn == NULL) {
  5687. return 0;
  5688. }
  5689. if (len > INT_MAX) {
  5690. return -1;
  5691. }
  5692. /* Mark connection as "data sent" */
  5693. conn->request_state = 10;
  5694. #if defined(USE_HTTP2)
  5695. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5696. http2_data_frame_head(conn, len, 0);
  5697. }
  5698. #endif
  5699. if (conn->throttle > 0) {
  5700. if ((now = time(NULL)) != conn->last_throttle_time) {
  5701. conn->last_throttle_time = now;
  5702. conn->last_throttle_bytes = 0;
  5703. }
  5704. allowed = conn->throttle - conn->last_throttle_bytes;
  5705. if (allowed > (int)len) {
  5706. allowed = (int)len;
  5707. }
  5708. total = push_all(conn->phys_ctx,
  5709. NULL,
  5710. conn->client.sock,
  5711. conn->ssl,
  5712. (const char *)buf,
  5713. allowed);
  5714. if (total == allowed) {
  5715. buf = (const char *)buf + total;
  5716. conn->last_throttle_bytes += total;
  5717. while ((total < (int)len)
  5718. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5719. allowed = (conn->throttle > ((int)len - total))
  5720. ? (int)len - total
  5721. : conn->throttle;
  5722. n = push_all(conn->phys_ctx,
  5723. NULL,
  5724. conn->client.sock,
  5725. conn->ssl,
  5726. (const char *)buf,
  5727. allowed);
  5728. if (n != allowed) {
  5729. break;
  5730. }
  5731. sleep(1);
  5732. conn->last_throttle_bytes = allowed;
  5733. conn->last_throttle_time = time(NULL);
  5734. buf = (const char *)buf + n;
  5735. total += n;
  5736. }
  5737. }
  5738. } else {
  5739. total = push_all(conn->phys_ctx,
  5740. NULL,
  5741. conn->client.sock,
  5742. conn->ssl,
  5743. (const char *)buf,
  5744. (int)len);
  5745. }
  5746. if (total > 0) {
  5747. conn->num_bytes_sent += total;
  5748. }
  5749. return total;
  5750. }
  5751. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5752. CIVETWEB_API int
  5753. mg_send_chunk(struct mg_connection *conn,
  5754. const char *chunk,
  5755. unsigned int chunk_len)
  5756. {
  5757. char lenbuf[16];
  5758. size_t lenbuf_len;
  5759. int ret;
  5760. int t;
  5761. /* First store the length information in a text buffer. */
  5762. sprintf(lenbuf, "%x\r\n", chunk_len);
  5763. lenbuf_len = strlen(lenbuf);
  5764. /* Then send length information, chunk and terminating \r\n. */
  5765. ret = mg_write(conn, lenbuf, lenbuf_len);
  5766. if (ret != (int)lenbuf_len) {
  5767. return -1;
  5768. }
  5769. t = ret;
  5770. ret = mg_write(conn, chunk, chunk_len);
  5771. if (ret != (int)chunk_len) {
  5772. return -1;
  5773. }
  5774. t += ret;
  5775. ret = mg_write(conn, "\r\n", 2);
  5776. if (ret != 2) {
  5777. return -1;
  5778. }
  5779. t += ret;
  5780. return t;
  5781. }
  5782. #if defined(GCC_DIAGNOSTIC)
  5783. /* This block forwards format strings to printf implementations,
  5784. * so we need to disable the format-nonliteral warning. */
  5785. #pragma GCC diagnostic push
  5786. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5787. #endif
  5788. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5789. static int
  5790. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5791. {
  5792. va_list ap_copy;
  5793. size_t size = MG_BUF_LEN / 4;
  5794. int len = -1;
  5795. *buf = NULL;
  5796. while (len < 0) {
  5797. if (*buf) {
  5798. mg_free(*buf);
  5799. }
  5800. size *= 4;
  5801. *buf = (char *)mg_malloc(size);
  5802. if (!*buf) {
  5803. break;
  5804. }
  5805. va_copy(ap_copy, ap);
  5806. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5807. va_end(ap_copy);
  5808. (*buf)[size - 1] = 0;
  5809. }
  5810. return len;
  5811. }
  5812. /* Print message to buffer. If buffer is large enough to hold the message,
  5813. * return buffer. If buffer is to small, allocate large enough buffer on
  5814. * heap,
  5815. * and return allocated buffer. */
  5816. static int
  5817. alloc_vprintf(char **out_buf,
  5818. char *prealloc_buf,
  5819. size_t prealloc_size,
  5820. const char *fmt,
  5821. va_list ap)
  5822. {
  5823. va_list ap_copy;
  5824. int len;
  5825. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5826. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5827. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5828. * Therefore, we make two passes: on first pass, get required message
  5829. * length.
  5830. * On second pass, actually print the message. */
  5831. va_copy(ap_copy, ap);
  5832. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5833. va_end(ap_copy);
  5834. if (len < 0) {
  5835. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5836. * Switch to alternative code path that uses incremental
  5837. * allocations.
  5838. */
  5839. va_copy(ap_copy, ap);
  5840. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5841. va_end(ap_copy);
  5842. } else if ((size_t)(len) >= prealloc_size) {
  5843. /* The pre-allocated buffer not large enough. */
  5844. /* Allocate a new buffer. */
  5845. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5846. if (!*out_buf) {
  5847. /* Allocation failed. Return -1 as "out of memory" error. */
  5848. return -1;
  5849. }
  5850. /* Buffer allocation successful. Store the string there. */
  5851. va_copy(ap_copy, ap);
  5852. IGNORE_UNUSED_RESULT(
  5853. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5854. va_end(ap_copy);
  5855. } else {
  5856. /* The pre-allocated buffer is large enough.
  5857. * Use it to store the string and return the address. */
  5858. va_copy(ap_copy, ap);
  5859. IGNORE_UNUSED_RESULT(
  5860. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5861. va_end(ap_copy);
  5862. *out_buf = prealloc_buf;
  5863. }
  5864. return len;
  5865. }
  5866. static int
  5867. alloc_printf(char **out_buf, const char *fmt, ...)
  5868. {
  5869. va_list ap;
  5870. int result;
  5871. va_start(ap, fmt);
  5872. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5873. va_end(ap);
  5874. return result;
  5875. }
  5876. #if defined(GCC_DIAGNOSTIC)
  5877. /* Enable format-nonliteral warning again. */
  5878. #pragma GCC diagnostic pop
  5879. #endif
  5880. static int
  5881. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5882. {
  5883. char mem[MG_BUF_LEN];
  5884. char *buf = NULL;
  5885. int len;
  5886. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5887. len = mg_write(conn, buf, (size_t)len);
  5888. }
  5889. if (buf != mem) {
  5890. mg_free(buf);
  5891. }
  5892. return len;
  5893. }
  5894. CIVETWEB_API int
  5895. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5896. {
  5897. va_list ap;
  5898. int result;
  5899. va_start(ap, fmt);
  5900. result = mg_vprintf(conn, fmt, ap);
  5901. va_end(ap);
  5902. return result;
  5903. }
  5904. CIVETWEB_API int
  5905. mg_url_decode(const char *src,
  5906. int src_len,
  5907. char *dst,
  5908. int dst_len,
  5909. int is_form_url_encoded)
  5910. {
  5911. int i, j, a, b;
  5912. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5913. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5914. if ((i < src_len - 2) && (src[i] == '%')
  5915. && isxdigit((unsigned char)src[i + 1])
  5916. && isxdigit((unsigned char)src[i + 2])) {
  5917. a = tolower((unsigned char)src[i + 1]);
  5918. b = tolower((unsigned char)src[i + 2]);
  5919. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5920. i += 2;
  5921. } else if (is_form_url_encoded && (src[i] == '+')) {
  5922. dst[j] = ' ';
  5923. } else {
  5924. dst[j] = src[i];
  5925. }
  5926. }
  5927. dst[j] = '\0'; /* Null-terminate the destination */
  5928. return (i >= src_len) ? j : -1;
  5929. }
  5930. /* form url decoding of an entire string */
  5931. static void
  5932. url_decode_in_place(char *buf)
  5933. {
  5934. int len = (int)strlen(buf);
  5935. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5936. }
  5937. CIVETWEB_API int
  5938. mg_get_var(const char *data,
  5939. size_t data_len,
  5940. const char *name,
  5941. char *dst,
  5942. size_t dst_len)
  5943. {
  5944. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5945. }
  5946. CIVETWEB_API int
  5947. mg_get_var2(const char *data,
  5948. size_t data_len,
  5949. const char *name,
  5950. char *dst,
  5951. size_t dst_len,
  5952. size_t occurrence)
  5953. {
  5954. const char *p, *e, *s;
  5955. size_t name_len;
  5956. int len;
  5957. if ((dst == NULL) || (dst_len == 0)) {
  5958. len = -2;
  5959. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5960. len = -1;
  5961. dst[0] = '\0';
  5962. } else {
  5963. name_len = strlen(name);
  5964. e = data + data_len;
  5965. len = -1;
  5966. dst[0] = '\0';
  5967. /* data is "var1=val1&var2=val2...". Find variable first */
  5968. for (p = data; p + name_len < e; p++) {
  5969. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5970. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5971. /* Point p to variable value */
  5972. p += name_len + 1;
  5973. /* Point s to the end of the value */
  5974. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5975. if (s == NULL) {
  5976. s = e;
  5977. }
  5978. DEBUG_ASSERT(s >= p);
  5979. if (s < p) {
  5980. return -3;
  5981. }
  5982. /* Decode variable into destination buffer */
  5983. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5984. /* Redirect error code from -1 to -2 (destination buffer too
  5985. * small). */
  5986. if (len == -1) {
  5987. len = -2;
  5988. }
  5989. break;
  5990. }
  5991. }
  5992. }
  5993. return len;
  5994. }
  5995. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5996. CIVETWEB_API int
  5997. mg_split_form_urlencoded(char *data,
  5998. struct mg_header *form_fields,
  5999. unsigned num_form_fields)
  6000. {
  6001. char *b;
  6002. int i;
  6003. int num = 0;
  6004. if (data == NULL) {
  6005. /* parameter error */
  6006. return -1;
  6007. }
  6008. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6009. /* determine the number of expected fields */
  6010. if (data[0] == 0) {
  6011. return 0;
  6012. }
  6013. /* count number of & to return the number of key-value-pairs */
  6014. num = 1;
  6015. while (*data) {
  6016. if (*data == '&') {
  6017. num++;
  6018. }
  6019. data++;
  6020. }
  6021. return num;
  6022. }
  6023. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6024. /* parameter error */
  6025. return -1;
  6026. }
  6027. for (i = 0; i < (int)num_form_fields; i++) {
  6028. /* extract key-value pairs from input data */
  6029. while ((*data == ' ') || (*data == '\t')) {
  6030. /* skip initial spaces */
  6031. data++;
  6032. }
  6033. if (*data == 0) {
  6034. /* end of string reached */
  6035. break;
  6036. }
  6037. form_fields[num].name = data;
  6038. /* find & or = */
  6039. b = data;
  6040. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6041. b++;
  6042. }
  6043. if (*b == 0) {
  6044. /* last key without value */
  6045. form_fields[num].value = NULL;
  6046. } else if (*b == '&') {
  6047. /* mid key without value */
  6048. form_fields[num].value = NULL;
  6049. } else {
  6050. /* terminate string */
  6051. *b = 0;
  6052. /* value starts after '=' */
  6053. data = b + 1;
  6054. form_fields[num].value = data;
  6055. }
  6056. /* new field is stored */
  6057. num++;
  6058. /* find a next key */
  6059. b = strchr(data, '&');
  6060. if (b == 0) {
  6061. /* no more data */
  6062. break;
  6063. } else {
  6064. /* terminate value of last field at '&' */
  6065. *b = 0;
  6066. /* next key-value-pairs starts after '&' */
  6067. data = b + 1;
  6068. }
  6069. }
  6070. /* Decode all values */
  6071. for (i = 0; i < num; i++) {
  6072. if (form_fields[i].name) {
  6073. url_decode_in_place((char *)form_fields[i].name);
  6074. }
  6075. if (form_fields[i].value) {
  6076. url_decode_in_place((char *)form_fields[i].value);
  6077. }
  6078. }
  6079. /* return number of fields found */
  6080. return num;
  6081. }
  6082. /* HCP24: some changes to compare whole var_name */
  6083. CIVETWEB_API int
  6084. mg_get_cookie(const char *cookie_header,
  6085. const char *var_name,
  6086. char *dst,
  6087. size_t dst_size)
  6088. {
  6089. const char *s, *p, *end;
  6090. int name_len, len = -1;
  6091. if ((dst == NULL) || (dst_size == 0)) {
  6092. return -2;
  6093. }
  6094. dst[0] = '\0';
  6095. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6096. return -1;
  6097. }
  6098. name_len = (int)strlen(var_name);
  6099. end = s + strlen(s);
  6100. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6101. if (s[name_len] == '=') {
  6102. /* HCP24: now check is it a substring or a full cookie name */
  6103. if ((s == cookie_header) || (s[-1] == ' ')) {
  6104. s += name_len + 1;
  6105. if ((p = strchr(s, ' ')) == NULL) {
  6106. p = end;
  6107. }
  6108. if (p[-1] == ';') {
  6109. p--;
  6110. }
  6111. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6112. s++;
  6113. p--;
  6114. }
  6115. if ((size_t)(p - s) < dst_size) {
  6116. len = (int)(p - s);
  6117. mg_strlcpy(dst, s, (size_t)len + 1);
  6118. } else {
  6119. len = -3;
  6120. }
  6121. break;
  6122. }
  6123. }
  6124. }
  6125. return len;
  6126. }
  6127. CIVETWEB_API int
  6128. mg_base64_encode(const unsigned char *src,
  6129. size_t src_len,
  6130. char *dst,
  6131. size_t *dst_len)
  6132. {
  6133. static const char *b64 =
  6134. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6135. size_t i, j;
  6136. int a, b, c;
  6137. if (dst_len != NULL) {
  6138. /* Expected length including 0 termination: */
  6139. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6140. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6141. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6142. if (*dst_len < expected_len) {
  6143. if (*dst_len > 0) {
  6144. dst[0] = '\0';
  6145. }
  6146. *dst_len = expected_len;
  6147. return 0;
  6148. }
  6149. }
  6150. for (i = j = 0; i < src_len; i += 3) {
  6151. a = src[i];
  6152. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6153. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6154. dst[j++] = b64[a >> 2];
  6155. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6156. if (i + 1 < src_len) {
  6157. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6158. }
  6159. if (i + 2 < src_len) {
  6160. dst[j++] = b64[c & 63];
  6161. }
  6162. }
  6163. while (j % 4 != 0) {
  6164. dst[j++] = '=';
  6165. }
  6166. dst[j++] = '\0';
  6167. if (dst_len != NULL) {
  6168. *dst_len = (size_t)j;
  6169. }
  6170. /* Return -1 for "OK" */
  6171. return -1;
  6172. }
  6173. static unsigned char
  6174. b64reverse(char letter)
  6175. {
  6176. if ((letter >= 'A') && (letter <= 'Z')) {
  6177. return letter - 'A';
  6178. }
  6179. if ((letter >= 'a') && (letter <= 'z')) {
  6180. return letter - 'a' + 26;
  6181. }
  6182. if ((letter >= '0') && (letter <= '9')) {
  6183. return letter - '0' + 52;
  6184. }
  6185. if (letter == '+') {
  6186. return 62;
  6187. }
  6188. if (letter == '/') {
  6189. return 63;
  6190. }
  6191. if (letter == '=') {
  6192. return 255; /* normal end */
  6193. }
  6194. return 254; /* error */
  6195. }
  6196. CIVETWEB_API int
  6197. mg_base64_decode(const char *src,
  6198. size_t src_len,
  6199. unsigned char *dst,
  6200. size_t *dst_len)
  6201. {
  6202. size_t i;
  6203. unsigned char a, b, c, d;
  6204. size_t dst_len_limit = (size_t)-1;
  6205. size_t dst_len_used = 0;
  6206. if (dst_len != NULL) {
  6207. dst_len_limit = *dst_len;
  6208. *dst_len = 0;
  6209. }
  6210. for (i = 0; i < src_len; i += 4) {
  6211. /* Read 4 characters from BASE64 string */
  6212. a = b64reverse(src[i]);
  6213. if (a >= 254) {
  6214. return (int)i;
  6215. }
  6216. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6217. if (b >= 254) {
  6218. return (int)i + 1;
  6219. }
  6220. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6221. if (c == 254) {
  6222. return (int)i + 2;
  6223. }
  6224. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6225. if (d == 254) {
  6226. return (int)i + 3;
  6227. }
  6228. /* Add first (of 3) decoded character */
  6229. if (dst_len_used < dst_len_limit) {
  6230. dst[dst_len_used] = (a << 2) + (b >> 4);
  6231. }
  6232. dst_len_used++;
  6233. if (c != 255) {
  6234. if (dst_len_used < dst_len_limit) {
  6235. dst[dst_len_used] = (b << 4) + (c >> 2);
  6236. }
  6237. dst_len_used++;
  6238. if (d != 255) {
  6239. if (dst_len_used < dst_len_limit) {
  6240. dst[dst_len_used] = (c << 6) + d;
  6241. }
  6242. dst_len_used++;
  6243. }
  6244. }
  6245. }
  6246. /* Add terminating zero */
  6247. if (dst_len_used < dst_len_limit) {
  6248. dst[dst_len_used] = '\0';
  6249. }
  6250. dst_len_used++;
  6251. if (dst_len != NULL) {
  6252. *dst_len = dst_len_used;
  6253. }
  6254. if (dst_len_used > dst_len_limit) {
  6255. /* Out of memory */
  6256. return 0;
  6257. }
  6258. /* Return -1 for "OK" */
  6259. return -1;
  6260. }
  6261. static int
  6262. is_put_or_delete_method(const struct mg_connection *conn)
  6263. {
  6264. if (conn) {
  6265. const char *s = conn->request_info.request_method;
  6266. if (s != NULL) {
  6267. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6268. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6269. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6270. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6271. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6272. || !strcmp(s, "COPY"));
  6273. }
  6274. }
  6275. return 0;
  6276. }
  6277. static int
  6278. is_civetweb_webdav_method(const struct mg_connection *conn)
  6279. {
  6280. /* Note: Here we only have to identify the WebDav methods that need special
  6281. * handling in the CivetWeb code - not all methods used in WebDav. In
  6282. * particular, methods used on directories (when using Windows Explorer as
  6283. * WebDav client).
  6284. */
  6285. if (conn) {
  6286. const char *s = conn->request_info.request_method;
  6287. if (s != NULL) {
  6288. /* These are the civetweb builtin DAV methods */
  6289. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6290. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6291. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6292. }
  6293. }
  6294. return 0;
  6295. }
  6296. #if !defined(NO_FILES)
  6297. static int
  6298. extention_matches_script(
  6299. struct mg_connection *conn, /* in: request (must be valid) */
  6300. const char *filename /* in: filename (must be valid) */
  6301. )
  6302. {
  6303. #if !defined(NO_CGI)
  6304. unsigned char cgi_config_idx, inc, max;
  6305. #endif
  6306. #if defined(USE_LUA)
  6307. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6308. filename)
  6309. > 0) {
  6310. return 1;
  6311. }
  6312. #endif
  6313. #if defined(USE_DUKTAPE)
  6314. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6315. filename)
  6316. > 0) {
  6317. return 1;
  6318. }
  6319. #endif
  6320. #if !defined(NO_CGI)
  6321. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6322. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6323. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6324. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6325. && (match_prefix_strlen(
  6326. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6327. filename)
  6328. > 0)) {
  6329. return 1;
  6330. }
  6331. }
  6332. #endif
  6333. /* filename and conn could be unused, if all preocessor conditions
  6334. * are false (no script language supported). */
  6335. (void)filename;
  6336. (void)conn;
  6337. return 0;
  6338. }
  6339. static int
  6340. extention_matches_template_text(
  6341. struct mg_connection *conn, /* in: request (must be valid) */
  6342. const char *filename /* in: filename (must be valid) */
  6343. )
  6344. {
  6345. #if defined(USE_LUA)
  6346. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6347. filename)
  6348. > 0) {
  6349. return 1;
  6350. }
  6351. #endif
  6352. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6353. > 0) {
  6354. return 1;
  6355. }
  6356. return 0;
  6357. }
  6358. /* For given directory path, substitute it to valid index file.
  6359. * Return 1 if index file has been found, 0 if not found.
  6360. * If the file is found, it's stats is returned in stp. */
  6361. static int
  6362. substitute_index_file(struct mg_connection *conn,
  6363. char *path,
  6364. size_t path_len,
  6365. struct mg_file_stat *filestat)
  6366. {
  6367. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6368. struct vec filename_vec;
  6369. size_t n = strlen(path);
  6370. int found = 0;
  6371. /* The 'path' given to us points to the directory. Remove all trailing
  6372. * directory separator characters from the end of the path, and
  6373. * then append single directory separator character. */
  6374. while ((n > 0) && (path[n - 1] == '/')) {
  6375. n--;
  6376. }
  6377. path[n] = '/';
  6378. /* Traverse index files list. For each entry, append it to the given
  6379. * path and see if the file exists. If it exists, break the loop */
  6380. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6381. /* Ignore too long entries that may overflow path buffer */
  6382. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6383. continue;
  6384. }
  6385. /* Prepare full path to the index file */
  6386. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6387. /* Does it exist? */
  6388. if (mg_stat(conn, path, filestat)) {
  6389. /* Yes it does, break the loop */
  6390. found = 1;
  6391. break;
  6392. }
  6393. }
  6394. /* If no index file exists, restore directory path */
  6395. if (!found) {
  6396. path[n] = '\0';
  6397. }
  6398. return found;
  6399. }
  6400. #endif
  6401. static void
  6402. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6403. char *filename, /* out: filename */
  6404. size_t filename_buf_len, /* in: size of filename buffer */
  6405. struct mg_file_stat *filestat, /* out: file status structure */
  6406. int *is_found, /* out: file found (directly) */
  6407. int *is_script_resource, /* out: handled by a script? */
  6408. int *is_websocket_request, /* out: websocket connetion? */
  6409. int *is_put_or_delete_request, /* out: put/delete a file? */
  6410. int *is_webdav_request, /* out: webdav request? */
  6411. int *is_template_text /* out: SSI file or LSP file? */
  6412. )
  6413. {
  6414. char const *accept_encoding;
  6415. #if !defined(NO_FILES)
  6416. const char *uri = conn->request_info.local_uri;
  6417. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6418. const char *rewrite;
  6419. struct vec a, b;
  6420. ptrdiff_t match_len;
  6421. char gz_path[UTF8_PATH_MAX];
  6422. int truncated;
  6423. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6424. char *tmp_str;
  6425. size_t tmp_str_len, sep_pos;
  6426. int allow_substitute_script_subresources;
  6427. #endif
  6428. #else
  6429. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6430. #endif
  6431. /* Step 1: Set all initially unknown outputs to zero */
  6432. memset(filestat, 0, sizeof(*filestat));
  6433. *filename = 0;
  6434. *is_found = 0;
  6435. *is_script_resource = 0;
  6436. *is_template_text = 0;
  6437. /* Step 2: Classify the request method */
  6438. /* Step 2a: Check if the request attempts to modify the file system */
  6439. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6440. /* Step 2b: Check if the request uses WebDav method that requires special
  6441. * handling */
  6442. *is_webdav_request = is_civetweb_webdav_method(conn);
  6443. /* Step 3: Check if it is a websocket request, and modify the document
  6444. * root if required */
  6445. #if defined(USE_WEBSOCKET)
  6446. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6447. #if !defined(NO_FILES)
  6448. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6449. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6450. }
  6451. #endif /* !NO_FILES */
  6452. #else /* USE_WEBSOCKET */
  6453. *is_websocket_request = 0;
  6454. #endif /* USE_WEBSOCKET */
  6455. /* Step 4: Check if gzip encoded response is allowed */
  6456. conn->accept_gzip = 0;
  6457. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6458. if (strstr(accept_encoding, "gzip") != NULL) {
  6459. conn->accept_gzip = 1;
  6460. }
  6461. }
  6462. #if !defined(NO_FILES)
  6463. /* Step 5: If there is no root directory, don't look for files. */
  6464. /* Note that root == NULL is a regular use case here. This occurs,
  6465. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6466. * config is not required. */
  6467. if (root == NULL) {
  6468. /* all file related outputs have already been set to 0, just return
  6469. */
  6470. return;
  6471. }
  6472. /* Step 6: Determine the local file path from the root path and the
  6473. * request uri. */
  6474. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6475. * part of the path one byte on the right. */
  6476. truncated = 0;
  6477. mg_snprintf(
  6478. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6479. if (truncated) {
  6480. goto interpret_cleanup;
  6481. }
  6482. /* Step 7: URI rewriting */
  6483. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6484. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6485. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6486. mg_snprintf(conn,
  6487. &truncated,
  6488. filename,
  6489. filename_buf_len - 1,
  6490. "%.*s%s",
  6491. (int)b.len,
  6492. b.ptr,
  6493. uri + match_len);
  6494. break;
  6495. }
  6496. }
  6497. if (truncated) {
  6498. goto interpret_cleanup;
  6499. }
  6500. /* Step 8: Check if the file exists at the server */
  6501. /* Local file path and name, corresponding to requested URI
  6502. * is now stored in "filename" variable. */
  6503. if (mg_stat(conn, filename, filestat)) {
  6504. int uri_len = (int)strlen(uri);
  6505. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6506. /* 8.1: File exists. */
  6507. *is_found = 1;
  6508. /* 8.2: Check if it is a script type. */
  6509. if (extention_matches_script(conn, filename)) {
  6510. /* The request addresses a CGI resource, Lua script or
  6511. * server-side javascript.
  6512. * The URI corresponds to the script itself (like
  6513. * /path/script.cgi), and there is no additional resource
  6514. * path (like /path/script.cgi/something).
  6515. * Requests that modify (replace or delete) a resource, like
  6516. * PUT and DELETE requests, should replace/delete the script
  6517. * file.
  6518. * Requests that read or write from/to a resource, like GET and
  6519. * POST requests, should call the script and return the
  6520. * generated response. */
  6521. *is_script_resource = (!*is_put_or_delete_request);
  6522. }
  6523. /* 8.3: Check for SSI and LSP files */
  6524. if (extention_matches_template_text(conn, filename)) {
  6525. /* Same as above, but for *.lsp and *.shtml files. */
  6526. /* A "template text" is a file delivered directly to the client,
  6527. * but with some text tags replaced by dynamic content.
  6528. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6529. * (LP, LSP) file. */
  6530. *is_template_text = (!*is_put_or_delete_request);
  6531. }
  6532. /* 8.4: If the request target is a directory, there could be
  6533. * a substitute file (index.html, index.cgi, ...). */
  6534. /* But do not substitute a directory for a WebDav request */
  6535. if (filestat->is_directory && is_uri_end_slash
  6536. && (!*is_webdav_request)) {
  6537. /* Use a local copy here, since substitute_index_file will
  6538. * change the content of the file status */
  6539. struct mg_file_stat tmp_filestat;
  6540. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6541. if (substitute_index_file(
  6542. conn, filename, filename_buf_len, &tmp_filestat)) {
  6543. /* Substitute file found. Copy stat to the output, then
  6544. * check if the file is a script file */
  6545. *filestat = tmp_filestat;
  6546. if (extention_matches_script(conn, filename)) {
  6547. /* Substitute file is a script file */
  6548. *is_script_resource = 1;
  6549. } else if (extention_matches_template_text(conn, filename)) {
  6550. /* Substitute file is a LSP or SSI file */
  6551. *is_template_text = 1;
  6552. } else {
  6553. /* Substitute file is a regular file */
  6554. *is_script_resource = 0;
  6555. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6556. }
  6557. }
  6558. /* If there is no substitute file, the server could return
  6559. * a directory listing in a later step */
  6560. }
  6561. return;
  6562. }
  6563. /* Step 9: Check for zipped files: */
  6564. /* If we can't find the actual file, look for the file
  6565. * with the same name but a .gz extension. If we find it,
  6566. * use that and set the gzipped flag in the file struct
  6567. * to indicate that the response need to have the content-
  6568. * encoding: gzip header.
  6569. * We can only do this if the browser declares support. */
  6570. if (conn->accept_gzip) {
  6571. mg_snprintf(
  6572. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6573. if (truncated) {
  6574. goto interpret_cleanup;
  6575. }
  6576. if (mg_stat(conn, gz_path, filestat)) {
  6577. if (filestat) {
  6578. filestat->is_gzipped = 1;
  6579. *is_found = 1;
  6580. }
  6581. /* Currently gz files can not be scripts. */
  6582. return;
  6583. }
  6584. }
  6585. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6586. /* Step 10: Script resources may handle sub-resources */
  6587. /* Support PATH_INFO for CGI scripts. */
  6588. tmp_str_len = strlen(filename);
  6589. tmp_str =
  6590. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6591. if (!tmp_str) {
  6592. /* Out of memory */
  6593. goto interpret_cleanup;
  6594. }
  6595. memcpy(tmp_str, filename, tmp_str_len + 1);
  6596. /* Check config, if index scripts may have sub-resources */
  6597. allow_substitute_script_subresources =
  6598. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6599. "yes");
  6600. if (*is_webdav_request) {
  6601. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6602. * PROPFIND fo their subresources? */
  6603. /* allow_substitute_script_subresources = 0; */
  6604. }
  6605. sep_pos = tmp_str_len;
  6606. while (sep_pos > 0) {
  6607. sep_pos--;
  6608. if (tmp_str[sep_pos] == '/') {
  6609. int is_script = 0, does_exist = 0;
  6610. tmp_str[sep_pos] = 0;
  6611. if (tmp_str[0]) {
  6612. is_script = extention_matches_script(conn, tmp_str);
  6613. does_exist = mg_stat(conn, tmp_str, filestat);
  6614. }
  6615. if (does_exist && is_script) {
  6616. filename[sep_pos] = 0;
  6617. memmove(filename + sep_pos + 2,
  6618. filename + sep_pos + 1,
  6619. strlen(filename + sep_pos + 1) + 1);
  6620. conn->path_info = filename + sep_pos + 1;
  6621. filename[sep_pos + 1] = '/';
  6622. *is_script_resource = 1;
  6623. *is_found = 1;
  6624. break;
  6625. }
  6626. if (allow_substitute_script_subresources) {
  6627. if (substitute_index_file(
  6628. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6629. /* some intermediate directory has an index file */
  6630. if (extention_matches_script(conn, tmp_str)) {
  6631. size_t script_name_len = strlen(tmp_str);
  6632. /* subres_name read before this memory locatio will be
  6633. overwritten */
  6634. char *subres_name = filename + sep_pos;
  6635. size_t subres_name_len = strlen(subres_name);
  6636. DEBUG_TRACE("Substitute script %s serving path %s",
  6637. tmp_str,
  6638. filename);
  6639. /* this index file is a script */
  6640. if ((script_name_len + subres_name_len + 2)
  6641. >= filename_buf_len) {
  6642. mg_free(tmp_str);
  6643. goto interpret_cleanup;
  6644. }
  6645. conn->path_info =
  6646. filename + script_name_len + 1; /* new target */
  6647. memmove(conn->path_info, subres_name, subres_name_len);
  6648. conn->path_info[subres_name_len] = 0;
  6649. memcpy(filename, tmp_str, script_name_len + 1);
  6650. *is_script_resource = 1;
  6651. *is_found = 1;
  6652. break;
  6653. } else {
  6654. DEBUG_TRACE("Substitute file %s serving path %s",
  6655. tmp_str,
  6656. filename);
  6657. /* non-script files will not have sub-resources */
  6658. filename[sep_pos] = 0;
  6659. conn->path_info = 0;
  6660. *is_script_resource = 0;
  6661. *is_found = 0;
  6662. break;
  6663. }
  6664. }
  6665. }
  6666. tmp_str[sep_pos] = '/';
  6667. }
  6668. }
  6669. mg_free(tmp_str);
  6670. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6671. #endif /* !defined(NO_FILES) */
  6672. return;
  6673. #if !defined(NO_FILES)
  6674. /* Reset all outputs */
  6675. interpret_cleanup:
  6676. memset(filestat, 0, sizeof(*filestat));
  6677. *filename = 0;
  6678. *is_found = 0;
  6679. *is_script_resource = 0;
  6680. *is_websocket_request = 0;
  6681. *is_put_or_delete_request = 0;
  6682. #endif /* !defined(NO_FILES) */
  6683. }
  6684. /* Check whether full request is buffered. Return:
  6685. * -1 if request or response is malformed
  6686. * 0 if request or response is not yet fully buffered
  6687. * >0 actual request length, including last \r\n\r\n */
  6688. static int
  6689. get_http_header_len(const char *buf, int buflen)
  6690. {
  6691. int i;
  6692. for (i = 0; i < buflen; i++) {
  6693. /* Do an unsigned comparison in some conditions below */
  6694. const unsigned char c = (unsigned char)buf[i];
  6695. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6696. && !isprint(c)) {
  6697. /* abort scan as soon as one malformed character is found */
  6698. return -1;
  6699. }
  6700. if (i < buflen - 1) {
  6701. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6702. /* Two newline, no carriage return - not standard compliant,
  6703. * but it should be accepted */
  6704. return i + 2;
  6705. }
  6706. }
  6707. if (i < buflen - 3) {
  6708. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6709. && (buf[i + 3] == '\n')) {
  6710. /* Two \r\n - standard compliant */
  6711. return i + 4;
  6712. }
  6713. }
  6714. }
  6715. return 0;
  6716. }
  6717. #if !defined(NO_CACHING)
  6718. /* Convert month to the month number. Return -1 on error, or month number */
  6719. static int
  6720. get_month_index(const char *s)
  6721. {
  6722. size_t i;
  6723. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6724. if (!strcmp(s, month_names[i])) {
  6725. return (int)i;
  6726. }
  6727. }
  6728. return -1;
  6729. }
  6730. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6731. static time_t
  6732. parse_date_string(const char *datetime)
  6733. {
  6734. char month_str[32] = {0};
  6735. int second, minute, hour, day, month, year;
  6736. time_t result = (time_t)0;
  6737. struct tm tm;
  6738. if ((sscanf(datetime,
  6739. "%d/%3s/%d %d:%d:%d",
  6740. &day,
  6741. month_str,
  6742. &year,
  6743. &hour,
  6744. &minute,
  6745. &second)
  6746. == 6)
  6747. || (sscanf(datetime,
  6748. "%d %3s %d %d:%d:%d",
  6749. &day,
  6750. month_str,
  6751. &year,
  6752. &hour,
  6753. &minute,
  6754. &second)
  6755. == 6)
  6756. || (sscanf(datetime,
  6757. "%*3s, %d %3s %d %d:%d:%d",
  6758. &day,
  6759. month_str,
  6760. &year,
  6761. &hour,
  6762. &minute,
  6763. &second)
  6764. == 6)
  6765. || (sscanf(datetime,
  6766. "%d-%3s-%d %d:%d:%d",
  6767. &day,
  6768. month_str,
  6769. &year,
  6770. &hour,
  6771. &minute,
  6772. &second)
  6773. == 6)) {
  6774. month = get_month_index(month_str);
  6775. if ((month >= 0) && (year >= 1970)) {
  6776. memset(&tm, 0, sizeof(tm));
  6777. tm.tm_year = year - 1900;
  6778. tm.tm_mon = month;
  6779. tm.tm_mday = day;
  6780. tm.tm_hour = hour;
  6781. tm.tm_min = minute;
  6782. tm.tm_sec = second;
  6783. result = timegm(&tm);
  6784. }
  6785. }
  6786. return result;
  6787. }
  6788. #endif /* !NO_CACHING */
  6789. /* Pre-process URIs according to RFC + protect against directory disclosure
  6790. * attacks by removing '..', excessive '/' and '\' characters */
  6791. static void
  6792. remove_dot_segments(char *inout)
  6793. {
  6794. /* Windows backend protection
  6795. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6796. * in URI by slash */
  6797. char *out_end = inout;
  6798. char *in = inout;
  6799. if (!in) {
  6800. /* Param error. */
  6801. return;
  6802. }
  6803. while (*in) {
  6804. if (*in == '\\') {
  6805. *in = '/';
  6806. }
  6807. in++;
  6808. }
  6809. /* Algorithm "remove_dot_segments" from
  6810. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6811. /* Step 1:
  6812. * The input buffer is initialized.
  6813. * The output buffer is initialized to the empty string.
  6814. */
  6815. in = inout;
  6816. /* Step 2:
  6817. * While the input buffer is not empty, loop as follows:
  6818. */
  6819. /* Less than out_end of the inout buffer is used as output, so keep
  6820. * condition: out_end <= in */
  6821. while (*in) {
  6822. /* Step 2a:
  6823. * If the input buffer begins with a prefix of "../" or "./",
  6824. * then remove that prefix from the input buffer;
  6825. */
  6826. if (!strncmp(in, "../", 3)) {
  6827. in += 3;
  6828. } else if (!strncmp(in, "./", 2)) {
  6829. in += 2;
  6830. }
  6831. /* otherwise */
  6832. /* Step 2b:
  6833. * if the input buffer begins with a prefix of "/./" or "/.",
  6834. * where "." is a complete path segment, then replace that
  6835. * prefix with "/" in the input buffer;
  6836. */
  6837. else if (!strncmp(in, "/./", 3)) {
  6838. in += 2;
  6839. } else if (!strcmp(in, "/.")) {
  6840. in[1] = 0;
  6841. }
  6842. /* otherwise */
  6843. /* Step 2c:
  6844. * if the input buffer begins with a prefix of "/../" or "/..",
  6845. * where ".." is a complete path segment, then replace that
  6846. * prefix with "/" in the input buffer and remove the last
  6847. * segment and its preceding "/" (if any) from the output
  6848. * buffer;
  6849. */
  6850. else if (!strncmp(in, "/../", 4)) {
  6851. in += 3;
  6852. if (inout != out_end) {
  6853. /* remove last segment */
  6854. do {
  6855. out_end--;
  6856. } while ((inout != out_end) && (*out_end != '/'));
  6857. }
  6858. } else if (!strcmp(in, "/..")) {
  6859. in[1] = 0;
  6860. if (inout != out_end) {
  6861. /* remove last segment */
  6862. do {
  6863. out_end--;
  6864. } while ((inout != out_end) && (*out_end != '/'));
  6865. }
  6866. }
  6867. /* otherwise */
  6868. /* Step 2d:
  6869. * if the input buffer consists only of "." or "..", then remove
  6870. * that from the input buffer;
  6871. */
  6872. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6873. *in = 0;
  6874. }
  6875. /* otherwise */
  6876. /* Step 2e:
  6877. * move the first path segment in the input buffer to the end of
  6878. * the output buffer, including the initial "/" character (if
  6879. * any) and any subsequent characters up to, but not including,
  6880. * the next "/" character or the end of the input buffer.
  6881. */
  6882. else {
  6883. do {
  6884. *out_end = *in;
  6885. out_end++;
  6886. in++;
  6887. } while ((*in != 0) && (*in != '/'));
  6888. }
  6889. }
  6890. /* Step 3:
  6891. * Finally, the output buffer is returned as the result of
  6892. * remove_dot_segments.
  6893. */
  6894. /* Terminate output */
  6895. *out_end = 0;
  6896. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6897. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6898. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6899. * or "//" anymore.
  6900. */
  6901. out_end = in = inout;
  6902. while (*in) {
  6903. if (*in == '.') {
  6904. /* remove . at the end or preceding of / */
  6905. char *in_ahead = in;
  6906. do {
  6907. in_ahead++;
  6908. } while (*in_ahead == '.');
  6909. if (*in_ahead == '/') {
  6910. in = in_ahead;
  6911. if ((out_end != inout) && (out_end[-1] == '/')) {
  6912. /* remove generated // */
  6913. out_end--;
  6914. }
  6915. } else if (*in_ahead == 0) {
  6916. in = in_ahead;
  6917. } else {
  6918. do {
  6919. *out_end++ = '.';
  6920. in++;
  6921. } while (in != in_ahead);
  6922. }
  6923. } else if (*in == '/') {
  6924. /* replace // by / */
  6925. *out_end++ = '/';
  6926. do {
  6927. in++;
  6928. } while (*in == '/');
  6929. } else {
  6930. *out_end++ = *in;
  6931. in++;
  6932. }
  6933. }
  6934. *out_end = 0;
  6935. }
  6936. static const struct {
  6937. const char *extension;
  6938. size_t ext_len;
  6939. const char *mime_type;
  6940. } builtin_mime_types[] = {
  6941. /* IANA registered MIME types
  6942. * (http://www.iana.org/assignments/media-types)
  6943. * application types */
  6944. {".bin", 4, "application/octet-stream"},
  6945. {".deb", 4, "application/octet-stream"},
  6946. {".dmg", 4, "application/octet-stream"},
  6947. {".dll", 4, "application/octet-stream"},
  6948. {".doc", 4, "application/msword"},
  6949. {".eps", 4, "application/postscript"},
  6950. {".exe", 4, "application/octet-stream"},
  6951. {".iso", 4, "application/octet-stream"},
  6952. {".js", 3, "application/javascript"},
  6953. {".json", 5, "application/json"},
  6954. {".msi", 4, "application/octet-stream"},
  6955. {".pdf", 4, "application/pdf"},
  6956. {".ps", 3, "application/postscript"},
  6957. {".rtf", 4, "application/rtf"},
  6958. {".xhtml", 6, "application/xhtml+xml"},
  6959. {".xsl", 4, "application/xml"},
  6960. {".xslt", 5, "application/xml"},
  6961. /* fonts */
  6962. {".ttf", 4, "application/font-sfnt"},
  6963. {".cff", 4, "application/font-sfnt"},
  6964. {".otf", 4, "application/font-sfnt"},
  6965. {".aat", 4, "application/font-sfnt"},
  6966. {".sil", 4, "application/font-sfnt"},
  6967. {".pfr", 4, "application/font-tdpfr"},
  6968. {".woff", 5, "application/font-woff"},
  6969. {".woff2", 6, "application/font-woff2"},
  6970. /* audio */
  6971. {".mp3", 4, "audio/mpeg"},
  6972. {".oga", 4, "audio/ogg"},
  6973. {".ogg", 4, "audio/ogg"},
  6974. /* image */
  6975. {".gif", 4, "image/gif"},
  6976. {".ief", 4, "image/ief"},
  6977. {".jpeg", 5, "image/jpeg"},
  6978. {".jpg", 4, "image/jpeg"},
  6979. {".jpm", 4, "image/jpm"},
  6980. {".jpx", 4, "image/jpx"},
  6981. {".png", 4, "image/png"},
  6982. {".svg", 4, "image/svg+xml"},
  6983. {".tif", 4, "image/tiff"},
  6984. {".tiff", 5, "image/tiff"},
  6985. /* model */
  6986. {".wrl", 4, "model/vrml"},
  6987. /* text */
  6988. {".css", 4, "text/css"},
  6989. {".csv", 4, "text/csv"},
  6990. {".htm", 4, "text/html"},
  6991. {".html", 5, "text/html"},
  6992. {".sgm", 4, "text/sgml"},
  6993. {".shtm", 5, "text/html"},
  6994. {".shtml", 6, "text/html"},
  6995. {".txt", 4, "text/plain"},
  6996. {".xml", 4, "text/xml"},
  6997. /* video */
  6998. {".mov", 4, "video/quicktime"},
  6999. {".mp4", 4, "video/mp4"},
  7000. {".mpeg", 5, "video/mpeg"},
  7001. {".mpg", 4, "video/mpeg"},
  7002. {".ogv", 4, "video/ogg"},
  7003. {".qt", 3, "video/quicktime"},
  7004. /* not registered types
  7005. * (http://reference.sitepoint.com/html/mime-types-full,
  7006. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7007. {".arj", 4, "application/x-arj-compressed"},
  7008. {".gz", 3, "application/x-gunzip"},
  7009. {".rar", 4, "application/x-arj-compressed"},
  7010. {".swf", 4, "application/x-shockwave-flash"},
  7011. {".tar", 4, "application/x-tar"},
  7012. {".tgz", 4, "application/x-tar-gz"},
  7013. {".torrent", 8, "application/x-bittorrent"},
  7014. {".ppt", 4, "application/x-mspowerpoint"},
  7015. {".xls", 4, "application/x-msexcel"},
  7016. {".zip", 4, "application/x-zip-compressed"},
  7017. {".aac",
  7018. 4,
  7019. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7020. {".flac", 5, "audio/flac"},
  7021. {".aif", 4, "audio/x-aif"},
  7022. {".m3u", 4, "audio/x-mpegurl"},
  7023. {".mid", 4, "audio/x-midi"},
  7024. {".ra", 3, "audio/x-pn-realaudio"},
  7025. {".ram", 4, "audio/x-pn-realaudio"},
  7026. {".wav", 4, "audio/x-wav"},
  7027. {".bmp", 4, "image/bmp"},
  7028. {".ico", 4, "image/x-icon"},
  7029. {".pct", 4, "image/x-pct"},
  7030. {".pict", 5, "image/pict"},
  7031. {".rgb", 4, "image/x-rgb"},
  7032. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7033. {".asf", 4, "video/x-ms-asf"},
  7034. {".avi", 4, "video/x-msvideo"},
  7035. {".m4v", 4, "video/x-m4v"},
  7036. {NULL, 0, NULL}};
  7037. CIVETWEB_API const char *
  7038. mg_get_builtin_mime_type(const char *path)
  7039. {
  7040. const char *ext;
  7041. size_t i, path_len;
  7042. path_len = strlen(path);
  7043. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7044. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7045. if ((path_len > builtin_mime_types[i].ext_len)
  7046. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7047. return builtin_mime_types[i].mime_type;
  7048. }
  7049. }
  7050. return "text/plain";
  7051. }
  7052. /* Look at the "path" extension and figure what mime type it has.
  7053. * Store mime type in the vector. */
  7054. static void
  7055. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7056. {
  7057. struct vec ext_vec, mime_vec;
  7058. const char *list, *ext;
  7059. size_t path_len;
  7060. path_len = strlen(path);
  7061. if ((conn == NULL) || (vec == NULL)) {
  7062. if (vec != NULL) {
  7063. memset(vec, '\0', sizeof(struct vec));
  7064. }
  7065. return;
  7066. }
  7067. /* Scan user-defined mime types first, in case user wants to
  7068. * override default mime types. */
  7069. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7070. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7071. /* ext now points to the path suffix */
  7072. ext = path + path_len - ext_vec.len;
  7073. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7074. *vec = mime_vec;
  7075. return;
  7076. }
  7077. }
  7078. vec->ptr = mg_get_builtin_mime_type(path);
  7079. vec->len = strlen(vec->ptr);
  7080. }
  7081. /* Stringify binary data. Output buffer must be twice as big as input,
  7082. * because each byte takes 2 bytes in string representation */
  7083. static void
  7084. bin2str(char *to, const unsigned char *p, size_t len)
  7085. {
  7086. static const char *hex = "0123456789abcdef";
  7087. for (; len--; p++) {
  7088. *to++ = hex[p[0] >> 4];
  7089. *to++ = hex[p[0] & 0x0f];
  7090. }
  7091. *to = '\0';
  7092. }
  7093. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7094. */
  7095. CIVETWEB_API char *
  7096. mg_md5(char buf[33], ...)
  7097. {
  7098. md5_byte_t hash[16];
  7099. const char *p;
  7100. va_list ap;
  7101. md5_state_t ctx;
  7102. md5_init(&ctx);
  7103. va_start(ap, buf);
  7104. while ((p = va_arg(ap, const char *)) != NULL) {
  7105. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7106. }
  7107. va_end(ap);
  7108. md5_finish(&ctx, hash);
  7109. bin2str(buf, hash, sizeof(hash));
  7110. return buf;
  7111. }
  7112. /* Check the user's password, return 1 if OK */
  7113. static int
  7114. check_password(const char *method,
  7115. const char *ha1,
  7116. const char *uri,
  7117. const char *nonce,
  7118. const char *nc,
  7119. const char *cnonce,
  7120. const char *qop,
  7121. const char *response)
  7122. {
  7123. char ha2[32 + 1], expected_response[32 + 1];
  7124. /* Some of the parameters may be NULL */
  7125. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7126. || (qop == NULL) || (response == NULL)) {
  7127. return 0;
  7128. }
  7129. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7130. if (strlen(response) != 32) {
  7131. return 0;
  7132. }
  7133. mg_md5(ha2, method, ":", uri, NULL);
  7134. mg_md5(expected_response,
  7135. ha1,
  7136. ":",
  7137. nonce,
  7138. ":",
  7139. nc,
  7140. ":",
  7141. cnonce,
  7142. ":",
  7143. qop,
  7144. ":",
  7145. ha2,
  7146. NULL);
  7147. return mg_strcasecmp(response, expected_response) == 0;
  7148. }
  7149. #if !defined(NO_FILESYSTEMS)
  7150. /* Use the global passwords file, if specified by auth_gpass option,
  7151. * or search for .htpasswd in the requested directory. */
  7152. static void
  7153. open_auth_file(struct mg_connection *conn,
  7154. const char *path,
  7155. struct mg_file *filep)
  7156. {
  7157. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7158. char name[UTF8_PATH_MAX];
  7159. const char *p, *e,
  7160. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7161. int truncated;
  7162. if (gpass != NULL) {
  7163. /* Use global passwords file */
  7164. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7165. #if defined(DEBUG)
  7166. /* Use mg_cry_internal here, since gpass has been
  7167. * configured. */
  7168. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7169. #endif
  7170. }
  7171. /* Important: using local struct mg_file to test path for
  7172. * is_directory flag. If filep is used, mg_stat() makes it
  7173. * appear as if auth file was opened.
  7174. * TODO(mid): Check if this is still required after rewriting
  7175. * mg_stat */
  7176. } else if (mg_stat(conn, path, &filep->stat)
  7177. && filep->stat.is_directory) {
  7178. mg_snprintf(conn,
  7179. &truncated,
  7180. name,
  7181. sizeof(name),
  7182. "%s/%s",
  7183. path,
  7184. PASSWORDS_FILE_NAME);
  7185. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7186. #if defined(DEBUG)
  7187. /* Don't use mg_cry_internal here, but only a trace, since
  7188. * this is a typical case. It will occur for every directory
  7189. * without a password file. */
  7190. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7191. #endif
  7192. }
  7193. } else {
  7194. /* Try to find .htpasswd in requested directory. */
  7195. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7196. if (e[0] == '/') {
  7197. break;
  7198. }
  7199. }
  7200. mg_snprintf(conn,
  7201. &truncated,
  7202. name,
  7203. sizeof(name),
  7204. "%.*s/%s",
  7205. (int)(e - p),
  7206. p,
  7207. PASSWORDS_FILE_NAME);
  7208. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7209. #if defined(DEBUG)
  7210. /* Don't use mg_cry_internal here, but only a trace, since
  7211. * this is a typical case. It will occur for every directory
  7212. * without a password file. */
  7213. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7214. #endif
  7215. }
  7216. }
  7217. }
  7218. }
  7219. #endif /* NO_FILESYSTEMS */
  7220. /* Parsed Authorization header */
  7221. struct ah {
  7222. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7223. };
  7224. /* Return 1 on success. Always initializes the ah structure. */
  7225. static int
  7226. parse_auth_header(struct mg_connection *conn,
  7227. char *buf,
  7228. size_t buf_size,
  7229. struct ah *ah)
  7230. {
  7231. char *name, *value, *s;
  7232. const char *auth_header;
  7233. uint64_t nonce;
  7234. if (!ah || !conn) {
  7235. return 0;
  7236. }
  7237. (void)memset(ah, 0, sizeof(*ah));
  7238. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7239. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7240. return 0;
  7241. }
  7242. /* Make modifiable copy of the auth header */
  7243. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7244. s = buf;
  7245. /* Parse authorization header */
  7246. for (;;) {
  7247. /* Gobble initial spaces */
  7248. while (isspace((unsigned char)*s)) {
  7249. s++;
  7250. }
  7251. name = skip_quoted(&s, "=", " ", 0);
  7252. /* Value is either quote-delimited, or ends at first comma or space.
  7253. */
  7254. if (s[0] == '\"') {
  7255. s++;
  7256. value = skip_quoted(&s, "\"", " ", '\\');
  7257. if (s[0] == ',') {
  7258. s++;
  7259. }
  7260. } else {
  7261. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7262. * uses spaces */
  7263. }
  7264. if (*name == '\0') {
  7265. break;
  7266. }
  7267. if (!strcmp(name, "username")) {
  7268. ah->user = value;
  7269. } else if (!strcmp(name, "cnonce")) {
  7270. ah->cnonce = value;
  7271. } else if (!strcmp(name, "response")) {
  7272. ah->response = value;
  7273. } else if (!strcmp(name, "uri")) {
  7274. ah->uri = value;
  7275. } else if (!strcmp(name, "qop")) {
  7276. ah->qop = value;
  7277. } else if (!strcmp(name, "nc")) {
  7278. ah->nc = value;
  7279. } else if (!strcmp(name, "nonce")) {
  7280. ah->nonce = value;
  7281. }
  7282. }
  7283. #if !defined(NO_NONCE_CHECK)
  7284. /* Read the nonce from the response. */
  7285. if (ah->nonce == NULL) {
  7286. return 0;
  7287. }
  7288. s = NULL;
  7289. nonce = strtoull(ah->nonce, &s, 10);
  7290. if ((s == NULL) || (*s != 0)) {
  7291. return 0;
  7292. }
  7293. /* Convert the nonce from the client to a number. */
  7294. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7295. /* The converted number corresponds to the time the nounce has been
  7296. * created. This should not be earlier than the server start. */
  7297. /* Server side nonce check is valuable in all situations but one:
  7298. * if the server restarts frequently, but the client should not see
  7299. * that, so the server should accept nonces from previous starts. */
  7300. /* However, the reasonable default is to not accept a nonce from a
  7301. * previous start, so if anyone changed the access rights between
  7302. * two restarts, a new login is required. */
  7303. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7304. /* nonce is from a previous start of the server and no longer valid
  7305. * (replay attack?) */
  7306. return 0;
  7307. }
  7308. /* Check if the nonce is too high, so it has not (yet) been used by the
  7309. * server. */
  7310. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7311. + conn->dom_ctx->nonce_count)) {
  7312. return 0;
  7313. }
  7314. #else
  7315. (void)nonce;
  7316. #endif
  7317. /* CGI needs it as REMOTE_USER */
  7318. if (ah->user != NULL) {
  7319. conn->request_info.remote_user =
  7320. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7321. } else {
  7322. return 0;
  7323. }
  7324. return 1;
  7325. }
  7326. static const char *
  7327. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7328. {
  7329. if (!filep) {
  7330. return NULL;
  7331. }
  7332. if (filep->access.fp != NULL) {
  7333. return fgets(buf, (int)size, filep->access.fp);
  7334. } else {
  7335. return NULL;
  7336. }
  7337. }
  7338. /* Define the initial recursion depth for procesesing htpasswd files that
  7339. * include other htpasswd
  7340. * (or even the same) files. It is not difficult to provide a file or files
  7341. * s.t. they force civetweb
  7342. * to infinitely recurse and then crash.
  7343. */
  7344. #define INITIAL_DEPTH 9
  7345. #if INITIAL_DEPTH <= 0
  7346. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7347. #endif
  7348. #if !defined(NO_FILESYSTEMS)
  7349. struct read_auth_file_struct {
  7350. struct mg_connection *conn;
  7351. struct ah ah;
  7352. const char *domain;
  7353. char buf[256 + 256 + 40];
  7354. const char *f_user;
  7355. const char *f_domain;
  7356. const char *f_ha1;
  7357. };
  7358. static int
  7359. read_auth_file(struct mg_file *filep,
  7360. struct read_auth_file_struct *workdata,
  7361. int depth)
  7362. {
  7363. int is_authorized = 0;
  7364. struct mg_file fp;
  7365. size_t l;
  7366. if (!filep || !workdata || (0 == depth)) {
  7367. return 0;
  7368. }
  7369. /* Loop over passwords file */
  7370. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7371. l = strlen(workdata->buf);
  7372. while (l > 0) {
  7373. if (isspace((unsigned char)workdata->buf[l - 1])
  7374. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7375. l--;
  7376. workdata->buf[l] = 0;
  7377. } else
  7378. break;
  7379. }
  7380. if (l < 1) {
  7381. continue;
  7382. }
  7383. workdata->f_user = workdata->buf;
  7384. if (workdata->f_user[0] == ':') {
  7385. /* user names may not contain a ':' and may not be empty,
  7386. * so lines starting with ':' may be used for a special purpose
  7387. */
  7388. if (workdata->f_user[1] == '#') {
  7389. /* :# is a comment */
  7390. continue;
  7391. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7392. if (mg_fopen(workdata->conn,
  7393. workdata->f_user + 9,
  7394. MG_FOPEN_MODE_READ,
  7395. &fp)) {
  7396. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7397. (void)mg_fclose(
  7398. &fp.access); /* ignore error on read only file */
  7399. /* No need to continue processing files once we have a
  7400. * match, since nothing will reset it back
  7401. * to 0.
  7402. */
  7403. if (is_authorized) {
  7404. return is_authorized;
  7405. }
  7406. } else {
  7407. mg_cry_internal(workdata->conn,
  7408. "%s: cannot open authorization file: %s",
  7409. __func__,
  7410. workdata->buf);
  7411. }
  7412. continue;
  7413. }
  7414. /* everything is invalid for the moment (might change in the
  7415. * future) */
  7416. mg_cry_internal(workdata->conn,
  7417. "%s: syntax error in authorization file: %s",
  7418. __func__,
  7419. workdata->buf);
  7420. continue;
  7421. }
  7422. workdata->f_domain = strchr(workdata->f_user, ':');
  7423. if (workdata->f_domain == NULL) {
  7424. mg_cry_internal(workdata->conn,
  7425. "%s: syntax error in authorization file: %s",
  7426. __func__,
  7427. workdata->buf);
  7428. continue;
  7429. }
  7430. *(char *)(workdata->f_domain) = 0;
  7431. (workdata->f_domain)++;
  7432. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7433. if (workdata->f_ha1 == NULL) {
  7434. mg_cry_internal(workdata->conn,
  7435. "%s: syntax error in authorization file: %s",
  7436. __func__,
  7437. workdata->buf);
  7438. continue;
  7439. }
  7440. *(char *)(workdata->f_ha1) = 0;
  7441. (workdata->f_ha1)++;
  7442. if (!strcmp(workdata->ah.user, workdata->f_user)
  7443. && !strcmp(workdata->domain, workdata->f_domain)) {
  7444. return check_password(workdata->conn->request_info.request_method,
  7445. workdata->f_ha1,
  7446. workdata->ah.uri,
  7447. workdata->ah.nonce,
  7448. workdata->ah.nc,
  7449. workdata->ah.cnonce,
  7450. workdata->ah.qop,
  7451. workdata->ah.response);
  7452. }
  7453. }
  7454. return is_authorized;
  7455. }
  7456. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7457. static int
  7458. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7459. {
  7460. struct read_auth_file_struct workdata;
  7461. char buf[MG_BUF_LEN];
  7462. if (!conn || !conn->dom_ctx) {
  7463. return 0;
  7464. }
  7465. memset(&workdata, 0, sizeof(workdata));
  7466. workdata.conn = conn;
  7467. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7468. return 0;
  7469. }
  7470. if (realm) {
  7471. workdata.domain = realm;
  7472. } else {
  7473. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7474. }
  7475. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7476. }
  7477. /* Public function to check http digest authentication header */
  7478. CIVETWEB_API int
  7479. mg_check_digest_access_authentication(struct mg_connection *conn,
  7480. const char *realm,
  7481. const char *filename)
  7482. {
  7483. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7484. int auth;
  7485. if (!conn || !filename) {
  7486. return -1;
  7487. }
  7488. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7489. return -2;
  7490. }
  7491. auth = authorize(conn, &file, realm);
  7492. mg_fclose(&file.access);
  7493. return auth;
  7494. }
  7495. #endif /* NO_FILESYSTEMS */
  7496. /* Return 1 if request is authorised, 0 otherwise. */
  7497. static int
  7498. check_authorization(struct mg_connection *conn, const char *path)
  7499. {
  7500. #if !defined(NO_FILESYSTEMS)
  7501. char fname[UTF8_PATH_MAX];
  7502. struct vec uri_vec, filename_vec;
  7503. const char *list;
  7504. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7505. int authorized = 1, truncated;
  7506. if (!conn || !conn->dom_ctx) {
  7507. return 0;
  7508. }
  7509. list = conn->dom_ctx->config[PROTECT_URI];
  7510. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7511. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7512. mg_snprintf(conn,
  7513. &truncated,
  7514. fname,
  7515. sizeof(fname),
  7516. "%.*s",
  7517. (int)filename_vec.len,
  7518. filename_vec.ptr);
  7519. if (truncated
  7520. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7521. mg_cry_internal(conn,
  7522. "%s: cannot open %s: %s",
  7523. __func__,
  7524. fname,
  7525. strerror(errno));
  7526. }
  7527. break;
  7528. }
  7529. }
  7530. if (!is_file_opened(&file.access)) {
  7531. open_auth_file(conn, path, &file);
  7532. }
  7533. if (is_file_opened(&file.access)) {
  7534. authorized = authorize(conn, &file, NULL);
  7535. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7536. }
  7537. return authorized;
  7538. #else
  7539. (void)conn;
  7540. (void)path;
  7541. return 1;
  7542. #endif /* NO_FILESYSTEMS */
  7543. }
  7544. /* Internal function. Assumes conn is valid */
  7545. static void
  7546. send_authorization_request(struct mg_connection *conn, const char *realm)
  7547. {
  7548. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7549. int trunc = 0;
  7550. char buf[128];
  7551. if (!realm) {
  7552. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7553. }
  7554. mg_lock_context(conn->phys_ctx);
  7555. nonce += conn->dom_ctx->nonce_count;
  7556. ++conn->dom_ctx->nonce_count;
  7557. mg_unlock_context(conn->phys_ctx);
  7558. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7559. conn->must_close = 1;
  7560. /* Create 401 response */
  7561. mg_response_header_start(conn, 401);
  7562. send_no_cache_header(conn);
  7563. send_additional_header(conn);
  7564. mg_response_header_add(conn, "Content-Length", "0", -1);
  7565. /* Content for "WWW-Authenticate" header */
  7566. mg_snprintf(conn,
  7567. &trunc,
  7568. buf,
  7569. sizeof(buf),
  7570. "Digest qop=\"auth\", realm=\"%s\", "
  7571. "nonce=\"%" UINT64_FMT "\"",
  7572. realm,
  7573. nonce);
  7574. if (!trunc) {
  7575. /* !trunc should always be true */
  7576. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7577. }
  7578. /* Send all headers */
  7579. mg_response_header_send(conn);
  7580. }
  7581. /* Interface function. Parameters are provided by the user, so do
  7582. * at least some basic checks.
  7583. */
  7584. CIVETWEB_API int
  7585. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7586. const char *realm)
  7587. {
  7588. if (conn && conn->dom_ctx) {
  7589. send_authorization_request(conn, realm);
  7590. return 0;
  7591. }
  7592. return -1;
  7593. }
  7594. #if !defined(NO_FILES)
  7595. static int
  7596. is_authorized_for_put(struct mg_connection *conn)
  7597. {
  7598. int ret = 0;
  7599. if (conn) {
  7600. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7601. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7602. if (passfile != NULL
  7603. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7604. ret = authorize(conn, &file, NULL);
  7605. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7606. }
  7607. }
  7608. DEBUG_TRACE("file write autorization: %i", ret);
  7609. return ret;
  7610. }
  7611. #endif
  7612. CIVETWEB_API int
  7613. mg_modify_passwords_file_ha1(const char *fname,
  7614. const char *domain,
  7615. const char *user,
  7616. const char *ha1)
  7617. {
  7618. int found = 0, i, result = 1;
  7619. char line[512], u[256], d[256], h[256];
  7620. struct stat st = {0};
  7621. FILE *fp = NULL;
  7622. char *temp_file = NULL;
  7623. int temp_file_offs = 0;
  7624. /* Regard empty password as no password - remove user record. */
  7625. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7626. ha1 = NULL;
  7627. }
  7628. /* Other arguments must not be empty */
  7629. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7630. return 0;
  7631. }
  7632. /* Using the given file format, user name and domain must not contain
  7633. * the ':' character */
  7634. if (strchr(user, ':') != NULL) {
  7635. return 0;
  7636. }
  7637. if (strchr(domain, ':') != NULL) {
  7638. return 0;
  7639. }
  7640. /* Do not allow control characters like newline in user name and domain.
  7641. * Do not allow excessively long names either. */
  7642. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7643. if (iscntrl((unsigned char)user[i])) {
  7644. return 0;
  7645. }
  7646. }
  7647. if (user[i]) {
  7648. return 0; /* user name too long */
  7649. }
  7650. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7651. if (iscntrl((unsigned char)domain[i])) {
  7652. return 0;
  7653. }
  7654. }
  7655. if (domain[i]) {
  7656. return 0; /* domain name too long */
  7657. }
  7658. /* The maximum length of the path to the password file is limited */
  7659. if (strlen(fname) >= UTF8_PATH_MAX) {
  7660. return 0;
  7661. }
  7662. /* Check if the file exists, and get file size */
  7663. if (0 == stat(fname, &st)) {
  7664. int temp_buf_len = (int)st.st_size + 1024;
  7665. /* Allocate memory (instead of using a temporary file) */
  7666. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7667. if (!temp_file) {
  7668. /* Out of memory */
  7669. return 0;
  7670. }
  7671. /* File exists. Read it into a memory buffer. */
  7672. fp = fopen(fname, "r");
  7673. if (fp == NULL) {
  7674. /* Cannot read file. No permission? */
  7675. mg_free(temp_file);
  7676. return 0;
  7677. }
  7678. /* Read content and store in memory */
  7679. while ((fgets(line, sizeof(line), fp) != NULL)
  7680. && ((temp_file_offs + 600) < temp_buf_len)) {
  7681. /* file format is "user:domain:hash\n" */
  7682. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7683. continue;
  7684. }
  7685. u[255] = 0;
  7686. d[255] = 0;
  7687. h[255] = 0;
  7688. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7689. /* Found the user: change the password hash or drop the user
  7690. */
  7691. if ((ha1 != NULL) && (!found)) {
  7692. i = sprintf(temp_file + temp_file_offs,
  7693. "%s:%s:%s\n",
  7694. user,
  7695. domain,
  7696. ha1);
  7697. if (i < 1) {
  7698. fclose(fp);
  7699. mg_free(temp_file);
  7700. return 0;
  7701. }
  7702. temp_file_offs += i;
  7703. }
  7704. found = 1;
  7705. } else {
  7706. /* Copy existing user, including password hash */
  7707. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7708. if (i < 1) {
  7709. fclose(fp);
  7710. mg_free(temp_file);
  7711. return 0;
  7712. }
  7713. temp_file_offs += i;
  7714. }
  7715. }
  7716. fclose(fp);
  7717. }
  7718. /* Create new file */
  7719. fp = fopen(fname, "w");
  7720. if (!fp) {
  7721. mg_free(temp_file);
  7722. return 0;
  7723. }
  7724. #if !defined(_WIN32)
  7725. /* On Linux & co., restrict file read/write permissions to the owner */
  7726. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7727. result = 0;
  7728. }
  7729. #endif
  7730. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7731. /* Store buffered content of old file */
  7732. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7733. != (size_t)temp_file_offs) {
  7734. result = 0;
  7735. }
  7736. }
  7737. /* If new user, just add it */
  7738. if ((ha1 != NULL) && (!found)) {
  7739. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7740. result = 0;
  7741. }
  7742. }
  7743. /* All data written */
  7744. if (fclose(fp) != 0) {
  7745. result = 0;
  7746. }
  7747. mg_free(temp_file);
  7748. return result;
  7749. }
  7750. CIVETWEB_API int
  7751. mg_modify_passwords_file(const char *fname,
  7752. const char *domain,
  7753. const char *user,
  7754. const char *pass)
  7755. {
  7756. char ha1buf[33];
  7757. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7758. return 0;
  7759. }
  7760. if ((pass == NULL) || (pass[0] == 0)) {
  7761. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7762. }
  7763. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7764. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7765. }
  7766. static int
  7767. is_valid_port(unsigned long port)
  7768. {
  7769. return (port <= 0xffff);
  7770. }
  7771. static int
  7772. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7773. {
  7774. struct addrinfo hints, *res, *ressave;
  7775. int func_ret = 0;
  7776. int gai_ret;
  7777. memset(&hints, 0, sizeof(struct addrinfo));
  7778. hints.ai_family = af;
  7779. if (!resolve_src) {
  7780. hints.ai_flags = AI_NUMERICHOST;
  7781. }
  7782. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7783. if (gai_ret != 0) {
  7784. /* gai_strerror could be used to convert gai_ret to a string */
  7785. /* POSIX return values: see
  7786. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7787. */
  7788. /* Windows return values: see
  7789. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7790. */
  7791. return 0;
  7792. }
  7793. ressave = res;
  7794. while (res) {
  7795. if ((dstlen >= (size_t)res->ai_addrlen)
  7796. && (res->ai_addr->sa_family == af)) {
  7797. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7798. func_ret = 1;
  7799. }
  7800. res = res->ai_next;
  7801. }
  7802. freeaddrinfo(ressave);
  7803. return func_ret;
  7804. }
  7805. static int
  7806. connect_socket(
  7807. struct mg_context *ctx /* may be NULL */,
  7808. const char *host,
  7809. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7810. int use_ssl, /* 0 or 1 */
  7811. struct mg_error_data *error,
  7812. SOCKET *sock /* output: socket, must not be NULL */,
  7813. union usa *sa /* output: socket address, must not be NULL */
  7814. )
  7815. {
  7816. int ip_ver = 0;
  7817. int conn_ret = -1;
  7818. int sockerr = 0;
  7819. *sock = INVALID_SOCKET;
  7820. memset(sa, 0, sizeof(*sa));
  7821. if (host == NULL) {
  7822. if (error != NULL) {
  7823. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7824. mg_snprintf(NULL,
  7825. NULL, /* No truncation check for ebuf */
  7826. error->text,
  7827. error->text_buffer_size,
  7828. "%s",
  7829. "NULL host");
  7830. }
  7831. return 0;
  7832. }
  7833. #if defined(USE_X_DOM_SOCKET)
  7834. if (port == -99) {
  7835. /* Unix domain socket */
  7836. size_t hostlen = strlen(host);
  7837. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7838. if (error != NULL) {
  7839. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7840. mg_snprintf(NULL,
  7841. NULL, /* No truncation check for ebuf */
  7842. error->text,
  7843. error->text_buffer_size,
  7844. "%s",
  7845. "host length exceeds limit");
  7846. }
  7847. return 0;
  7848. }
  7849. } else
  7850. #endif
  7851. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7852. if (error != NULL) {
  7853. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  7854. mg_snprintf(NULL,
  7855. NULL, /* No truncation check for ebuf */
  7856. error->text,
  7857. error->text_buffer_size,
  7858. "%s",
  7859. "invalid port");
  7860. }
  7861. return 0;
  7862. }
  7863. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7864. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7865. if (use_ssl && (TLS_client_method == NULL)) {
  7866. if (error != NULL) {
  7867. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7868. mg_snprintf(NULL,
  7869. NULL, /* No truncation check for ebuf */
  7870. error->text,
  7871. error->text_buffer_size,
  7872. "%s",
  7873. "SSL is not initialized");
  7874. }
  7875. return 0;
  7876. }
  7877. #else
  7878. if (use_ssl && (SSLv23_client_method == NULL)) {
  7879. if (error != 0) {
  7880. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  7881. mg_snprintf(NULL,
  7882. NULL, /* No truncation check for ebuf */
  7883. error->text,
  7884. error->text_buffer_size,
  7885. "%s",
  7886. "SSL is not initialized");
  7887. }
  7888. return 0;
  7889. }
  7890. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7891. #else
  7892. (void)use_ssl;
  7893. #endif /* NO SSL */
  7894. #if defined(USE_X_DOM_SOCKET)
  7895. if (port == -99) {
  7896. size_t hostlen = strlen(host);
  7897. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7898. ip_ver = -99;
  7899. sa->sun.sun_family = AF_UNIX;
  7900. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7901. memcpy(sa->sun.sun_path, host, hostlen);
  7902. } else
  7903. #endif
  7904. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7905. sa->sin.sin_port = htons((uint16_t)port);
  7906. ip_ver = 4;
  7907. #if defined(USE_IPV6)
  7908. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7909. sa->sin6.sin6_port = htons((uint16_t)port);
  7910. ip_ver = 6;
  7911. } else if (host[0] == '[') {
  7912. /* While getaddrinfo on Windows will work with [::1],
  7913. * getaddrinfo on Linux only works with ::1 (without []). */
  7914. size_t l = strlen(host + 1);
  7915. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7916. if (h) {
  7917. h[l - 1] = 0;
  7918. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7919. sa->sin6.sin6_port = htons((uint16_t)port);
  7920. ip_ver = 6;
  7921. }
  7922. mg_free(h);
  7923. }
  7924. #endif
  7925. }
  7926. if (ip_ver == 0) {
  7927. if (error != NULL) {
  7928. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  7929. mg_snprintf(NULL,
  7930. NULL, /* No truncation check for ebuf */
  7931. error->text,
  7932. error->text_buffer_size,
  7933. "%s",
  7934. "host not found");
  7935. }
  7936. return 0;
  7937. }
  7938. if (ip_ver == 4) {
  7939. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7940. }
  7941. #if defined(USE_IPV6)
  7942. else if (ip_ver == 6) {
  7943. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7944. }
  7945. #endif
  7946. #if defined(USE_X_DOM_SOCKET)
  7947. else if (ip_ver == -99) {
  7948. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7949. }
  7950. #endif
  7951. if (*sock == INVALID_SOCKET) {
  7952. if (error != NULL) {
  7953. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  7954. error->code_sub = ERRNO;
  7955. mg_snprintf(NULL,
  7956. NULL, /* No truncation check for ebuf */
  7957. error->text,
  7958. error->text_buffer_size,
  7959. "socket(): %s",
  7960. strerror(ERRNO));
  7961. }
  7962. return 0;
  7963. }
  7964. if (0 != set_non_blocking_mode(*sock)) {
  7965. if (error != NULL) {
  7966. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  7967. error->code_sub = ERRNO;
  7968. mg_snprintf(NULL,
  7969. NULL, /* No truncation check for ebuf */
  7970. error->text,
  7971. error->text_buffer_size,
  7972. "Cannot set socket to non-blocking: %s",
  7973. strerror(ERRNO));
  7974. }
  7975. closesocket(*sock);
  7976. *sock = INVALID_SOCKET;
  7977. return 0;
  7978. }
  7979. set_close_on_exec(*sock, NULL, ctx);
  7980. if (ip_ver == 4) {
  7981. /* connected with IPv4 */
  7982. conn_ret = connect(*sock,
  7983. (struct sockaddr *)((void *)&sa->sin),
  7984. sizeof(sa->sin));
  7985. }
  7986. #if defined(USE_IPV6)
  7987. else if (ip_ver == 6) {
  7988. /* connected with IPv6 */
  7989. conn_ret = connect(*sock,
  7990. (struct sockaddr *)((void *)&sa->sin6),
  7991. sizeof(sa->sin6));
  7992. }
  7993. #endif
  7994. #if defined(USE_X_DOM_SOCKET)
  7995. else if (ip_ver == -99) {
  7996. /* connected to domain socket */
  7997. conn_ret = connect(*sock,
  7998. (struct sockaddr *)((void *)&sa->sun),
  7999. sizeof(sa->sun));
  8000. }
  8001. #endif
  8002. if (conn_ret != 0) {
  8003. sockerr = ERRNO;
  8004. }
  8005. #if defined(_WIN32)
  8006. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8007. #else
  8008. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8009. #endif
  8010. /* Data for getsockopt */
  8011. void *psockerr = &sockerr;
  8012. int ret;
  8013. #if defined(_WIN32)
  8014. int len = (int)sizeof(sockerr);
  8015. #else
  8016. socklen_t len = (socklen_t)sizeof(sockerr);
  8017. #endif
  8018. /* Data for poll */
  8019. struct mg_pollfd pfd[1];
  8020. int pollres;
  8021. int ms_wait = 10000; /* 10 second timeout */
  8022. stop_flag_t nonstop;
  8023. STOP_FLAG_ASSIGN(&nonstop, 0);
  8024. /* For a non-blocking socket, the connect sequence is:
  8025. * 1) call connect (will not block)
  8026. * 2) wait until the socket is ready for writing (select or poll)
  8027. * 3) check connection state with getsockopt
  8028. */
  8029. pfd[0].fd = *sock;
  8030. pfd[0].events = POLLOUT;
  8031. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8032. if (pollres != 1) {
  8033. /* Not connected */
  8034. if (error != NULL) {
  8035. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8036. mg_snprintf(NULL,
  8037. NULL, /* No truncation check for ebuf */
  8038. error->text,
  8039. error->text_buffer_size,
  8040. "connect(%s:%d): timeout",
  8041. host,
  8042. port);
  8043. }
  8044. closesocket(*sock);
  8045. *sock = INVALID_SOCKET;
  8046. return 0;
  8047. }
  8048. #if defined(_WIN32)
  8049. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8050. #else
  8051. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8052. #endif
  8053. if ((ret == 0) && (sockerr == 0)) {
  8054. conn_ret = 0;
  8055. }
  8056. }
  8057. if (conn_ret != 0) {
  8058. /* Not connected */
  8059. if (error != NULL) {
  8060. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8061. error->code_sub = ERRNO;
  8062. mg_snprintf(NULL,
  8063. NULL, /* No truncation check for ebuf */
  8064. error->text,
  8065. error->text_buffer_size,
  8066. "connect(%s:%d): error %s",
  8067. host,
  8068. port,
  8069. strerror(sockerr));
  8070. }
  8071. closesocket(*sock);
  8072. *sock = INVALID_SOCKET;
  8073. return 0;
  8074. }
  8075. return 1;
  8076. }
  8077. CIVETWEB_API int
  8078. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8079. {
  8080. static const char *dont_escape = "._-$,;~()";
  8081. static const char *hex = "0123456789abcdef";
  8082. char *pos = dst;
  8083. const char *end = dst + dst_len - 1;
  8084. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8085. if (isalnum((unsigned char)*src)
  8086. || (strchr(dont_escape, *src) != NULL)) {
  8087. *pos = *src;
  8088. } else if (pos + 2 < end) {
  8089. pos[0] = '%';
  8090. pos[1] = hex[(unsigned char)*src >> 4];
  8091. pos[2] = hex[(unsigned char)*src & 0xf];
  8092. pos += 2;
  8093. } else {
  8094. break;
  8095. }
  8096. }
  8097. *pos = '\0';
  8098. return (*src == '\0') ? (int)(pos - dst) : -1;
  8099. }
  8100. /* Return 0 on success, non-zero if an error occurs. */
  8101. static int
  8102. print_dir_entry(struct mg_connection *conn, struct de *de)
  8103. {
  8104. size_t namesize, escsize, i;
  8105. char *href, *esc, *p;
  8106. char size[64], mod[64];
  8107. #if defined(REENTRANT_TIME)
  8108. struct tm _tm;
  8109. struct tm *tm = &_tm;
  8110. #else
  8111. struct tm *tm;
  8112. #endif
  8113. /* Estimate worst case size for encoding and escaping */
  8114. namesize = strlen(de->file_name) + 1;
  8115. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8116. href = (char *)mg_malloc(namesize * 3 + escsize);
  8117. if (href == NULL) {
  8118. return -1;
  8119. }
  8120. mg_url_encode(de->file_name, href, namesize * 3);
  8121. esc = NULL;
  8122. if (escsize > 0) {
  8123. /* HTML escaping needed */
  8124. esc = href + namesize * 3;
  8125. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8126. mg_strlcpy(p, de->file_name + i, 2);
  8127. if (*p == '&') {
  8128. strcpy(p, "&amp;");
  8129. } else if (*p == '<') {
  8130. strcpy(p, "&lt;");
  8131. } else if (*p == '>') {
  8132. strcpy(p, "&gt;");
  8133. }
  8134. }
  8135. }
  8136. if (de->file.is_directory) {
  8137. mg_snprintf(conn,
  8138. NULL, /* Buffer is big enough */
  8139. size,
  8140. sizeof(size),
  8141. "%s",
  8142. "[DIRECTORY]");
  8143. } else {
  8144. /* We use (signed) cast below because MSVC 6 compiler cannot
  8145. * convert unsigned __int64 to double. Sigh. */
  8146. if (de->file.size < 1024) {
  8147. mg_snprintf(conn,
  8148. NULL, /* Buffer is big enough */
  8149. size,
  8150. sizeof(size),
  8151. "%d",
  8152. (int)de->file.size);
  8153. } else if (de->file.size < 0x100000) {
  8154. mg_snprintf(conn,
  8155. NULL, /* Buffer is big enough */
  8156. size,
  8157. sizeof(size),
  8158. "%.1fk",
  8159. (double)de->file.size / 1024.0);
  8160. } else if (de->file.size < 0x40000000) {
  8161. mg_snprintf(conn,
  8162. NULL, /* Buffer is big enough */
  8163. size,
  8164. sizeof(size),
  8165. "%.1fM",
  8166. (double)de->file.size / 1048576);
  8167. } else {
  8168. mg_snprintf(conn,
  8169. NULL, /* Buffer is big enough */
  8170. size,
  8171. sizeof(size),
  8172. "%.1fG",
  8173. (double)de->file.size / 1073741824);
  8174. }
  8175. }
  8176. /* Note: mg_snprintf will not cause a buffer overflow above.
  8177. * So, string truncation checks are not required here. */
  8178. #if defined(REENTRANT_TIME)
  8179. localtime_r(&de->file.last_modified, tm);
  8180. #else
  8181. tm = localtime(&de->file.last_modified);
  8182. #endif
  8183. if (tm != NULL) {
  8184. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8185. } else {
  8186. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8187. mod[sizeof(mod) - 1] = '\0';
  8188. }
  8189. mg_printf(conn,
  8190. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8191. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8192. href,
  8193. de->file.is_directory ? "/" : "",
  8194. esc ? esc : de->file_name,
  8195. de->file.is_directory ? "/" : "",
  8196. mod,
  8197. size);
  8198. mg_free(href);
  8199. return 0;
  8200. }
  8201. /* This function is called from send_directory() and used for
  8202. * sorting directory entries by size, name, or modification time. */
  8203. static int
  8204. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8205. {
  8206. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8207. if (p1 && p2) {
  8208. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8209. int cmp_result = 0;
  8210. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8211. query_string = "n";
  8212. }
  8213. /* Sort Directories vs Files */
  8214. if (a->file.is_directory && !b->file.is_directory) {
  8215. return -1; /* Always put directories on top */
  8216. } else if (!a->file.is_directory && b->file.is_directory) {
  8217. return 1; /* Always put directories on top */
  8218. }
  8219. /* Sort by size or date */
  8220. if (*query_string == 's') {
  8221. cmp_result = (a->file.size == b->file.size)
  8222. ? 0
  8223. : ((a->file.size > b->file.size) ? 1 : -1);
  8224. } else if (*query_string == 'd') {
  8225. cmp_result =
  8226. (a->file.last_modified == b->file.last_modified)
  8227. ? 0
  8228. : ((a->file.last_modified > b->file.last_modified) ? 1
  8229. : -1);
  8230. }
  8231. /* Sort by name:
  8232. * if (*query_string == 'n') ...
  8233. * but also sort files of same size/date by name as secondary criterion.
  8234. */
  8235. if (cmp_result == 0) {
  8236. cmp_result = strcmp(a->file_name, b->file_name);
  8237. }
  8238. /* For descending order, invert result */
  8239. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8240. }
  8241. return 0;
  8242. }
  8243. static int
  8244. must_hide_file(struct mg_connection *conn, const char *path)
  8245. {
  8246. if (conn && conn->dom_ctx) {
  8247. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8248. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8249. return (match_prefix_strlen(pw_pattern, path) > 0)
  8250. || (match_prefix_strlen(pattern, path) > 0);
  8251. }
  8252. return 0;
  8253. }
  8254. #if !defined(NO_FILESYSTEMS)
  8255. static int
  8256. scan_directory(struct mg_connection *conn,
  8257. const char *dir,
  8258. void *data,
  8259. int (*cb)(struct de *, void *))
  8260. {
  8261. char path[UTF8_PATH_MAX];
  8262. struct dirent *dp;
  8263. DIR *dirp;
  8264. struct de de;
  8265. int truncated;
  8266. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8267. return 0;
  8268. } else {
  8269. while ((dp = mg_readdir(dirp)) != NULL) {
  8270. /* Do not show current dir and hidden files */
  8271. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8272. || must_hide_file(conn, dp->d_name)) {
  8273. continue;
  8274. }
  8275. mg_snprintf(
  8276. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8277. /* If we don't memset stat structure to zero, mtime will have
  8278. * garbage and strftime() will segfault later on in
  8279. * print_dir_entry(). memset is required only if mg_stat()
  8280. * fails. For more details, see
  8281. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8282. memset(&de.file, 0, sizeof(de.file));
  8283. if (truncated) {
  8284. /* If the path is not complete, skip processing. */
  8285. continue;
  8286. }
  8287. if (!mg_stat(conn, path, &de.file)) {
  8288. mg_cry_internal(conn,
  8289. "%s: mg_stat(%s) failed: %s",
  8290. __func__,
  8291. path,
  8292. strerror(ERRNO));
  8293. }
  8294. de.file_name = dp->d_name;
  8295. if (cb(&de, data)) {
  8296. /* stopped */
  8297. break;
  8298. }
  8299. }
  8300. (void)mg_closedir(dirp);
  8301. }
  8302. return 1;
  8303. }
  8304. #endif /* NO_FILESYSTEMS */
  8305. #if !defined(NO_FILES)
  8306. static int
  8307. remove_directory(struct mg_connection *conn, const char *dir)
  8308. {
  8309. char path[UTF8_PATH_MAX];
  8310. struct dirent *dp;
  8311. DIR *dirp;
  8312. struct de de;
  8313. int truncated;
  8314. int ok = 1;
  8315. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8316. return 0;
  8317. } else {
  8318. while ((dp = mg_readdir(dirp)) != NULL) {
  8319. /* Do not show current dir (but show hidden files as they will
  8320. * also be removed) */
  8321. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8322. continue;
  8323. }
  8324. mg_snprintf(
  8325. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8326. /* If we don't memset stat structure to zero, mtime will have
  8327. * garbage and strftime() will segfault later on in
  8328. * print_dir_entry(). memset is required only if mg_stat()
  8329. * fails. For more details, see
  8330. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8331. memset(&de.file, 0, sizeof(de.file));
  8332. if (truncated) {
  8333. /* Do not delete anything shorter */
  8334. ok = 0;
  8335. continue;
  8336. }
  8337. if (!mg_stat(conn, path, &de.file)) {
  8338. mg_cry_internal(conn,
  8339. "%s: mg_stat(%s) failed: %s",
  8340. __func__,
  8341. path,
  8342. strerror(ERRNO));
  8343. ok = 0;
  8344. }
  8345. if (de.file.is_directory) {
  8346. if (remove_directory(conn, path) == 0) {
  8347. ok = 0;
  8348. }
  8349. } else {
  8350. /* This will fail file is the file is in memory */
  8351. if (mg_remove(conn, path) == 0) {
  8352. ok = 0;
  8353. }
  8354. }
  8355. }
  8356. (void)mg_closedir(dirp);
  8357. IGNORE_UNUSED_RESULT(rmdir(dir));
  8358. }
  8359. return ok;
  8360. }
  8361. #endif
  8362. struct dir_scan_data {
  8363. struct de *entries;
  8364. size_t num_entries;
  8365. size_t arr_size;
  8366. };
  8367. #if !defined(NO_FILESYSTEMS)
  8368. static int
  8369. dir_scan_callback(struct de *de, void *data)
  8370. {
  8371. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8372. struct de *entries = dsd->entries;
  8373. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8374. /* Here "entries" is a temporary pointer and can be replaced,
  8375. * "dsd->entries" is the original pointer */
  8376. entries =
  8377. (struct de *)mg_realloc(entries,
  8378. dsd->arr_size * 2 * sizeof(entries[0]));
  8379. if (entries == NULL) {
  8380. /* stop scan */
  8381. return 1;
  8382. }
  8383. dsd->entries = entries;
  8384. dsd->arr_size *= 2;
  8385. }
  8386. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8387. if (entries[dsd->num_entries].file_name == NULL) {
  8388. /* stop scan */
  8389. return 1;
  8390. }
  8391. entries[dsd->num_entries].file = de->file;
  8392. dsd->num_entries++;
  8393. return 0;
  8394. }
  8395. static void
  8396. handle_directory_request(struct mg_connection *conn, const char *dir)
  8397. {
  8398. size_t i;
  8399. int sort_direction;
  8400. struct dir_scan_data data = {NULL, 0, 128};
  8401. char date[64], *esc, *p;
  8402. const char *title;
  8403. time_t curtime = time(NULL);
  8404. if (!conn) {
  8405. return;
  8406. }
  8407. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8408. mg_send_http_error(conn,
  8409. 500,
  8410. "Error: Cannot open directory\nopendir(%s): %s",
  8411. dir,
  8412. strerror(ERRNO));
  8413. return;
  8414. }
  8415. gmt_time_string(date, sizeof(date), &curtime);
  8416. esc = NULL;
  8417. title = conn->request_info.local_uri;
  8418. if (title[strcspn(title, "&<>")]) {
  8419. /* HTML escaping needed */
  8420. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8421. if (esc) {
  8422. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8423. mg_strlcpy(p, title + i, 2);
  8424. if (*p == '&') {
  8425. strcpy(p, "&amp;");
  8426. } else if (*p == '<') {
  8427. strcpy(p, "&lt;");
  8428. } else if (*p == '>') {
  8429. strcpy(p, "&gt;");
  8430. }
  8431. }
  8432. } else {
  8433. title = "";
  8434. }
  8435. }
  8436. sort_direction = ((conn->request_info.query_string != NULL)
  8437. && (conn->request_info.query_string[0] != '\0')
  8438. && (conn->request_info.query_string[1] == 'd'))
  8439. ? 'a'
  8440. : 'd';
  8441. conn->must_close = 1;
  8442. /* Create 200 OK response */
  8443. mg_response_header_start(conn, 200);
  8444. send_static_cache_header(conn);
  8445. send_additional_header(conn);
  8446. mg_response_header_add(conn,
  8447. "Content-Type",
  8448. "text/html; charset=utf-8",
  8449. -1);
  8450. /* Send all headers */
  8451. mg_response_header_send(conn);
  8452. /* Body */
  8453. mg_printf(conn,
  8454. "<html><head><title>Index of %s</title>"
  8455. "<style>th {text-align: left;}</style></head>"
  8456. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8457. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8458. "<th><a href=\"?d%c\">Modified</a></th>"
  8459. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8460. "<tr><td colspan=\"3\"><hr></td></tr>",
  8461. esc ? esc : title,
  8462. esc ? esc : title,
  8463. sort_direction,
  8464. sort_direction,
  8465. sort_direction);
  8466. mg_free(esc);
  8467. /* Print first entry - link to a parent directory */
  8468. mg_printf(conn,
  8469. "<tr><td><a href=\"%s\">%s</a></td>"
  8470. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8471. "..",
  8472. "Parent directory",
  8473. "-",
  8474. "-");
  8475. /* Sort and print directory entries */
  8476. if (data.entries != NULL) {
  8477. mg_sort(data.entries,
  8478. data.num_entries,
  8479. sizeof(data.entries[0]),
  8480. compare_dir_entries,
  8481. (void *)conn->request_info.query_string);
  8482. for (i = 0; i < data.num_entries; i++) {
  8483. print_dir_entry(conn, &data.entries[i]);
  8484. mg_free(data.entries[i].file_name);
  8485. }
  8486. mg_free(data.entries);
  8487. }
  8488. mg_printf(conn, "%s", "</table></pre></body></html>");
  8489. conn->status_code = 200;
  8490. }
  8491. #endif /* NO_FILESYSTEMS */
  8492. /* Send len bytes from the opened file to the client. */
  8493. static void
  8494. send_file_data(struct mg_connection *conn,
  8495. struct mg_file *filep,
  8496. int64_t offset,
  8497. int64_t len,
  8498. int no_buffering)
  8499. {
  8500. char buf[MG_BUF_LEN];
  8501. int to_read, num_read, num_written;
  8502. int64_t size;
  8503. if (!filep || !conn) {
  8504. return;
  8505. }
  8506. /* Sanity check the offset */
  8507. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8508. : (int64_t)(filep->stat.size);
  8509. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8510. if (len > 0 && filep->access.fp != NULL) {
  8511. /* file stored on disk */
  8512. #if defined(__linux__)
  8513. /* sendfile is only available for Linux */
  8514. if ((conn->ssl == 0) && (conn->throttle == 0)
  8515. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8516. "yes"))) {
  8517. off_t sf_offs = (off_t)offset;
  8518. ssize_t sf_sent;
  8519. int sf_file = fileno(filep->access.fp);
  8520. int loop_cnt = 0;
  8521. do {
  8522. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8523. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8524. size_t sf_tosend =
  8525. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8526. sf_sent =
  8527. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8528. if (sf_sent > 0) {
  8529. len -= sf_sent;
  8530. offset += sf_sent;
  8531. } else if (loop_cnt == 0) {
  8532. /* This file can not be sent using sendfile.
  8533. * This might be the case for pseudo-files in the
  8534. * /sys/ and /proc/ file system.
  8535. * Use the regular user mode copy code instead. */
  8536. break;
  8537. } else if (sf_sent == 0) {
  8538. /* No error, but 0 bytes sent. May be EOF? */
  8539. return;
  8540. }
  8541. loop_cnt++;
  8542. } while ((len > 0) && (sf_sent >= 0));
  8543. if (sf_sent > 0) {
  8544. return; /* OK */
  8545. }
  8546. /* sf_sent<0 means error, thus fall back to the classic way */
  8547. /* This is always the case, if sf_file is not a "normal" file,
  8548. * e.g., for sending data from the output of a CGI process. */
  8549. offset = (int64_t)sf_offs;
  8550. }
  8551. #endif
  8552. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8553. mg_cry_internal(conn,
  8554. "%s: fseeko() failed: %s",
  8555. __func__,
  8556. strerror(ERRNO));
  8557. mg_send_http_error(
  8558. conn,
  8559. 500,
  8560. "%s",
  8561. "Error: Unable to access file at requested position.");
  8562. } else {
  8563. while (len > 0) {
  8564. /* Calculate how much to read from the file into the buffer. */
  8565. /* If no_buffering is set, we should not wait until the
  8566. * CGI->Server buffer is filled, but send everything
  8567. * immediately. In theory buffering could be turned off using
  8568. * setbuf(filep->access.fp, NULL);
  8569. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8570. * but in practice this does not work. A "Linux only" solution
  8571. * may be to use select(). The only portable way is to read byte
  8572. * by byte, but this is quite inefficient from a performance
  8573. * point of view. */
  8574. to_read = no_buffering ? 1 : sizeof(buf);
  8575. if ((int64_t)to_read > len) {
  8576. to_read = (int)len;
  8577. }
  8578. /* Read from file, exit the loop on error */
  8579. if ((num_read =
  8580. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8581. <= 0) {
  8582. break;
  8583. }
  8584. /* Send read bytes to the client, exit the loop on error */
  8585. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8586. != num_read) {
  8587. break;
  8588. }
  8589. /* Both read and were successful, adjust counters */
  8590. len -= num_written;
  8591. }
  8592. }
  8593. }
  8594. }
  8595. static int
  8596. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8597. {
  8598. return sscanf(header,
  8599. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8600. a,
  8601. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8602. // to an integer value, but function will not report
  8603. // conversion errors; consider using 'strtol' instead
  8604. }
  8605. static void
  8606. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8607. {
  8608. if ((filestat != NULL) && (buf != NULL)) {
  8609. mg_snprintf(NULL,
  8610. NULL, /* All calls to construct_etag use 64 byte buffer */
  8611. buf,
  8612. buf_len,
  8613. "\"%lx.%" INT64_FMT "\"",
  8614. (unsigned long)filestat->last_modified,
  8615. filestat->size);
  8616. }
  8617. }
  8618. static void
  8619. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8620. {
  8621. if (filep != NULL && filep->fp != NULL) {
  8622. #if defined(_WIN32)
  8623. (void)conn; /* Unused. */
  8624. #else
  8625. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8626. mg_cry_internal(conn,
  8627. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8628. __func__,
  8629. strerror(ERRNO));
  8630. }
  8631. #endif
  8632. }
  8633. }
  8634. #if defined(USE_ZLIB)
  8635. #include "mod_zlib.inl"
  8636. #endif
  8637. #if !defined(NO_FILESYSTEMS)
  8638. static void
  8639. handle_static_file_request(struct mg_connection *conn,
  8640. const char *path,
  8641. struct mg_file *filep,
  8642. const char *mime_type,
  8643. const char *additional_headers)
  8644. {
  8645. char lm[64], etag[64];
  8646. char range[128]; /* large enough, so there will be no overflow */
  8647. const char *range_hdr;
  8648. int64_t cl, r1, r2;
  8649. struct vec mime_vec;
  8650. int n, truncated;
  8651. char gz_path[UTF8_PATH_MAX];
  8652. const char *encoding = 0;
  8653. int is_head_request;
  8654. #if defined(USE_ZLIB)
  8655. /* Compression is allowed, unless there is a reason not to use
  8656. * compression. If the file is already compressed, too small or a
  8657. * "range" request was made, on the fly compression is not possible. */
  8658. int allow_on_the_fly_compression = 1;
  8659. #endif
  8660. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8661. return;
  8662. }
  8663. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8664. if (mime_type == NULL) {
  8665. get_mime_type(conn, path, &mime_vec);
  8666. } else {
  8667. mime_vec.ptr = mime_type;
  8668. mime_vec.len = strlen(mime_type);
  8669. }
  8670. if (filep->stat.size > INT64_MAX) {
  8671. mg_send_http_error(conn,
  8672. 500,
  8673. "Error: File size is too large to send\n%" INT64_FMT,
  8674. filep->stat.size);
  8675. return;
  8676. }
  8677. cl = (int64_t)filep->stat.size;
  8678. conn->status_code = 200;
  8679. range[0] = '\0';
  8680. #if defined(USE_ZLIB)
  8681. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8682. * it's important to rewrite the filename after resolving
  8683. * the mime type from it, to preserve the actual file's type */
  8684. if (!conn->accept_gzip) {
  8685. allow_on_the_fly_compression = 0;
  8686. }
  8687. #endif
  8688. /* Check if there is a range header */
  8689. range_hdr = mg_get_header(conn, "Range");
  8690. /* For gzipped files, add *.gz */
  8691. if (filep->stat.is_gzipped) {
  8692. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8693. if (truncated) {
  8694. mg_send_http_error(conn,
  8695. 500,
  8696. "Error: Path of zipped file too long (%s)",
  8697. path);
  8698. return;
  8699. }
  8700. path = gz_path;
  8701. encoding = "gzip";
  8702. #if defined(USE_ZLIB)
  8703. /* File is already compressed. No "on the fly" compression. */
  8704. allow_on_the_fly_compression = 0;
  8705. #endif
  8706. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8707. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8708. struct mg_file_stat file_stat;
  8709. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8710. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8711. && !file_stat.is_directory) {
  8712. file_stat.is_gzipped = 1;
  8713. filep->stat = file_stat;
  8714. cl = (int64_t)filep->stat.size;
  8715. path = gz_path;
  8716. encoding = "gzip";
  8717. #if defined(USE_ZLIB)
  8718. /* File is already compressed. No "on the fly" compression. */
  8719. allow_on_the_fly_compression = 0;
  8720. #endif
  8721. }
  8722. }
  8723. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8724. mg_send_http_error(conn,
  8725. 500,
  8726. "Error: Cannot open file\nfopen(%s): %s",
  8727. path,
  8728. strerror(ERRNO));
  8729. return;
  8730. }
  8731. fclose_on_exec(&filep->access, conn);
  8732. /* If "Range" request was made: parse header, send only selected part
  8733. * of the file. */
  8734. r1 = r2 = 0;
  8735. if ((range_hdr != NULL)
  8736. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8737. && (r2 >= 0)) {
  8738. /* actually, range requests don't play well with a pre-gzipped
  8739. * file (since the range is specified in the uncompressed space) */
  8740. if (filep->stat.is_gzipped) {
  8741. mg_send_http_error(
  8742. conn,
  8743. 416, /* 416 = Range Not Satisfiable */
  8744. "%s",
  8745. "Error: Range requests in gzipped files are not supported");
  8746. (void)mg_fclose(
  8747. &filep->access); /* ignore error on read only file */
  8748. return;
  8749. }
  8750. conn->status_code = 206;
  8751. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8752. mg_snprintf(conn,
  8753. NULL, /* range buffer is big enough */
  8754. range,
  8755. sizeof(range),
  8756. "bytes "
  8757. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8758. r1,
  8759. r1 + cl - 1,
  8760. filep->stat.size);
  8761. #if defined(USE_ZLIB)
  8762. /* Do not compress ranges. */
  8763. allow_on_the_fly_compression = 0;
  8764. #endif
  8765. }
  8766. /* Do not compress small files. Small files do not benefit from file
  8767. * compression, but there is still some overhead. */
  8768. #if defined(USE_ZLIB)
  8769. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8770. /* File is below the size limit. */
  8771. allow_on_the_fly_compression = 0;
  8772. }
  8773. #endif
  8774. /* Prepare Etag, and Last-Modified headers. */
  8775. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8776. construct_etag(etag, sizeof(etag), &filep->stat);
  8777. /* Create 2xx (200, 206) response */
  8778. mg_response_header_start(conn, conn->status_code);
  8779. send_static_cache_header(conn);
  8780. send_additional_header(conn);
  8781. send_cors_header(conn);
  8782. mg_response_header_add(conn,
  8783. "Content-Type",
  8784. mime_vec.ptr,
  8785. (int)mime_vec.len);
  8786. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8787. mg_response_header_add(conn, "Etag", etag, -1);
  8788. #if defined(USE_ZLIB)
  8789. /* On the fly compression allowed */
  8790. if (allow_on_the_fly_compression) {
  8791. /* For on the fly compression, we don't know the content size in
  8792. * advance, so we have to use chunked encoding */
  8793. encoding = "gzip";
  8794. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8795. /* HTTP/2 is always using "chunks" (frames) */
  8796. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8797. }
  8798. } else
  8799. #endif
  8800. {
  8801. /* Without on-the-fly compression, we know the content-length
  8802. * and we can use ranges (with on-the-fly compression we cannot).
  8803. * So we send these response headers only in this case. */
  8804. char len[32];
  8805. int trunc = 0;
  8806. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8807. if (!trunc) {
  8808. mg_response_header_add(conn, "Content-Length", len, -1);
  8809. }
  8810. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8811. }
  8812. if (encoding) {
  8813. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8814. }
  8815. if (range[0] != 0) {
  8816. mg_response_header_add(conn, "Content-Range", range, -1);
  8817. }
  8818. /* The code above does not add any header starting with X- to make
  8819. * sure no one of the additional_headers is included twice */
  8820. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8821. mg_response_header_add_lines(conn, additional_headers);
  8822. }
  8823. /* Send all headers */
  8824. mg_response_header_send(conn);
  8825. if (!is_head_request) {
  8826. #if defined(USE_ZLIB)
  8827. if (allow_on_the_fly_compression) {
  8828. /* Compress and send */
  8829. send_compressed_data(conn, filep);
  8830. } else
  8831. #endif
  8832. {
  8833. /* Send file directly */
  8834. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  8835. }
  8836. }
  8837. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8838. }
  8839. CIVETWEB_API int
  8840. mg_send_file_body(struct mg_connection *conn, const char *path)
  8841. {
  8842. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8843. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8844. return -1;
  8845. }
  8846. fclose_on_exec(&file.access, conn);
  8847. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  8848. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8849. return 0; /* >= 0 for OK */
  8850. }
  8851. #endif /* NO_FILESYSTEMS */
  8852. #if !defined(NO_CACHING)
  8853. /* Return True if we should reply 304 Not Modified. */
  8854. static int
  8855. is_not_modified(const struct mg_connection *conn,
  8856. const struct mg_file_stat *filestat)
  8857. {
  8858. char etag[64];
  8859. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8860. const char *inm = mg_get_header(conn, "If-None-Match");
  8861. construct_etag(etag, sizeof(etag), filestat);
  8862. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8863. || ((ims != NULL)
  8864. && (filestat->last_modified <= parse_date_string(ims)));
  8865. }
  8866. static void
  8867. handle_not_modified_static_file_request(struct mg_connection *conn,
  8868. struct mg_file *filep)
  8869. {
  8870. char lm[64], etag[64];
  8871. if ((conn == NULL) || (filep == NULL)) {
  8872. return;
  8873. }
  8874. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8875. construct_etag(etag, sizeof(etag), &filep->stat);
  8876. /* Create 304 "not modified" response */
  8877. mg_response_header_start(conn, 304);
  8878. send_static_cache_header(conn);
  8879. send_additional_header(conn);
  8880. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8881. mg_response_header_add(conn, "Etag", etag, -1);
  8882. /* Send all headers */
  8883. mg_response_header_send(conn);
  8884. }
  8885. #endif
  8886. #if !defined(NO_FILESYSTEMS)
  8887. CIVETWEB_API void
  8888. mg_send_file(struct mg_connection *conn, const char *path)
  8889. {
  8890. mg_send_mime_file2(conn, path, NULL, NULL);
  8891. }
  8892. CIVETWEB_API void
  8893. mg_send_mime_file(struct mg_connection *conn,
  8894. const char *path,
  8895. const char *mime_type)
  8896. {
  8897. mg_send_mime_file2(conn, path, mime_type, NULL);
  8898. }
  8899. CIVETWEB_API void
  8900. mg_send_mime_file2(struct mg_connection *conn,
  8901. const char *path,
  8902. const char *mime_type,
  8903. const char *additional_headers)
  8904. {
  8905. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8906. if (!conn) {
  8907. /* No conn */
  8908. return;
  8909. }
  8910. if (mg_stat(conn, path, &file.stat)) {
  8911. #if !defined(NO_CACHING)
  8912. if (is_not_modified(conn, &file.stat)) {
  8913. /* Send 304 "Not Modified" - this must not send any body data */
  8914. handle_not_modified_static_file_request(conn, &file);
  8915. } else
  8916. #endif /* NO_CACHING */
  8917. if (file.stat.is_directory) {
  8918. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8919. "yes")) {
  8920. handle_directory_request(conn, path);
  8921. } else {
  8922. mg_send_http_error(conn,
  8923. 403,
  8924. "%s",
  8925. "Error: Directory listing denied");
  8926. }
  8927. } else {
  8928. handle_static_file_request(
  8929. conn, path, &file, mime_type, additional_headers);
  8930. }
  8931. } else {
  8932. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8933. }
  8934. }
  8935. /* For a given PUT path, create all intermediate subdirectories.
  8936. * Return 0 if the path itself is a directory.
  8937. * Return 1 if the path leads to a file.
  8938. * Return -1 for if the path is too long.
  8939. * Return -2 if path can not be created.
  8940. */
  8941. static int
  8942. put_dir(struct mg_connection *conn, const char *path)
  8943. {
  8944. char buf[UTF8_PATH_MAX];
  8945. const char *s, *p;
  8946. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8947. size_t len;
  8948. int res = 1;
  8949. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8950. len = (size_t)(p - path);
  8951. if (len >= sizeof(buf)) {
  8952. /* path too long */
  8953. res = -1;
  8954. break;
  8955. }
  8956. memcpy(buf, path, len);
  8957. buf[len] = '\0';
  8958. /* Try to create intermediate directory */
  8959. DEBUG_TRACE("mkdir(%s)", buf);
  8960. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8961. /* path does not exixt and can not be created */
  8962. res = -2;
  8963. break;
  8964. }
  8965. /* Is path itself a directory? */
  8966. if (p[1] == '\0') {
  8967. res = 0;
  8968. }
  8969. }
  8970. return res;
  8971. }
  8972. static void
  8973. remove_bad_file(const struct mg_connection *conn, const char *path)
  8974. {
  8975. int r = mg_remove(conn, path);
  8976. if (r != 0) {
  8977. mg_cry_internal(conn,
  8978. "%s: Cannot remove invalid file %s",
  8979. __func__,
  8980. path);
  8981. }
  8982. }
  8983. CIVETWEB_API long long
  8984. mg_store_body(struct mg_connection *conn, const char *path)
  8985. {
  8986. char buf[MG_BUF_LEN];
  8987. long long len = 0;
  8988. int ret, n;
  8989. struct mg_file fi;
  8990. if (conn->consumed_content != 0) {
  8991. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8992. return -11;
  8993. }
  8994. ret = put_dir(conn, path);
  8995. if (ret < 0) {
  8996. /* -1 for path too long,
  8997. * -2 for path can not be created. */
  8998. return ret;
  8999. }
  9000. if (ret != 1) {
  9001. /* Return 0 means, path itself is a directory. */
  9002. return 0;
  9003. }
  9004. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9005. return -12;
  9006. }
  9007. ret = mg_read(conn, buf, sizeof(buf));
  9008. while (ret > 0) {
  9009. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9010. if (n != ret) {
  9011. (void)mg_fclose(
  9012. &fi.access); /* File is bad and will be removed anyway. */
  9013. remove_bad_file(conn, path);
  9014. return -13;
  9015. }
  9016. len += ret;
  9017. ret = mg_read(conn, buf, sizeof(buf));
  9018. }
  9019. /* File is open for writing. If fclose fails, there was probably an
  9020. * error flushing the buffer to disk, so the file on disk might be
  9021. * broken. Delete it and return an error to the caller. */
  9022. if (mg_fclose(&fi.access) != 0) {
  9023. remove_bad_file(conn, path);
  9024. return -14;
  9025. }
  9026. return len;
  9027. }
  9028. #endif /* NO_FILESYSTEMS */
  9029. /* Parse a buffer:
  9030. * Forward the string pointer till the end of a word, then
  9031. * terminate it and forward till the begin of the next word.
  9032. */
  9033. static int
  9034. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9035. {
  9036. /* Forward until a space is found - use isgraph here */
  9037. /* See http://www.cplusplus.com/reference/cctype/ */
  9038. while (isgraph((unsigned char)**ppw)) {
  9039. (*ppw)++;
  9040. }
  9041. /* Check end of word */
  9042. if (eol) {
  9043. /* must be a end of line */
  9044. if ((**ppw != '\r') && (**ppw != '\n')) {
  9045. return -1;
  9046. }
  9047. } else {
  9048. /* must be a end of a word, but not a line */
  9049. if (**ppw != ' ') {
  9050. return -1;
  9051. }
  9052. }
  9053. /* Terminate and forward to the next word */
  9054. do {
  9055. **ppw = 0;
  9056. (*ppw)++;
  9057. } while (isspace((unsigned char)**ppw));
  9058. /* Check after term */
  9059. if (!eol) {
  9060. /* if it's not the end of line, there must be a next word */
  9061. if (!isgraph((unsigned char)**ppw)) {
  9062. return -1;
  9063. }
  9064. }
  9065. /* ok */
  9066. return 1;
  9067. }
  9068. /* Parse HTTP headers from the given buffer, advance buf pointer
  9069. * to the point where parsing stopped.
  9070. * All parameters must be valid pointers (not NULL).
  9071. * Return <0 on error. */
  9072. static int
  9073. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9074. {
  9075. int i;
  9076. int num_headers = 0;
  9077. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9078. char *dp = *buf;
  9079. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9080. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9081. dp++;
  9082. }
  9083. if (dp == *buf) {
  9084. /* End of headers reached. */
  9085. break;
  9086. }
  9087. /* Drop all spaces after header name before : */
  9088. while (*dp == ' ') {
  9089. *dp = 0;
  9090. dp++;
  9091. }
  9092. if (*dp != ':') {
  9093. /* This is not a valid field. */
  9094. return -1;
  9095. }
  9096. /* End of header key (*dp == ':') */
  9097. /* Truncate here and set the key name */
  9098. *dp = 0;
  9099. hdr[i].name = *buf;
  9100. /* Skip all spaces */
  9101. do {
  9102. dp++;
  9103. } while ((*dp == ' ') || (*dp == '\t'));
  9104. /* The rest of the line is the value */
  9105. hdr[i].value = dp;
  9106. /* Find end of line */
  9107. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9108. dp++;
  9109. };
  9110. /* eliminate \r */
  9111. if (*dp == '\r') {
  9112. *dp = 0;
  9113. dp++;
  9114. if (*dp != '\n') {
  9115. /* This is not a valid line. */
  9116. return -1;
  9117. }
  9118. }
  9119. /* here *dp is either 0 or '\n' */
  9120. /* in any case, we have a new header */
  9121. num_headers = i + 1;
  9122. if (*dp) {
  9123. *dp = 0;
  9124. dp++;
  9125. *buf = dp;
  9126. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9127. /* This is the end of the header */
  9128. break;
  9129. }
  9130. } else {
  9131. *buf = dp;
  9132. break;
  9133. }
  9134. }
  9135. return num_headers;
  9136. }
  9137. struct mg_http_method_info {
  9138. const char *name;
  9139. int request_has_body;
  9140. int response_has_body;
  9141. int is_safe;
  9142. int is_idempotent;
  9143. int is_cacheable;
  9144. };
  9145. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9146. static const struct mg_http_method_info http_methods[] = {
  9147. /* HTTP (RFC 2616) */
  9148. {"GET", 0, 1, 1, 1, 1},
  9149. {"POST", 1, 1, 0, 0, 0},
  9150. {"PUT", 1, 0, 0, 1, 0},
  9151. {"DELETE", 0, 0, 0, 1, 0},
  9152. {"HEAD", 0, 0, 1, 1, 1},
  9153. {"OPTIONS", 0, 0, 1, 1, 0},
  9154. {"CONNECT", 1, 1, 0, 0, 0},
  9155. /* TRACE method (RFC 2616) is not supported for security reasons */
  9156. /* PATCH method (RFC 5789) */
  9157. {"PATCH", 1, 0, 0, 0, 0},
  9158. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9159. /* WEBDAV (RFC 2518) */
  9160. {"PROPFIND", 0, 1, 1, 1, 0},
  9161. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9162. * Some PROPFIND results MAY be cached, with care,
  9163. * as there is no cache validation mechanism for
  9164. * most properties. This method is both safe and
  9165. * idempotent (see Section 9.1 of [RFC2616]). */
  9166. {"MKCOL", 0, 0, 0, 1, 0},
  9167. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9168. * When MKCOL is invoked without a request body,
  9169. * the newly created collection SHOULD have no
  9170. * members. A MKCOL request message may contain
  9171. * a message body. The precise behavior of a MKCOL
  9172. * request when the body is present is undefined,
  9173. * ... ==> We do not support MKCOL with body data.
  9174. * This method is idempotent, but not safe (see
  9175. * Section 9.1 of [RFC2616]). Responses to this
  9176. * method MUST NOT be cached. */
  9177. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9178. {"LOCK", 1, 1, 0, 0, 0},
  9179. {"UNLOCK", 1, 0, 0, 0, 0},
  9180. {"PROPPATCH", 1, 1, 0, 0, 0},
  9181. {"COPY", 1, 0, 0, 0, 0},
  9182. {"MOVE", 1, 1, 0, 0, 0},
  9183. /* Unsupported WEBDAV Methods: */
  9184. /* + 11 methods from RFC 3253 */
  9185. /* ORDERPATCH (RFC 3648) */
  9186. /* ACL (RFC 3744) */
  9187. /* SEARCH (RFC 5323) */
  9188. /* + MicroSoft extensions
  9189. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9190. /* REPORT method (RFC 3253) */
  9191. {"REPORT", 1, 1, 1, 1, 1},
  9192. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9193. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9194. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9195. * to be useful for REST in case a "GET request with body" is
  9196. * required. */
  9197. {NULL, 0, 0, 0, 0, 0}
  9198. /* end of list */
  9199. };
  9200. /* All method names */
  9201. static char *all_methods = NULL; /* Built by mg_init_library */
  9202. static const struct mg_http_method_info *
  9203. get_http_method_info(const char *method)
  9204. {
  9205. /* Check if the method is known to the server. The list of all known
  9206. * HTTP methods can be found here at
  9207. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9208. */
  9209. const struct mg_http_method_info *m = http_methods;
  9210. while (m->name) {
  9211. if (!strcmp(m->name, method)) {
  9212. return m;
  9213. }
  9214. m++;
  9215. }
  9216. return NULL;
  9217. }
  9218. static int
  9219. is_valid_http_method(const char *method)
  9220. {
  9221. return (get_http_method_info(method) != NULL);
  9222. }
  9223. /* Parse HTTP request, fill in mg_request_info structure.
  9224. * This function modifies the buffer by NUL-terminating
  9225. * HTTP request components, header names and header values.
  9226. * Parameters:
  9227. * buf (in/out): pointer to the HTTP header to parse and split
  9228. * len (in): length of HTTP header buffer
  9229. * re (out): parsed header as mg_request_info
  9230. * buf and ri must be valid pointers (not NULL), len>0.
  9231. * Returns <0 on error. */
  9232. static int
  9233. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9234. {
  9235. int request_length;
  9236. int init_skip = 0;
  9237. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9238. * remote_port */
  9239. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9240. NULL;
  9241. ri->num_headers = 0;
  9242. /* RFC says that all initial whitespaces should be ignored */
  9243. /* This included all leading \r and \n (isspace) */
  9244. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9245. while ((len > 0) && isspace((unsigned char)*buf)) {
  9246. buf++;
  9247. len--;
  9248. init_skip++;
  9249. }
  9250. if (len == 0) {
  9251. /* Incomplete request */
  9252. return 0;
  9253. }
  9254. /* Control characters are not allowed, including zero */
  9255. if (iscntrl((unsigned char)*buf)) {
  9256. return -1;
  9257. }
  9258. /* Find end of HTTP header */
  9259. request_length = get_http_header_len(buf, len);
  9260. if (request_length <= 0) {
  9261. return request_length;
  9262. }
  9263. buf[request_length - 1] = '\0';
  9264. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9265. return -1;
  9266. }
  9267. /* The first word has to be the HTTP method */
  9268. ri->request_method = buf;
  9269. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9270. return -1;
  9271. }
  9272. /* The second word is the URI */
  9273. ri->request_uri = buf;
  9274. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9275. return -1;
  9276. }
  9277. /* Next would be the HTTP version */
  9278. ri->http_version = buf;
  9279. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9280. return -1;
  9281. }
  9282. /* Check for a valid HTTP version key */
  9283. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9284. /* Invalid request */
  9285. return -1;
  9286. }
  9287. ri->http_version += 5;
  9288. /* Check for a valid http method */
  9289. if (!is_valid_http_method(ri->request_method)) {
  9290. return -1;
  9291. }
  9292. /* Parse all HTTP headers */
  9293. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9294. if (ri->num_headers < 0) {
  9295. /* Error while parsing headers */
  9296. return -1;
  9297. }
  9298. return request_length + init_skip;
  9299. }
  9300. static int
  9301. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9302. {
  9303. int response_length;
  9304. int init_skip = 0;
  9305. char *tmp, *tmp2;
  9306. long l;
  9307. /* Initialize elements. */
  9308. ri->http_version = ri->status_text = NULL;
  9309. ri->num_headers = ri->status_code = 0;
  9310. /* RFC says that all initial whitespaces should be ingored */
  9311. /* This included all leading \r and \n (isspace) */
  9312. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9313. while ((len > 0) && isspace((unsigned char)*buf)) {
  9314. buf++;
  9315. len--;
  9316. init_skip++;
  9317. }
  9318. if (len == 0) {
  9319. /* Incomplete request */
  9320. return 0;
  9321. }
  9322. /* Control characters are not allowed, including zero */
  9323. if (iscntrl((unsigned char)*buf)) {
  9324. return -1;
  9325. }
  9326. /* Find end of HTTP header */
  9327. response_length = get_http_header_len(buf, len);
  9328. if (response_length <= 0) {
  9329. return response_length;
  9330. }
  9331. buf[response_length - 1] = '\0';
  9332. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9333. return -1;
  9334. }
  9335. /* The first word is the HTTP version */
  9336. /* Check for a valid HTTP version key */
  9337. if (strncmp(buf, "HTTP/", 5) != 0) {
  9338. /* Invalid request */
  9339. return -1;
  9340. }
  9341. buf += 5;
  9342. if (!isgraph((unsigned char)buf[0])) {
  9343. /* Invalid request */
  9344. return -1;
  9345. }
  9346. ri->http_version = buf;
  9347. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9348. return -1;
  9349. }
  9350. /* The second word is the status as a number */
  9351. tmp = buf;
  9352. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9353. return -1;
  9354. }
  9355. l = strtol(tmp, &tmp2, 10);
  9356. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9357. /* Everything else but a 3 digit code is invalid */
  9358. return -1;
  9359. }
  9360. ri->status_code = (int)l;
  9361. /* The rest of the line is the status text */
  9362. ri->status_text = buf;
  9363. /* Find end of status text */
  9364. /* isgraph or isspace = isprint */
  9365. while (isprint((unsigned char)*buf)) {
  9366. buf++;
  9367. }
  9368. if ((*buf != '\r') && (*buf != '\n')) {
  9369. return -1;
  9370. }
  9371. /* Terminate string and forward buf to next line */
  9372. do {
  9373. *buf = 0;
  9374. buf++;
  9375. } while (isspace((unsigned char)*buf));
  9376. /* Parse all HTTP headers */
  9377. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9378. if (ri->num_headers < 0) {
  9379. /* Error while parsing headers */
  9380. return -1;
  9381. }
  9382. return response_length + init_skip;
  9383. }
  9384. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9385. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9386. * buffer (which marks the end of HTTP request). Buffer buf may already
  9387. * have some data. The length of the data is stored in nread.
  9388. * Upon every read operation, increase nread by the number of bytes read. */
  9389. static int
  9390. read_message(FILE *fp,
  9391. struct mg_connection *conn,
  9392. char *buf,
  9393. int bufsiz,
  9394. int *nread)
  9395. {
  9396. int request_len, n = 0;
  9397. struct timespec last_action_time;
  9398. double request_timeout;
  9399. if (!conn) {
  9400. return 0;
  9401. }
  9402. memset(&last_action_time, 0, sizeof(last_action_time));
  9403. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9404. /* value of request_timeout is in seconds, config in milliseconds */
  9405. request_timeout =
  9406. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9407. } else {
  9408. request_timeout =
  9409. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9410. / 1000.0;
  9411. }
  9412. if (conn->handled_requests > 0) {
  9413. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9414. request_timeout =
  9415. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9416. / 1000.0;
  9417. }
  9418. }
  9419. request_len = get_http_header_len(buf, *nread);
  9420. while (request_len == 0) {
  9421. /* Full request not yet received */
  9422. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9423. /* Server is to be stopped. */
  9424. return -1;
  9425. }
  9426. if (*nread >= bufsiz) {
  9427. /* Request too long */
  9428. return -2;
  9429. }
  9430. n = pull_inner(
  9431. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9432. if (n == -2) {
  9433. /* Receive error */
  9434. return -1;
  9435. }
  9436. /* update clock after every read request */
  9437. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9438. if (n > 0) {
  9439. *nread += n;
  9440. request_len = get_http_header_len(buf, *nread);
  9441. }
  9442. if ((request_len == 0) && (request_timeout >= 0)) {
  9443. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9444. > request_timeout) {
  9445. /* Timeout */
  9446. return -1;
  9447. }
  9448. }
  9449. }
  9450. return request_len;
  9451. }
  9452. #if !defined(NO_CGI) || !defined(NO_FILES)
  9453. static int
  9454. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9455. {
  9456. const char *expect;
  9457. char buf[MG_BUF_LEN];
  9458. int success = 0;
  9459. if (!conn) {
  9460. return 0;
  9461. }
  9462. expect = mg_get_header(conn, "Expect");
  9463. DEBUG_ASSERT(fp != NULL);
  9464. if (!fp) {
  9465. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9466. return 0;
  9467. }
  9468. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9469. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9470. */
  9471. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9472. } else {
  9473. if (expect != NULL) {
  9474. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9475. conn->status_code = 100;
  9476. } else {
  9477. conn->status_code = 200;
  9478. }
  9479. DEBUG_ASSERT(conn->consumed_content == 0);
  9480. if (conn->consumed_content != 0) {
  9481. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9482. return 0;
  9483. }
  9484. for (;;) {
  9485. int nread = mg_read(conn, buf, sizeof(buf));
  9486. if (nread <= 0) {
  9487. success = (nread == 0);
  9488. break;
  9489. }
  9490. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9491. break;
  9492. }
  9493. }
  9494. /* Each error code path in this function must send an error */
  9495. if (!success) {
  9496. /* NOTE: Maybe some data has already been sent. */
  9497. /* TODO (low): If some data has been sent, a correct error
  9498. * reply can no longer be sent, so just close the connection */
  9499. mg_send_http_error(conn, 500, "%s", "");
  9500. }
  9501. }
  9502. return success;
  9503. }
  9504. #endif
  9505. #if defined(USE_TIMERS)
  9506. #define TIMER_API static
  9507. #include "timer.inl"
  9508. #endif /* USE_TIMERS */
  9509. #if !defined(NO_CGI)
  9510. /* This structure helps to create an environment for the spawned CGI
  9511. * program.
  9512. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9513. * last element must be NULL.
  9514. * However, on Windows there is a requirement that all these
  9515. * VARIABLE=VALUE\0
  9516. * strings must reside in a contiguous buffer. The end of the buffer is
  9517. * marked by two '\0' characters.
  9518. * We satisfy both worlds: we create an envp array (which is vars), all
  9519. * entries are actually pointers inside buf. */
  9520. struct cgi_environment {
  9521. struct mg_connection *conn;
  9522. /* Data block */
  9523. char *buf; /* Environment buffer */
  9524. size_t buflen; /* Space available in buf */
  9525. size_t bufused; /* Space taken in buf */
  9526. /* Index block */
  9527. char **var; /* char **envp */
  9528. size_t varlen; /* Number of variables available in var */
  9529. size_t varused; /* Number of variables stored in var */
  9530. };
  9531. static void addenv(struct cgi_environment *env,
  9532. PRINTF_FORMAT_STRING(const char *fmt),
  9533. ...) PRINTF_ARGS(2, 3);
  9534. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9535. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9536. static void
  9537. addenv(struct cgi_environment *env, const char *fmt, ...)
  9538. {
  9539. size_t i, n, space;
  9540. int truncated = 0;
  9541. char *added;
  9542. va_list ap;
  9543. if ((env->varlen - env->varused) < 2) {
  9544. mg_cry_internal(env->conn,
  9545. "%s: Cannot register CGI variable [%s]",
  9546. __func__,
  9547. fmt);
  9548. return;
  9549. }
  9550. /* Calculate how much space is left in the buffer */
  9551. space = (env->buflen - env->bufused);
  9552. do {
  9553. /* Space for "\0\0" is always needed. */
  9554. if (space <= 2) {
  9555. /* Allocate new buffer */
  9556. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9557. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9558. if (!added) {
  9559. /* Out of memory */
  9560. mg_cry_internal(
  9561. env->conn,
  9562. "%s: Cannot allocate memory for CGI variable [%s]",
  9563. __func__,
  9564. fmt);
  9565. return;
  9566. }
  9567. /* Retarget pointers */
  9568. env->buf = added;
  9569. env->buflen = n;
  9570. for (i = 0, n = 0; i < env->varused; i++) {
  9571. env->var[i] = added + n;
  9572. n += strlen(added + n) + 1;
  9573. }
  9574. space = (env->buflen - env->bufused);
  9575. }
  9576. /* Make a pointer to the free space int the buffer */
  9577. added = env->buf + env->bufused;
  9578. /* Copy VARIABLE=VALUE\0 string into the free space */
  9579. va_start(ap, fmt);
  9580. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9581. va_end(ap);
  9582. /* Do not add truncated strings to the environment */
  9583. if (truncated) {
  9584. /* Reallocate the buffer */
  9585. space = 0;
  9586. }
  9587. } while (truncated);
  9588. /* Calculate number of bytes added to the environment */
  9589. n = strlen(added) + 1;
  9590. env->bufused += n;
  9591. /* Append a pointer to the added string into the envp array */
  9592. env->var[env->varused] = added;
  9593. env->varused++;
  9594. }
  9595. /* Return 0 on success, non-zero if an error occurs. */
  9596. static int
  9597. prepare_cgi_environment(struct mg_connection *conn,
  9598. const char *prog,
  9599. struct cgi_environment *env,
  9600. unsigned char cgi_config_idx)
  9601. {
  9602. const char *s;
  9603. struct vec var_vec;
  9604. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9605. int i, truncated, uri_len;
  9606. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9607. return -1;
  9608. }
  9609. env->conn = conn;
  9610. env->buflen = CGI_ENVIRONMENT_SIZE;
  9611. env->bufused = 0;
  9612. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9613. if (env->buf == NULL) {
  9614. mg_cry_internal(conn,
  9615. "%s: Not enough memory for environmental buffer",
  9616. __func__);
  9617. return -1;
  9618. }
  9619. env->varlen = MAX_CGI_ENVIR_VARS;
  9620. env->varused = 0;
  9621. env->var =
  9622. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9623. if (env->var == NULL) {
  9624. mg_cry_internal(conn,
  9625. "%s: Not enough memory for environmental variables",
  9626. __func__);
  9627. mg_free(env->buf);
  9628. return -1;
  9629. }
  9630. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9631. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9632. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9633. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9634. /* Prepare the environment block */
  9635. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9636. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9637. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9638. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9639. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9640. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9641. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9642. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9643. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9644. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9645. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9646. /* SCRIPT_NAME */
  9647. uri_len = (int)strlen(conn->request_info.local_uri);
  9648. if (conn->path_info == NULL) {
  9649. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9650. /* URI: /path_to_script/script.cgi */
  9651. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9652. } else {
  9653. /* URI: /path_to_script/ ... using index.cgi */
  9654. const char *index_file = strrchr(prog, '/');
  9655. if (index_file) {
  9656. addenv(env,
  9657. "SCRIPT_NAME=%s%s",
  9658. conn->request_info.local_uri,
  9659. index_file + 1);
  9660. }
  9661. }
  9662. } else {
  9663. /* URI: /path_to_script/script.cgi/path_info */
  9664. addenv(env,
  9665. "SCRIPT_NAME=%.*s",
  9666. uri_len - (int)strlen(conn->path_info),
  9667. conn->request_info.local_uri);
  9668. }
  9669. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9670. if (conn->path_info == NULL) {
  9671. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9672. } else {
  9673. addenv(env,
  9674. "PATH_TRANSLATED=%s%s",
  9675. conn->dom_ctx->config[DOCUMENT_ROOT],
  9676. conn->path_info);
  9677. }
  9678. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9679. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9680. addenv(env, "CONTENT_TYPE=%s", s);
  9681. }
  9682. if (conn->request_info.query_string != NULL) {
  9683. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9684. }
  9685. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9686. addenv(env, "CONTENT_LENGTH=%s", s);
  9687. }
  9688. if ((s = getenv("PATH")) != NULL) {
  9689. addenv(env, "PATH=%s", s);
  9690. }
  9691. if (conn->path_info != NULL) {
  9692. addenv(env, "PATH_INFO=%s", conn->path_info);
  9693. }
  9694. if (conn->status_code > 0) {
  9695. /* CGI error handler should show the status code */
  9696. addenv(env, "STATUS=%d", conn->status_code);
  9697. }
  9698. #if defined(_WIN32)
  9699. if ((s = getenv("COMSPEC")) != NULL) {
  9700. addenv(env, "COMSPEC=%s", s);
  9701. }
  9702. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9703. addenv(env, "SYSTEMROOT=%s", s);
  9704. }
  9705. if ((s = getenv("SystemDrive")) != NULL) {
  9706. addenv(env, "SystemDrive=%s", s);
  9707. }
  9708. if ((s = getenv("ProgramFiles")) != NULL) {
  9709. addenv(env, "ProgramFiles=%s", s);
  9710. }
  9711. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9712. addenv(env, "ProgramFiles(x86)=%s", s);
  9713. }
  9714. #else
  9715. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9716. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9717. }
  9718. #endif /* _WIN32 */
  9719. if ((s = getenv("PERLLIB")) != NULL) {
  9720. addenv(env, "PERLLIB=%s", s);
  9721. }
  9722. if (conn->request_info.remote_user != NULL) {
  9723. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9724. addenv(env, "%s", "AUTH_TYPE=Digest");
  9725. }
  9726. /* Add all headers as HTTP_* variables */
  9727. for (i = 0; i < conn->request_info.num_headers; i++) {
  9728. (void)mg_snprintf(conn,
  9729. &truncated,
  9730. http_var_name,
  9731. sizeof(http_var_name),
  9732. "HTTP_%s",
  9733. conn->request_info.http_headers[i].name);
  9734. if (truncated) {
  9735. mg_cry_internal(conn,
  9736. "%s: HTTP header variable too long [%s]",
  9737. __func__,
  9738. conn->request_info.http_headers[i].name);
  9739. continue;
  9740. }
  9741. /* Convert variable name into uppercase, and change - to _ */
  9742. for (p = http_var_name; *p != '\0'; p++) {
  9743. if (*p == '-') {
  9744. *p = '_';
  9745. }
  9746. *p = (char)toupper((unsigned char)*p);
  9747. }
  9748. addenv(env,
  9749. "%s=%s",
  9750. http_var_name,
  9751. conn->request_info.http_headers[i].value);
  9752. }
  9753. /* Add user-specified variables */
  9754. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9755. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9756. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9757. }
  9758. env->var[env->varused] = NULL;
  9759. env->buf[env->bufused] = '\0';
  9760. return 0;
  9761. }
  9762. /* Data for CGI process control: PID and number of references */
  9763. struct process_control_data {
  9764. pid_t pid;
  9765. ptrdiff_t references;
  9766. };
  9767. static int
  9768. abort_cgi_process(void *data)
  9769. {
  9770. /* Waitpid checks for child status and won't work for a pid that does
  9771. * not identify a child of the current process. Thus, if the pid is
  9772. * reused, we will not affect a different process. */
  9773. struct process_control_data *proc = (struct process_control_data *)data;
  9774. int status = 0;
  9775. ptrdiff_t refs;
  9776. pid_t ret_pid;
  9777. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9778. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9779. /* Stop child process */
  9780. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9781. kill(proc->pid, SIGABRT);
  9782. /* Wait until process is terminated (don't leave zombies) */
  9783. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9784. ;
  9785. } else {
  9786. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9787. }
  9788. /* Dec reference counter */
  9789. refs = mg_atomic_dec(&proc->references);
  9790. if (refs == 0) {
  9791. /* no more references - free data */
  9792. mg_free(data);
  9793. }
  9794. return 0;
  9795. }
  9796. /* Local (static) function assumes all arguments are valid. */
  9797. static void
  9798. handle_cgi_request(struct mg_connection *conn,
  9799. const char *prog,
  9800. unsigned char cgi_config_idx)
  9801. {
  9802. char *buf;
  9803. size_t buflen;
  9804. int headers_len, data_len, i, truncated;
  9805. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9806. const char *status, *status_text, *connection_state;
  9807. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9808. struct mg_request_info ri;
  9809. struct cgi_environment blk;
  9810. FILE *in = NULL, *out = NULL, *err = NULL;
  9811. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9812. pid_t pid = (pid_t)-1;
  9813. struct process_control_data *proc = NULL;
  9814. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  9815. int no_buffering = 0;
  9816. #if defined(USE_TIMERS)
  9817. double cgi_timeout;
  9818. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9819. /* Get timeout in seconds */
  9820. cgi_timeout =
  9821. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9822. } else {
  9823. cgi_timeout =
  9824. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9825. }
  9826. #endif
  9827. if (cfg_buffering != NULL) {
  9828. if (!mg_strcasecmp(cfg_buffering, "no")) {
  9829. no_buffering = 1;
  9830. }
  9831. }
  9832. buf = NULL;
  9833. buflen = conn->phys_ctx->max_request_size;
  9834. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9835. if (i != 0) {
  9836. blk.buf = NULL;
  9837. blk.var = NULL;
  9838. goto done;
  9839. }
  9840. /* CGI must be executed in its own directory. 'dir' must point to the
  9841. * directory containing executable program, 'p' must point to the
  9842. * executable program name relative to 'dir'. */
  9843. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9844. if (truncated) {
  9845. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9846. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9847. goto done;
  9848. }
  9849. if ((p = strrchr(dir, '/')) != NULL) {
  9850. *p++ = '\0';
  9851. } else {
  9852. dir[0] = '.';
  9853. dir[1] = '\0';
  9854. p = (char *)prog;
  9855. }
  9856. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9857. status = strerror(ERRNO);
  9858. mg_cry_internal(
  9859. conn,
  9860. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9861. prog,
  9862. status);
  9863. mg_send_http_error(conn,
  9864. 500,
  9865. "Error: Cannot create CGI pipe: %s",
  9866. status);
  9867. goto done;
  9868. }
  9869. proc = (struct process_control_data *)
  9870. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9871. if (proc == NULL) {
  9872. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9873. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9874. goto done;
  9875. }
  9876. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9877. pid = spawn_process(
  9878. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9879. if (pid == (pid_t)-1) {
  9880. status = strerror(ERRNO);
  9881. mg_cry_internal(
  9882. conn,
  9883. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9884. prog,
  9885. status);
  9886. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9887. mg_free(proc);
  9888. proc = NULL;
  9889. goto done;
  9890. }
  9891. /* Store data in shared process_control_data */
  9892. proc->pid = pid;
  9893. proc->references = 1;
  9894. #if defined(USE_TIMERS)
  9895. if (cgi_timeout > 0.0) {
  9896. proc->references = 2;
  9897. // Start a timer for CGI
  9898. timer_add(conn->phys_ctx,
  9899. cgi_timeout /* in seconds */,
  9900. 0.0,
  9901. 1,
  9902. abort_cgi_process,
  9903. (void *)proc,
  9904. NULL);
  9905. }
  9906. #endif
  9907. /* Parent closes only one side of the pipes.
  9908. * If we don't mark them as closed, close() attempt before
  9909. * return from this function throws an exception on Windows.
  9910. * Windows does not like when closed descriptor is closed again. */
  9911. (void)close(fdin[0]);
  9912. (void)close(fdout[1]);
  9913. (void)close(fderr[1]);
  9914. fdin[0] = fdout[1] = fderr[1] = -1;
  9915. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9916. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9917. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9918. status = strerror(ERRNO);
  9919. mg_cry_internal(conn,
  9920. "Error: CGI program \"%s\": Can not open fd: %s",
  9921. prog,
  9922. status);
  9923. mg_send_http_error(conn,
  9924. 500,
  9925. "Error: CGI can not open fd\nfdopen: %s",
  9926. status);
  9927. goto done;
  9928. }
  9929. setbuf(in, NULL);
  9930. setbuf(out, NULL);
  9931. setbuf(err, NULL);
  9932. fout.access.fp = out;
  9933. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9934. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9935. conn->content_len);
  9936. /* This is a POST/PUT request, or another request with body data. */
  9937. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9938. /* Error sending the body data */
  9939. mg_cry_internal(
  9940. conn,
  9941. "Error: CGI program \"%s\": Forward body data failed",
  9942. prog);
  9943. goto done;
  9944. }
  9945. }
  9946. /* Close so child gets an EOF. */
  9947. fclose(in);
  9948. in = NULL;
  9949. fdin[1] = -1;
  9950. /* Now read CGI reply into a buffer. We need to set correct
  9951. * status code, thus we need to see all HTTP headers first.
  9952. * Do not send anything back to client, until we buffer in all
  9953. * HTTP headers. */
  9954. data_len = 0;
  9955. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9956. if (buf == NULL) {
  9957. mg_send_http_error(conn,
  9958. 500,
  9959. "Error: Not enough memory for CGI buffer (%u bytes)",
  9960. (unsigned int)buflen);
  9961. mg_cry_internal(
  9962. conn,
  9963. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9964. "bytes)",
  9965. prog,
  9966. (unsigned int)buflen);
  9967. goto done;
  9968. }
  9969. DEBUG_TRACE("CGI: %s", "wait for response");
  9970. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9971. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9972. if (headers_len <= 0) {
  9973. /* Could not parse the CGI response. Check if some error message on
  9974. * stderr. */
  9975. i = pull_all(err, conn, buf, (int)buflen);
  9976. if (i > 0) {
  9977. /* CGI program explicitly sent an error */
  9978. /* Write the error message to the internal log */
  9979. mg_cry_internal(conn,
  9980. "Error: CGI program \"%s\" sent error "
  9981. "message: [%.*s]",
  9982. prog,
  9983. i,
  9984. buf);
  9985. /* Don't send the error message back to the client */
  9986. mg_send_http_error(conn,
  9987. 500,
  9988. "Error: CGI program \"%s\" failed.",
  9989. prog);
  9990. } else {
  9991. /* CGI program did not explicitly send an error, but a broken
  9992. * respon header */
  9993. mg_cry_internal(conn,
  9994. "Error: CGI program sent malformed or too big "
  9995. "(>%u bytes) HTTP headers: [%.*s]",
  9996. (unsigned)buflen,
  9997. data_len,
  9998. buf);
  9999. mg_send_http_error(conn,
  10000. 500,
  10001. "Error: CGI program sent malformed or too big "
  10002. "(>%u bytes) HTTP headers: [%.*s]",
  10003. (unsigned)buflen,
  10004. data_len,
  10005. buf);
  10006. }
  10007. /* in both cases, abort processing CGI */
  10008. goto done;
  10009. }
  10010. pbuf = buf;
  10011. buf[headers_len - 1] = '\0';
  10012. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10013. /* Make up and send the status line */
  10014. status_text = "OK";
  10015. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10016. != NULL) {
  10017. conn->status_code = atoi(status);
  10018. status_text = status;
  10019. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10020. status_text++;
  10021. }
  10022. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10023. != NULL) {
  10024. conn->status_code = 307;
  10025. } else {
  10026. conn->status_code = 200;
  10027. }
  10028. connection_state =
  10029. get_header(ri.http_headers, ri.num_headers, "Connection");
  10030. if (!header_has_option(connection_state, "keep-alive")) {
  10031. conn->must_close = 1;
  10032. }
  10033. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10034. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10035. /* Send headers */
  10036. for (i = 0; i < ri.num_headers; i++) {
  10037. DEBUG_TRACE("CGI header: %s: %s",
  10038. ri.http_headers[i].name,
  10039. ri.http_headers[i].value);
  10040. mg_printf(conn,
  10041. "%s: %s\r\n",
  10042. ri.http_headers[i].name,
  10043. ri.http_headers[i].value);
  10044. }
  10045. mg_write(conn, "\r\n", 2);
  10046. /* Send chunk of data that may have been read after the headers */
  10047. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10048. /* Read the rest of CGI output and send to the client */
  10049. DEBUG_TRACE("CGI: %s", "forward all data");
  10050. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10051. DEBUG_TRACE("CGI: %s", "all data sent");
  10052. done:
  10053. mg_free(blk.var);
  10054. mg_free(blk.buf);
  10055. if (pid != (pid_t)-1) {
  10056. abort_cgi_process((void *)proc);
  10057. }
  10058. if (fdin[0] != -1) {
  10059. close(fdin[0]);
  10060. }
  10061. if (fdout[1] != -1) {
  10062. close(fdout[1]);
  10063. }
  10064. if (fderr[1] != -1) {
  10065. close(fderr[1]);
  10066. }
  10067. if (in != NULL) {
  10068. fclose(in);
  10069. } else if (fdin[1] != -1) {
  10070. close(fdin[1]);
  10071. }
  10072. if (out != NULL) {
  10073. fclose(out);
  10074. } else if (fdout[0] != -1) {
  10075. close(fdout[0]);
  10076. }
  10077. if (err != NULL) {
  10078. fclose(err);
  10079. } else if (fderr[0] != -1) {
  10080. close(fderr[0]);
  10081. }
  10082. mg_free(buf);
  10083. }
  10084. #endif /* !NO_CGI */
  10085. #if !defined(NO_FILES)
  10086. static void
  10087. dav_mkcol(struct mg_connection *conn, const char *path)
  10088. {
  10089. int rc, body_len;
  10090. struct de de;
  10091. if (conn == NULL) {
  10092. return;
  10093. }
  10094. /* TODO (mid): Check the mg_send_http_error situations in this function
  10095. */
  10096. memset(&de.file, 0, sizeof(de.file));
  10097. if (!mg_stat(conn, path, &de.file)) {
  10098. mg_cry_internal(conn,
  10099. "%s: mg_stat(%s) failed: %s",
  10100. __func__,
  10101. path,
  10102. strerror(ERRNO));
  10103. }
  10104. if (de.file.last_modified) {
  10105. /* TODO (mid): This check does not seem to make any sense ! */
  10106. /* TODO (mid): Add a webdav unit test first, before changing
  10107. * anything here. */
  10108. mg_send_http_error(
  10109. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10110. return;
  10111. }
  10112. body_len = conn->data_len - conn->request_len;
  10113. if (body_len > 0) {
  10114. mg_send_http_error(
  10115. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10116. return;
  10117. }
  10118. rc = mg_mkdir(conn, path, 0755);
  10119. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10120. if (rc == 0) {
  10121. /* Create 201 "Created" response */
  10122. mg_response_header_start(conn, 201);
  10123. send_static_cache_header(conn);
  10124. send_additional_header(conn);
  10125. mg_response_header_add(conn, "Content-Length", "0", -1);
  10126. /* Send all headers - there is no body */
  10127. mg_response_header_send(conn);
  10128. } else {
  10129. int http_status = 500;
  10130. switch (errno) {
  10131. case EEXIST:
  10132. http_status = 405;
  10133. break;
  10134. case EACCES:
  10135. http_status = 403;
  10136. break;
  10137. case ENOENT:
  10138. http_status = 409;
  10139. break;
  10140. }
  10141. mg_send_http_error(conn,
  10142. http_status,
  10143. "Error processing %s: %s",
  10144. path,
  10145. strerror(ERRNO));
  10146. }
  10147. }
  10148. /* Forward decrlaration */
  10149. static int get_uri_type(const char *uri);
  10150. static const char *
  10151. get_rel_url_at_current_server(const char *uri,
  10152. const struct mg_connection *conn);
  10153. static void
  10154. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10155. {
  10156. const char *overwrite_hdr;
  10157. const char *destination_hdr;
  10158. const char *root;
  10159. int rc, dest_uri_type;
  10160. int http_status = 400;
  10161. int do_overwrite = 0;
  10162. int destination_ok = 0;
  10163. char dest_path[UTF8_PATH_MAX];
  10164. struct mg_file_stat ignored;
  10165. if (conn == NULL) {
  10166. return;
  10167. }
  10168. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10169. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10170. destination_hdr = mg_get_header(conn, "Destination");
  10171. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10172. do_overwrite = 1;
  10173. }
  10174. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10175. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10176. return;
  10177. }
  10178. if (root != NULL) {
  10179. char *local_dest = NULL;
  10180. dest_uri_type = get_uri_type(destination_hdr);
  10181. if (dest_uri_type == 2) {
  10182. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10183. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10184. const char *h =
  10185. get_rel_url_at_current_server(destination_hdr, conn);
  10186. if (h) {
  10187. int len = (int)strlen(h);
  10188. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10189. mg_url_decode(h, len, local_dest, len + 1, 0);
  10190. }
  10191. }
  10192. if (local_dest != NULL) {
  10193. remove_dot_segments(local_dest);
  10194. if (local_dest[0] == '/') {
  10195. int trunc_check = 0;
  10196. mg_snprintf(conn,
  10197. &trunc_check,
  10198. dest_path,
  10199. sizeof(dest_path),
  10200. "%s/%s",
  10201. root,
  10202. local_dest);
  10203. if (trunc_check == 0) {
  10204. destination_ok = 1;
  10205. }
  10206. }
  10207. mg_free(local_dest);
  10208. }
  10209. }
  10210. if (!destination_ok) {
  10211. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10212. return;
  10213. }
  10214. /* Check now if this file exists */
  10215. if (mg_stat(conn, dest_path, &ignored)) {
  10216. /* File exists */
  10217. if (do_overwrite) {
  10218. /* Overwrite allowed: delete the file first */
  10219. if (0 != remove(dest_path)) {
  10220. /* No overwrite: return error */
  10221. mg_send_http_error(conn,
  10222. 403,
  10223. "Cannot overwrite file: %s",
  10224. dest_path);
  10225. return;
  10226. }
  10227. } else {
  10228. /* No overwrite: return error */
  10229. mg_send_http_error(conn,
  10230. 412,
  10231. "Destination already exists: %s",
  10232. dest_path);
  10233. return;
  10234. }
  10235. }
  10236. /* Copy / Move / Rename operation. */
  10237. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10238. #if defined(_WIN32)
  10239. {
  10240. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10241. wchar_t wSource[UTF16_PATH_MAX];
  10242. wchar_t wDest[UTF16_PATH_MAX];
  10243. BOOL ok;
  10244. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10245. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10246. if (do_copy) {
  10247. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10248. } else {
  10249. ok = MoveFileExW(wSource,
  10250. wDest,
  10251. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10252. }
  10253. if (ok) {
  10254. rc = 0;
  10255. } else {
  10256. DWORD lastErr = GetLastError();
  10257. if (lastErr == ERROR_ALREADY_EXISTS) {
  10258. mg_send_http_error(conn,
  10259. 412,
  10260. "Destination already exists: %s",
  10261. dest_path);
  10262. return;
  10263. }
  10264. rc = -1;
  10265. http_status = 400;
  10266. }
  10267. }
  10268. #else
  10269. {
  10270. /* Linux uses already UTF-8, we don't need to convert file names. */
  10271. if (do_copy) {
  10272. /* TODO: COPY for Linux. */
  10273. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10274. return;
  10275. }
  10276. rc = rename(path, dest_path);
  10277. if (rc) {
  10278. switch (errno) {
  10279. case EEXIST:
  10280. http_status = 412;
  10281. break;
  10282. case EACCES:
  10283. http_status = 403;
  10284. break;
  10285. case ENOENT:
  10286. http_status = 409;
  10287. break;
  10288. }
  10289. }
  10290. }
  10291. #endif
  10292. if (rc == 0) {
  10293. /* Create 204 "No Content" response */
  10294. mg_response_header_start(conn, 204);
  10295. mg_response_header_add(conn, "Content-Length", "0", -1);
  10296. /* Send all headers - there is no body */
  10297. mg_response_header_send(conn);
  10298. } else {
  10299. mg_send_http_error(conn, http_status, "Operation failed");
  10300. }
  10301. }
  10302. static void
  10303. put_file(struct mg_connection *conn, const char *path)
  10304. {
  10305. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10306. const char *range;
  10307. int64_t r1, r2;
  10308. int rc;
  10309. if (conn == NULL) {
  10310. return;
  10311. }
  10312. DEBUG_TRACE("store %s", path);
  10313. if (mg_stat(conn, path, &file.stat)) {
  10314. /* File already exists */
  10315. conn->status_code = 200;
  10316. if (file.stat.is_directory) {
  10317. /* This is an already existing directory,
  10318. * so there is nothing to do for the server. */
  10319. rc = 0;
  10320. } else {
  10321. /* File exists and is not a directory. */
  10322. /* Can it be replaced? */
  10323. /* Check if the server may write this file */
  10324. if (access(path, W_OK) == 0) {
  10325. /* Access granted */
  10326. rc = 1;
  10327. } else {
  10328. mg_send_http_error(
  10329. conn,
  10330. 403,
  10331. "Error: Put not possible\nReplacing %s is not allowed",
  10332. path);
  10333. return;
  10334. }
  10335. }
  10336. } else {
  10337. /* File should be created */
  10338. conn->status_code = 201;
  10339. rc = put_dir(conn, path);
  10340. }
  10341. if (rc == 0) {
  10342. /* put_dir returns 0 if path is a directory */
  10343. /* Create response */
  10344. mg_response_header_start(conn, conn->status_code);
  10345. send_no_cache_header(conn);
  10346. send_additional_header(conn);
  10347. mg_response_header_add(conn, "Content-Length", "0", -1);
  10348. /* Send all headers - there is no body */
  10349. mg_response_header_send(conn);
  10350. /* Request to create a directory has been fulfilled successfully.
  10351. * No need to put a file. */
  10352. return;
  10353. }
  10354. if (rc == -1) {
  10355. /* put_dir returns -1 if the path is too long */
  10356. mg_send_http_error(conn,
  10357. 414,
  10358. "Error: Path too long\nput_dir(%s): %s",
  10359. path,
  10360. strerror(ERRNO));
  10361. return;
  10362. }
  10363. if (rc == -2) {
  10364. /* put_dir returns -2 if the directory can not be created */
  10365. mg_send_http_error(conn,
  10366. 500,
  10367. "Error: Can not create directory\nput_dir(%s): %s",
  10368. path,
  10369. strerror(ERRNO));
  10370. return;
  10371. }
  10372. /* A file should be created or overwritten. */
  10373. /* Currently CivetWeb does not nead read+write access. */
  10374. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10375. || file.access.fp == NULL) {
  10376. (void)mg_fclose(&file.access);
  10377. mg_send_http_error(conn,
  10378. 500,
  10379. "Error: Can not create file\nfopen(%s): %s",
  10380. path,
  10381. strerror(ERRNO));
  10382. return;
  10383. }
  10384. fclose_on_exec(&file.access, conn);
  10385. range = mg_get_header(conn, "Content-Range");
  10386. r1 = r2 = 0;
  10387. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10388. conn->status_code = 206; /* Partial content */
  10389. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10390. mg_send_http_error(conn,
  10391. 500,
  10392. "Error: Internal error processing file %s",
  10393. path);
  10394. return;
  10395. }
  10396. }
  10397. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10398. /* forward_body_data failed.
  10399. * The error code has already been sent to the client,
  10400. * and conn->status_code is already set. */
  10401. (void)mg_fclose(&file.access);
  10402. return;
  10403. }
  10404. if (mg_fclose(&file.access) != 0) {
  10405. /* fclose failed. This might have different reasons, but a likely
  10406. * one is "no space on disk", http 507. */
  10407. conn->status_code = 507;
  10408. }
  10409. /* Create response (status_code has been set before) */
  10410. mg_response_header_start(conn, conn->status_code);
  10411. send_no_cache_header(conn);
  10412. send_additional_header(conn);
  10413. mg_response_header_add(conn, "Content-Length", "0", -1);
  10414. /* Send all headers - there is no body */
  10415. mg_response_header_send(conn);
  10416. }
  10417. static void
  10418. delete_file(struct mg_connection *conn, const char *path)
  10419. {
  10420. struct de de;
  10421. memset(&de.file, 0, sizeof(de.file));
  10422. if (!mg_stat(conn, path, &de.file)) {
  10423. /* mg_stat returns 0 if the file does not exist */
  10424. mg_send_http_error(conn,
  10425. 404,
  10426. "Error: Cannot delete file\nFile %s not found",
  10427. path);
  10428. return;
  10429. }
  10430. DEBUG_TRACE("delete %s", path);
  10431. if (de.file.is_directory) {
  10432. if (remove_directory(conn, path)) {
  10433. /* Delete is successful: Return 204 without content. */
  10434. mg_send_http_error(conn, 204, "%s", "");
  10435. } else {
  10436. /* Delete is not successful: Return 500 (Server error). */
  10437. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10438. }
  10439. return;
  10440. }
  10441. /* This is an existing file (not a directory).
  10442. * Check if write permission is granted. */
  10443. if (access(path, W_OK) != 0) {
  10444. /* File is read only */
  10445. mg_send_http_error(
  10446. conn,
  10447. 403,
  10448. "Error: Delete not possible\nDeleting %s is not allowed",
  10449. path);
  10450. return;
  10451. }
  10452. /* Try to delete it. */
  10453. if (mg_remove(conn, path) == 0) {
  10454. /* Delete was successful: Return 204 without content. */
  10455. mg_response_header_start(conn, 204);
  10456. send_no_cache_header(conn);
  10457. send_additional_header(conn);
  10458. mg_response_header_add(conn, "Content-Length", "0", -1);
  10459. mg_response_header_send(conn);
  10460. } else {
  10461. /* Delete not successful (file locked). */
  10462. mg_send_http_error(conn,
  10463. 423,
  10464. "Error: Cannot delete file\nremove(%s): %s",
  10465. path,
  10466. strerror(ERRNO));
  10467. }
  10468. }
  10469. #endif /* !NO_FILES */
  10470. #if !defined(NO_FILESYSTEMS)
  10471. static void
  10472. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10473. static void
  10474. do_ssi_include(struct mg_connection *conn,
  10475. const char *ssi,
  10476. char *tag,
  10477. int include_level)
  10478. {
  10479. char file_name[MG_BUF_LEN], path[512], *p;
  10480. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10481. size_t len;
  10482. int truncated = 0;
  10483. if (conn == NULL) {
  10484. return;
  10485. }
  10486. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10487. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10488. * always < MG_BUF_LEN. */
  10489. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10490. /* File name is relative to the webserver root */
  10491. file_name[511] = 0;
  10492. (void)mg_snprintf(conn,
  10493. &truncated,
  10494. path,
  10495. sizeof(path),
  10496. "%s/%s",
  10497. conn->dom_ctx->config[DOCUMENT_ROOT],
  10498. file_name);
  10499. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10500. /* File name is relative to the webserver working directory
  10501. * or it is absolute system path */
  10502. file_name[511] = 0;
  10503. (void)
  10504. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10505. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10506. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10507. /* File name is relative to the currect document */
  10508. file_name[511] = 0;
  10509. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10510. if (!truncated) {
  10511. if ((p = strrchr(path, '/')) != NULL) {
  10512. p[1] = '\0';
  10513. }
  10514. len = strlen(path);
  10515. (void)mg_snprintf(conn,
  10516. &truncated,
  10517. path + len,
  10518. sizeof(path) - len,
  10519. "%s",
  10520. file_name);
  10521. }
  10522. } else {
  10523. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10524. return;
  10525. }
  10526. if (truncated) {
  10527. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10528. return;
  10529. }
  10530. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10531. mg_cry_internal(conn,
  10532. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10533. tag,
  10534. path,
  10535. strerror(ERRNO));
  10536. } else {
  10537. fclose_on_exec(&file.access, conn);
  10538. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10539. > 0) {
  10540. send_ssi_file(conn, path, &file, include_level + 1);
  10541. } else {
  10542. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10543. }
  10544. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10545. }
  10546. }
  10547. #if !defined(NO_POPEN)
  10548. static void
  10549. do_ssi_exec(struct mg_connection *conn, char *tag)
  10550. {
  10551. char cmd[1024] = "";
  10552. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10553. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10554. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10555. } else {
  10556. cmd[1023] = 0;
  10557. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10558. mg_cry_internal(conn,
  10559. "Cannot SSI #exec: [%s]: %s",
  10560. cmd,
  10561. strerror(ERRNO));
  10562. } else {
  10563. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10564. pclose(file.access.fp);
  10565. }
  10566. }
  10567. }
  10568. #endif /* !NO_POPEN */
  10569. static int
  10570. mg_fgetc(struct mg_file *filep)
  10571. {
  10572. if (filep == NULL) {
  10573. return EOF;
  10574. }
  10575. if (filep->access.fp != NULL) {
  10576. return fgetc(filep->access.fp);
  10577. } else {
  10578. return EOF;
  10579. }
  10580. }
  10581. static void
  10582. send_ssi_file(struct mg_connection *conn,
  10583. const char *path,
  10584. struct mg_file *filep,
  10585. int include_level)
  10586. {
  10587. char buf[MG_BUF_LEN];
  10588. int ch, len, in_tag, in_ssi_tag;
  10589. if (include_level > 10) {
  10590. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10591. return;
  10592. }
  10593. in_tag = in_ssi_tag = len = 0;
  10594. /* Read file, byte by byte, and look for SSI include tags */
  10595. while ((ch = mg_fgetc(filep)) != EOF) {
  10596. if (in_tag) {
  10597. /* We are in a tag, either SSI tag or html tag */
  10598. if (ch == '>') {
  10599. /* Tag is closing */
  10600. buf[len++] = '>';
  10601. if (in_ssi_tag) {
  10602. /* Handle SSI tag */
  10603. buf[len] = 0;
  10604. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10605. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10606. #if !defined(NO_POPEN)
  10607. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10608. do_ssi_exec(conn, buf + 9);
  10609. #endif /* !NO_POPEN */
  10610. } else {
  10611. mg_cry_internal(conn,
  10612. "%s: unknown SSI "
  10613. "command: \"%s\"",
  10614. path,
  10615. buf);
  10616. }
  10617. len = 0;
  10618. in_ssi_tag = in_tag = 0;
  10619. } else {
  10620. /* Not an SSI tag */
  10621. /* Flush buffer */
  10622. (void)mg_write(conn, buf, (size_t)len);
  10623. len = 0;
  10624. in_tag = 0;
  10625. }
  10626. } else {
  10627. /* Tag is still open */
  10628. buf[len++] = (char)(ch & 0xff);
  10629. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10630. /* All SSI tags start with <!--# */
  10631. in_ssi_tag = 1;
  10632. }
  10633. if ((len + 2) > (int)sizeof(buf)) {
  10634. /* Tag to long for buffer */
  10635. mg_cry_internal(conn, "%s: tag is too large", path);
  10636. return;
  10637. }
  10638. }
  10639. } else {
  10640. /* We are not in a tag yet. */
  10641. if (ch == '<') {
  10642. /* Tag is opening */
  10643. in_tag = 1;
  10644. if (len > 0) {
  10645. /* Flush current buffer.
  10646. * Buffer is filled with "len" bytes. */
  10647. (void)mg_write(conn, buf, (size_t)len);
  10648. }
  10649. /* Store the < */
  10650. len = 1;
  10651. buf[0] = '<';
  10652. } else {
  10653. /* No Tag */
  10654. /* Add data to buffer */
  10655. buf[len++] = (char)(ch & 0xff);
  10656. /* Flush if buffer is full */
  10657. if (len == (int)sizeof(buf)) {
  10658. mg_write(conn, buf, (size_t)len);
  10659. len = 0;
  10660. }
  10661. }
  10662. }
  10663. }
  10664. /* Send the rest of buffered data */
  10665. if (len > 0) {
  10666. mg_write(conn, buf, (size_t)len);
  10667. }
  10668. }
  10669. static void
  10670. handle_ssi_file_request(struct mg_connection *conn,
  10671. const char *path,
  10672. struct mg_file *filep)
  10673. {
  10674. char date[64];
  10675. time_t curtime = time(NULL);
  10676. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10677. return;
  10678. }
  10679. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10680. /* File exists (precondition for calling this function),
  10681. * but can not be opened by the server. */
  10682. mg_send_http_error(conn,
  10683. 500,
  10684. "Error: Cannot read file\nfopen(%s): %s",
  10685. path,
  10686. strerror(ERRNO));
  10687. } else {
  10688. /* Set "must_close" for HTTP/1.x, since we do not know the
  10689. * content length */
  10690. conn->must_close = 1;
  10691. gmt_time_string(date, sizeof(date), &curtime);
  10692. fclose_on_exec(&filep->access, conn);
  10693. /* 200 OK response */
  10694. mg_response_header_start(conn, 200);
  10695. send_no_cache_header(conn);
  10696. send_additional_header(conn);
  10697. send_cors_header(conn);
  10698. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10699. mg_response_header_send(conn);
  10700. /* Header sent, now send body */
  10701. send_ssi_file(conn, path, filep, 0);
  10702. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10703. }
  10704. }
  10705. #endif /* NO_FILESYSTEMS */
  10706. #if !defined(NO_FILES)
  10707. static void
  10708. send_options(struct mg_connection *conn)
  10709. {
  10710. if (!conn || !all_methods) {
  10711. return;
  10712. }
  10713. /* We do not set a "Cache-Control" header here, but leave the default.
  10714. * Since browsers do not send an OPTIONS request, we can not test the
  10715. * effect anyway. */
  10716. mg_response_header_start(conn, 200);
  10717. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10718. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10719. /* Use the same as before */
  10720. mg_response_header_add(conn, "Allow", all_methods, -1);
  10721. mg_response_header_add(conn, "DAV", "1", -1);
  10722. } else {
  10723. /* TODO: Check this later for HTTP/2 */
  10724. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10725. }
  10726. send_additional_header(conn);
  10727. mg_response_header_send(conn);
  10728. }
  10729. /* Writes PROPFIND properties for a collection element */
  10730. static int
  10731. print_props(struct mg_connection *conn,
  10732. const char *uri,
  10733. const char *name,
  10734. struct mg_file_stat *filep)
  10735. {
  10736. size_t i;
  10737. char mtime[64];
  10738. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10739. char *link_concat;
  10740. size_t link_concat_len;
  10741. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10742. return 0;
  10743. }
  10744. link_concat_len = strlen(uri) + strlen(name) + 1;
  10745. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  10746. if (!link_concat) {
  10747. return 0;
  10748. }
  10749. strcpy(link_concat, uri);
  10750. strcat(link_concat, name);
  10751. /* Get full link used in request */
  10752. mg_construct_local_link(
  10753. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  10754. /*
  10755. OutputDebugStringA("print_props:\n uri: ");
  10756. OutputDebugStringA(uri);
  10757. OutputDebugStringA("\n name: ");
  10758. OutputDebugStringA(name);
  10759. OutputDebugStringA("\n link: ");
  10760. OutputDebugStringA(link_buf);
  10761. OutputDebugStringA("\n");
  10762. */
  10763. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10764. mg_printf(conn,
  10765. "<d:response>"
  10766. "<d:href>%s</d:href>"
  10767. "<d:propstat>"
  10768. "<d:prop>"
  10769. "<d:resourcetype>%s</d:resourcetype>"
  10770. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10771. "<d:getlastmodified>%s</d:getlastmodified>"
  10772. "<d:lockdiscovery>",
  10773. link_buf,
  10774. filep->is_directory ? "<d:collection/>" : "",
  10775. filep->size,
  10776. mtime);
  10777. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10778. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10779. if (!strcmp(dav_lock[i].path, link_buf)) {
  10780. mg_printf(conn,
  10781. "<d:activelock>"
  10782. "<d:locktype><d:write/></d:locktype>"
  10783. "<d:lockscope><d:exclusive/></d:lockscope>"
  10784. "<d:depth>0</d:depth>"
  10785. "<d:owner>%s</d:owner>"
  10786. "<d:timeout>Second-%u</d:timeout>"
  10787. "<d:locktoken>"
  10788. "<d:href>%s</d:href>"
  10789. "</d:locktoken>"
  10790. "</d:activelock>\n",
  10791. dav_lock[i].user,
  10792. (unsigned)LOCK_DURATION_S,
  10793. dav_lock[i].token);
  10794. }
  10795. }
  10796. mg_printf(conn,
  10797. "</d:lockdiscovery>"
  10798. "</d:prop>"
  10799. "<d:status>HTTP/1.1 200 OK</d:status>"
  10800. "</d:propstat>"
  10801. "</d:response>\n");
  10802. mg_free(link_concat);
  10803. return 1;
  10804. }
  10805. static int
  10806. print_dav_dir_entry(struct de *de, void *data)
  10807. {
  10808. struct mg_connection *conn = (struct mg_connection *)data;
  10809. if (!de || !conn
  10810. || !print_props(
  10811. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10812. /* stop scan */
  10813. return 1;
  10814. }
  10815. return 0;
  10816. }
  10817. static void
  10818. handle_propfind(struct mg_connection *conn,
  10819. const char *path,
  10820. struct mg_file_stat *filep)
  10821. {
  10822. const char *depth = mg_get_header(conn, "Depth");
  10823. if (!conn || !path || !filep || !conn->dom_ctx) {
  10824. return;
  10825. }
  10826. /* return 207 "Multi-Status" */
  10827. conn->must_close = 1;
  10828. mg_response_header_start(conn, 207);
  10829. send_static_cache_header(conn);
  10830. send_additional_header(conn);
  10831. mg_response_header_add(conn,
  10832. "Content-Type",
  10833. "application/xml; charset=utf-8",
  10834. -1);
  10835. mg_response_header_send(conn);
  10836. /* Content */
  10837. mg_printf(conn,
  10838. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10839. "<d:multistatus xmlns:d='DAV:'>\n");
  10840. /* Print properties for the requested resource itself */
  10841. print_props(conn, conn->request_info.local_uri, "", filep);
  10842. /* If it is a directory, print directory entries too if Depth is not 0
  10843. */
  10844. if (filep->is_directory
  10845. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10846. "yes")
  10847. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10848. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10849. }
  10850. mg_printf(conn, "%s\n", "</d:multistatus>");
  10851. }
  10852. static void
  10853. dav_lock_file(struct mg_connection *conn, const char *path)
  10854. {
  10855. /* internal function - therefore conn is assumed to be valid */
  10856. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10857. uint64_t new_locktime;
  10858. int lock_index = -1;
  10859. int i;
  10860. uint64_t LOCK_DURATION_NS =
  10861. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10862. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10863. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10864. return;
  10865. }
  10866. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10867. /* const char *refresh = mg_get_header(conn, "If"); */
  10868. /* Link refresh should have an "If" header:
  10869. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10870. * But it seems Windows Explorer does not send them.
  10871. */
  10872. mg_lock_context(conn->phys_ctx);
  10873. new_locktime = mg_get_current_time_ns();
  10874. /* Find a slot for a lock */
  10875. while (lock_index < 0) {
  10876. /* find existing lock */
  10877. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10878. if (!strcmp(dav_lock[i].path, link_buf)) {
  10879. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10880. /* locked by the same user */
  10881. dav_lock[i].locktime = new_locktime;
  10882. lock_index = i;
  10883. break;
  10884. } else {
  10885. /* already locked by someone else */
  10886. if (new_locktime
  10887. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10888. /* Lock expired */
  10889. dav_lock[i].path[0] = 0;
  10890. } else {
  10891. /* Lock still valid */
  10892. mg_unlock_context(conn->phys_ctx);
  10893. mg_send_http_error(conn, 423, "%s", "Already locked");
  10894. return;
  10895. }
  10896. }
  10897. }
  10898. }
  10899. /* create new lock token */
  10900. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10901. if (dav_lock[i].path[0] == 0) {
  10902. char s[32];
  10903. dav_lock[i].locktime = mg_get_current_time_ns();
  10904. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10905. mg_md5(dav_lock[i].token,
  10906. link_buf,
  10907. "\x01",
  10908. s,
  10909. "\x01",
  10910. conn->request_info.remote_user,
  10911. NULL);
  10912. strncpy(dav_lock[i].path,
  10913. link_buf,
  10914. sizeof(dav_lock[i].path) - 1);
  10915. strncpy(dav_lock[i].user,
  10916. conn->request_info.remote_user,
  10917. sizeof(dav_lock[i].user) - 1);
  10918. lock_index = i;
  10919. break;
  10920. }
  10921. }
  10922. if (lock_index < 0) {
  10923. /* too many locks. Find oldest lock */
  10924. uint64_t oldest_locktime = dav_lock[0].locktime;
  10925. lock_index = 0;
  10926. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10927. if (dav_lock[i].locktime < oldest_locktime) {
  10928. oldest_locktime = dav_lock[i].locktime;
  10929. lock_index = i;
  10930. }
  10931. }
  10932. /* invalidate oldest lock */
  10933. dav_lock[lock_index].path[0] = 0;
  10934. }
  10935. }
  10936. mg_unlock_context(conn->phys_ctx);
  10937. /* return 200 "OK" */
  10938. conn->must_close = 1;
  10939. mg_response_header_start(conn, 200);
  10940. send_static_cache_header(conn);
  10941. send_additional_header(conn);
  10942. mg_response_header_add(conn,
  10943. "Content-Type",
  10944. "application/xml; charset=utf-8",
  10945. -1);
  10946. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10947. mg_response_header_send(conn);
  10948. /* Content */
  10949. mg_printf(conn,
  10950. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10951. "<d:prop xmlns:d=\"DAV:\">\n"
  10952. " <d:lockdiscovery>\n"
  10953. " <d:activelock>\n"
  10954. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  10955. " <d:locktype><d:write/></d:locktype>\n"
  10956. " <d:owner>\n"
  10957. " <d:href>%s</d:href>\n"
  10958. " </d:owner>\n"
  10959. " <d:timeout>Second-%u</d:timeout>\n"
  10960. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  10961. " <d:lockroot>\n"
  10962. " <d:href>%s</d:href>\n"
  10963. " </d:lockroot>\n"
  10964. " </d:activelock>\n"
  10965. " </d:lockdiscovery>\n"
  10966. " </d:prop>\n",
  10967. dav_lock[lock_index].user,
  10968. (LOCK_DURATION_S),
  10969. dav_lock[lock_index].token,
  10970. dav_lock[lock_index].path);
  10971. }
  10972. static void
  10973. dav_unlock_file(struct mg_connection *conn, const char *path)
  10974. {
  10975. /* internal function - therefore conn is assumed to be valid */
  10976. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10977. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10978. int lock_index;
  10979. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10980. return;
  10981. }
  10982. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10983. mg_lock_context(conn->phys_ctx);
  10984. /* find existing lock */
  10985. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  10986. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  10987. /* Success: return 204 "No Content" */
  10988. mg_unlock_context(conn->phys_ctx);
  10989. conn->must_close = 1;
  10990. mg_response_header_start(conn, 204);
  10991. mg_response_header_send(conn);
  10992. return;
  10993. }
  10994. }
  10995. mg_unlock_context(conn->phys_ctx);
  10996. /* Error: Cannot unlock a resource that is not locked */
  10997. mg_send_http_error(conn, 423, "%s", "Lock not found");
  10998. }
  10999. static void
  11000. dav_proppatch(struct mg_connection *conn, const char *path)
  11001. {
  11002. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11003. if (!conn || !path || !conn->dom_ctx) {
  11004. return;
  11005. }
  11006. /* return 207 "Multi-Status" */
  11007. conn->must_close = 1;
  11008. mg_response_header_start(conn, 207);
  11009. send_static_cache_header(conn);
  11010. send_additional_header(conn);
  11011. mg_response_header_add(conn,
  11012. "Content-Type",
  11013. "application/xml; charset=utf-8",
  11014. -1);
  11015. mg_response_header_send(conn);
  11016. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11017. /* Content */
  11018. mg_printf(conn,
  11019. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11020. "<d:multistatus xmlns:d='DAV:'>\n"
  11021. "<d:response>\n<d:href>%s</d:href>\n",
  11022. link_buf);
  11023. mg_printf(conn,
  11024. "<d:propstat><d:status>HTTP/1.1 403 "
  11025. "Forbidden</d:status></d:propstat>\n");
  11026. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11027. }
  11028. #endif
  11029. CIVETWEB_API void
  11030. mg_lock_connection(struct mg_connection *conn)
  11031. {
  11032. if (conn) {
  11033. (void)pthread_mutex_lock(&conn->mutex);
  11034. }
  11035. }
  11036. CIVETWEB_API void
  11037. mg_unlock_connection(struct mg_connection *conn)
  11038. {
  11039. if (conn) {
  11040. (void)pthread_mutex_unlock(&conn->mutex);
  11041. }
  11042. }
  11043. CIVETWEB_API void
  11044. mg_lock_context(struct mg_context *ctx)
  11045. {
  11046. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11047. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11048. }
  11049. }
  11050. CIVETWEB_API void
  11051. mg_unlock_context(struct mg_context *ctx)
  11052. {
  11053. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11054. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11055. }
  11056. }
  11057. #if defined(USE_LUA)
  11058. #include "mod_lua.inl"
  11059. #endif /* USE_LUA */
  11060. #if defined(USE_DUKTAPE)
  11061. #include "mod_duktape.inl"
  11062. #endif /* USE_DUKTAPE */
  11063. #if defined(USE_WEBSOCKET)
  11064. #if !defined(NO_SSL_DL)
  11065. #define SHA_API static
  11066. #include "sha1.inl"
  11067. #endif
  11068. static int
  11069. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11070. {
  11071. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11072. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11073. size_t dst_len = sizeof(b64_sha);
  11074. SHA_CTX sha_ctx;
  11075. int truncated;
  11076. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11077. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11078. if (truncated) {
  11079. conn->must_close = 1;
  11080. return 0;
  11081. }
  11082. DEBUG_TRACE("%s", "Send websocket handshake");
  11083. SHA1_Init(&sha_ctx);
  11084. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11085. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11086. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11087. mg_printf(conn,
  11088. "HTTP/1.1 101 Switching Protocols\r\n"
  11089. "Upgrade: websocket\r\n"
  11090. "Connection: Upgrade\r\n"
  11091. "Sec-WebSocket-Accept: %s\r\n",
  11092. b64_sha);
  11093. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11094. // Send negotiated compression extension parameters
  11095. websocket_deflate_response(conn);
  11096. #endif
  11097. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11098. mg_printf(conn,
  11099. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11100. conn->request_info.acceptedWebSocketSubprotocol);
  11101. } else {
  11102. mg_printf(conn, "%s", "\r\n");
  11103. }
  11104. return 1;
  11105. }
  11106. #if !defined(MG_MAX_UNANSWERED_PING)
  11107. /* Configuration of the maximum number of websocket PINGs that might
  11108. * stay unanswered before the connection is considered broken.
  11109. * Note: The name of this define may still change (until it is
  11110. * defined as a compile parameter in a documentation).
  11111. */
  11112. #define MG_MAX_UNANSWERED_PING (5)
  11113. #endif
  11114. static void
  11115. read_websocket(struct mg_connection *conn,
  11116. mg_websocket_data_handler ws_data_handler,
  11117. void *callback_data)
  11118. {
  11119. /* Pointer to the beginning of the portion of the incoming websocket
  11120. * message queue.
  11121. * The original websocket upgrade request is never removed, so the queue
  11122. * begins after it. */
  11123. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11124. int n, error, exit_by_callback;
  11125. int ret;
  11126. /* body_len is the length of the entire queue in bytes
  11127. * len is the length of the current message
  11128. * data_len is the length of the current message's data payload
  11129. * header_len is the length of the current message's header */
  11130. size_t i, len, mask_len = 0, header_len, body_len;
  11131. uint64_t data_len = 0;
  11132. /* "The masking key is a 32-bit value chosen at random by the client."
  11133. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11134. */
  11135. unsigned char mask[4];
  11136. /* data points to the place where the message is stored when passed to
  11137. * the websocket_data callback. This is either mem on the stack, or a
  11138. * dynamically allocated buffer if it is too large. */
  11139. unsigned char mem[4096];
  11140. unsigned char mop; /* mask flag and opcode */
  11141. /* Variables used for connection monitoring */
  11142. double timeout = -1.0;
  11143. int enable_ping_pong = 0;
  11144. int ping_count = 0;
  11145. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11146. enable_ping_pong =
  11147. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11148. "yes");
  11149. }
  11150. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11151. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11152. }
  11153. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11154. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11155. }
  11156. if (timeout <= 0.0) {
  11157. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11158. }
  11159. /* Enter data processing loop */
  11160. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11161. conn->request_info.remote_addr,
  11162. conn->request_info.remote_port);
  11163. conn->in_websocket_handling = 1;
  11164. mg_set_thread_name("wsock");
  11165. /* Loop continuously, reading messages from the socket, invoking the
  11166. * callback, and waiting repeatedly until an error occurs. */
  11167. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11168. && (!conn->must_close)) {
  11169. header_len = 0;
  11170. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11171. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11172. len = buf[1] & 127;
  11173. mask_len = (buf[1] & 128) ? 4 : 0;
  11174. if ((len < 126) && (body_len >= mask_len)) {
  11175. /* inline 7-bit length field */
  11176. data_len = len;
  11177. header_len = 2 + mask_len;
  11178. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11179. /* 16-bit length field */
  11180. header_len = 4 + mask_len;
  11181. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11182. } else if (body_len >= (10 + mask_len)) {
  11183. /* 64-bit length field */
  11184. uint32_t l1, l2;
  11185. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11186. memcpy(&l2, &buf[6], 4);
  11187. header_len = 10 + mask_len;
  11188. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11189. if (data_len > (uint64_t)0x7FFF0000ul) {
  11190. /* no can do */
  11191. mg_cry_internal(
  11192. conn,
  11193. "%s",
  11194. "websocket out of memory; closing connection");
  11195. break;
  11196. }
  11197. }
  11198. }
  11199. if ((header_len > 0) && (body_len >= header_len)) {
  11200. /* Allocate space to hold websocket payload */
  11201. unsigned char *data = mem;
  11202. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11203. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11204. conn->phys_ctx);
  11205. if (data == NULL) {
  11206. /* Allocation failed, exit the loop and then close the
  11207. * connection */
  11208. mg_cry_internal(
  11209. conn,
  11210. "%s",
  11211. "websocket out of memory; closing connection");
  11212. break;
  11213. }
  11214. }
  11215. /* Copy the mask before we shift the queue and destroy it */
  11216. if (mask_len > 0) {
  11217. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11218. } else {
  11219. memset(mask, 0, sizeof(mask));
  11220. }
  11221. /* Read frame payload from the first message in the queue into
  11222. * data and advance the queue by moving the memory in place. */
  11223. DEBUG_ASSERT(body_len >= header_len);
  11224. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11225. mop = buf[0]; /* current mask and opcode */
  11226. /* Overflow case */
  11227. len = body_len - header_len;
  11228. memcpy(data, buf + header_len, len);
  11229. error = 0;
  11230. while ((uint64_t)len < data_len) {
  11231. n = pull_inner(NULL,
  11232. conn,
  11233. (char *)(data + len),
  11234. (int)(data_len - len),
  11235. timeout);
  11236. if (n <= -2) {
  11237. error = 1;
  11238. break;
  11239. } else if (n > 0) {
  11240. len += (size_t)n;
  11241. } else {
  11242. /* Timeout: should retry */
  11243. /* TODO: retry condition */
  11244. }
  11245. }
  11246. if (error) {
  11247. mg_cry_internal(
  11248. conn,
  11249. "%s",
  11250. "Websocket pull failed; closing connection");
  11251. if (data != mem) {
  11252. mg_free(data);
  11253. }
  11254. break;
  11255. }
  11256. conn->data_len = conn->request_len;
  11257. } else {
  11258. mop = buf[0]; /* current mask and opcode, overwritten by
  11259. * memmove() */
  11260. /* Length of the message being read at the front of the
  11261. * queue. Cast to 31 bit is OK, since we limited
  11262. * data_len before. */
  11263. len = (size_t)data_len + header_len;
  11264. /* Copy the data payload into the data pointer for the
  11265. * callback. Cast to 31 bit is OK, since we
  11266. * limited data_len */
  11267. memcpy(data, buf + header_len, (size_t)data_len);
  11268. /* Move the queue forward len bytes */
  11269. memmove(buf, buf + len, body_len - len);
  11270. /* Mark the queue as advanced */
  11271. conn->data_len -= (int)len;
  11272. }
  11273. /* Apply mask if necessary */
  11274. if (mask_len > 0) {
  11275. for (i = 0; i < (size_t)data_len; i++) {
  11276. data[i] ^= mask[i & 3];
  11277. }
  11278. }
  11279. exit_by_callback = 0;
  11280. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11281. /* filter PONG messages */
  11282. DEBUG_TRACE("PONG from %s:%u",
  11283. conn->request_info.remote_addr,
  11284. conn->request_info.remote_port);
  11285. /* No unanwered PINGs left */
  11286. ping_count = 0;
  11287. } else if (enable_ping_pong
  11288. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11289. /* reply PING messages */
  11290. DEBUG_TRACE("Reply PING from %s:%u",
  11291. conn->request_info.remote_addr,
  11292. conn->request_info.remote_port);
  11293. ret = mg_websocket_write(conn,
  11294. MG_WEBSOCKET_OPCODE_PONG,
  11295. (char *)data,
  11296. (size_t)data_len);
  11297. if (ret <= 0) {
  11298. /* Error: send failed */
  11299. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11300. break;
  11301. }
  11302. } else {
  11303. /* Exit the loop if callback signals to exit (server side),
  11304. * or "connection close" opcode received (client side). */
  11305. if (ws_data_handler != NULL) {
  11306. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11307. if (mop & 0x40) {
  11308. /* Inflate the data received if bit RSV1 is set. */
  11309. if (!conn->websocket_deflate_initialized) {
  11310. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11311. exit_by_callback = 1;
  11312. }
  11313. if (!exit_by_callback) {
  11314. size_t inflate_buf_size_old = 0;
  11315. size_t inflate_buf_size =
  11316. data_len
  11317. * 4; // Initial guess of the inflated message
  11318. // size. We double the memory when needed.
  11319. Bytef *inflated = NULL;
  11320. Bytef *new_mem = NULL;
  11321. conn->websocket_inflate_state.avail_in =
  11322. (uInt)(data_len + 4);
  11323. conn->websocket_inflate_state.next_in = data;
  11324. // Add trailing 0x00 0x00 0xff 0xff bytes
  11325. data[data_len] = '\x00';
  11326. data[data_len + 1] = '\x00';
  11327. data[data_len + 2] = '\xff';
  11328. data[data_len + 3] = '\xff';
  11329. do {
  11330. if (inflate_buf_size_old == 0) {
  11331. new_mem =
  11332. (Bytef *)mg_calloc(inflate_buf_size,
  11333. sizeof(Bytef));
  11334. } else {
  11335. inflate_buf_size *= 2;
  11336. new_mem =
  11337. (Bytef *)mg_realloc(inflated,
  11338. inflate_buf_size);
  11339. }
  11340. if (new_mem == NULL) {
  11341. mg_cry_internal(
  11342. conn,
  11343. "Out of memory: Cannot allocate "
  11344. "inflate buffer of %lu bytes",
  11345. (unsigned long)inflate_buf_size);
  11346. exit_by_callback = 1;
  11347. break;
  11348. }
  11349. inflated = new_mem;
  11350. conn->websocket_inflate_state.avail_out =
  11351. (uInt)(inflate_buf_size
  11352. - inflate_buf_size_old);
  11353. conn->websocket_inflate_state.next_out =
  11354. inflated + inflate_buf_size_old;
  11355. ret = inflate(&conn->websocket_inflate_state,
  11356. Z_SYNC_FLUSH);
  11357. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11358. || ret == Z_MEM_ERROR) {
  11359. mg_cry_internal(
  11360. conn,
  11361. "ZLIB inflate error: %i %s",
  11362. ret,
  11363. (conn->websocket_inflate_state.msg
  11364. ? conn->websocket_inflate_state.msg
  11365. : "<no error message>"));
  11366. exit_by_callback = 1;
  11367. break;
  11368. }
  11369. inflate_buf_size_old = inflate_buf_size;
  11370. } while (conn->websocket_inflate_state.avail_out
  11371. == 0);
  11372. inflate_buf_size -=
  11373. conn->websocket_inflate_state.avail_out;
  11374. if (!ws_data_handler(conn,
  11375. mop,
  11376. (char *)inflated,
  11377. inflate_buf_size,
  11378. callback_data)) {
  11379. exit_by_callback = 1;
  11380. }
  11381. mg_free(inflated);
  11382. }
  11383. } else
  11384. #endif
  11385. if (!ws_data_handler(conn,
  11386. mop,
  11387. (char *)data,
  11388. (size_t)data_len,
  11389. callback_data)) {
  11390. exit_by_callback = 1;
  11391. }
  11392. }
  11393. }
  11394. /* It a buffer has been allocated, free it again */
  11395. if (data != mem) {
  11396. mg_free(data);
  11397. }
  11398. if (exit_by_callback) {
  11399. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11400. conn->request_info.remote_addr,
  11401. conn->request_info.remote_port);
  11402. break;
  11403. }
  11404. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11405. /* Opcode == 8, connection close */
  11406. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11407. conn->request_info.remote_addr,
  11408. conn->request_info.remote_port);
  11409. break;
  11410. }
  11411. /* Not breaking the loop, process next websocket frame. */
  11412. } else {
  11413. /* Read from the socket into the next available location in the
  11414. * message queue. */
  11415. n = pull_inner(NULL,
  11416. conn,
  11417. conn->buf + conn->data_len,
  11418. conn->buf_size - conn->data_len,
  11419. timeout);
  11420. if (n <= -2) {
  11421. /* Error, no bytes read */
  11422. DEBUG_TRACE("PULL from %s:%u failed",
  11423. conn->request_info.remote_addr,
  11424. conn->request_info.remote_port);
  11425. break;
  11426. }
  11427. if (n > 0) {
  11428. conn->data_len += n;
  11429. /* Reset open PING count */
  11430. ping_count = 0;
  11431. } else {
  11432. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11433. && (!conn->must_close)) {
  11434. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11435. /* Stop sending PING */
  11436. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11437. "- closing connection",
  11438. ping_count,
  11439. conn->request_info.remote_addr,
  11440. conn->request_info.remote_port);
  11441. break;
  11442. }
  11443. if (enable_ping_pong) {
  11444. /* Send Websocket PING message */
  11445. DEBUG_TRACE("PING to %s:%u",
  11446. conn->request_info.remote_addr,
  11447. conn->request_info.remote_port);
  11448. ret = mg_websocket_write(conn,
  11449. MG_WEBSOCKET_OPCODE_PING,
  11450. NULL,
  11451. 0);
  11452. if (ret <= 0) {
  11453. /* Error: send failed */
  11454. DEBUG_TRACE("Send PING failed (%i)", ret);
  11455. break;
  11456. }
  11457. ping_count++;
  11458. }
  11459. }
  11460. /* Timeout: should retry */
  11461. /* TODO: get timeout def */
  11462. }
  11463. }
  11464. }
  11465. /* Leave data processing loop */
  11466. mg_set_thread_name("worker");
  11467. conn->in_websocket_handling = 0;
  11468. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11469. conn->request_info.remote_addr,
  11470. conn->request_info.remote_port);
  11471. }
  11472. static int
  11473. mg_websocket_write_exec(struct mg_connection *conn,
  11474. int opcode,
  11475. const char *data,
  11476. size_t dataLen,
  11477. uint32_t masking_key)
  11478. {
  11479. unsigned char header[14];
  11480. size_t headerLen;
  11481. int retval;
  11482. #if defined(GCC_DIAGNOSTIC)
  11483. /* Disable spurious conversion warning for GCC */
  11484. #pragma GCC diagnostic push
  11485. #pragma GCC diagnostic ignored "-Wconversion"
  11486. #endif
  11487. /* Note that POSIX/Winsock's send() is threadsafe
  11488. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11489. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11490. * push(), although that is only a problem if the packet is large or
  11491. * outgoing buffer is full). */
  11492. /* TODO: Check if this lock should be moved to user land.
  11493. * Currently the server sets this lock for websockets, but
  11494. * not for any other connection. It must be set for every
  11495. * conn read/written by more than one thread, no matter if
  11496. * it is a websocket or regular connection. */
  11497. (void)mg_lock_connection(conn);
  11498. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11499. size_t deflated_size = 0;
  11500. Bytef *deflated = 0;
  11501. // Deflate websocket messages over 100kb
  11502. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11503. if (use_deflate) {
  11504. if (!conn->websocket_deflate_initialized) {
  11505. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11506. return 0;
  11507. }
  11508. // Deflating the message
  11509. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11510. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11511. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11512. deflated_size = (size_t)compressBound((uLong)dataLen);
  11513. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11514. if (deflated == NULL) {
  11515. mg_cry_internal(
  11516. conn,
  11517. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11518. (unsigned long)deflated_size);
  11519. mg_unlock_connection(conn);
  11520. return -1;
  11521. }
  11522. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11523. conn->websocket_deflate_state.next_out = deflated;
  11524. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11525. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11526. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11527. } else
  11528. #endif
  11529. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11530. #if defined(GCC_DIAGNOSTIC)
  11531. #pragma GCC diagnostic pop
  11532. #endif
  11533. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11534. if (dataLen < 126) {
  11535. /* inline 7-bit length field */
  11536. header[1] = (unsigned char)dataLen;
  11537. headerLen = 2;
  11538. } else if (dataLen <= 0xFFFF) {
  11539. /* 16-bit length field */
  11540. uint16_t len = htons((uint16_t)dataLen);
  11541. header[1] = 126;
  11542. memcpy(header + 2, &len, 2);
  11543. headerLen = 4;
  11544. } else {
  11545. /* 64-bit length field */
  11546. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11547. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11548. header[1] = 127;
  11549. memcpy(header + 2, &len1, 4);
  11550. memcpy(header + 6, &len2, 4);
  11551. headerLen = 10;
  11552. }
  11553. if (masking_key) {
  11554. /* add mask */
  11555. header[1] |= 0x80;
  11556. memcpy(header + headerLen, &masking_key, 4);
  11557. headerLen += 4;
  11558. }
  11559. retval = mg_write(conn, header, headerLen);
  11560. if (retval != (int)headerLen) {
  11561. /* Did not send complete header */
  11562. retval = -1;
  11563. } else {
  11564. if (dataLen > 0) {
  11565. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11566. if (use_deflate) {
  11567. retval = mg_write(conn, deflated, dataLen);
  11568. mg_free(deflated);
  11569. } else
  11570. #endif
  11571. retval = mg_write(conn, data, dataLen);
  11572. }
  11573. /* if dataLen == 0, the header length (2) is returned */
  11574. }
  11575. /* TODO: Remove this unlock as well, when lock is removed. */
  11576. mg_unlock_connection(conn);
  11577. return retval;
  11578. }
  11579. CIVETWEB_API int
  11580. mg_websocket_write(struct mg_connection *conn,
  11581. int opcode,
  11582. const char *data,
  11583. size_t dataLen)
  11584. {
  11585. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11586. }
  11587. static void
  11588. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11589. {
  11590. size_t i = 0;
  11591. i = 0;
  11592. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11593. /* Convert in 32 bit words, if data is 4 byte aligned */
  11594. while (i < (in_len - 3)) {
  11595. *(uint32_t *)(void *)(out + i) =
  11596. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11597. i += 4;
  11598. }
  11599. }
  11600. if (i != in_len) {
  11601. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11602. while (i < in_len) {
  11603. *(uint8_t *)(void *)(out + i) =
  11604. *(uint8_t *)(void *)(in + i)
  11605. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11606. i++;
  11607. }
  11608. }
  11609. }
  11610. CIVETWEB_API int
  11611. mg_websocket_client_write(struct mg_connection *conn,
  11612. int opcode,
  11613. const char *data,
  11614. size_t dataLen)
  11615. {
  11616. int retval = -1;
  11617. char *masked_data =
  11618. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11619. uint32_t masking_key = 0;
  11620. if (masked_data == NULL) {
  11621. /* Return -1 in an error case */
  11622. mg_cry_internal(conn,
  11623. "%s",
  11624. "Cannot allocate buffer for masked websocket response: "
  11625. "Out of memory");
  11626. return -1;
  11627. }
  11628. do {
  11629. /* Get a masking key - but not 0 */
  11630. masking_key = (uint32_t)get_random();
  11631. } while (masking_key == 0);
  11632. mask_data(data, dataLen, masking_key, masked_data);
  11633. retval = mg_websocket_write_exec(
  11634. conn, opcode, masked_data, dataLen, masking_key);
  11635. mg_free(masked_data);
  11636. return retval;
  11637. }
  11638. static void
  11639. handle_websocket_request(struct mg_connection *conn,
  11640. const char *path,
  11641. int is_callback_resource,
  11642. struct mg_websocket_subprotocols *subprotocols,
  11643. mg_websocket_connect_handler ws_connect_handler,
  11644. mg_websocket_ready_handler ws_ready_handler,
  11645. mg_websocket_data_handler ws_data_handler,
  11646. mg_websocket_close_handler ws_close_handler,
  11647. void *cbData)
  11648. {
  11649. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11650. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11651. ptrdiff_t lua_websock = 0;
  11652. #if !defined(USE_LUA)
  11653. (void)path;
  11654. #endif
  11655. /* Step 1: Check websocket protocol version. */
  11656. /* Step 1.1: Check Sec-WebSocket-Key. */
  11657. if (!websock_key) {
  11658. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11659. * requires a Sec-WebSocket-Key header.
  11660. */
  11661. /* It could be the hixie draft version
  11662. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11663. */
  11664. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11665. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11666. char key3[8];
  11667. if ((key1 != NULL) && (key2 != NULL)) {
  11668. /* This version uses 8 byte body data in a GET request */
  11669. conn->content_len = 8;
  11670. if (8 == mg_read(conn, key3, 8)) {
  11671. /* This is the hixie version */
  11672. mg_send_http_error(conn,
  11673. 426,
  11674. "%s",
  11675. "Protocol upgrade to RFC 6455 required");
  11676. return;
  11677. }
  11678. }
  11679. /* This is an unknown version */
  11680. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11681. return;
  11682. }
  11683. /* Step 1.2: Check websocket protocol version. */
  11684. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11685. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11686. /* Reject wrong versions */
  11687. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11688. return;
  11689. }
  11690. /* Step 1.3: Could check for "Host", but we do not really nead this
  11691. * value for anything, so just ignore it. */
  11692. /* Step 2: If a callback is responsible, call it. */
  11693. if (is_callback_resource) {
  11694. /* Step 2.1 check and select subprotocol */
  11695. const char *protocols[64]; // max 64 headers
  11696. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11697. "Sec-WebSocket-Protocol",
  11698. protocols,
  11699. 64);
  11700. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11701. int headerNo, idx;
  11702. size_t len;
  11703. const char *sep, *curSubProtocol,
  11704. *acceptedWebSocketSubprotocol = NULL;
  11705. /* look for matching subprotocol */
  11706. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11707. /* There might be multiple headers ... */
  11708. const char *protocol = protocols[headerNo];
  11709. curSubProtocol = protocol;
  11710. /* ... and in every header there might be a , separated list */
  11711. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11712. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11713. curSubProtocol++;
  11714. sep = strchr(curSubProtocol, ',');
  11715. if (sep) {
  11716. len = (size_t)(sep - curSubProtocol);
  11717. } else {
  11718. len = strlen(curSubProtocol);
  11719. }
  11720. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11721. // COMPARE: curSubProtocol ==
  11722. // subprotocols->subprotocols[idx]
  11723. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11724. && (strncmp(curSubProtocol,
  11725. subprotocols->subprotocols[idx],
  11726. len)
  11727. == 0)) {
  11728. acceptedWebSocketSubprotocol =
  11729. subprotocols->subprotocols[idx];
  11730. break;
  11731. }
  11732. }
  11733. curSubProtocol += len;
  11734. }
  11735. }
  11736. conn->request_info.acceptedWebSocketSubprotocol =
  11737. acceptedWebSocketSubprotocol;
  11738. }
  11739. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11740. websocket_deflate_negotiate(conn);
  11741. #endif
  11742. if ((ws_connect_handler != NULL)
  11743. && (ws_connect_handler(conn, cbData) != 0)) {
  11744. /* C callback has returned non-zero, do not proceed with
  11745. * handshake.
  11746. */
  11747. /* Note that C callbacks are no longer called when Lua is
  11748. * responsible, so C can no longer filter callbacks for Lua. */
  11749. return;
  11750. }
  11751. }
  11752. #if defined(USE_LUA)
  11753. /* Step 3: No callback. Check if Lua is responsible. */
  11754. else {
  11755. /* Step 3.1: Check if Lua is responsible. */
  11756. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11757. lua_websock = match_prefix_strlen(
  11758. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11759. }
  11760. if (lua_websock > 0) {
  11761. /* Step 3.2: Lua is responsible: call it. */
  11762. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11763. if (!conn->lua_websocket_state) {
  11764. /* Lua rejected the new client */
  11765. return;
  11766. }
  11767. }
  11768. }
  11769. #endif
  11770. /* Step 4: Check if there is a responsible websocket handler. */
  11771. if (!is_callback_resource && !lua_websock) {
  11772. /* There is no callback, and Lua is not responsible either. */
  11773. /* Reply with a 404 Not Found. We are still at a standard
  11774. * HTTP request here, before the websocket handshake, so
  11775. * we can still send standard HTTP error replies. */
  11776. mg_send_http_error(conn, 404, "%s", "Not found");
  11777. return;
  11778. }
  11779. /* Step 5: The websocket connection has been accepted */
  11780. if (!send_websocket_handshake(conn, websock_key)) {
  11781. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11782. return;
  11783. }
  11784. /* Step 6: Call the ready handler */
  11785. if (is_callback_resource) {
  11786. if (ws_ready_handler != NULL) {
  11787. ws_ready_handler(conn, cbData);
  11788. }
  11789. #if defined(USE_LUA)
  11790. } else if (lua_websock) {
  11791. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11792. /* the ready handler returned false */
  11793. return;
  11794. }
  11795. #endif
  11796. }
  11797. /* Step 7: Enter the read loop */
  11798. if (is_callback_resource) {
  11799. read_websocket(conn, ws_data_handler, cbData);
  11800. #if defined(USE_LUA)
  11801. } else if (lua_websock) {
  11802. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11803. #endif
  11804. }
  11805. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11806. /* Step 8: Close the deflate & inflate buffers */
  11807. if (conn->websocket_deflate_initialized) {
  11808. deflateEnd(&conn->websocket_deflate_state);
  11809. inflateEnd(&conn->websocket_inflate_state);
  11810. }
  11811. #endif
  11812. /* Step 9: Call the close handler */
  11813. if (ws_close_handler) {
  11814. ws_close_handler(conn, cbData);
  11815. }
  11816. }
  11817. #endif /* !USE_WEBSOCKET */
  11818. /* Is upgrade request:
  11819. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11820. * 1 = upgrade to websocket
  11821. * 2 = upgrade to HTTP/2
  11822. * -1 = upgrade to unknown protocol
  11823. */
  11824. static int
  11825. should_switch_to_protocol(const struct mg_connection *conn)
  11826. {
  11827. const char *upgrade, *connection;
  11828. /* A websocket protocoll has the following HTTP headers:
  11829. *
  11830. * Connection: Upgrade
  11831. * Upgrade: Websocket
  11832. */
  11833. connection = mg_get_header(conn, "Connection");
  11834. if (connection == NULL) {
  11835. return PROTOCOL_TYPE_HTTP1;
  11836. }
  11837. if (!mg_strcasestr(connection, "upgrade")) {
  11838. return PROTOCOL_TYPE_HTTP1;
  11839. }
  11840. upgrade = mg_get_header(conn, "Upgrade");
  11841. if (upgrade == NULL) {
  11842. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11843. return -1;
  11844. }
  11845. /* Upgrade to ... */
  11846. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11847. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11848. * "Sec-WebSocket-Version" are also required.
  11849. * Don't check them here, since even an unsupported websocket protocol
  11850. * request still IS a websocket request (in contrast to a standard HTTP
  11851. * request). It will fail later in handle_websocket_request.
  11852. */
  11853. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11854. }
  11855. if (0 != mg_strcasestr(upgrade, "h2")) {
  11856. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11857. }
  11858. /* Upgrade to another protocol */
  11859. return -1;
  11860. }
  11861. static int
  11862. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11863. {
  11864. int n;
  11865. unsigned int a, b, c, d, slash;
  11866. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11867. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11868. // integer value, but function will not report conversion
  11869. // errors; consider using 'strtol' instead
  11870. slash = 32;
  11871. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11872. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11873. // an integer value, but function will not report conversion
  11874. // errors; consider using 'strtol' instead
  11875. n = 0;
  11876. }
  11877. }
  11878. if ((n > 0) && ((size_t)n == vec->len)) {
  11879. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11880. /* IPv4 format */
  11881. if (sa->sa.sa_family == AF_INET) {
  11882. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11883. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11884. | ((uint32_t)c << 8) | (uint32_t)d;
  11885. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11886. return (ip & mask) == net;
  11887. }
  11888. return 0;
  11889. }
  11890. }
  11891. #if defined(USE_IPV6)
  11892. else {
  11893. char ad[50];
  11894. const char *p;
  11895. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11896. slash = 128;
  11897. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11898. n = 0;
  11899. }
  11900. }
  11901. if ((n <= 0) && no_strict) {
  11902. /* no square brackets? */
  11903. p = strchr(vec->ptr, '/');
  11904. if (p && (p < (vec->ptr + vec->len))) {
  11905. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11906. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11907. n += (int)(p - vec->ptr);
  11908. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11909. } else {
  11910. n = 0;
  11911. }
  11912. } else if (vec->len < sizeof(ad)) {
  11913. n = (int)vec->len;
  11914. slash = 128;
  11915. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11916. }
  11917. }
  11918. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11919. p = ad;
  11920. c = 0;
  11921. /* zone indexes are unsupported, at least two colons are needed */
  11922. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11923. if (*(p++) == ':') {
  11924. c++;
  11925. }
  11926. }
  11927. if ((*p == '\0') && (c >= 2)) {
  11928. struct sockaddr_in6 sin6;
  11929. unsigned int i;
  11930. /* for strict validation, an actual IPv6 argument is needed */
  11931. if (sa->sa.sa_family != AF_INET6) {
  11932. return 0;
  11933. }
  11934. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11935. /* IPv6 format */
  11936. for (i = 0; i < 16; i++) {
  11937. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11938. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11939. uint8_t mask = 0;
  11940. if (8 * i + 8 < slash) {
  11941. mask = 0xFFu;
  11942. } else if (8 * i < slash) {
  11943. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11944. }
  11945. if ((ip & mask) != net) {
  11946. return 0;
  11947. }
  11948. }
  11949. return 1;
  11950. }
  11951. }
  11952. }
  11953. }
  11954. #else
  11955. (void)no_strict;
  11956. #endif
  11957. /* malformed */
  11958. return -1;
  11959. }
  11960. static int
  11961. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11962. {
  11963. int throttle = 0;
  11964. struct vec vec, val;
  11965. char mult;
  11966. double v;
  11967. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11968. mult = ',';
  11969. if ((val.ptr == NULL)
  11970. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11971. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11972. // to an integer value, but function will not report
  11973. // conversion errors; consider using 'strtol' instead
  11974. || (v < 0)
  11975. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11976. && (mult != ','))) {
  11977. continue;
  11978. }
  11979. v *= (lowercase(&mult) == 'k')
  11980. ? 1024
  11981. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11982. if (vec.len == 1 && vec.ptr[0] == '*') {
  11983. throttle = (int)v;
  11984. } else {
  11985. int matched = parse_match_net(&vec, rsa, 0);
  11986. if (matched >= 0) {
  11987. /* a valid IP subnet */
  11988. if (matched) {
  11989. throttle = (int)v;
  11990. }
  11991. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11992. throttle = (int)v;
  11993. }
  11994. }
  11995. }
  11996. return throttle;
  11997. }
  11998. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11999. #include "handle_form.inl"
  12000. static int
  12001. get_first_ssl_listener_index(const struct mg_context *ctx)
  12002. {
  12003. unsigned int i;
  12004. int idx = -1;
  12005. if (ctx) {
  12006. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12007. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12008. }
  12009. }
  12010. return idx;
  12011. }
  12012. /* Return host (without port) */
  12013. static void
  12014. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12015. {
  12016. const char *host_header =
  12017. get_header(ri->http_headers, ri->num_headers, "Host");
  12018. host->ptr = NULL;
  12019. host->len = 0;
  12020. if (host_header != NULL) {
  12021. const char *pos;
  12022. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12023. * is found. */
  12024. if (*host_header == '[') {
  12025. pos = strchr(host_header, ']');
  12026. if (!pos) {
  12027. /* Malformed hostname starts with '[', but no ']' found */
  12028. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12029. return;
  12030. }
  12031. /* terminate after ']' */
  12032. host->ptr = host_header;
  12033. host->len = (size_t)(pos + 1 - host_header);
  12034. } else {
  12035. /* Otherwise, a ':' separates hostname and port number */
  12036. pos = strchr(host_header, ':');
  12037. if (pos != NULL) {
  12038. host->len = (size_t)(pos - host_header);
  12039. } else {
  12040. host->len = strlen(host_header);
  12041. }
  12042. host->ptr = host_header;
  12043. }
  12044. }
  12045. }
  12046. static int
  12047. switch_domain_context(struct mg_connection *conn)
  12048. {
  12049. struct vec host;
  12050. get_host_from_request_info(&host, &conn->request_info);
  12051. if (host.ptr) {
  12052. if (conn->ssl) {
  12053. /* This is a HTTPS connection, maybe we have a hostname
  12054. * from SNI (set in ssl_servername_callback). */
  12055. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12056. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12057. /* We are not using the default domain */
  12058. if ((strlen(sslhost) != host.len)
  12059. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12060. /* Mismatch between SNI domain and HTTP domain */
  12061. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12062. sslhost,
  12063. (int)host.len,
  12064. host.ptr);
  12065. return 0;
  12066. }
  12067. }
  12068. } else {
  12069. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12070. while (dom) {
  12071. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12072. size_t domNameLen = strlen(domName);
  12073. if ((domNameLen == host.len)
  12074. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12075. /* Found matching domain */
  12076. DEBUG_TRACE("HTTP domain %s found",
  12077. dom->config[AUTHENTICATION_DOMAIN]);
  12078. /* TODO: Check if this is a HTTP or HTTPS domain */
  12079. conn->dom_ctx = dom;
  12080. break;
  12081. }
  12082. mg_lock_context(conn->phys_ctx);
  12083. dom = dom->next;
  12084. mg_unlock_context(conn->phys_ctx);
  12085. }
  12086. }
  12087. DEBUG_TRACE("HTTP%s Host: %.*s",
  12088. conn->ssl ? "S" : "",
  12089. (int)host.len,
  12090. host.ptr);
  12091. } else {
  12092. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12093. return 1;
  12094. }
  12095. return 1;
  12096. }
  12097. static void
  12098. redirect_to_https_port(struct mg_connection *conn, int port)
  12099. {
  12100. char target_url[MG_BUF_LEN];
  12101. int truncated = 0;
  12102. const char *expect_proto =
  12103. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12104. /* Use "308 Permanent Redirect" */
  12105. int redirect_code = 308;
  12106. /* In any case, close the current connection */
  12107. conn->must_close = 1;
  12108. /* Send host, port, uri and (if it exists) ?query_string */
  12109. if (mg_construct_local_link(
  12110. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12111. < 0) {
  12112. truncated = 1;
  12113. } else if (conn->request_info.query_string != NULL) {
  12114. size_t slen1 = strlen(target_url);
  12115. size_t slen2 = strlen(conn->request_info.query_string);
  12116. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12117. target_url[slen1] = '?';
  12118. memcpy(target_url + slen1 + 1,
  12119. conn->request_info.query_string,
  12120. slen2);
  12121. target_url[slen1 + slen2 + 1] = 0;
  12122. } else {
  12123. truncated = 1;
  12124. }
  12125. }
  12126. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12127. * is used as buffer size) */
  12128. if (truncated) {
  12129. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12130. return;
  12131. }
  12132. /* Use redirect helper function */
  12133. mg_send_http_redirect(conn, target_url, redirect_code);
  12134. }
  12135. static void
  12136. mg_set_handler_type(struct mg_context *phys_ctx,
  12137. struct mg_domain_context *dom_ctx,
  12138. const char *uri,
  12139. int handler_type,
  12140. int is_delete_request,
  12141. mg_request_handler handler,
  12142. struct mg_websocket_subprotocols *subprotocols,
  12143. mg_websocket_connect_handler connect_handler,
  12144. mg_websocket_ready_handler ready_handler,
  12145. mg_websocket_data_handler data_handler,
  12146. mg_websocket_close_handler close_handler,
  12147. mg_authorization_handler auth_handler,
  12148. void *cbdata)
  12149. {
  12150. struct mg_handler_info *tmp_rh, **lastref;
  12151. size_t urilen = strlen(uri);
  12152. if (handler_type == WEBSOCKET_HANDLER) {
  12153. DEBUG_ASSERT(handler == NULL);
  12154. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12155. || ready_handler != NULL || data_handler != NULL
  12156. || close_handler != NULL);
  12157. DEBUG_ASSERT(auth_handler == NULL);
  12158. if (handler != NULL) {
  12159. return;
  12160. }
  12161. if (!is_delete_request && (connect_handler == NULL)
  12162. && (ready_handler == NULL) && (data_handler == NULL)
  12163. && (close_handler == NULL)) {
  12164. return;
  12165. }
  12166. if (auth_handler != NULL) {
  12167. return;
  12168. }
  12169. } else if (handler_type == REQUEST_HANDLER) {
  12170. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12171. && data_handler == NULL && close_handler == NULL);
  12172. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12173. DEBUG_ASSERT(auth_handler == NULL);
  12174. if ((connect_handler != NULL) || (ready_handler != NULL)
  12175. || (data_handler != NULL) || (close_handler != NULL)) {
  12176. return;
  12177. }
  12178. if (!is_delete_request && (handler == NULL)) {
  12179. return;
  12180. }
  12181. if (auth_handler != NULL) {
  12182. return;
  12183. }
  12184. } else if (handler_type == AUTH_HANDLER) {
  12185. DEBUG_ASSERT(handler == NULL);
  12186. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12187. && data_handler == NULL && close_handler == NULL);
  12188. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12189. if (handler != NULL) {
  12190. return;
  12191. }
  12192. if ((connect_handler != NULL) || (ready_handler != NULL)
  12193. || (data_handler != NULL) || (close_handler != NULL)) {
  12194. return;
  12195. }
  12196. if (!is_delete_request && (auth_handler == NULL)) {
  12197. return;
  12198. }
  12199. } else {
  12200. /* Unknown handler type. */
  12201. return;
  12202. }
  12203. if (!phys_ctx || !dom_ctx) {
  12204. /* no context available */
  12205. return;
  12206. }
  12207. mg_lock_context(phys_ctx);
  12208. /* first try to find an existing handler */
  12209. do {
  12210. lastref = &(dom_ctx->handlers);
  12211. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12212. tmp_rh = tmp_rh->next) {
  12213. if (tmp_rh->handler_type == handler_type
  12214. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12215. if (!is_delete_request) {
  12216. /* update existing handler */
  12217. if (handler_type == REQUEST_HANDLER) {
  12218. /* Wait for end of use before updating */
  12219. if (tmp_rh->refcount) {
  12220. mg_unlock_context(phys_ctx);
  12221. mg_sleep(1);
  12222. mg_lock_context(phys_ctx);
  12223. /* tmp_rh might have been freed, search again. */
  12224. break;
  12225. }
  12226. /* Ok, the handler is no more use -> Update it */
  12227. tmp_rh->handler = handler;
  12228. } else if (handler_type == WEBSOCKET_HANDLER) {
  12229. tmp_rh->subprotocols = subprotocols;
  12230. tmp_rh->connect_handler = connect_handler;
  12231. tmp_rh->ready_handler = ready_handler;
  12232. tmp_rh->data_handler = data_handler;
  12233. tmp_rh->close_handler = close_handler;
  12234. } else { /* AUTH_HANDLER */
  12235. tmp_rh->auth_handler = auth_handler;
  12236. }
  12237. tmp_rh->cbdata = cbdata;
  12238. } else {
  12239. /* remove existing handler */
  12240. if (handler_type == REQUEST_HANDLER) {
  12241. /* Wait for end of use before removing */
  12242. if (tmp_rh->refcount) {
  12243. tmp_rh->removing = 1;
  12244. mg_unlock_context(phys_ctx);
  12245. mg_sleep(1);
  12246. mg_lock_context(phys_ctx);
  12247. /* tmp_rh might have been freed, search again. */
  12248. break;
  12249. }
  12250. /* Ok, the handler is no more used */
  12251. }
  12252. *lastref = tmp_rh->next;
  12253. mg_free(tmp_rh->uri);
  12254. mg_free(tmp_rh);
  12255. }
  12256. mg_unlock_context(phys_ctx);
  12257. return;
  12258. }
  12259. lastref = &(tmp_rh->next);
  12260. }
  12261. } while (tmp_rh != NULL);
  12262. if (is_delete_request) {
  12263. /* no handler to set, this was a remove request to a non-existing
  12264. * handler */
  12265. mg_unlock_context(phys_ctx);
  12266. return;
  12267. }
  12268. tmp_rh =
  12269. (struct mg_handler_info *)mg_calloc_ctx(1,
  12270. sizeof(struct mg_handler_info),
  12271. phys_ctx);
  12272. if (tmp_rh == NULL) {
  12273. mg_unlock_context(phys_ctx);
  12274. mg_cry_ctx_internal(phys_ctx,
  12275. "%s",
  12276. "Cannot create new request handler struct, OOM");
  12277. return;
  12278. }
  12279. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12280. if (!tmp_rh->uri) {
  12281. mg_unlock_context(phys_ctx);
  12282. mg_free(tmp_rh);
  12283. mg_cry_ctx_internal(phys_ctx,
  12284. "%s",
  12285. "Cannot create new request handler struct, OOM");
  12286. return;
  12287. }
  12288. tmp_rh->uri_len = urilen;
  12289. if (handler_type == REQUEST_HANDLER) {
  12290. tmp_rh->refcount = 0;
  12291. tmp_rh->removing = 0;
  12292. tmp_rh->handler = handler;
  12293. } else if (handler_type == WEBSOCKET_HANDLER) {
  12294. tmp_rh->subprotocols = subprotocols;
  12295. tmp_rh->connect_handler = connect_handler;
  12296. tmp_rh->ready_handler = ready_handler;
  12297. tmp_rh->data_handler = data_handler;
  12298. tmp_rh->close_handler = close_handler;
  12299. } else { /* AUTH_HANDLER */
  12300. tmp_rh->auth_handler = auth_handler;
  12301. }
  12302. tmp_rh->cbdata = cbdata;
  12303. tmp_rh->handler_type = handler_type;
  12304. tmp_rh->next = NULL;
  12305. *lastref = tmp_rh;
  12306. mg_unlock_context(phys_ctx);
  12307. }
  12308. CIVETWEB_API void
  12309. mg_set_request_handler(struct mg_context *ctx,
  12310. const char *uri,
  12311. mg_request_handler handler,
  12312. void *cbdata)
  12313. {
  12314. mg_set_handler_type(ctx,
  12315. &(ctx->dd),
  12316. uri,
  12317. REQUEST_HANDLER,
  12318. handler == NULL,
  12319. handler,
  12320. NULL,
  12321. NULL,
  12322. NULL,
  12323. NULL,
  12324. NULL,
  12325. NULL,
  12326. cbdata);
  12327. }
  12328. CIVETWEB_API void
  12329. mg_set_websocket_handler(struct mg_context *ctx,
  12330. const char *uri,
  12331. mg_websocket_connect_handler connect_handler,
  12332. mg_websocket_ready_handler ready_handler,
  12333. mg_websocket_data_handler data_handler,
  12334. mg_websocket_close_handler close_handler,
  12335. void *cbdata)
  12336. {
  12337. mg_set_websocket_handler_with_subprotocols(ctx,
  12338. uri,
  12339. NULL,
  12340. connect_handler,
  12341. ready_handler,
  12342. data_handler,
  12343. close_handler,
  12344. cbdata);
  12345. }
  12346. CIVETWEB_API void
  12347. mg_set_websocket_handler_with_subprotocols(
  12348. struct mg_context *ctx,
  12349. const char *uri,
  12350. struct mg_websocket_subprotocols *subprotocols,
  12351. mg_websocket_connect_handler connect_handler,
  12352. mg_websocket_ready_handler ready_handler,
  12353. mg_websocket_data_handler data_handler,
  12354. mg_websocket_close_handler close_handler,
  12355. void *cbdata)
  12356. {
  12357. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12358. && (data_handler == NULL)
  12359. && (close_handler == NULL);
  12360. mg_set_handler_type(ctx,
  12361. &(ctx->dd),
  12362. uri,
  12363. WEBSOCKET_HANDLER,
  12364. is_delete_request,
  12365. NULL,
  12366. subprotocols,
  12367. connect_handler,
  12368. ready_handler,
  12369. data_handler,
  12370. close_handler,
  12371. NULL,
  12372. cbdata);
  12373. }
  12374. CIVETWEB_API void
  12375. mg_set_auth_handler(struct mg_context *ctx,
  12376. const char *uri,
  12377. mg_authorization_handler handler,
  12378. void *cbdata)
  12379. {
  12380. mg_set_handler_type(ctx,
  12381. &(ctx->dd),
  12382. uri,
  12383. AUTH_HANDLER,
  12384. handler == NULL,
  12385. NULL,
  12386. NULL,
  12387. NULL,
  12388. NULL,
  12389. NULL,
  12390. NULL,
  12391. handler,
  12392. cbdata);
  12393. }
  12394. static int
  12395. get_request_handler(struct mg_connection *conn,
  12396. int handler_type,
  12397. mg_request_handler *handler,
  12398. struct mg_websocket_subprotocols **subprotocols,
  12399. mg_websocket_connect_handler *connect_handler,
  12400. mg_websocket_ready_handler *ready_handler,
  12401. mg_websocket_data_handler *data_handler,
  12402. mg_websocket_close_handler *close_handler,
  12403. mg_authorization_handler *auth_handler,
  12404. void **cbdata,
  12405. struct mg_handler_info **handler_info)
  12406. {
  12407. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12408. if (request_info) {
  12409. const char *uri = request_info->local_uri;
  12410. size_t urilen = strlen(uri);
  12411. struct mg_handler_info *tmp_rh;
  12412. int step, matched;
  12413. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12414. return 0;
  12415. }
  12416. mg_lock_context(conn->phys_ctx);
  12417. for (step = 0; step < 3; step++) {
  12418. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12419. tmp_rh = tmp_rh->next) {
  12420. if (tmp_rh->handler_type != handler_type) {
  12421. continue;
  12422. }
  12423. if (step == 0) {
  12424. /* first try for an exact match */
  12425. matched = (tmp_rh->uri_len == urilen)
  12426. && (strcmp(tmp_rh->uri, uri) == 0);
  12427. } else if (step == 1) {
  12428. /* next try for a partial match, we will accept
  12429. uri/something */
  12430. matched =
  12431. (tmp_rh->uri_len < urilen)
  12432. && (uri[tmp_rh->uri_len] == '/')
  12433. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12434. } else {
  12435. /* finally try for pattern match */
  12436. matched =
  12437. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12438. }
  12439. if (matched) {
  12440. if (handler_type == WEBSOCKET_HANDLER) {
  12441. *subprotocols = tmp_rh->subprotocols;
  12442. *connect_handler = tmp_rh->connect_handler;
  12443. *ready_handler = tmp_rh->ready_handler;
  12444. *data_handler = tmp_rh->data_handler;
  12445. *close_handler = tmp_rh->close_handler;
  12446. } else if (handler_type == REQUEST_HANDLER) {
  12447. if (tmp_rh->removing) {
  12448. /* Treat as none found */
  12449. step = 2;
  12450. break;
  12451. }
  12452. *handler = tmp_rh->handler;
  12453. /* Acquire handler and give it back */
  12454. tmp_rh->refcount++;
  12455. *handler_info = tmp_rh;
  12456. } else { /* AUTH_HANDLER */
  12457. *auth_handler = tmp_rh->auth_handler;
  12458. }
  12459. *cbdata = tmp_rh->cbdata;
  12460. mg_unlock_context(conn->phys_ctx);
  12461. return 1;
  12462. }
  12463. }
  12464. }
  12465. mg_unlock_context(conn->phys_ctx);
  12466. }
  12467. return 0; /* none found */
  12468. }
  12469. /* Check if the script file is in a path, allowed for script files.
  12470. * This can be used if uploading files is possible not only for the server
  12471. * admin, and the upload mechanism does not check the file extension.
  12472. */
  12473. static int
  12474. is_in_script_path(const struct mg_connection *conn, const char *path)
  12475. {
  12476. /* TODO (Feature): Add config value for allowed script path.
  12477. * Default: All allowed. */
  12478. (void)conn;
  12479. (void)path;
  12480. return 1;
  12481. }
  12482. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12483. static int
  12484. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12485. int bits,
  12486. char *data,
  12487. size_t len,
  12488. void *cbdata)
  12489. {
  12490. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12491. if (pcallbacks->websocket_data) {
  12492. return pcallbacks->websocket_data(conn, bits, data, len);
  12493. }
  12494. /* No handler set - assume "OK" */
  12495. return 1;
  12496. }
  12497. static void
  12498. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12499. void *cbdata)
  12500. {
  12501. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12502. if (pcallbacks->connection_close) {
  12503. pcallbacks->connection_close(conn);
  12504. }
  12505. }
  12506. #endif
  12507. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12508. */
  12509. static void
  12510. release_handler_ref(struct mg_connection *conn,
  12511. struct mg_handler_info *handler_info)
  12512. {
  12513. if (handler_info != NULL) {
  12514. /* Use context lock for ref counter */
  12515. mg_lock_context(conn->phys_ctx);
  12516. handler_info->refcount--;
  12517. mg_unlock_context(conn->phys_ctx);
  12518. }
  12519. }
  12520. /* This is the heart of the Civetweb's logic.
  12521. * This function is called when the request is read, parsed and validated,
  12522. * and Civetweb must decide what action to take: serve a file, or
  12523. * a directory, or call embedded function, etcetera. */
  12524. static void
  12525. handle_request(struct mg_connection *conn)
  12526. {
  12527. struct mg_request_info *ri = &conn->request_info;
  12528. char path[UTF8_PATH_MAX];
  12529. int uri_len, ssl_index;
  12530. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12531. is_put_or_delete_request = 0, is_callback_resource = 0,
  12532. is_template_text_file = 0, is_webdav_request = 0;
  12533. int i;
  12534. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12535. mg_request_handler callback_handler = NULL;
  12536. struct mg_handler_info *handler_info = NULL;
  12537. struct mg_websocket_subprotocols *subprotocols;
  12538. mg_websocket_connect_handler ws_connect_handler = NULL;
  12539. mg_websocket_ready_handler ws_ready_handler = NULL;
  12540. mg_websocket_data_handler ws_data_handler = NULL;
  12541. mg_websocket_close_handler ws_close_handler = NULL;
  12542. void *callback_data = NULL;
  12543. mg_authorization_handler auth_handler = NULL;
  12544. void *auth_callback_data = NULL;
  12545. int handler_type;
  12546. time_t curtime = time(NULL);
  12547. char date[64];
  12548. char *tmp;
  12549. path[0] = 0;
  12550. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12551. conn->request_state = 0;
  12552. /* 1. get the request url */
  12553. /* 1.1. split into url and query string */
  12554. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12555. != NULL) {
  12556. *((char *)conn->request_info.query_string++) = '\0';
  12557. }
  12558. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12559. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12560. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12561. if (ssl_index >= 0) {
  12562. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12563. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12564. redirect_to_https_port(conn, port);
  12565. } else {
  12566. /* A http to https forward port has been specified,
  12567. * but no https port to forward to. */
  12568. mg_send_http_error(conn,
  12569. 503,
  12570. "%s",
  12571. "Error: SSL forward not configured properly");
  12572. mg_cry_internal(conn,
  12573. "%s",
  12574. "Can not redirect to SSL, no SSL port available");
  12575. }
  12576. return;
  12577. }
  12578. uri_len = (int)strlen(ri->local_uri);
  12579. /* 1.3. decode url (if config says so) */
  12580. if (should_decode_url(conn)) {
  12581. url_decode_in_place((char *)ri->local_uri);
  12582. }
  12583. /* URL decode the query-string only if explicity set in the configuration */
  12584. if (conn->request_info.query_string) {
  12585. if (should_decode_query_string(conn)) {
  12586. url_decode_in_place((char *)conn->request_info.query_string);
  12587. }
  12588. }
  12589. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12590. * possible. The fact that we cleaned the URI is stored in that the
  12591. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12592. * ri->local_uri_raw still points to memory allocated in
  12593. * worker_thread_run(). ri->local_uri is private to the request so we
  12594. * don't have to use preallocated memory here. */
  12595. tmp = mg_strdup(ri->local_uri_raw);
  12596. if (!tmp) {
  12597. /* Out of memory. We cannot do anything reasonable here. */
  12598. return;
  12599. }
  12600. remove_dot_segments(tmp);
  12601. ri->local_uri = tmp;
  12602. /* step 1. completed, the url is known now */
  12603. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12604. /* 2. if this ip has limited speed, set it for this connection */
  12605. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12606. &conn->client.rsa,
  12607. ri->local_uri);
  12608. /* 3. call a "handle everything" callback, if registered */
  12609. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12610. /* Note that since V1.7 the "begin_request" function is called
  12611. * before an authorization check. If an authorization check is
  12612. * required, use a request_handler instead. */
  12613. i = conn->phys_ctx->callbacks.begin_request(conn);
  12614. if (i > 0) {
  12615. /* callback already processed the request. Store the
  12616. return value as a status code for the access log. */
  12617. conn->status_code = i;
  12618. if (!conn->must_close) {
  12619. discard_unread_request_data(conn);
  12620. }
  12621. DEBUG_TRACE("%s", "begin_request handled request");
  12622. return;
  12623. } else if (i == 0) {
  12624. /* civetweb should process the request */
  12625. } else {
  12626. /* unspecified - may change with the next version */
  12627. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12628. return;
  12629. }
  12630. }
  12631. /* request not yet handled by a handler or redirect, so the request
  12632. * is processed here */
  12633. /* 4. Check for CORS preflight requests and handle them (if configured).
  12634. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12635. */
  12636. if (!strcmp(ri->request_method, "OPTIONS")) {
  12637. /* Send a response to CORS preflights only if
  12638. * access_control_allow_methods is not NULL and not an empty string.
  12639. * In this case, scripts can still handle CORS. */
  12640. const char *cors_meth_cfg =
  12641. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12642. const char *cors_orig_cfg =
  12643. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12644. const char *cors_origin =
  12645. get_header(ri->http_headers, ri->num_headers, "Origin");
  12646. const char *cors_acrm = get_header(ri->http_headers,
  12647. ri->num_headers,
  12648. "Access-Control-Request-Method");
  12649. /* Todo: check if cors_origin is in cors_orig_cfg.
  12650. * Or, let the client check this. */
  12651. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12652. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12653. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12654. /* This is a valid CORS preflight, and the server is configured
  12655. * to handle it automatically. */
  12656. const char *cors_acrh =
  12657. get_header(ri->http_headers,
  12658. ri->num_headers,
  12659. "Access-Control-Request-Headers");
  12660. gmt_time_string(date, sizeof(date), &curtime);
  12661. mg_printf(conn,
  12662. "HTTP/1.1 200 OK\r\n"
  12663. "Date: %s\r\n"
  12664. "Access-Control-Allow-Origin: %s\r\n"
  12665. "Access-Control-Allow-Methods: %s\r\n"
  12666. "Content-Length: 0\r\n"
  12667. "Connection: %s\r\n",
  12668. date,
  12669. cors_orig_cfg,
  12670. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12671. suggest_connection_header(conn));
  12672. if (cors_acrh != NULL) {
  12673. /* CORS request is asking for additional headers */
  12674. const char *cors_hdr_cfg =
  12675. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12676. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12677. /* Allow only if access_control_allow_headers is
  12678. * not NULL and not an empty string. If this
  12679. * configuration is set to *, allow everything.
  12680. * Otherwise this configuration must be a list
  12681. * of allowed HTTP header names. */
  12682. mg_printf(conn,
  12683. "Access-Control-Allow-Headers: %s\r\n",
  12684. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12685. : cors_hdr_cfg));
  12686. }
  12687. }
  12688. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12689. mg_printf(conn, "\r\n");
  12690. DEBUG_TRACE("%s", "OPTIONS done");
  12691. return;
  12692. }
  12693. }
  12694. /* 5. interpret the url to find out how the request must be handled
  12695. */
  12696. /* 5.1. first test, if the request targets the regular http(s)://
  12697. * protocol namespace or the websocket ws(s):// protocol namespace.
  12698. */
  12699. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12700. #if defined(USE_WEBSOCKET)
  12701. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12702. #else
  12703. handler_type = REQUEST_HANDLER;
  12704. #endif /* defined(USE_WEBSOCKET) */
  12705. if (is_websocket_request) {
  12706. HTTP1_only;
  12707. }
  12708. /* 5.2. check if the request will be handled by a callback */
  12709. if (get_request_handler(conn,
  12710. handler_type,
  12711. &callback_handler,
  12712. &subprotocols,
  12713. &ws_connect_handler,
  12714. &ws_ready_handler,
  12715. &ws_data_handler,
  12716. &ws_close_handler,
  12717. NULL,
  12718. &callback_data,
  12719. &handler_info)) {
  12720. /* 5.2.1. A callback will handle this request. All requests
  12721. * handled by a callback have to be considered as requests
  12722. * to a script resource. */
  12723. is_callback_resource = 1;
  12724. is_script_resource = 1;
  12725. is_put_or_delete_request = is_put_or_delete_method(conn);
  12726. /* Never handle a C callback according to File WebDav rules,
  12727. * even if it is a webdav method */
  12728. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12729. } else {
  12730. no_callback_resource:
  12731. /* 5.2.2. No callback is responsible for this request. The URI
  12732. * addresses a file based resource (static content or Lua/cgi
  12733. * scripts in the file system). */
  12734. is_callback_resource = 0;
  12735. interpret_uri(conn,
  12736. path,
  12737. sizeof(path),
  12738. &file.stat,
  12739. &is_found,
  12740. &is_script_resource,
  12741. &is_websocket_request,
  12742. &is_put_or_delete_request,
  12743. &is_webdav_request,
  12744. &is_template_text_file);
  12745. }
  12746. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12747. if (is_webdav_request) {
  12748. /* TODO: Do we need a config option? */
  12749. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  12750. if (webdav_enable[0] != 'y') {
  12751. mg_send_http_error(conn,
  12752. 405,
  12753. "%s method not allowed",
  12754. conn->request_info.request_method);
  12755. DEBUG_TRACE("%s", "webdav rejected");
  12756. return;
  12757. }
  12758. }
  12759. /* 6. authorization check */
  12760. /* 6.1. a custom authorization handler is installed */
  12761. if (get_request_handler(conn,
  12762. AUTH_HANDLER,
  12763. NULL,
  12764. NULL,
  12765. NULL,
  12766. NULL,
  12767. NULL,
  12768. NULL,
  12769. &auth_handler,
  12770. &auth_callback_data,
  12771. NULL)) {
  12772. if (!auth_handler(conn, auth_callback_data)) {
  12773. /* Callback handler will not be used anymore. Release it */
  12774. release_handler_ref(conn, handler_info);
  12775. DEBUG_TRACE("%s", "auth handler rejected request");
  12776. return;
  12777. }
  12778. } else if (is_put_or_delete_request && !is_script_resource
  12779. && !is_callback_resource) {
  12780. HTTP1_only;
  12781. /* 6.2. this request is a PUT/DELETE to a real file */
  12782. /* 6.2.1. thus, the server must have real files */
  12783. #if defined(NO_FILES)
  12784. if (1) {
  12785. #else
  12786. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12787. #endif
  12788. /* This code path will not be called for request handlers */
  12789. DEBUG_ASSERT(handler_info == NULL);
  12790. /* This server does not have any real files, thus the
  12791. * PUT/DELETE methods are not valid. */
  12792. mg_send_http_error(conn,
  12793. 405,
  12794. "%s method not allowed",
  12795. conn->request_info.request_method);
  12796. DEBUG_TRACE("%s", "all file based requests rejected");
  12797. return;
  12798. }
  12799. #if !defined(NO_FILES)
  12800. /* 6.2.2. Check if put authorization for static files is
  12801. * available.
  12802. */
  12803. if (!is_authorized_for_put(conn)) {
  12804. send_authorization_request(conn, NULL);
  12805. DEBUG_TRACE("%s", "file write needs authorization");
  12806. return;
  12807. }
  12808. #endif
  12809. } else {
  12810. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12811. * or it is a PUT or DELETE request to a resource that does not
  12812. * correspond to a file. Check authorization. */
  12813. if (!check_authorization(conn, path)) {
  12814. send_authorization_request(conn, NULL);
  12815. /* Callback handler will not be used anymore. Release it */
  12816. release_handler_ref(conn, handler_info);
  12817. DEBUG_TRACE("%s", "access authorization required");
  12818. return;
  12819. }
  12820. }
  12821. /* request is authorized or does not need authorization */
  12822. /* 7. check if there are request handlers for this uri */
  12823. if (is_callback_resource) {
  12824. HTTP1_only;
  12825. if (!is_websocket_request) {
  12826. i = callback_handler(conn, callback_data);
  12827. /* Callback handler will not be used anymore. Release it */
  12828. release_handler_ref(conn, handler_info);
  12829. if (i > 0) {
  12830. /* Do nothing, callback has served the request. Store
  12831. * then return value as status code for the log and discard
  12832. * all data from the client not used by the callback. */
  12833. conn->status_code = i;
  12834. if (!conn->must_close) {
  12835. discard_unread_request_data(conn);
  12836. }
  12837. } else {
  12838. /* The handler did NOT handle the request. */
  12839. /* Some proper reactions would be:
  12840. * a) close the connections without sending anything
  12841. * b) send a 404 not found
  12842. * c) try if there is a file matching the URI
  12843. * It would be possible to do a, b or c in the callback
  12844. * implementation, and return 1 - we cannot do anything
  12845. * here, that is not possible in the callback.
  12846. *
  12847. * TODO: What would be the best reaction here?
  12848. * (Note: The reaction may change, if there is a better
  12849. * idea.)
  12850. */
  12851. /* For the moment, use option c: We look for a proper file,
  12852. * but since a file request is not always a script resource,
  12853. * the authorization check might be different. */
  12854. callback_handler = NULL;
  12855. /* Here we are at a dead end:
  12856. * According to URI matching, a callback should be
  12857. * responsible for handling the request,
  12858. * we called it, but the callback declared itself
  12859. * not responsible.
  12860. * We use a goto here, to get out of this dead end,
  12861. * and continue with the default handling.
  12862. * A goto here is simpler and better to understand
  12863. * than some curious loop. */
  12864. goto no_callback_resource;
  12865. }
  12866. } else {
  12867. #if defined(USE_WEBSOCKET)
  12868. handle_websocket_request(conn,
  12869. path,
  12870. is_callback_resource,
  12871. subprotocols,
  12872. ws_connect_handler,
  12873. ws_ready_handler,
  12874. ws_data_handler,
  12875. ws_close_handler,
  12876. callback_data);
  12877. #endif
  12878. }
  12879. DEBUG_TRACE("%s", "websocket handling done");
  12880. return;
  12881. }
  12882. /* 8. handle websocket requests */
  12883. #if defined(USE_WEBSOCKET)
  12884. if (is_websocket_request) {
  12885. HTTP1_only;
  12886. if (is_script_resource) {
  12887. if (is_in_script_path(conn, path)) {
  12888. /* Websocket Lua script */
  12889. handle_websocket_request(conn,
  12890. path,
  12891. 0 /* Lua Script */,
  12892. NULL,
  12893. NULL,
  12894. NULL,
  12895. NULL,
  12896. NULL,
  12897. conn->phys_ctx->user_data);
  12898. } else {
  12899. /* Script was in an illegal path */
  12900. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12901. }
  12902. } else {
  12903. mg_send_http_error(conn, 404, "%s", "Not found");
  12904. }
  12905. DEBUG_TRACE("%s", "websocket script done");
  12906. return;
  12907. } else
  12908. #endif
  12909. #if defined(NO_FILES)
  12910. /* 9a. In case the server uses only callbacks, this uri is
  12911. * unknown.
  12912. * Then, all request handling ends here. */
  12913. mg_send_http_error(conn, 404, "%s", "Not Found");
  12914. #else
  12915. /* 9b. This request is either for a static file or resource handled
  12916. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12917. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12918. mg_send_http_error(conn, 404, "%s", "Not Found");
  12919. DEBUG_TRACE("%s", "no document root available");
  12920. return;
  12921. }
  12922. /* 10. Request is handled by a script */
  12923. if (is_script_resource) {
  12924. HTTP1_only;
  12925. handle_file_based_request(conn, path, &file);
  12926. DEBUG_TRACE("%s", "script handling done");
  12927. return;
  12928. }
  12929. /* Request was not handled by a callback or script. It will be
  12930. * handled by a server internal method. */
  12931. /* 11. Handle put/delete/mkcol requests */
  12932. if (is_put_or_delete_request) {
  12933. HTTP1_only;
  12934. /* 11.1. PUT method */
  12935. if (!strcmp(ri->request_method, "PUT")) {
  12936. put_file(conn, path);
  12937. DEBUG_TRACE("handling %s request to %s done",
  12938. ri->request_method,
  12939. path);
  12940. return;
  12941. }
  12942. /* 11.2. DELETE method */
  12943. if (!strcmp(ri->request_method, "DELETE")) {
  12944. delete_file(conn, path);
  12945. DEBUG_TRACE("handling %s request to %s done",
  12946. ri->request_method,
  12947. path);
  12948. return;
  12949. }
  12950. /* 11.3. MKCOL method */
  12951. if (!strcmp(ri->request_method, "MKCOL")) {
  12952. dav_mkcol(conn, path);
  12953. DEBUG_TRACE("handling %s request to %s done",
  12954. ri->request_method,
  12955. path);
  12956. return;
  12957. }
  12958. /* 11.4. MOVE method */
  12959. if (!strcmp(ri->request_method, "MOVE")) {
  12960. dav_move_file(conn, path, 0);
  12961. DEBUG_TRACE("handling %s request to %s done",
  12962. ri->request_method,
  12963. path);
  12964. return;
  12965. }
  12966. if (!strcmp(ri->request_method, "COPY")) {
  12967. dav_move_file(conn, path, 1);
  12968. DEBUG_TRACE("handling %s request to %s done",
  12969. ri->request_method,
  12970. path);
  12971. return;
  12972. }
  12973. /* 11.5. LOCK method */
  12974. if (!strcmp(ri->request_method, "LOCK")) {
  12975. dav_lock_file(conn, path);
  12976. DEBUG_TRACE("handling %s request to %s done",
  12977. ri->request_method,
  12978. path);
  12979. return;
  12980. }
  12981. /* 11.6. UNLOCK method */
  12982. if (!strcmp(ri->request_method, "UNLOCK")) {
  12983. dav_unlock_file(conn, path);
  12984. DEBUG_TRACE("handling %s request to %s done",
  12985. ri->request_method,
  12986. path);
  12987. return;
  12988. }
  12989. /* 11.7. PROPPATCH method */
  12990. if (!strcmp(ri->request_method, "PROPPATCH")) {
  12991. dav_proppatch(conn, path);
  12992. DEBUG_TRACE("handling %s request to %s done",
  12993. ri->request_method,
  12994. path);
  12995. return;
  12996. }
  12997. /* 11.8. Other methods, e.g.: PATCH
  12998. * This method is not supported for static resources,
  12999. * only for scripts (Lua, CGI) and callbacks. */
  13000. mg_send_http_error(conn,
  13001. 405,
  13002. "%s method not allowed",
  13003. conn->request_info.request_method);
  13004. DEBUG_TRACE("method %s on %s is not supported",
  13005. ri->request_method,
  13006. path);
  13007. return;
  13008. }
  13009. /* 11. File does not exist, or it was configured that it should be
  13010. * hidden */
  13011. if (!is_found || (must_hide_file(conn, path))) {
  13012. mg_send_http_error(conn, 404, "%s", "Not found");
  13013. DEBUG_TRACE("handling %s request to %s: file not found",
  13014. ri->request_method,
  13015. path);
  13016. return;
  13017. }
  13018. /* 12. Directory uris should end with a slash */
  13019. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13020. && (ri->local_uri[uri_len - 1] != '/')) {
  13021. /* Path + server root */
  13022. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13023. char *new_path;
  13024. if (ri->query_string) {
  13025. buflen += strlen(ri->query_string);
  13026. }
  13027. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13028. if (!new_path) {
  13029. mg_send_http_error(conn, 500, "out or memory");
  13030. } else {
  13031. mg_get_request_link(conn, new_path, buflen - 1);
  13032. strcat(new_path, "/");
  13033. if (ri->query_string) {
  13034. /* Append ? and query string */
  13035. strcat(new_path, "?");
  13036. strcat(new_path, ri->query_string);
  13037. }
  13038. mg_send_http_redirect(conn, new_path, 301);
  13039. mg_free(new_path);
  13040. }
  13041. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13042. ri->request_method,
  13043. path);
  13044. return;
  13045. }
  13046. /* 13. Handle other methods than GET/HEAD */
  13047. /* 13.1. Handle PROPFIND */
  13048. if (!strcmp(ri->request_method, "PROPFIND")) {
  13049. handle_propfind(conn, path, &file.stat);
  13050. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13051. return;
  13052. }
  13053. /* 13.2. Handle OPTIONS for files */
  13054. if (!strcmp(ri->request_method, "OPTIONS")) {
  13055. /* This standard handler is only used for real files.
  13056. * Scripts should support the OPTIONS method themselves, to allow a
  13057. * maximum flexibility.
  13058. * Lua and CGI scripts may fully support CORS this way (including
  13059. * preflights). */
  13060. send_options(conn);
  13061. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13062. return;
  13063. }
  13064. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13065. if ((0 != strcmp(ri->request_method, "GET"))
  13066. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13067. mg_send_http_error(conn,
  13068. 405,
  13069. "%s method not allowed",
  13070. conn->request_info.request_method);
  13071. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13072. return;
  13073. }
  13074. /* 14. directories */
  13075. if (file.stat.is_directory) {
  13076. /* Substitute files have already been handled above. */
  13077. /* Here we can either generate and send a directory listing,
  13078. * or send an "access denied" error. */
  13079. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13080. "yes")) {
  13081. handle_directory_request(conn, path);
  13082. } else {
  13083. mg_send_http_error(conn,
  13084. 403,
  13085. "%s",
  13086. "Error: Directory listing denied");
  13087. }
  13088. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13089. return;
  13090. }
  13091. /* 15. Files with search/replace patterns: LSP and SSI */
  13092. if (is_template_text_file) {
  13093. HTTP1_only;
  13094. handle_file_based_request(conn, path, &file);
  13095. DEBUG_TRACE("handling %s request to %s done (template)",
  13096. ri->request_method,
  13097. path);
  13098. return;
  13099. }
  13100. /* 16. Static file - maybe cached */
  13101. #if !defined(NO_CACHING)
  13102. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13103. /* Send 304 "Not Modified" - this must not send any body data */
  13104. handle_not_modified_static_file_request(conn, &file);
  13105. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13106. ri->request_method,
  13107. path);
  13108. return;
  13109. }
  13110. #endif /* !NO_CACHING */
  13111. /* 17. Static file - not cached */
  13112. handle_static_file_request(conn, path, &file, NULL, NULL);
  13113. DEBUG_TRACE("handling %s request to %s done (static)",
  13114. ri->request_method,
  13115. path);
  13116. #endif /* !defined(NO_FILES) */
  13117. }
  13118. #if !defined(NO_FILESYSTEMS)
  13119. static void
  13120. handle_file_based_request(struct mg_connection *conn,
  13121. const char *path,
  13122. struct mg_file *file)
  13123. {
  13124. #if !defined(NO_CGI)
  13125. unsigned char cgi_config_idx, inc, max;
  13126. #endif
  13127. if (!conn || !conn->dom_ctx) {
  13128. return;
  13129. }
  13130. #if defined(USE_LUA)
  13131. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13132. path)
  13133. > 0) {
  13134. if (is_in_script_path(conn, path)) {
  13135. /* Lua server page: an SSI like page containing mostly plain
  13136. * html code plus some tags with server generated contents. */
  13137. handle_lsp_request(conn, path, file, NULL);
  13138. } else {
  13139. /* Script was in an illegal path */
  13140. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13141. }
  13142. return;
  13143. }
  13144. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13145. > 0) {
  13146. if (is_in_script_path(conn, path)) {
  13147. /* Lua in-server module script: a CGI like script used to
  13148. * generate the entire reply. */
  13149. mg_exec_lua_script(conn, path, NULL);
  13150. } else {
  13151. /* Script was in an illegal path */
  13152. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13153. }
  13154. return;
  13155. }
  13156. #endif
  13157. #if defined(USE_DUKTAPE)
  13158. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13159. path)
  13160. > 0) {
  13161. if (is_in_script_path(conn, path)) {
  13162. /* Call duktape to generate the page */
  13163. mg_exec_duktape_script(conn, path);
  13164. } else {
  13165. /* Script was in an illegal path */
  13166. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13167. }
  13168. return;
  13169. }
  13170. #endif
  13171. #if !defined(NO_CGI)
  13172. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13173. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13174. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13175. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13176. if (match_prefix_strlen(
  13177. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13178. path)
  13179. > 0) {
  13180. if (is_in_script_path(conn, path)) {
  13181. /* CGI scripts may support all HTTP methods */
  13182. handle_cgi_request(conn, path, cgi_config_idx);
  13183. } else {
  13184. /* Script was in an illegal path */
  13185. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13186. }
  13187. return;
  13188. }
  13189. }
  13190. }
  13191. #endif /* !NO_CGI */
  13192. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13193. if (is_in_script_path(conn, path)) {
  13194. handle_ssi_file_request(conn, path, file);
  13195. } else {
  13196. /* Script was in an illegal path */
  13197. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13198. }
  13199. return;
  13200. }
  13201. #if !defined(NO_CACHING)
  13202. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13203. /* Send 304 "Not Modified" - this must not send any body data */
  13204. handle_not_modified_static_file_request(conn, file);
  13205. return;
  13206. }
  13207. #endif /* !NO_CACHING */
  13208. handle_static_file_request(conn, path, file, NULL, NULL);
  13209. }
  13210. #endif /* NO_FILESYSTEMS */
  13211. static void
  13212. close_all_listening_sockets(struct mg_context *ctx)
  13213. {
  13214. unsigned int i;
  13215. if (!ctx) {
  13216. return;
  13217. }
  13218. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13219. closesocket(ctx->listening_sockets[i].sock);
  13220. #if defined(USE_X_DOM_SOCKET)
  13221. /* For unix domain sockets, the socket name represents a file that has
  13222. * to be deleted. */
  13223. /* See
  13224. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13225. */
  13226. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13227. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13228. IGNORE_UNUSED_RESULT(
  13229. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13230. }
  13231. #endif
  13232. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13233. }
  13234. mg_free(ctx->listening_sockets);
  13235. ctx->listening_sockets = NULL;
  13236. mg_free(ctx->listening_socket_fds);
  13237. ctx->listening_socket_fds = NULL;
  13238. }
  13239. /* Valid listening port specification is: [ip_address:]port[s]
  13240. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13241. * Examples for IPv6: [::]:80, [::1]:80,
  13242. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13243. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13244. * In order to bind to both, IPv4 and IPv6, you can either add
  13245. * both ports using 8080,[::]:8080, or the short form +8080.
  13246. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13247. * one only accepting IPv4 the other only IPv6. +8080 creates
  13248. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13249. * environment, they might work differently, or might not work
  13250. * at all - it must be tested what options work best in the
  13251. * relevant network environment.
  13252. */
  13253. static int
  13254. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13255. {
  13256. unsigned int a, b, c, d;
  13257. unsigned port;
  13258. unsigned long portUL;
  13259. int ch, len;
  13260. const char *cb;
  13261. char *endptr;
  13262. #if defined(USE_IPV6)
  13263. char buf[100] = {0};
  13264. #endif
  13265. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13266. * Also, all-zeroes in the socket address means binding to all addresses
  13267. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13268. memset(so, 0, sizeof(*so));
  13269. so->lsa.sin.sin_family = AF_INET;
  13270. *ip_version = 0;
  13271. /* Initialize len as invalid. */
  13272. port = 0;
  13273. len = 0;
  13274. /* Test for different ways to format this string */
  13275. if (sscanf(vec->ptr,
  13276. "%u.%u.%u.%u:%u%n",
  13277. &a,
  13278. &b,
  13279. &c,
  13280. &d,
  13281. &port,
  13282. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13283. // to an integer value, but function will not report
  13284. // conversion errors; consider using 'strtol' instead
  13285. == 5) {
  13286. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13287. so->lsa.sin.sin_addr.s_addr =
  13288. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13289. so->lsa.sin.sin_port = htons((uint16_t)port);
  13290. *ip_version = 4;
  13291. #if defined(USE_IPV6)
  13292. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13293. && ((size_t)len <= vec->len)
  13294. && mg_inet_pton(
  13295. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13296. /* IPv6 address, examples: see above */
  13297. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13298. */
  13299. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13300. *ip_version = 6;
  13301. #endif
  13302. } else if ((vec->ptr[0] == '+')
  13303. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13304. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13305. // string to an integer value, but function will not
  13306. // report conversion errors; consider using 'strtol'
  13307. // instead
  13308. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13309. /* Add 1 to len for the + character we skipped before */
  13310. len++;
  13311. #if defined(USE_IPV6)
  13312. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13313. so->lsa.sin6.sin6_family = AF_INET6;
  13314. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13315. *ip_version = 4 + 6;
  13316. #else
  13317. /* Bind to IPv4 only, since IPv6 is not built in. */
  13318. so->lsa.sin.sin_port = htons((uint16_t)port);
  13319. *ip_version = 4;
  13320. #endif
  13321. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13322. && (vec->ptr != endptr)) {
  13323. len = (int)(endptr - vec->ptr);
  13324. port = (uint16_t)portUL;
  13325. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13326. so->lsa.sin.sin_port = htons((uint16_t)port);
  13327. *ip_version = 4;
  13328. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13329. /* String could be a hostname. This check algotithm
  13330. * will only work for RFC 952 compliant hostnames,
  13331. * starting with a letter, containing only letters,
  13332. * digits and hyphen ('-'). Newer specs may allow
  13333. * more, but this is not guaranteed here, since it
  13334. * may interfere with rules for port option lists. */
  13335. /* According to RFC 1035, hostnames are restricted to 255 characters
  13336. * in total (63 between two dots). */
  13337. char hostname[256];
  13338. size_t hostnlen = (size_t)(cb - vec->ptr);
  13339. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13340. /* This would be invalid in any case */
  13341. *ip_version = 0;
  13342. return 0;
  13343. }
  13344. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13345. if (mg_inet_pton(
  13346. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13347. if (sscanf(cb + 1, "%u%n", &port, &len)
  13348. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13349. // string to an integer value, but function will not
  13350. // report conversion errors; consider using 'strtol'
  13351. // instead
  13352. *ip_version = 4;
  13353. so->lsa.sin.sin_port = htons((uint16_t)port);
  13354. len += (int)(hostnlen + 1);
  13355. } else {
  13356. len = 0;
  13357. }
  13358. #if defined(USE_IPV6)
  13359. } else if (mg_inet_pton(AF_INET6,
  13360. hostname,
  13361. &so->lsa.sin6,
  13362. sizeof(so->lsa.sin6),
  13363. 1)) {
  13364. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13365. *ip_version = 6;
  13366. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13367. len += (int)(hostnlen + 1);
  13368. } else {
  13369. len = 0;
  13370. }
  13371. #endif
  13372. } else {
  13373. len = 0;
  13374. }
  13375. #if defined(USE_X_DOM_SOCKET)
  13376. } else if (vec->ptr[0] == 'x') {
  13377. /* unix (linux) domain socket */
  13378. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13379. len = vec->len;
  13380. so->lsa.sun.sun_family = AF_UNIX;
  13381. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13382. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13383. port = 0;
  13384. *ip_version = 99;
  13385. } else {
  13386. /* String too long */
  13387. len = 0;
  13388. }
  13389. #endif
  13390. } else {
  13391. /* Parsing failure. */
  13392. len = 0;
  13393. }
  13394. /* sscanf and the option splitting code ensure the following condition
  13395. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13396. if ((len > 0) && is_valid_port(port)
  13397. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13398. /* Next character after the port number */
  13399. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13400. so->is_ssl = (ch == 's');
  13401. so->ssl_redir = (ch == 'r');
  13402. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13403. return 1;
  13404. }
  13405. }
  13406. /* Reset ip_version to 0 if there is an error */
  13407. *ip_version = 0;
  13408. return 0;
  13409. }
  13410. /* Is there any SSL port in use? */
  13411. static int
  13412. is_ssl_port_used(const char *ports)
  13413. {
  13414. if (ports) {
  13415. /* There are several different allowed syntax variants:
  13416. * - "80" for a single port using every network interface
  13417. * - "localhost:80" for a single port using only localhost
  13418. * - "80,localhost:8080" for two ports, one bound to localhost
  13419. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13420. * to IPv4 localhost, one to IPv6 localhost
  13421. * - "+80" use port 80 for IPv4 and IPv6
  13422. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13423. * for both: IPv4 and IPv4
  13424. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13425. * additionally port 8080 bound to localhost connections
  13426. *
  13427. * If we just look for 's' anywhere in the string, "localhost:80"
  13428. * will be detected as SSL (false positive).
  13429. * Looking for 's' after a digit may cause false positives in
  13430. * "my24service:8080".
  13431. * Looking from 's' backward if there are only ':' and numbers
  13432. * before will not work for "24service:8080" (non SSL, port 8080)
  13433. * or "24s" (SSL, port 24).
  13434. *
  13435. * Remark: Initially hostnames were not allowed to start with a
  13436. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13437. * Section 2.1).
  13438. *
  13439. * To get this correct, the entire string must be parsed as a whole,
  13440. * reading it as a list element for element and parsing with an
  13441. * algorithm equivalent to parse_port_string.
  13442. *
  13443. * In fact, we use local interface names here, not arbitrary
  13444. * hostnames, so in most cases the only name will be "localhost".
  13445. *
  13446. * So, for now, we use this simple algorithm, that may still return
  13447. * a false positive in bizarre cases.
  13448. */
  13449. int i;
  13450. int portslen = (int)strlen(ports);
  13451. char prevIsNumber = 0;
  13452. for (i = 0; i < portslen; i++) {
  13453. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13454. return 1;
  13455. }
  13456. if (ports[i] >= '0' && ports[i] <= '9') {
  13457. prevIsNumber = 1;
  13458. } else {
  13459. prevIsNumber = 0;
  13460. }
  13461. }
  13462. }
  13463. return 0;
  13464. }
  13465. static int
  13466. set_ports_option(struct mg_context *phys_ctx)
  13467. {
  13468. const char *list;
  13469. int on = 1;
  13470. #if defined(USE_IPV6)
  13471. int off = 0;
  13472. #endif
  13473. struct vec vec;
  13474. struct socket so, *ptr;
  13475. struct mg_pollfd *pfd;
  13476. union usa usa;
  13477. socklen_t len;
  13478. int ip_version;
  13479. int portsTotal = 0;
  13480. int portsOk = 0;
  13481. const char *opt_txt;
  13482. long opt_listen_backlog;
  13483. if (!phys_ctx) {
  13484. return 0;
  13485. }
  13486. memset(&so, 0, sizeof(so));
  13487. memset(&usa, 0, sizeof(usa));
  13488. len = sizeof(usa);
  13489. list = phys_ctx->dd.config[LISTENING_PORTS];
  13490. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13491. portsTotal++;
  13492. if (!parse_port_string(&vec, &so, &ip_version)) {
  13493. mg_cry_ctx_internal(
  13494. phys_ctx,
  13495. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13496. (int)vec.len,
  13497. vec.ptr,
  13498. portsTotal,
  13499. "[IP_ADDRESS:]PORT[s|r]");
  13500. continue;
  13501. }
  13502. #if !defined(NO_SSL)
  13503. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13504. mg_cry_ctx_internal(phys_ctx,
  13505. "Cannot add SSL socket (entry %i)",
  13506. portsTotal);
  13507. continue;
  13508. }
  13509. #endif
  13510. /* Create socket. */
  13511. /* For a list of protocol numbers (e.g., TCP==6) see:
  13512. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13513. */
  13514. if ((so.sock =
  13515. socket(so.lsa.sa.sa_family,
  13516. SOCK_STREAM,
  13517. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13518. == INVALID_SOCKET) {
  13519. mg_cry_ctx_internal(phys_ctx,
  13520. "cannot create socket (entry %i)",
  13521. portsTotal);
  13522. continue;
  13523. }
  13524. #if defined(_WIN32)
  13525. /* Windows SO_REUSEADDR lets many procs binds to a
  13526. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13527. * if someone already has the socket -- DTL */
  13528. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13529. * Windows might need a few seconds before
  13530. * the same port can be used again in the
  13531. * same process, so a short Sleep may be
  13532. * required between mg_stop and mg_start.
  13533. */
  13534. if (setsockopt(so.sock,
  13535. SOL_SOCKET,
  13536. SO_EXCLUSIVEADDRUSE,
  13537. (SOCK_OPT_TYPE)&on,
  13538. sizeof(on))
  13539. != 0) {
  13540. /* Set reuse option, but don't abort on errors. */
  13541. mg_cry_ctx_internal(
  13542. phys_ctx,
  13543. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13544. portsTotal);
  13545. }
  13546. #else
  13547. if (setsockopt(so.sock,
  13548. SOL_SOCKET,
  13549. SO_REUSEADDR,
  13550. (SOCK_OPT_TYPE)&on,
  13551. sizeof(on))
  13552. != 0) {
  13553. /* Set reuse option, but don't abort on errors. */
  13554. mg_cry_ctx_internal(
  13555. phys_ctx,
  13556. "cannot set socket option SO_REUSEADDR (entry %i)",
  13557. portsTotal);
  13558. }
  13559. #endif
  13560. #if defined(USE_X_DOM_SOCKET)
  13561. if (ip_version == 99) {
  13562. /* Unix domain socket */
  13563. } else
  13564. #endif
  13565. if (ip_version > 4) {
  13566. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13567. #if defined(USE_IPV6)
  13568. if (ip_version > 6) {
  13569. if (so.lsa.sa.sa_family == AF_INET6
  13570. && setsockopt(so.sock,
  13571. IPPROTO_IPV6,
  13572. IPV6_V6ONLY,
  13573. (void *)&off,
  13574. sizeof(off))
  13575. != 0) {
  13576. /* Set IPv6 only option, but don't abort on errors. */
  13577. mg_cry_ctx_internal(phys_ctx,
  13578. "cannot set socket option "
  13579. "IPV6_V6ONLY=off (entry %i)",
  13580. portsTotal);
  13581. }
  13582. } else {
  13583. if (so.lsa.sa.sa_family == AF_INET6
  13584. && setsockopt(so.sock,
  13585. IPPROTO_IPV6,
  13586. IPV6_V6ONLY,
  13587. (void *)&on,
  13588. sizeof(on))
  13589. != 0) {
  13590. /* Set IPv6 only option, but don't abort on errors. */
  13591. mg_cry_ctx_internal(phys_ctx,
  13592. "cannot set socket option "
  13593. "IPV6_V6ONLY=on (entry %i)",
  13594. portsTotal);
  13595. }
  13596. }
  13597. #else
  13598. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13599. closesocket(so.sock);
  13600. so.sock = INVALID_SOCKET;
  13601. continue;
  13602. #endif
  13603. }
  13604. if (so.lsa.sa.sa_family == AF_INET) {
  13605. len = sizeof(so.lsa.sin);
  13606. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13607. mg_cry_ctx_internal(phys_ctx,
  13608. "cannot bind to %.*s: %d (%s)",
  13609. (int)vec.len,
  13610. vec.ptr,
  13611. (int)ERRNO,
  13612. strerror(errno));
  13613. closesocket(so.sock);
  13614. so.sock = INVALID_SOCKET;
  13615. continue;
  13616. }
  13617. }
  13618. #if defined(USE_IPV6)
  13619. else if (so.lsa.sa.sa_family == AF_INET6) {
  13620. len = sizeof(so.lsa.sin6);
  13621. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13622. mg_cry_ctx_internal(phys_ctx,
  13623. "cannot bind to IPv6 %.*s: %d (%s)",
  13624. (int)vec.len,
  13625. vec.ptr,
  13626. (int)ERRNO,
  13627. strerror(errno));
  13628. closesocket(so.sock);
  13629. so.sock = INVALID_SOCKET;
  13630. continue;
  13631. }
  13632. }
  13633. #endif
  13634. #if defined(USE_X_DOM_SOCKET)
  13635. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13636. len = sizeof(so.lsa.sun);
  13637. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13638. mg_cry_ctx_internal(phys_ctx,
  13639. "cannot bind to unix socket %s: %d (%s)",
  13640. so.lsa.sun.sun_path,
  13641. (int)ERRNO,
  13642. strerror(errno));
  13643. closesocket(so.sock);
  13644. so.sock = INVALID_SOCKET;
  13645. continue;
  13646. }
  13647. }
  13648. #endif
  13649. else {
  13650. mg_cry_ctx_internal(
  13651. phys_ctx,
  13652. "cannot bind: address family not supported (entry %i)",
  13653. portsTotal);
  13654. closesocket(so.sock);
  13655. so.sock = INVALID_SOCKET;
  13656. continue;
  13657. }
  13658. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13659. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13660. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13661. mg_cry_ctx_internal(phys_ctx,
  13662. "%s value \"%s\" is invalid",
  13663. config_options[LISTEN_BACKLOG_SIZE].name,
  13664. opt_txt);
  13665. closesocket(so.sock);
  13666. so.sock = INVALID_SOCKET;
  13667. continue;
  13668. }
  13669. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13670. mg_cry_ctx_internal(phys_ctx,
  13671. "cannot listen to %.*s: %d (%s)",
  13672. (int)vec.len,
  13673. vec.ptr,
  13674. (int)ERRNO,
  13675. strerror(errno));
  13676. closesocket(so.sock);
  13677. so.sock = INVALID_SOCKET;
  13678. continue;
  13679. }
  13680. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13681. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13682. int err = (int)ERRNO;
  13683. mg_cry_ctx_internal(phys_ctx,
  13684. "call to getsockname failed %.*s: %d (%s)",
  13685. (int)vec.len,
  13686. vec.ptr,
  13687. err,
  13688. strerror(errno));
  13689. closesocket(so.sock);
  13690. so.sock = INVALID_SOCKET;
  13691. continue;
  13692. }
  13693. /* Update lsa port in case of random free ports */
  13694. #if defined(USE_IPV6)
  13695. if (so.lsa.sa.sa_family == AF_INET6) {
  13696. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13697. } else
  13698. #endif
  13699. {
  13700. so.lsa.sin.sin_port = usa.sin.sin_port;
  13701. }
  13702. if ((ptr = (struct socket *)
  13703. mg_realloc_ctx(phys_ctx->listening_sockets,
  13704. (phys_ctx->num_listening_sockets + 1)
  13705. * sizeof(phys_ctx->listening_sockets[0]),
  13706. phys_ctx))
  13707. == NULL) {
  13708. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13709. closesocket(so.sock);
  13710. so.sock = INVALID_SOCKET;
  13711. continue;
  13712. }
  13713. if ((pfd = (struct mg_pollfd *)
  13714. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13715. (phys_ctx->num_listening_sockets + 1)
  13716. * sizeof(phys_ctx->listening_socket_fds[0]),
  13717. phys_ctx))
  13718. == NULL) {
  13719. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13720. closesocket(so.sock);
  13721. so.sock = INVALID_SOCKET;
  13722. mg_free(ptr);
  13723. continue;
  13724. }
  13725. set_close_on_exec(so.sock, NULL, phys_ctx);
  13726. phys_ctx->listening_sockets = ptr;
  13727. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13728. phys_ctx->listening_socket_fds = pfd;
  13729. phys_ctx->num_listening_sockets++;
  13730. portsOk++;
  13731. }
  13732. if (portsOk != portsTotal) {
  13733. close_all_listening_sockets(phys_ctx);
  13734. portsOk = 0;
  13735. }
  13736. return portsOk;
  13737. }
  13738. static const char *
  13739. header_val(const struct mg_connection *conn, const char *header)
  13740. {
  13741. const char *header_value;
  13742. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13743. return "-";
  13744. } else {
  13745. return header_value;
  13746. }
  13747. }
  13748. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13749. #include "external_log_access.inl"
  13750. #elif !defined(NO_FILESYSTEMS)
  13751. static void
  13752. log_access(const struct mg_connection *conn)
  13753. {
  13754. const struct mg_request_info *ri;
  13755. struct mg_file fi;
  13756. char date[64], src_addr[IP_ADDR_STR_LEN];
  13757. struct tm *tm;
  13758. const char *referer;
  13759. const char *user_agent;
  13760. char log_buf[4096];
  13761. if (!conn || !conn->dom_ctx) {
  13762. return;
  13763. }
  13764. /* Set log message to "empty" */
  13765. log_buf[0] = 0;
  13766. #if defined(USE_LUA)
  13767. if (conn->phys_ctx->lua_bg_log_available) {
  13768. int ret;
  13769. struct mg_context *ctx = conn->phys_ctx;
  13770. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13771. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13772. /* call "log()" in Lua */
  13773. lua_getglobal(lstate, "log");
  13774. prepare_lua_request_info_inner(conn, lstate);
  13775. push_lua_response_log_data(conn, lstate);
  13776. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13777. if (ret == 0) {
  13778. int t = lua_type(lstate, -1);
  13779. if (t == LUA_TBOOLEAN) {
  13780. if (lua_toboolean(lstate, -1) == 0) {
  13781. /* log() returned false: do not log */
  13782. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13783. return;
  13784. }
  13785. /* log returned true: continue logging */
  13786. } else if (t == LUA_TSTRING) {
  13787. size_t len;
  13788. const char *txt = lua_tolstring(lstate, -1, &len);
  13789. if ((len == 0) || (*txt == 0)) {
  13790. /* log() returned empty string: do not log */
  13791. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13792. return;
  13793. }
  13794. /* Copy test from Lua into log_buf */
  13795. if (len >= sizeof(log_buf)) {
  13796. len = sizeof(log_buf) - 1;
  13797. }
  13798. memcpy(log_buf, txt, len);
  13799. log_buf[len] = 0;
  13800. }
  13801. } else {
  13802. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13803. }
  13804. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13805. }
  13806. #endif
  13807. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13808. if (mg_fopen(conn,
  13809. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13810. MG_FOPEN_MODE_APPEND,
  13811. &fi)
  13812. == 0) {
  13813. fi.access.fp = NULL;
  13814. }
  13815. } else {
  13816. fi.access.fp = NULL;
  13817. }
  13818. /* Log is written to a file and/or a callback. If both are not set,
  13819. * executing the rest of the function is pointless. */
  13820. if ((fi.access.fp == NULL)
  13821. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13822. return;
  13823. }
  13824. /* If we did not get a log message from Lua, create it here. */
  13825. if (!log_buf[0]) {
  13826. tm = localtime(&conn->conn_birth_time);
  13827. if (tm != NULL) {
  13828. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13829. } else {
  13830. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13831. date[sizeof(date) - 1] = '\0';
  13832. }
  13833. ri = &conn->request_info;
  13834. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13835. referer = header_val(conn, "Referer");
  13836. user_agent = header_val(conn, "User-Agent");
  13837. mg_snprintf(conn,
  13838. NULL, /* Ignore truncation in access log */
  13839. log_buf,
  13840. sizeof(log_buf),
  13841. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13842. " %s %s",
  13843. src_addr,
  13844. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13845. date,
  13846. ri->request_method ? ri->request_method : "-",
  13847. ri->request_uri ? ri->request_uri : "-",
  13848. ri->query_string ? "?" : "",
  13849. ri->query_string ? ri->query_string : "",
  13850. ri->http_version,
  13851. conn->status_code,
  13852. conn->num_bytes_sent,
  13853. referer,
  13854. user_agent);
  13855. }
  13856. /* Here we have a log message in log_buf. Call the callback */
  13857. if (conn->phys_ctx->callbacks.log_access) {
  13858. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13859. /* do not log if callack returns non-zero */
  13860. if (fi.access.fp) {
  13861. mg_fclose(&fi.access);
  13862. }
  13863. return;
  13864. }
  13865. }
  13866. /* Store in file */
  13867. if (fi.access.fp) {
  13868. int ok = 1;
  13869. flockfile(fi.access.fp);
  13870. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13871. ok = 0;
  13872. }
  13873. if (fflush(fi.access.fp) != 0) {
  13874. ok = 0;
  13875. }
  13876. funlockfile(fi.access.fp);
  13877. if (mg_fclose(&fi.access) != 0) {
  13878. ok = 0;
  13879. }
  13880. if (!ok) {
  13881. mg_cry_internal(conn,
  13882. "Error writing log file %s",
  13883. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13884. }
  13885. }
  13886. }
  13887. #else
  13888. #error "Either enable filesystems or provide a custom log_access implementation"
  13889. #endif /* Externally provided function */
  13890. /* Verify given socket address against the ACL.
  13891. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13892. */
  13893. static int
  13894. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13895. {
  13896. int allowed, flag, matched;
  13897. struct vec vec;
  13898. if (phys_ctx) {
  13899. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13900. /* If any ACL is set, deny by default */
  13901. allowed = (list == NULL) ? '+' : '-';
  13902. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13903. flag = vec.ptr[0];
  13904. matched = -1;
  13905. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13906. vec.ptr++;
  13907. vec.len--;
  13908. matched = parse_match_net(&vec, sa, 1);
  13909. }
  13910. if (matched < 0) {
  13911. mg_cry_ctx_internal(phys_ctx,
  13912. "%s: subnet must be [+|-]IP-addr[/x]",
  13913. __func__);
  13914. return -1;
  13915. }
  13916. if (matched) {
  13917. allowed = flag;
  13918. }
  13919. }
  13920. return allowed == '+';
  13921. }
  13922. return -1;
  13923. }
  13924. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13925. static int
  13926. set_uid_option(struct mg_context *phys_ctx)
  13927. {
  13928. int success = 0;
  13929. if (phys_ctx) {
  13930. /* We are currently running as curr_uid. */
  13931. const uid_t curr_uid = getuid();
  13932. /* If set, we want to run as run_as_user. */
  13933. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13934. const struct passwd *to_pw = NULL;
  13935. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13936. /* run_as_user does not exist on the system. We can't proceed
  13937. * further. */
  13938. mg_cry_ctx_internal(phys_ctx,
  13939. "%s: unknown user [%s]",
  13940. __func__,
  13941. run_as_user);
  13942. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13943. /* There was either no request to change user, or we're already
  13944. * running as run_as_user. Nothing else to do.
  13945. */
  13946. success = 1;
  13947. } else {
  13948. /* Valid change request. */
  13949. if (setgid(to_pw->pw_gid) == -1) {
  13950. mg_cry_ctx_internal(phys_ctx,
  13951. "%s: setgid(%s): %s",
  13952. __func__,
  13953. run_as_user,
  13954. strerror(errno));
  13955. } else if (setgroups(0, NULL) == -1) {
  13956. mg_cry_ctx_internal(phys_ctx,
  13957. "%s: setgroups(): %s",
  13958. __func__,
  13959. strerror(errno));
  13960. } else if (setuid(to_pw->pw_uid) == -1) {
  13961. mg_cry_ctx_internal(phys_ctx,
  13962. "%s: setuid(%s): %s",
  13963. __func__,
  13964. run_as_user,
  13965. strerror(errno));
  13966. } else {
  13967. success = 1;
  13968. }
  13969. }
  13970. }
  13971. return success;
  13972. }
  13973. #endif /* !_WIN32 */
  13974. static void
  13975. tls_dtor(void *key)
  13976. {
  13977. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13978. /* key == pthread_getspecific(sTlsKey); */
  13979. if (tls) {
  13980. if (tls->is_master == 2) {
  13981. tls->is_master = -3; /* Mark memory as dead */
  13982. mg_free(tls);
  13983. }
  13984. }
  13985. pthread_setspecific(sTlsKey, NULL);
  13986. }
  13987. #if defined(USE_MBEDTLS)
  13988. /* Check if SSL is required.
  13989. * If so, set up ctx->ssl_ctx pointer. */
  13990. static int
  13991. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13992. {
  13993. if (!phys_ctx) {
  13994. return 0;
  13995. }
  13996. if (!dom_ctx) {
  13997. dom_ctx = &(phys_ctx->dd);
  13998. }
  13999. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14000. /* No SSL port is set. No need to setup SSL. */
  14001. return 1;
  14002. }
  14003. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14004. if (dom_ctx->ssl_ctx == NULL) {
  14005. fprintf(stderr, "ssl_ctx malloc failed\n");
  14006. return 0;
  14007. }
  14008. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14009. == 0
  14010. ? 1
  14011. : 0;
  14012. }
  14013. #elif !defined(NO_SSL)
  14014. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14015. struct mg_domain_context *dom_ctx,
  14016. const char *pem,
  14017. const char *chain);
  14018. static const char *ssl_error(void);
  14019. static int
  14020. refresh_trust(struct mg_connection *conn)
  14021. {
  14022. struct stat cert_buf;
  14023. int64_t t = 0;
  14024. const char *pem;
  14025. const char *chain;
  14026. int should_verify_peer;
  14027. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14028. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14029. * refresh_trust still can not work. */
  14030. return 0;
  14031. }
  14032. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14033. if (chain == NULL) {
  14034. /* pem is not NULL here */
  14035. chain = pem;
  14036. }
  14037. if (*chain == 0) {
  14038. chain = NULL;
  14039. }
  14040. if (stat(pem, &cert_buf) != -1) {
  14041. t = (int64_t)cert_buf.st_mtime;
  14042. }
  14043. mg_lock_context(conn->phys_ctx);
  14044. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14045. conn->dom_ctx->ssl_cert_last_mtime = t;
  14046. should_verify_peer = 0;
  14047. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14048. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14049. == 0) {
  14050. should_verify_peer = 1;
  14051. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14052. "optional")
  14053. == 0) {
  14054. should_verify_peer = 1;
  14055. }
  14056. }
  14057. if (should_verify_peer) {
  14058. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14059. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14060. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14061. ca_file,
  14062. ca_path)
  14063. != 1) {
  14064. mg_unlock_context(conn->phys_ctx);
  14065. mg_cry_ctx_internal(
  14066. conn->phys_ctx,
  14067. "SSL_CTX_load_verify_locations error: %s "
  14068. "ssl_verify_peer requires setting "
  14069. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14070. "present in "
  14071. "the .conf file?",
  14072. ssl_error());
  14073. return 0;
  14074. }
  14075. }
  14076. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14077. mg_unlock_context(conn->phys_ctx);
  14078. return 0;
  14079. }
  14080. }
  14081. mg_unlock_context(conn->phys_ctx);
  14082. return 1;
  14083. }
  14084. #if defined(OPENSSL_API_1_1)
  14085. #else
  14086. static pthread_mutex_t *ssl_mutexes;
  14087. #endif /* OPENSSL_API_1_1 */
  14088. static int
  14089. sslize(struct mg_connection *conn,
  14090. int (*func)(SSL *),
  14091. const struct mg_client_options *client_options)
  14092. {
  14093. int ret, err;
  14094. int short_trust;
  14095. unsigned timeout = 1024;
  14096. unsigned i;
  14097. if (!conn) {
  14098. return 0;
  14099. }
  14100. short_trust =
  14101. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14102. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14103. if (short_trust) {
  14104. int trust_ret = refresh_trust(conn);
  14105. if (!trust_ret) {
  14106. return trust_ret;
  14107. }
  14108. }
  14109. mg_lock_context(conn->phys_ctx);
  14110. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14111. mg_unlock_context(conn->phys_ctx);
  14112. if (conn->ssl == NULL) {
  14113. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14114. OPENSSL_REMOVE_THREAD_STATE();
  14115. return 0;
  14116. }
  14117. SSL_set_app_data(conn->ssl, (char *)conn);
  14118. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14119. if (ret != 1) {
  14120. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14121. SSL_free(conn->ssl);
  14122. conn->ssl = NULL;
  14123. OPENSSL_REMOVE_THREAD_STATE();
  14124. return 0;
  14125. }
  14126. if (client_options) {
  14127. if (client_options->host_name) {
  14128. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14129. }
  14130. }
  14131. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14132. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14133. /* NOTE: The loop below acts as a back-off, so we can end
  14134. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14135. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14136. if (to >= 0) {
  14137. timeout = (unsigned)to;
  14138. }
  14139. }
  14140. /* SSL functions may fail and require to be called again:
  14141. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14142. * Here "func" could be SSL_connect or SSL_accept. */
  14143. for (i = 0; i <= timeout; i += 50) {
  14144. ERR_clear_error();
  14145. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14146. ret = func(conn->ssl);
  14147. if (ret != 1) {
  14148. err = SSL_get_error(conn->ssl, ret);
  14149. if ((err == SSL_ERROR_WANT_CONNECT)
  14150. || (err == SSL_ERROR_WANT_ACCEPT)
  14151. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14152. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14153. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14154. /* Don't wait if the server is going to be stopped. */
  14155. break;
  14156. }
  14157. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14158. /* Simply retry the function call. */
  14159. mg_sleep(50);
  14160. } else {
  14161. /* Need to retry the function call "later".
  14162. * See https://linux.die.net/man/3/ssl_get_error
  14163. * This is typical for non-blocking sockets. */
  14164. struct mg_pollfd pfd;
  14165. int pollres;
  14166. pfd.fd = conn->client.sock;
  14167. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14168. || (err == SSL_ERROR_WANT_WRITE))
  14169. ? POLLOUT
  14170. : POLLIN;
  14171. pollres =
  14172. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14173. if (pollres < 0) {
  14174. /* Break if error occured (-1)
  14175. * or server shutdown (-2) */
  14176. break;
  14177. }
  14178. }
  14179. } else if (err == SSL_ERROR_SYSCALL) {
  14180. /* This is an IO error. Look at errno. */
  14181. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14182. break;
  14183. } else {
  14184. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14185. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14186. break;
  14187. }
  14188. } else {
  14189. /* success */
  14190. break;
  14191. }
  14192. }
  14193. ERR_clear_error();
  14194. if (ret != 1) {
  14195. SSL_free(conn->ssl);
  14196. conn->ssl = NULL;
  14197. OPENSSL_REMOVE_THREAD_STATE();
  14198. return 0;
  14199. }
  14200. return 1;
  14201. }
  14202. /* Return OpenSSL error message (from CRYPTO lib) */
  14203. static const char *
  14204. ssl_error(void)
  14205. {
  14206. unsigned long err;
  14207. err = ERR_get_error();
  14208. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14209. }
  14210. static int
  14211. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14212. {
  14213. int i;
  14214. const char hexdigit[] = "0123456789abcdef";
  14215. if ((memlen <= 0) || (buflen <= 0)) {
  14216. return 0;
  14217. }
  14218. if (buflen < (3 * memlen)) {
  14219. return 0;
  14220. }
  14221. for (i = 0; i < memlen; i++) {
  14222. if (i > 0) {
  14223. buf[3 * i - 1] = ' ';
  14224. }
  14225. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14226. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14227. }
  14228. buf[3 * memlen - 1] = 0;
  14229. return 1;
  14230. }
  14231. static int
  14232. ssl_get_client_cert_info(const struct mg_connection *conn,
  14233. struct mg_client_cert *client_cert)
  14234. {
  14235. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14236. if (cert) {
  14237. char str_buf[1024];
  14238. unsigned char buf[256];
  14239. char *str_serial = NULL;
  14240. unsigned int ulen;
  14241. int ilen;
  14242. unsigned char *tmp_buf;
  14243. unsigned char *tmp_p;
  14244. /* Handle to algorithm used for fingerprint */
  14245. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14246. /* Get Subject and issuer */
  14247. X509_NAME *subj = X509_get_subject_name(cert);
  14248. X509_NAME *iss = X509_get_issuer_name(cert);
  14249. /* Get serial number */
  14250. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14251. /* Translate serial number to a hex string */
  14252. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14253. if (serial_bn) {
  14254. str_serial = BN_bn2hex(serial_bn);
  14255. BN_free(serial_bn);
  14256. }
  14257. client_cert->serial =
  14258. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14259. /* Translate subject and issuer to a string */
  14260. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14261. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14262. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14263. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14264. /* Calculate SHA1 fingerprint and store as a hex string */
  14265. ulen = 0;
  14266. /* ASN1_digest is deprecated. Do the calculation manually,
  14267. * using EVP_Digest. */
  14268. ilen = i2d_X509(cert, NULL);
  14269. tmp_buf = (ilen > 0)
  14270. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14271. conn->phys_ctx)
  14272. : NULL;
  14273. if (tmp_buf) {
  14274. tmp_p = tmp_buf;
  14275. (void)i2d_X509(cert, &tmp_p);
  14276. if (!EVP_Digest(
  14277. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14278. ulen = 0;
  14279. }
  14280. mg_free(tmp_buf);
  14281. }
  14282. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14283. *str_buf = 0;
  14284. }
  14285. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14286. client_cert->peer_cert = (void *)cert;
  14287. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14288. * see https://linux.die.net/man/3/bn_bn2hex */
  14289. OPENSSL_free(str_serial);
  14290. return 1;
  14291. }
  14292. return 0;
  14293. }
  14294. #if defined(OPENSSL_API_1_1)
  14295. #else
  14296. static void
  14297. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14298. {
  14299. (void)line;
  14300. (void)file;
  14301. if (mode & 1) {
  14302. /* 1 is CRYPTO_LOCK */
  14303. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14304. } else {
  14305. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14306. }
  14307. }
  14308. #endif /* OPENSSL_API_1_1 */
  14309. #if !defined(NO_SSL_DL)
  14310. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14311. static void *
  14312. load_tls_dll(char *ebuf,
  14313. size_t ebuf_len,
  14314. const char *dll_name,
  14315. struct ssl_func *sw,
  14316. int *feature_missing)
  14317. {
  14318. union {
  14319. void *p;
  14320. void (*fp)(void);
  14321. } u;
  14322. void *dll_handle;
  14323. struct ssl_func *fp;
  14324. int ok;
  14325. int truncated = 0;
  14326. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14327. mg_snprintf(NULL,
  14328. NULL, /* No truncation check for ebuf */
  14329. ebuf,
  14330. ebuf_len,
  14331. "%s: cannot load %s",
  14332. __func__,
  14333. dll_name);
  14334. return NULL;
  14335. }
  14336. ok = 1;
  14337. for (fp = sw; fp->name != NULL; fp++) {
  14338. #if defined(_WIN32)
  14339. /* GetProcAddress() returns pointer to function */
  14340. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14341. #else
  14342. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14343. * pointers to function pointers. We need to use a union to make a
  14344. * cast. */
  14345. u.p = dlsym(dll_handle, fp->name);
  14346. #endif /* _WIN32 */
  14347. /* Set pointer (might be NULL) */
  14348. fp->ptr = u.fp;
  14349. if (u.fp == NULL) {
  14350. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14351. if (feature_missing) {
  14352. feature_missing[fp->required]++;
  14353. }
  14354. if (fp->required == TLS_Mandatory) {
  14355. /* Mandatory function is missing */
  14356. if (ok) {
  14357. /* This is the first missing function.
  14358. * Create a new error message. */
  14359. mg_snprintf(NULL,
  14360. &truncated,
  14361. ebuf,
  14362. ebuf_len,
  14363. "%s: %s: cannot find %s",
  14364. __func__,
  14365. dll_name,
  14366. fp->name);
  14367. ok = 0;
  14368. } else {
  14369. /* This is yet anothermissing function.
  14370. * Append existing error message. */
  14371. size_t cur_len = strlen(ebuf);
  14372. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14373. mg_snprintf(NULL,
  14374. &truncated,
  14375. ebuf + cur_len,
  14376. ebuf_len - cur_len - 3,
  14377. ", %s",
  14378. fp->name);
  14379. if (truncated) {
  14380. /* If truncated, add "..." */
  14381. strcat(ebuf, "...");
  14382. }
  14383. }
  14384. }
  14385. }
  14386. }
  14387. }
  14388. if (!ok) {
  14389. (void)dlclose(dll_handle);
  14390. return NULL;
  14391. }
  14392. return dll_handle;
  14393. }
  14394. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14395. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14396. #endif /* NO_SSL_DL */
  14397. #if defined(SSL_ALREADY_INITIALIZED)
  14398. static volatile ptrdiff_t cryptolib_users =
  14399. 1; /* Reference counter for crypto library. */
  14400. #else
  14401. static volatile ptrdiff_t cryptolib_users =
  14402. 0; /* Reference counter for crypto library. */
  14403. #endif
  14404. static int
  14405. initialize_openssl(char *ebuf, size_t ebuf_len)
  14406. {
  14407. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14408. int i, num_locks;
  14409. size_t size;
  14410. #endif
  14411. if (ebuf_len > 0) {
  14412. ebuf[0] = 0;
  14413. }
  14414. #if !defined(NO_SSL_DL)
  14415. if (!cryptolib_dll_handle) {
  14416. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14417. cryptolib_dll_handle = load_tls_dll(
  14418. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14419. if (!cryptolib_dll_handle) {
  14420. mg_snprintf(NULL,
  14421. NULL, /* No truncation check for ebuf */
  14422. ebuf,
  14423. ebuf_len,
  14424. "%s: error loading library %s",
  14425. __func__,
  14426. CRYPTO_LIB);
  14427. DEBUG_TRACE("%s", ebuf);
  14428. return 0;
  14429. }
  14430. }
  14431. #endif /* NO_SSL_DL */
  14432. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14433. return 1;
  14434. }
  14435. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14436. /* Initialize locking callbacks, needed for thread safety.
  14437. * http://www.openssl.org/support/faq.html#PROG1
  14438. */
  14439. num_locks = CRYPTO_num_locks();
  14440. if (num_locks < 0) {
  14441. num_locks = 0;
  14442. }
  14443. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14444. /* allocate mutex array, if required */
  14445. if (num_locks == 0) {
  14446. /* No mutex array required */
  14447. ssl_mutexes = NULL;
  14448. } else {
  14449. /* Mutex array required - allocate it */
  14450. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14451. /* Check OOM */
  14452. if (ssl_mutexes == NULL) {
  14453. mg_snprintf(NULL,
  14454. NULL, /* No truncation check for ebuf */
  14455. ebuf,
  14456. ebuf_len,
  14457. "%s: cannot allocate mutexes: %s",
  14458. __func__,
  14459. ssl_error());
  14460. DEBUG_TRACE("%s", ebuf);
  14461. return 0;
  14462. }
  14463. /* initialize mutex array */
  14464. for (i = 0; i < num_locks; i++) {
  14465. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14466. mg_snprintf(NULL,
  14467. NULL, /* No truncation check for ebuf */
  14468. ebuf,
  14469. ebuf_len,
  14470. "%s: error initializing mutex %i of %i",
  14471. __func__,
  14472. i,
  14473. num_locks);
  14474. DEBUG_TRACE("%s", ebuf);
  14475. mg_free(ssl_mutexes);
  14476. return 0;
  14477. }
  14478. }
  14479. }
  14480. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14481. CRYPTO_set_id_callback(&mg_current_thread_id);
  14482. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14483. #if !defined(NO_SSL_DL)
  14484. if (!ssllib_dll_handle) {
  14485. ssllib_dll_handle =
  14486. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14487. if (!ssllib_dll_handle) {
  14488. #if !defined(OPENSSL_API_1_1)
  14489. mg_free(ssl_mutexes);
  14490. #endif
  14491. DEBUG_TRACE("%s", ebuf);
  14492. return 0;
  14493. }
  14494. }
  14495. #endif /* NO_SSL_DL */
  14496. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14497. && !defined(NO_SSL_DL)
  14498. /* Initialize SSL library */
  14499. OPENSSL_init_ssl(0, NULL);
  14500. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14501. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14502. NULL);
  14503. #else
  14504. /* Initialize SSL library */
  14505. SSL_library_init();
  14506. SSL_load_error_strings();
  14507. #endif
  14508. return 1;
  14509. }
  14510. static int
  14511. ssl_use_pem_file(struct mg_context *phys_ctx,
  14512. struct mg_domain_context *dom_ctx,
  14513. const char *pem,
  14514. const char *chain)
  14515. {
  14516. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14517. mg_cry_ctx_internal(phys_ctx,
  14518. "%s: cannot open certificate file %s: %s",
  14519. __func__,
  14520. pem,
  14521. ssl_error());
  14522. return 0;
  14523. }
  14524. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14525. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14526. mg_cry_ctx_internal(phys_ctx,
  14527. "%s: cannot open private key file %s: %s",
  14528. __func__,
  14529. pem,
  14530. ssl_error());
  14531. return 0;
  14532. }
  14533. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14534. mg_cry_ctx_internal(phys_ctx,
  14535. "%s: certificate and private key do not match: %s",
  14536. __func__,
  14537. pem);
  14538. return 0;
  14539. }
  14540. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14541. * chain files that contain private keys and certificates in
  14542. * SSL_CTX_use_certificate_chain_file.
  14543. * The CivetWeb-Server used pem-Files that contained both information.
  14544. * In order to make wolfSSL work, it is split in two files.
  14545. * One file that contains key and certificate used by the server and
  14546. * an optional chain file for the ssl stack.
  14547. */
  14548. if (chain) {
  14549. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14550. mg_cry_ctx_internal(phys_ctx,
  14551. "%s: cannot use certificate chain file %s: %s",
  14552. __func__,
  14553. chain,
  14554. ssl_error());
  14555. return 0;
  14556. }
  14557. }
  14558. return 1;
  14559. }
  14560. #if defined(OPENSSL_API_1_1)
  14561. static unsigned long
  14562. ssl_get_protocol(int version_id)
  14563. {
  14564. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14565. if (version_id > 0)
  14566. ret |= SSL_OP_NO_SSLv2;
  14567. if (version_id > 1)
  14568. ret |= SSL_OP_NO_SSLv3;
  14569. if (version_id > 2)
  14570. ret |= SSL_OP_NO_TLSv1;
  14571. if (version_id > 3)
  14572. ret |= SSL_OP_NO_TLSv1_1;
  14573. if (version_id > 4)
  14574. ret |= SSL_OP_NO_TLSv1_2;
  14575. #if defined(SSL_OP_NO_TLSv1_3)
  14576. if (version_id > 5)
  14577. ret |= SSL_OP_NO_TLSv1_3;
  14578. #endif
  14579. return ret;
  14580. }
  14581. #else
  14582. static long
  14583. ssl_get_protocol(int version_id)
  14584. {
  14585. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14586. if (version_id > 0)
  14587. ret |= SSL_OP_NO_SSLv2;
  14588. if (version_id > 1)
  14589. ret |= SSL_OP_NO_SSLv3;
  14590. if (version_id > 2)
  14591. ret |= SSL_OP_NO_TLSv1;
  14592. if (version_id > 3)
  14593. ret |= SSL_OP_NO_TLSv1_1;
  14594. if (version_id > 4)
  14595. ret |= SSL_OP_NO_TLSv1_2;
  14596. #if defined(SSL_OP_NO_TLSv1_3)
  14597. if (version_id > 5)
  14598. ret |= SSL_OP_NO_TLSv1_3;
  14599. #endif
  14600. return (long)ret;
  14601. }
  14602. #endif /* OPENSSL_API_1_1 */
  14603. /* SSL callback documentation:
  14604. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14605. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14606. * https://linux.die.net/man/3/ssl_set_info_callback */
  14607. /* Note: There is no "const" for the first argument in the documentation
  14608. * examples, however some (maybe most, but not all) headers of OpenSSL
  14609. * versions / OpenSSL compatibility layers have it. Having a different
  14610. * definition will cause a warning in C and an error in C++. Use "const SSL
  14611. * *", while automatical conversion from "SSL *" works for all compilers,
  14612. * but not other way around */
  14613. static void
  14614. ssl_info_callback(const SSL *ssl, int what, int ret)
  14615. {
  14616. (void)ret;
  14617. if (what & SSL_CB_HANDSHAKE_START) {
  14618. SSL_get_app_data(ssl);
  14619. }
  14620. if (what & SSL_CB_HANDSHAKE_DONE) {
  14621. /* TODO: check for openSSL 1.1 */
  14622. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14623. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14624. }
  14625. }
  14626. static int
  14627. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14628. {
  14629. #if defined(GCC_DIAGNOSTIC)
  14630. #pragma GCC diagnostic push
  14631. #pragma GCC diagnostic ignored "-Wcast-align"
  14632. #endif /* defined(GCC_DIAGNOSTIC) */
  14633. /* We used an aligned pointer in SSL_set_app_data */
  14634. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14635. #if defined(GCC_DIAGNOSTIC)
  14636. #pragma GCC diagnostic pop
  14637. #endif /* defined(GCC_DIAGNOSTIC) */
  14638. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14639. (void)ad;
  14640. (void)arg;
  14641. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14642. DEBUG_ASSERT(0);
  14643. return SSL_TLSEXT_ERR_NOACK;
  14644. }
  14645. conn->dom_ctx = &(conn->phys_ctx->dd);
  14646. /* Old clients (Win XP) will not support SNI. Then, there
  14647. * is no server name available in the request - we can
  14648. * only work with the default certificate.
  14649. * Multiple HTTPS hosts on one IP+port are only possible
  14650. * with a certificate containing all alternative names.
  14651. */
  14652. if ((servername == NULL) || (*servername == 0)) {
  14653. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14654. mg_lock_context(conn->phys_ctx);
  14655. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14656. mg_unlock_context(conn->phys_ctx);
  14657. return SSL_TLSEXT_ERR_NOACK;
  14658. }
  14659. DEBUG_TRACE("TLS connection to host %s", servername);
  14660. while (conn->dom_ctx) {
  14661. if (!mg_strcasecmp(servername,
  14662. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14663. /* Found matching domain */
  14664. DEBUG_TRACE("TLS domain %s found",
  14665. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14666. break;
  14667. }
  14668. mg_lock_context(conn->phys_ctx);
  14669. conn->dom_ctx = conn->dom_ctx->next;
  14670. mg_unlock_context(conn->phys_ctx);
  14671. }
  14672. if (conn->dom_ctx == NULL) {
  14673. /* Default domain */
  14674. DEBUG_TRACE("TLS default domain %s used",
  14675. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14676. conn->dom_ctx = &(conn->phys_ctx->dd);
  14677. }
  14678. mg_lock_context(conn->phys_ctx);
  14679. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14680. mg_unlock_context(conn->phys_ctx);
  14681. return SSL_TLSEXT_ERR_OK;
  14682. }
  14683. #if defined(USE_ALPN)
  14684. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14685. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14686. alpn_proto_list + 3 + 8,
  14687. NULL};
  14688. #if defined(USE_HTTP2)
  14689. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14690. alpn_proto_list + 3,
  14691. alpn_proto_list + 3 + 8,
  14692. NULL};
  14693. #endif
  14694. static int
  14695. alpn_select_cb(SSL *ssl,
  14696. const unsigned char **out,
  14697. unsigned char *outlen,
  14698. const unsigned char *in,
  14699. unsigned int inlen,
  14700. void *arg)
  14701. {
  14702. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14703. unsigned int i, j, enable_http2 = 0;
  14704. const char **alpn_proto_order = alpn_proto_order_http1;
  14705. struct mg_workerTLS *tls =
  14706. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14707. (void)ssl;
  14708. if (tls == NULL) {
  14709. /* Need to store protocol in Thread Local Storage */
  14710. /* If there is no Thread Local Storage, don't use ALPN */
  14711. return SSL_TLSEXT_ERR_NOACK;
  14712. }
  14713. #if defined(USE_HTTP2)
  14714. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14715. if (enable_http2) {
  14716. alpn_proto_order = alpn_proto_order_http2;
  14717. }
  14718. #endif
  14719. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14720. /* check all accepted protocols in this order */
  14721. const char *alpn_proto = alpn_proto_order[j];
  14722. /* search input for matching protocol */
  14723. for (i = 0; i < inlen; i++) {
  14724. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14725. *out = in + i + 1;
  14726. *outlen = in[i];
  14727. tls->alpn_proto = alpn_proto;
  14728. return SSL_TLSEXT_ERR_OK;
  14729. }
  14730. }
  14731. }
  14732. /* Nothing found */
  14733. return SSL_TLSEXT_ERR_NOACK;
  14734. }
  14735. static int
  14736. next_protos_advertised_cb(SSL *ssl,
  14737. const unsigned char **data,
  14738. unsigned int *len,
  14739. void *arg)
  14740. {
  14741. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14742. *data = (const unsigned char *)alpn_proto_list;
  14743. *len = (unsigned int)strlen((const char *)data);
  14744. (void)ssl;
  14745. (void)dom_ctx;
  14746. return SSL_TLSEXT_ERR_OK;
  14747. }
  14748. static int
  14749. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14750. {
  14751. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14752. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14753. (const unsigned char *)alpn_proto_list,
  14754. alpn_len);
  14755. if (ret != 0) {
  14756. mg_cry_ctx_internal(phys_ctx,
  14757. "SSL_CTX_set_alpn_protos error: %s",
  14758. ssl_error());
  14759. }
  14760. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14761. alpn_select_cb,
  14762. (void *)dom_ctx);
  14763. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14764. next_protos_advertised_cb,
  14765. (void *)dom_ctx);
  14766. return ret;
  14767. }
  14768. #endif
  14769. /* Setup SSL CTX as required by CivetWeb */
  14770. static int
  14771. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14772. struct mg_domain_context *dom_ctx,
  14773. const char *pem,
  14774. const char *chain)
  14775. {
  14776. int callback_ret;
  14777. int should_verify_peer;
  14778. int peer_certificate_optional;
  14779. const char *ca_path;
  14780. const char *ca_file;
  14781. int use_default_verify_paths;
  14782. int verify_depth;
  14783. struct timespec now_mt;
  14784. md5_byte_t ssl_context_id[16];
  14785. md5_state_t md5state;
  14786. int protocol_ver;
  14787. int ssl_cache_timeout;
  14788. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14789. && !defined(NO_SSL_DL)
  14790. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14791. mg_cry_ctx_internal(phys_ctx,
  14792. "SSL_CTX_new (server) error: %s",
  14793. ssl_error());
  14794. return 0;
  14795. }
  14796. #else
  14797. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14798. mg_cry_ctx_internal(phys_ctx,
  14799. "SSL_CTX_new (server) error: %s",
  14800. ssl_error());
  14801. return 0;
  14802. }
  14803. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14804. #if defined(SSL_OP_NO_TLSv1_3)
  14805. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14806. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14807. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14808. | SSL_OP_NO_TLSv1_3);
  14809. #else
  14810. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14811. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14812. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14813. #endif
  14814. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14815. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14816. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14817. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14818. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14819. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14820. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14821. #if defined(SSL_OP_NO_RENEGOTIATION)
  14822. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14823. #endif
  14824. #if !defined(NO_SSL_DL)
  14825. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14826. #endif /* NO_SSL_DL */
  14827. /* In SSL documentation examples callback defined without const
  14828. * specifier 'void (*)(SSL *, int, int)' See:
  14829. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14830. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14831. * But in the source code const SSL is used:
  14832. * 'void (*)(const SSL *, int, int)' See:
  14833. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14834. * Problem about wrong documentation described, but not resolved:
  14835. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14836. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14837. * But when compiled with modern C++ compiler, correct const should be
  14838. * provided
  14839. */
  14840. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14841. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14842. ssl_servername_callback);
  14843. /* If a callback has been specified, call it. */
  14844. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14845. ? 0
  14846. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14847. phys_ctx->user_data));
  14848. /* If callback returns 0, civetweb sets up the SSL certificate.
  14849. * If it returns 1, civetweb assumes the calback already did this.
  14850. * If it returns -1, initializing ssl fails. */
  14851. if (callback_ret < 0) {
  14852. mg_cry_ctx_internal(phys_ctx,
  14853. "SSL callback returned error: %i",
  14854. callback_ret);
  14855. return 0;
  14856. }
  14857. if (callback_ret > 0) {
  14858. /* Callback did everything. */
  14859. return 1;
  14860. }
  14861. /* If a domain callback has been specified, call it. */
  14862. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14863. ? 0
  14864. : (phys_ctx->callbacks.init_ssl_domain(
  14865. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14866. dom_ctx->ssl_ctx,
  14867. phys_ctx->user_data));
  14868. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14869. * If it returns 1, civetweb assumes the calback already did this.
  14870. * If it returns -1, initializing ssl fails. */
  14871. if (callback_ret < 0) {
  14872. mg_cry_ctx_internal(phys_ctx,
  14873. "Domain SSL callback returned error: %i",
  14874. callback_ret);
  14875. return 0;
  14876. }
  14877. if (callback_ret > 0) {
  14878. /* Domain callback did everything. */
  14879. return 1;
  14880. }
  14881. /* Use some combination of start time, domain and port as a SSL
  14882. * context ID. This should be unique on the current machine. */
  14883. md5_init(&md5state);
  14884. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14885. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14886. md5_append(&md5state,
  14887. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14888. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14889. md5_append(&md5state,
  14890. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14891. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14892. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14893. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14894. md5_finish(&md5state, ssl_context_id);
  14895. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14896. (unsigned char *)ssl_context_id,
  14897. sizeof(ssl_context_id));
  14898. if (pem != NULL) {
  14899. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14900. return 0;
  14901. }
  14902. }
  14903. /* Should we support client certificates? */
  14904. /* Default is "no". */
  14905. should_verify_peer = 0;
  14906. peer_certificate_optional = 0;
  14907. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14908. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14909. /* Yes, they are mandatory */
  14910. should_verify_peer = 1;
  14911. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14912. "optional")
  14913. == 0) {
  14914. /* Yes, they are optional */
  14915. should_verify_peer = 1;
  14916. peer_certificate_optional = 1;
  14917. }
  14918. }
  14919. use_default_verify_paths =
  14920. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14921. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14922. == 0);
  14923. if (should_verify_peer) {
  14924. ca_path = dom_ctx->config[SSL_CA_PATH];
  14925. ca_file = dom_ctx->config[SSL_CA_FILE];
  14926. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14927. != 1) {
  14928. mg_cry_ctx_internal(phys_ctx,
  14929. "SSL_CTX_load_verify_locations error: %s "
  14930. "ssl_verify_peer requires setting "
  14931. "either ssl_ca_path or ssl_ca_file. "
  14932. "Is any of them present in the "
  14933. ".conf file?",
  14934. ssl_error());
  14935. return 0;
  14936. }
  14937. if (peer_certificate_optional) {
  14938. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14939. } else {
  14940. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14941. SSL_VERIFY_PEER
  14942. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14943. NULL);
  14944. }
  14945. if (use_default_verify_paths
  14946. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14947. mg_cry_ctx_internal(phys_ctx,
  14948. "SSL_CTX_set_default_verify_paths error: %s",
  14949. ssl_error());
  14950. return 0;
  14951. }
  14952. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14953. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14954. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14955. }
  14956. }
  14957. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14958. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14959. dom_ctx->config[SSL_CIPHER_LIST])
  14960. != 1) {
  14961. mg_cry_ctx_internal(phys_ctx,
  14962. "SSL_CTX_set_cipher_list error: %s",
  14963. ssl_error());
  14964. }
  14965. }
  14966. /* SSL session caching */
  14967. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14968. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14969. : 0);
  14970. if (ssl_cache_timeout > 0) {
  14971. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14972. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14973. * default */
  14974. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14975. }
  14976. #if defined(USE_ALPN)
  14977. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14978. #if !defined(NO_SSL_DL)
  14979. if (!tls_feature_missing[TLS_ALPN])
  14980. #endif
  14981. {
  14982. init_alpn(phys_ctx, dom_ctx);
  14983. }
  14984. #endif
  14985. return 1;
  14986. }
  14987. /* Check if SSL is required.
  14988. * If so, dynamically load SSL library
  14989. * and set up ctx->ssl_ctx pointer. */
  14990. static int
  14991. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14992. {
  14993. void *ssl_ctx = 0;
  14994. int callback_ret;
  14995. const char *pem;
  14996. const char *chain;
  14997. char ebuf[128];
  14998. if (!phys_ctx) {
  14999. return 0;
  15000. }
  15001. if (!dom_ctx) {
  15002. dom_ctx = &(phys_ctx->dd);
  15003. }
  15004. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15005. /* No SSL port is set. No need to setup SSL. */
  15006. return 1;
  15007. }
  15008. /* Check for external SSL_CTX */
  15009. callback_ret =
  15010. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15011. ? 0
  15012. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15013. phys_ctx->user_data));
  15014. if (callback_ret < 0) {
  15015. /* Callback exists and returns <0: Initializing failed. */
  15016. mg_cry_ctx_internal(phys_ctx,
  15017. "external_ssl_ctx callback returned error: %i",
  15018. callback_ret);
  15019. return 0;
  15020. } else if (callback_ret > 0) {
  15021. /* Callback exists and returns >0: Initializing complete,
  15022. * civetweb should not modify the SSL context. */
  15023. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15024. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15025. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15026. return 0;
  15027. }
  15028. return 1;
  15029. }
  15030. /* If the callback does not exist or return 0, civetweb must initialize
  15031. * the SSL context. Handle "domain" callback next. */
  15032. /* Check for external domain SSL_CTX callback. */
  15033. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15034. ? 0
  15035. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15036. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15037. &ssl_ctx,
  15038. phys_ctx->user_data));
  15039. if (callback_ret < 0) {
  15040. /* Callback < 0: Error. Abort init. */
  15041. mg_cry_ctx_internal(
  15042. phys_ctx,
  15043. "external_ssl_ctx_domain callback returned error: %i",
  15044. callback_ret);
  15045. return 0;
  15046. } else if (callback_ret > 0) {
  15047. /* Callback > 0: Consider init done. */
  15048. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15049. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15050. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15051. return 0;
  15052. }
  15053. return 1;
  15054. }
  15055. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15056. * 0, CivetWeb should continue initializing SSL */
  15057. /* If PEM file is not specified and the init_ssl callbacks
  15058. * are not specified, setup will fail. */
  15059. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15060. && (phys_ctx->callbacks.init_ssl == NULL)
  15061. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15062. /* No certificate and no init_ssl callbacks:
  15063. * Essential data to set up TLS is missing.
  15064. */
  15065. mg_cry_ctx_internal(phys_ctx,
  15066. "Initializing SSL failed: -%s is not set",
  15067. config_options[SSL_CERTIFICATE].name);
  15068. return 0;
  15069. }
  15070. /* If a certificate chain is configured, use it. */
  15071. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15072. if (chain == NULL) {
  15073. /* Default: certificate chain in PEM file */
  15074. chain = pem;
  15075. }
  15076. if ((chain != NULL) && (*chain == 0)) {
  15077. /* If the chain is an empty string, don't use it. */
  15078. chain = NULL;
  15079. }
  15080. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15081. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15082. return 0;
  15083. }
  15084. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15085. }
  15086. static void
  15087. uninitialize_openssl(void)
  15088. {
  15089. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15090. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15091. /* Shutdown according to
  15092. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15093. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15094. */
  15095. CONF_modules_unload(1);
  15096. #else
  15097. int i;
  15098. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15099. /* Shutdown according to
  15100. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15101. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15102. */
  15103. CRYPTO_set_locking_callback(NULL);
  15104. CRYPTO_set_id_callback(NULL);
  15105. ENGINE_cleanup();
  15106. CONF_modules_unload(1);
  15107. ERR_free_strings();
  15108. EVP_cleanup();
  15109. CRYPTO_cleanup_all_ex_data();
  15110. OPENSSL_REMOVE_THREAD_STATE();
  15111. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15112. pthread_mutex_destroy(&ssl_mutexes[i]);
  15113. }
  15114. mg_free(ssl_mutexes);
  15115. ssl_mutexes = NULL;
  15116. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15117. }
  15118. }
  15119. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15120. #if !defined(NO_FILESYSTEMS)
  15121. static int
  15122. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15123. {
  15124. if (phys_ctx) {
  15125. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15126. const char *path;
  15127. struct mg_connection fc;
  15128. if (!dom_ctx) {
  15129. dom_ctx = &(phys_ctx->dd);
  15130. }
  15131. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15132. if ((path != NULL)
  15133. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15134. mg_cry_ctx_internal(phys_ctx,
  15135. "Cannot open %s: %s",
  15136. path,
  15137. strerror(ERRNO));
  15138. return 0;
  15139. }
  15140. return 1;
  15141. }
  15142. return 0;
  15143. }
  15144. #endif /* NO_FILESYSTEMS */
  15145. static int
  15146. set_acl_option(struct mg_context *phys_ctx)
  15147. {
  15148. union usa sa;
  15149. memset(&sa, 0, sizeof(sa));
  15150. #if defined(USE_IPV6)
  15151. sa.sin6.sin6_family = AF_INET6;
  15152. #else
  15153. sa.sin.sin_family = AF_INET;
  15154. #endif
  15155. return check_acl(phys_ctx, &sa) != -1;
  15156. }
  15157. static void
  15158. reset_per_request_attributes(struct mg_connection *conn)
  15159. {
  15160. if (!conn) {
  15161. return;
  15162. }
  15163. conn->num_bytes_sent = conn->consumed_content = 0;
  15164. conn->path_info = NULL;
  15165. conn->status_code = -1;
  15166. conn->content_len = -1;
  15167. conn->is_chunked = 0;
  15168. conn->must_close = 0;
  15169. conn->request_len = 0;
  15170. conn->request_state = 0;
  15171. conn->throttle = 0;
  15172. conn->accept_gzip = 0;
  15173. conn->response_info.content_length = conn->request_info.content_length = -1;
  15174. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15175. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15176. conn->response_info.status_text = NULL;
  15177. conn->response_info.status_code = 0;
  15178. conn->request_info.remote_user = NULL;
  15179. conn->request_info.request_method = NULL;
  15180. conn->request_info.request_uri = NULL;
  15181. /* Free cleaned local URI (if any) */
  15182. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15183. mg_free((void *)conn->request_info.local_uri);
  15184. conn->request_info.local_uri = NULL;
  15185. }
  15186. conn->request_info.local_uri = NULL;
  15187. #if defined(USE_SERVER_STATS)
  15188. conn->processing_time = 0;
  15189. #endif
  15190. }
  15191. static int
  15192. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15193. {
  15194. if ((so->lsa.sa.sa_family == AF_INET)
  15195. || (so->lsa.sa.sa_family == AF_INET6)) {
  15196. /* Only for TCP sockets */
  15197. if (setsockopt(so->sock,
  15198. IPPROTO_TCP,
  15199. TCP_NODELAY,
  15200. (SOCK_OPT_TYPE)&nodelay_on,
  15201. sizeof(nodelay_on))
  15202. != 0) {
  15203. /* Error */
  15204. return 1;
  15205. }
  15206. }
  15207. /* OK */
  15208. return 0;
  15209. }
  15210. #if !defined(__ZEPHYR__)
  15211. static void
  15212. close_socket_gracefully(struct mg_connection *conn)
  15213. {
  15214. #if defined(_WIN32)
  15215. char buf[MG_BUF_LEN];
  15216. int n;
  15217. #endif
  15218. struct linger linger;
  15219. int error_code = 0;
  15220. int linger_timeout = -2;
  15221. socklen_t opt_len = sizeof(error_code);
  15222. if (!conn) {
  15223. return;
  15224. }
  15225. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15226. * "Note that enabling a nonzero timeout on a nonblocking socket
  15227. * is not recommended.", so set it to blocking now */
  15228. set_blocking_mode(conn->client.sock);
  15229. /* Send FIN to the client */
  15230. shutdown(conn->client.sock, SHUTDOWN_WR);
  15231. #if defined(_WIN32)
  15232. /* Read and discard pending incoming data. If we do not do that and
  15233. * close
  15234. * the socket, the data in the send buffer may be discarded. This
  15235. * behaviour is seen on Windows, when client keeps sending data
  15236. * when server decides to close the connection; then when client
  15237. * does recv() it gets no data back. */
  15238. do {
  15239. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15240. } while (n > 0);
  15241. #endif
  15242. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15243. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15244. }
  15245. /* Set linger option according to configuration */
  15246. if (linger_timeout >= 0) {
  15247. /* Set linger option to avoid socket hanging out after close. This
  15248. * prevent ephemeral port exhaust problem under high QPS. */
  15249. linger.l_onoff = 1;
  15250. #if defined(_MSC_VER)
  15251. #pragma warning(push)
  15252. #pragma warning(disable : 4244)
  15253. #endif
  15254. #if defined(GCC_DIAGNOSTIC)
  15255. #pragma GCC diagnostic push
  15256. #pragma GCC diagnostic ignored "-Wconversion"
  15257. #endif
  15258. /* Data type of linger structure elements may differ,
  15259. * so we don't know what cast we need here.
  15260. * Disable type conversion warnings. */
  15261. linger.l_linger = (linger_timeout + 999) / 1000;
  15262. #if defined(GCC_DIAGNOSTIC)
  15263. #pragma GCC diagnostic pop
  15264. #endif
  15265. #if defined(_MSC_VER)
  15266. #pragma warning(pop)
  15267. #endif
  15268. } else {
  15269. linger.l_onoff = 0;
  15270. linger.l_linger = 0;
  15271. }
  15272. if (linger_timeout < -1) {
  15273. /* Default: don't configure any linger */
  15274. } else if (getsockopt(conn->client.sock,
  15275. SOL_SOCKET,
  15276. SO_ERROR,
  15277. #if defined(_WIN32) /* WinSock uses different data type here */
  15278. (char *)&error_code,
  15279. #else
  15280. &error_code,
  15281. #endif
  15282. &opt_len)
  15283. != 0) {
  15284. /* Cannot determine if socket is already closed. This should
  15285. * not occur and never did in a test. Log an error message
  15286. * and continue. */
  15287. mg_cry_internal(conn,
  15288. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15289. __func__,
  15290. strerror(ERRNO));
  15291. #if defined(_WIN32)
  15292. } else if (error_code == WSAECONNRESET) {
  15293. #else
  15294. } else if (error_code == ECONNRESET) {
  15295. #endif
  15296. /* Socket already closed by client/peer, close socket without linger
  15297. */
  15298. } else {
  15299. /* Set linger timeout */
  15300. if (setsockopt(conn->client.sock,
  15301. SOL_SOCKET,
  15302. SO_LINGER,
  15303. (char *)&linger,
  15304. sizeof(linger))
  15305. != 0) {
  15306. mg_cry_internal(
  15307. conn,
  15308. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15309. __func__,
  15310. linger.l_onoff,
  15311. linger.l_linger,
  15312. strerror(ERRNO));
  15313. }
  15314. }
  15315. /* Now we know that our FIN is ACK-ed, safe to close */
  15316. closesocket(conn->client.sock);
  15317. conn->client.sock = INVALID_SOCKET;
  15318. }
  15319. #endif
  15320. static void
  15321. close_connection(struct mg_connection *conn)
  15322. {
  15323. #if defined(USE_SERVER_STATS)
  15324. conn->conn_state = 6; /* to close */
  15325. #endif
  15326. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15327. if (conn->lua_websocket_state) {
  15328. lua_websocket_close(conn, conn->lua_websocket_state);
  15329. conn->lua_websocket_state = NULL;
  15330. }
  15331. #endif
  15332. mg_lock_connection(conn);
  15333. /* Set close flag, so keep-alive loops will stop */
  15334. conn->must_close = 1;
  15335. /* call the connection_close callback if assigned */
  15336. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15337. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15338. conn->phys_ctx->callbacks.connection_close(conn);
  15339. }
  15340. }
  15341. /* Reset user data, after close callback is called.
  15342. * Do not reuse it. If the user needs a destructor,
  15343. * it must be done in the connection_close callback. */
  15344. mg_set_user_connection_data(conn, NULL);
  15345. #if defined(USE_SERVER_STATS)
  15346. conn->conn_state = 7; /* closing */
  15347. #endif
  15348. #if defined(USE_MBEDTLS)
  15349. if (conn->ssl != NULL) {
  15350. mbed_ssl_close(conn->ssl);
  15351. conn->ssl = NULL;
  15352. }
  15353. #elif !defined(NO_SSL)
  15354. if (conn->ssl != NULL) {
  15355. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15356. */
  15357. SSL_shutdown(conn->ssl);
  15358. SSL_free(conn->ssl);
  15359. OPENSSL_REMOVE_THREAD_STATE();
  15360. conn->ssl = NULL;
  15361. }
  15362. #endif
  15363. if (conn->client.sock != INVALID_SOCKET) {
  15364. #if defined(__ZEPHYR__)
  15365. closesocket(conn->client.sock);
  15366. #else
  15367. close_socket_gracefully(conn);
  15368. #endif
  15369. conn->client.sock = INVALID_SOCKET;
  15370. }
  15371. /* call the connection_closed callback if assigned */
  15372. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15373. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15374. conn->phys_ctx->callbacks.connection_closed(conn);
  15375. }
  15376. }
  15377. mg_unlock_connection(conn);
  15378. #if defined(USE_SERVER_STATS)
  15379. conn->conn_state = 8; /* closed */
  15380. #endif
  15381. }
  15382. CIVETWEB_API void
  15383. mg_close_connection(struct mg_connection *conn)
  15384. {
  15385. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15386. return;
  15387. }
  15388. #if defined(USE_WEBSOCKET)
  15389. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15390. if (conn->in_websocket_handling) {
  15391. /* Set close flag, so the server thread can exit. */
  15392. conn->must_close = 1;
  15393. return;
  15394. }
  15395. }
  15396. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15397. unsigned int i;
  15398. /* client context: loops must end */
  15399. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15400. conn->must_close = 1;
  15401. /* We need to get the client thread out of the select/recv call
  15402. * here. */
  15403. /* Since we use a sleep quantum of some seconds to check for recv
  15404. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15405. /* join worker thread */
  15406. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15407. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15408. }
  15409. }
  15410. #endif /* defined(USE_WEBSOCKET) */
  15411. close_connection(conn);
  15412. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15413. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15414. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15415. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15416. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15417. }
  15418. #endif
  15419. #if defined(USE_WEBSOCKET)
  15420. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15421. mg_free(conn->phys_ctx->worker_threadids);
  15422. (void)pthread_mutex_destroy(&conn->mutex);
  15423. mg_free(conn);
  15424. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15425. (void)pthread_mutex_destroy(&conn->mutex);
  15426. mg_free(conn);
  15427. }
  15428. #else
  15429. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15430. (void)pthread_mutex_destroy(&conn->mutex);
  15431. mg_free(conn);
  15432. }
  15433. #endif /* defined(USE_WEBSOCKET) */
  15434. }
  15435. static struct mg_connection *
  15436. mg_connect_client_impl(const struct mg_client_options *client_options,
  15437. int use_ssl,
  15438. struct mg_init_data *init,
  15439. struct mg_error_data *error)
  15440. {
  15441. struct mg_connection *conn = NULL;
  15442. SOCKET sock;
  15443. union usa sa;
  15444. struct sockaddr *psa;
  15445. socklen_t len;
  15446. unsigned max_req_size =
  15447. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15448. /* Size of structures, aligned to 8 bytes */
  15449. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15450. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15451. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15452. (void)init; /* TODO: Implement required options */
  15453. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15454. if (error != NULL) {
  15455. error->code = MG_ERROR_DATA_CODE_OK;
  15456. error->code_sub = 0;
  15457. if (error->text_buffer_size > 0) {
  15458. error->text[0] = 0;
  15459. }
  15460. }
  15461. if (conn == NULL) {
  15462. if (error != NULL) {
  15463. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15464. error->code_sub = (unsigned)alloc_size;
  15465. mg_snprintf(NULL,
  15466. NULL, /* No truncation check for ebuf */
  15467. error->text,
  15468. error->text_buffer_size,
  15469. "calloc(): %s",
  15470. strerror(ERRNO));
  15471. }
  15472. return NULL;
  15473. }
  15474. #if defined(GCC_DIAGNOSTIC)
  15475. #pragma GCC diagnostic push
  15476. #pragma GCC diagnostic ignored "-Wcast-align"
  15477. #endif /* defined(GCC_DIAGNOSTIC) */
  15478. /* conn_size is aligned to 8 bytes */
  15479. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15480. #if defined(GCC_DIAGNOSTIC)
  15481. #pragma GCC diagnostic pop
  15482. #endif /* defined(GCC_DIAGNOSTIC) */
  15483. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15484. conn->buf_size = (int)max_req_size;
  15485. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15486. conn->dom_ctx = &(conn->phys_ctx->dd);
  15487. if (!connect_socket(conn->phys_ctx,
  15488. client_options->host,
  15489. client_options->port,
  15490. use_ssl,
  15491. error,
  15492. &sock,
  15493. &sa)) {
  15494. /* "error" will be set by connect_socket. */
  15495. /* free all memory and return NULL; */
  15496. mg_free(conn);
  15497. return NULL;
  15498. }
  15499. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15500. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15501. && !defined(NO_SSL_DL)
  15502. if (use_ssl
  15503. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15504. == NULL) {
  15505. if (error != NULL) {
  15506. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15507. mg_snprintf(NULL,
  15508. NULL, /* No truncation check for ebuf */
  15509. error->text,
  15510. error->text_buffer_size,
  15511. "SSL_CTX_new error: %s",
  15512. ssl_error());
  15513. }
  15514. closesocket(sock);
  15515. mg_free(conn);
  15516. return NULL;
  15517. }
  15518. #else
  15519. if (use_ssl
  15520. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15521. == NULL) {
  15522. if (error != NULL) {
  15523. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15524. mg_snprintf(NULL,
  15525. NULL, /* No truncation check for ebuf */
  15526. error->text,
  15527. error->text_buffer_size,
  15528. "SSL_CTX_new error: %s",
  15529. ssl_error());
  15530. }
  15531. closesocket(sock);
  15532. mg_free(conn);
  15533. return NULL;
  15534. }
  15535. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15536. #endif /* NO_SSL */
  15537. #if defined(USE_IPV6)
  15538. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15539. : sizeof(conn->client.rsa.sin6);
  15540. psa = (sa.sa.sa_family == AF_INET)
  15541. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15542. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15543. #else
  15544. len = sizeof(conn->client.rsa.sin);
  15545. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15546. #endif
  15547. conn->client.sock = sock;
  15548. conn->client.lsa = sa;
  15549. if (getsockname(sock, psa, &len) != 0) {
  15550. mg_cry_internal(conn,
  15551. "%s: getsockname() failed: %s",
  15552. __func__,
  15553. strerror(ERRNO));
  15554. }
  15555. conn->client.is_ssl = use_ssl ? 1 : 0;
  15556. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15557. if (error != NULL) {
  15558. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15559. error->code_sub = (unsigned)ERRNO;
  15560. mg_snprintf(NULL,
  15561. NULL, /* No truncation check for ebuf */
  15562. error->text,
  15563. error->text_buffer_size,
  15564. "Can not create mutex");
  15565. }
  15566. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15567. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15568. #endif
  15569. closesocket(sock);
  15570. mg_free(conn);
  15571. return NULL;
  15572. }
  15573. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15574. if (use_ssl) {
  15575. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15576. * SSL_CTX_set_verify call is needed to switch off server
  15577. * certificate checking, which is off by default in OpenSSL and
  15578. * on in yaSSL. */
  15579. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15580. * SSL_VERIFY_PEER, verify_ssl_server); */
  15581. if (client_options->client_cert) {
  15582. if (!ssl_use_pem_file(conn->phys_ctx,
  15583. conn->dom_ctx,
  15584. client_options->client_cert,
  15585. NULL)) {
  15586. if (error != NULL) {
  15587. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15588. mg_snprintf(NULL,
  15589. NULL, /* No truncation check for ebuf */
  15590. error->text,
  15591. error->text_buffer_size,
  15592. "Can not use SSL client certificate");
  15593. }
  15594. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15595. closesocket(sock);
  15596. mg_free(conn);
  15597. return NULL;
  15598. }
  15599. }
  15600. if (client_options->server_cert) {
  15601. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15602. client_options->server_cert,
  15603. NULL)
  15604. != 1) {
  15605. if (error != NULL) {
  15606. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15607. mg_snprintf(NULL,
  15608. NULL, /* No truncation check for ebuf */
  15609. error->text,
  15610. error->text_buffer_size,
  15611. "SSL_CTX_load_verify_locations error: %s",
  15612. ssl_error());
  15613. }
  15614. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15615. closesocket(sock);
  15616. mg_free(conn);
  15617. return NULL;
  15618. }
  15619. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15620. } else {
  15621. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15622. }
  15623. if (!sslize(conn, SSL_connect, client_options)) {
  15624. if (error != NULL) {
  15625. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15626. mg_snprintf(NULL,
  15627. NULL, /* No truncation check for ebuf */
  15628. error->text,
  15629. error->text_buffer_size,
  15630. "SSL connection error");
  15631. }
  15632. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15633. closesocket(sock);
  15634. mg_free(conn);
  15635. return NULL;
  15636. }
  15637. }
  15638. #endif
  15639. return conn;
  15640. }
  15641. CIVETWEB_API struct mg_connection *
  15642. mg_connect_client_secure(const struct mg_client_options *client_options,
  15643. char *error_buffer,
  15644. size_t error_buffer_size)
  15645. {
  15646. struct mg_init_data init;
  15647. struct mg_error_data error;
  15648. memset(&init, 0, sizeof(init));
  15649. memset(&error, 0, sizeof(error));
  15650. error.text_buffer_size = error_buffer_size;
  15651. error.text = error_buffer;
  15652. return mg_connect_client_impl(client_options, 1, &init, &error);
  15653. }
  15654. CIVETWEB_API struct mg_connection *
  15655. mg_connect_client(const char *host,
  15656. int port,
  15657. int use_ssl,
  15658. char *error_buffer,
  15659. size_t error_buffer_size)
  15660. {
  15661. struct mg_client_options opts;
  15662. struct mg_init_data init;
  15663. struct mg_error_data error;
  15664. memset(&init, 0, sizeof(init));
  15665. memset(&error, 0, sizeof(error));
  15666. error.text_buffer_size = error_buffer_size;
  15667. error.text = error_buffer;
  15668. memset(&opts, 0, sizeof(opts));
  15669. opts.host = host;
  15670. opts.port = port;
  15671. if (use_ssl) {
  15672. opts.host_name = host;
  15673. }
  15674. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  15675. }
  15676. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15677. CIVETWEB_API struct mg_connection *
  15678. mg_connect_client2(const char *host,
  15679. const char *protocol,
  15680. int port,
  15681. const char *path,
  15682. struct mg_init_data *init,
  15683. struct mg_error_data *error)
  15684. {
  15685. (void)path;
  15686. int is_ssl, is_ws;
  15687. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15688. if (error != NULL) {
  15689. error->code = MG_ERROR_DATA_CODE_OK;
  15690. error->code_sub = 0;
  15691. if (error->text_buffer_size > 0) {
  15692. *error->text = 0;
  15693. }
  15694. }
  15695. if ((host == NULL) || (protocol == NULL)) {
  15696. if (error != NULL) {
  15697. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15698. mg_snprintf(NULL,
  15699. NULL, /* No truncation check for error buffers */
  15700. error->text,
  15701. error->text_buffer_size,
  15702. "%s",
  15703. "Invalid parameters");
  15704. }
  15705. return NULL;
  15706. }
  15707. /* check all known protocolls */
  15708. if (!mg_strcasecmp(protocol, "http")) {
  15709. is_ssl = 0;
  15710. is_ws = 0;
  15711. } else if (!mg_strcasecmp(protocol, "https")) {
  15712. is_ssl = 1;
  15713. is_ws = 0;
  15714. #if defined(USE_WEBSOCKET)
  15715. } else if (!mg_strcasecmp(protocol, "ws")) {
  15716. is_ssl = 0;
  15717. is_ws = 1;
  15718. } else if (!mg_strcasecmp(protocol, "wss")) {
  15719. is_ssl = 1;
  15720. is_ws = 1;
  15721. #endif
  15722. } else {
  15723. if (error != NULL) {
  15724. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  15725. mg_snprintf(NULL,
  15726. NULL, /* No truncation check for error buffers */
  15727. error->text,
  15728. error->text_buffer_size,
  15729. "Protocol %s not supported",
  15730. protocol);
  15731. }
  15732. return NULL;
  15733. }
  15734. /* TODO: The current implementation here just calls the old
  15735. * implementations, without using any new options. This is just a first
  15736. * step to test the new interfaces. */
  15737. #if defined(USE_WEBSOCKET)
  15738. if (is_ws) {
  15739. /* TODO: implement all options */
  15740. return mg_connect_websocket_client(
  15741. host,
  15742. port,
  15743. is_ssl,
  15744. ((error != NULL) ? error->text : NULL),
  15745. ((error != NULL) ? error->text_buffer_size : 0),
  15746. (path ? path : ""),
  15747. NULL /* TODO: origin */,
  15748. experimental_websocket_client_data_wrapper,
  15749. experimental_websocket_client_close_wrapper,
  15750. (void *)init->callbacks);
  15751. }
  15752. #else
  15753. (void)is_ws;
  15754. #endif
  15755. /* TODO: all additional options */
  15756. struct mg_client_options opts;
  15757. memset(&opts, 0, sizeof(opts));
  15758. opts.host = host;
  15759. opts.port = port;
  15760. return mg_connect_client_impl(&opts, is_ssl, init, error);
  15761. }
  15762. #endif
  15763. static const struct {
  15764. const char *proto;
  15765. size_t proto_len;
  15766. unsigned default_port;
  15767. } abs_uri_protocols[] = {{"http://", 7, 80},
  15768. {"https://", 8, 443},
  15769. {"ws://", 5, 80},
  15770. {"wss://", 6, 443},
  15771. {NULL, 0, 0}};
  15772. /* Check if the uri is valid.
  15773. * return 0 for invalid uri,
  15774. * return 1 for *,
  15775. * return 2 for relative uri,
  15776. * return 3 for absolute uri without port,
  15777. * return 4 for absolute uri with port */
  15778. static int
  15779. get_uri_type(const char *uri)
  15780. {
  15781. int i;
  15782. const char *hostend, *portbegin;
  15783. char *portend;
  15784. unsigned long port;
  15785. /* According to the HTTP standard
  15786. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15787. * URI can be an asterisk (*) or should start with slash (relative uri),
  15788. * or it should start with the protocol (absolute uri). */
  15789. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15790. /* asterisk */
  15791. return 1;
  15792. }
  15793. /* Valid URIs according to RFC 3986
  15794. * (https://www.ietf.org/rfc/rfc3986.txt)
  15795. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15796. * and unreserved characters A-Z a-z 0-9 and -._~
  15797. * and % encoded symbols.
  15798. */
  15799. for (i = 0; uri[i] != 0; i++) {
  15800. if (uri[i] < 33) {
  15801. /* control characters and spaces are invalid */
  15802. return 0;
  15803. }
  15804. /* Allow everything else here (See #894) */
  15805. }
  15806. /* A relative uri starts with a / character */
  15807. if (uri[0] == '/') {
  15808. /* relative uri */
  15809. return 2;
  15810. }
  15811. /* It could be an absolute uri: */
  15812. /* This function only checks if the uri is valid, not if it is
  15813. * addressing the current server. So civetweb can also be used
  15814. * as a proxy server. */
  15815. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15816. if (mg_strncasecmp(uri,
  15817. abs_uri_protocols[i].proto,
  15818. abs_uri_protocols[i].proto_len)
  15819. == 0) {
  15820. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15821. if (!hostend) {
  15822. return 0;
  15823. }
  15824. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15825. if (!portbegin) {
  15826. return 3;
  15827. }
  15828. port = strtoul(portbegin + 1, &portend, 10);
  15829. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15830. return 0;
  15831. }
  15832. return 4;
  15833. }
  15834. }
  15835. return 0;
  15836. }
  15837. /* Return NULL or the relative uri at the current server */
  15838. static const char *
  15839. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15840. {
  15841. const char *server_domain;
  15842. size_t server_domain_len;
  15843. size_t request_domain_len = 0;
  15844. unsigned long port = 0;
  15845. int i, auth_domain_check_enabled;
  15846. const char *hostbegin = NULL;
  15847. const char *hostend = NULL;
  15848. const char *portbegin;
  15849. char *portend;
  15850. auth_domain_check_enabled =
  15851. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15852. /* DNS is case insensitive, so use case insensitive string compare here
  15853. */
  15854. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15855. if (mg_strncasecmp(uri,
  15856. abs_uri_protocols[i].proto,
  15857. abs_uri_protocols[i].proto_len)
  15858. == 0) {
  15859. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15860. hostend = strchr(hostbegin, '/');
  15861. if (!hostend) {
  15862. return 0;
  15863. }
  15864. portbegin = strchr(hostbegin, ':');
  15865. if ((!portbegin) || (portbegin > hostend)) {
  15866. port = abs_uri_protocols[i].default_port;
  15867. request_domain_len = (size_t)(hostend - hostbegin);
  15868. } else {
  15869. port = strtoul(portbegin + 1, &portend, 10);
  15870. if ((portend != hostend) || (port <= 0)
  15871. || !is_valid_port(port)) {
  15872. return 0;
  15873. }
  15874. request_domain_len = (size_t)(portbegin - hostbegin);
  15875. }
  15876. /* protocol found, port set */
  15877. break;
  15878. }
  15879. }
  15880. if (!port) {
  15881. /* port remains 0 if the protocol is not found */
  15882. return 0;
  15883. }
  15884. /* Check if the request is directed to a different server. */
  15885. /* First check if the port is the same. */
  15886. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15887. /* Request is directed to a different port */
  15888. return 0;
  15889. }
  15890. /* Finally check if the server corresponds to the authentication
  15891. * domain of the server (the server domain).
  15892. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15893. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15894. * but do not allow substrings (like
  15895. * http://notmydomain.com/path/file.ext
  15896. * or http://mydomain.com.fake/path/file.ext).
  15897. */
  15898. if (auth_domain_check_enabled) {
  15899. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15900. server_domain_len = strlen(server_domain);
  15901. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15902. return 0;
  15903. }
  15904. if ((request_domain_len == server_domain_len)
  15905. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15906. /* Request is directed to this server - full name match. */
  15907. } else {
  15908. if (request_domain_len < (server_domain_len + 2)) {
  15909. /* Request is directed to another server: The server name
  15910. * is longer than the request name.
  15911. * Drop this case here to avoid overflows in the
  15912. * following checks. */
  15913. return 0;
  15914. }
  15915. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15916. /* Request is directed to another server: It could be a
  15917. * substring
  15918. * like notmyserver.com */
  15919. return 0;
  15920. }
  15921. if (0
  15922. != memcmp(server_domain,
  15923. hostbegin + request_domain_len - server_domain_len,
  15924. server_domain_len)) {
  15925. /* Request is directed to another server:
  15926. * The server name is different. */
  15927. return 0;
  15928. }
  15929. }
  15930. }
  15931. return hostend;
  15932. }
  15933. static int
  15934. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15935. {
  15936. if (ebuf_len > 0) {
  15937. ebuf[0] = '\0';
  15938. }
  15939. *err = 0;
  15940. reset_per_request_attributes(conn);
  15941. if (!conn) {
  15942. mg_snprintf(conn,
  15943. NULL, /* No truncation check for ebuf */
  15944. ebuf,
  15945. ebuf_len,
  15946. "%s",
  15947. "Internal error");
  15948. *err = 500;
  15949. return 0;
  15950. }
  15951. /* Set the time the request was received. This value should be used for
  15952. * timeouts. */
  15953. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15954. conn->request_len =
  15955. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15956. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15957. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15958. mg_snprintf(conn,
  15959. NULL, /* No truncation check for ebuf */
  15960. ebuf,
  15961. ebuf_len,
  15962. "%s",
  15963. "Invalid message size");
  15964. *err = 500;
  15965. return 0;
  15966. }
  15967. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15968. mg_snprintf(conn,
  15969. NULL, /* No truncation check for ebuf */
  15970. ebuf,
  15971. ebuf_len,
  15972. "%s",
  15973. "Message too large");
  15974. *err = 413;
  15975. return 0;
  15976. }
  15977. if (conn->request_len <= 0) {
  15978. if (conn->data_len > 0) {
  15979. mg_snprintf(conn,
  15980. NULL, /* No truncation check for ebuf */
  15981. ebuf,
  15982. ebuf_len,
  15983. "%s",
  15984. "Malformed message");
  15985. *err = 400;
  15986. } else {
  15987. /* Server did not recv anything -> just close the connection */
  15988. conn->must_close = 1;
  15989. mg_snprintf(conn,
  15990. NULL, /* No truncation check for ebuf */
  15991. ebuf,
  15992. ebuf_len,
  15993. "%s",
  15994. "No data received");
  15995. *err = 0;
  15996. }
  15997. return 0;
  15998. }
  15999. return 1;
  16000. }
  16001. static int
  16002. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16003. {
  16004. const char *cl;
  16005. conn->connection_type =
  16006. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16007. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16008. return 0;
  16009. }
  16010. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16011. <= 0) {
  16012. mg_snprintf(conn,
  16013. NULL, /* No truncation check for ebuf */
  16014. ebuf,
  16015. ebuf_len,
  16016. "%s",
  16017. "Bad request");
  16018. *err = 400;
  16019. return 0;
  16020. }
  16021. /* Message is a valid request */
  16022. if (!switch_domain_context(conn)) {
  16023. mg_snprintf(conn,
  16024. NULL, /* No truncation check for ebuf */
  16025. ebuf,
  16026. ebuf_len,
  16027. "%s",
  16028. "Bad request: Host mismatch");
  16029. *err = 400;
  16030. return 0;
  16031. }
  16032. #if USE_ZLIB
  16033. if (((cl = get_header(conn->request_info.http_headers,
  16034. conn->request_info.num_headers,
  16035. "Accept-Encoding"))
  16036. != NULL)
  16037. && strstr(cl, "gzip")) {
  16038. conn->accept_gzip = 1;
  16039. }
  16040. #endif
  16041. if (((cl = get_header(conn->request_info.http_headers,
  16042. conn->request_info.num_headers,
  16043. "Transfer-Encoding"))
  16044. != NULL)
  16045. && mg_strcasecmp(cl, "identity")) {
  16046. if (mg_strcasecmp(cl, "chunked")) {
  16047. mg_snprintf(conn,
  16048. NULL, /* No truncation check for ebuf */
  16049. ebuf,
  16050. ebuf_len,
  16051. "%s",
  16052. "Bad request");
  16053. *err = 400;
  16054. return 0;
  16055. }
  16056. conn->is_chunked = 1;
  16057. conn->content_len = 0; /* not yet read */
  16058. } else if ((cl = get_header(conn->request_info.http_headers,
  16059. conn->request_info.num_headers,
  16060. "Content-Length"))
  16061. != NULL) {
  16062. /* Request has content length set */
  16063. char *endptr = NULL;
  16064. conn->content_len = strtoll(cl, &endptr, 10);
  16065. if ((endptr == cl) || (conn->content_len < 0)) {
  16066. mg_snprintf(conn,
  16067. NULL, /* No truncation check for ebuf */
  16068. ebuf,
  16069. ebuf_len,
  16070. "%s",
  16071. "Bad request");
  16072. *err = 411;
  16073. return 0;
  16074. }
  16075. /* Publish the content length back to the request info. */
  16076. conn->request_info.content_length = conn->content_len;
  16077. } else {
  16078. /* There is no exception, see RFC7230. */
  16079. conn->content_len = 0;
  16080. }
  16081. return 1;
  16082. }
  16083. /* conn is assumed to be valid in this internal function */
  16084. static int
  16085. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16086. {
  16087. const char *cl;
  16088. conn->connection_type =
  16089. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16090. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16091. return 0;
  16092. }
  16093. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16094. <= 0) {
  16095. mg_snprintf(conn,
  16096. NULL, /* No truncation check for ebuf */
  16097. ebuf,
  16098. ebuf_len,
  16099. "%s",
  16100. "Bad response");
  16101. *err = 400;
  16102. return 0;
  16103. }
  16104. /* Message is a valid response */
  16105. if (((cl = get_header(conn->response_info.http_headers,
  16106. conn->response_info.num_headers,
  16107. "Transfer-Encoding"))
  16108. != NULL)
  16109. && mg_strcasecmp(cl, "identity")) {
  16110. if (mg_strcasecmp(cl, "chunked")) {
  16111. mg_snprintf(conn,
  16112. NULL, /* No truncation check for ebuf */
  16113. ebuf,
  16114. ebuf_len,
  16115. "%s",
  16116. "Bad request");
  16117. *err = 400;
  16118. return 0;
  16119. }
  16120. conn->is_chunked = 1;
  16121. conn->content_len = 0; /* not yet read */
  16122. } else if ((cl = get_header(conn->response_info.http_headers,
  16123. conn->response_info.num_headers,
  16124. "Content-Length"))
  16125. != NULL) {
  16126. char *endptr = NULL;
  16127. conn->content_len = strtoll(cl, &endptr, 10);
  16128. if ((endptr == cl) || (conn->content_len < 0)) {
  16129. mg_snprintf(conn,
  16130. NULL, /* No truncation check for ebuf */
  16131. ebuf,
  16132. ebuf_len,
  16133. "%s",
  16134. "Bad request");
  16135. *err = 411;
  16136. return 0;
  16137. }
  16138. /* Publish the content length back to the response info. */
  16139. conn->response_info.content_length = conn->content_len;
  16140. /* TODO: check if it is still used in response_info */
  16141. conn->request_info.content_length = conn->content_len;
  16142. /* TODO: we should also consider HEAD method */
  16143. if (conn->response_info.status_code == 304) {
  16144. conn->content_len = 0;
  16145. }
  16146. } else {
  16147. /* TODO: we should also consider HEAD method */
  16148. if (((conn->response_info.status_code >= 100)
  16149. && (conn->response_info.status_code <= 199))
  16150. || (conn->response_info.status_code == 204)
  16151. || (conn->response_info.status_code == 304)) {
  16152. conn->content_len = 0;
  16153. } else {
  16154. conn->content_len = -1; /* unknown content length */
  16155. }
  16156. }
  16157. return 1;
  16158. }
  16159. CIVETWEB_API int
  16160. mg_get_response(struct mg_connection *conn,
  16161. char *ebuf,
  16162. size_t ebuf_len,
  16163. int timeout)
  16164. {
  16165. int err, ret;
  16166. char txt[32]; /* will not overflow */
  16167. char *save_timeout;
  16168. char *new_timeout;
  16169. if (ebuf_len > 0) {
  16170. ebuf[0] = '\0';
  16171. }
  16172. if (!conn) {
  16173. mg_snprintf(conn,
  16174. NULL, /* No truncation check for ebuf */
  16175. ebuf,
  16176. ebuf_len,
  16177. "%s",
  16178. "Parameter error");
  16179. return -1;
  16180. }
  16181. /* Reset the previous responses */
  16182. conn->data_len = 0;
  16183. /* Implementation of API function for HTTP clients */
  16184. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16185. if (timeout >= 0) {
  16186. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16187. new_timeout = txt;
  16188. } else {
  16189. new_timeout = NULL;
  16190. }
  16191. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16192. ret = get_response(conn, ebuf, ebuf_len, &err);
  16193. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16194. /* TODO: here, the URI is the http response code */
  16195. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16196. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16197. /* TODO (mid): Define proper return values - maybe return length?
  16198. * For the first test use <0 for error and >0 for OK */
  16199. return (ret == 0) ? -1 : +1;
  16200. }
  16201. CIVETWEB_API struct mg_connection *
  16202. mg_download(const char *host,
  16203. int port,
  16204. int use_ssl,
  16205. char *ebuf,
  16206. size_t ebuf_len,
  16207. const char *fmt,
  16208. ...)
  16209. {
  16210. struct mg_connection *conn;
  16211. va_list ap;
  16212. int i;
  16213. int reqerr;
  16214. if (ebuf_len > 0) {
  16215. ebuf[0] = '\0';
  16216. }
  16217. va_start(ap, fmt);
  16218. /* open a connection */
  16219. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16220. if (conn != NULL) {
  16221. i = mg_vprintf(conn, fmt, ap);
  16222. if (i <= 0) {
  16223. mg_snprintf(conn,
  16224. NULL, /* No truncation check for ebuf */
  16225. ebuf,
  16226. ebuf_len,
  16227. "%s",
  16228. "Error sending request");
  16229. } else {
  16230. /* make sure the buffer is clear */
  16231. conn->data_len = 0;
  16232. get_response(conn, ebuf, ebuf_len, &reqerr);
  16233. /* TODO: here, the URI is the http response code */
  16234. conn->request_info.local_uri = conn->request_info.request_uri;
  16235. }
  16236. }
  16237. /* if an error occurred, close the connection */
  16238. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16239. mg_close_connection(conn);
  16240. conn = NULL;
  16241. }
  16242. va_end(ap);
  16243. return conn;
  16244. }
  16245. struct websocket_client_thread_data {
  16246. struct mg_connection *conn;
  16247. mg_websocket_data_handler data_handler;
  16248. mg_websocket_close_handler close_handler;
  16249. void *callback_data;
  16250. };
  16251. #if defined(USE_WEBSOCKET)
  16252. #if defined(_WIN32)
  16253. static unsigned __stdcall websocket_client_thread(void *data)
  16254. #else
  16255. static void *
  16256. websocket_client_thread(void *data)
  16257. #endif
  16258. {
  16259. struct websocket_client_thread_data *cdata =
  16260. (struct websocket_client_thread_data *)data;
  16261. void *user_thread_ptr = NULL;
  16262. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16263. struct sigaction sa;
  16264. /* Ignore SIGPIPE */
  16265. memset(&sa, 0, sizeof(sa));
  16266. sa.sa_handler = SIG_IGN;
  16267. sigaction(SIGPIPE, &sa, NULL);
  16268. #endif
  16269. mg_set_thread_name("ws-clnt");
  16270. if (cdata->conn->phys_ctx) {
  16271. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16272. /* 3 indicates a websocket client thread */
  16273. /* TODO: check if conn->phys_ctx can be set */
  16274. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16275. cdata->conn->phys_ctx, 3);
  16276. }
  16277. }
  16278. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16279. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16280. if (cdata->close_handler != NULL) {
  16281. cdata->close_handler(cdata->conn, cdata->callback_data);
  16282. }
  16283. /* The websocket_client context has only this thread. If it runs out,
  16284. set the stop_flag to 2 (= "stopped"). */
  16285. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16286. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16287. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16288. 3,
  16289. user_thread_ptr);
  16290. }
  16291. mg_free((void *)cdata);
  16292. #if defined(_WIN32)
  16293. return 0;
  16294. #else
  16295. return NULL;
  16296. #endif
  16297. }
  16298. #endif
  16299. static struct mg_connection *
  16300. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16301. int use_ssl,
  16302. char *error_buffer,
  16303. size_t error_buffer_size,
  16304. const char *path,
  16305. const char *origin,
  16306. const char *extensions,
  16307. mg_websocket_data_handler data_func,
  16308. mg_websocket_close_handler close_func,
  16309. void *user_data)
  16310. {
  16311. struct mg_connection *conn = NULL;
  16312. #if defined(USE_WEBSOCKET)
  16313. struct websocket_client_thread_data *thread_data;
  16314. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16315. const char *host = client_options->host;
  16316. int i;
  16317. struct mg_init_data init;
  16318. struct mg_error_data error;
  16319. memset(&init, 0, sizeof(init));
  16320. memset(&error, 0, sizeof(error));
  16321. error.text_buffer_size = error_buffer_size;
  16322. error.text = error_buffer;
  16323. #if defined(__clang__)
  16324. #pragma clang diagnostic push
  16325. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16326. #endif
  16327. /* Establish the client connection and request upgrade */
  16328. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16329. /* Connection object will be null if something goes wrong */
  16330. if (conn == NULL) {
  16331. /* error_buffer should be already filled ... */
  16332. if (!error_buffer[0]) {
  16333. /* ... if not add an error message */
  16334. mg_snprintf(conn,
  16335. NULL, /* No truncation check for ebuf */
  16336. error_buffer,
  16337. error_buffer_size,
  16338. "Unexpected error");
  16339. }
  16340. return NULL;
  16341. }
  16342. if (origin != NULL) {
  16343. if (extensions != NULL) {
  16344. i = mg_printf(conn,
  16345. "GET %s HTTP/1.1\r\n"
  16346. "Host: %s\r\n"
  16347. "Upgrade: websocket\r\n"
  16348. "Connection: Upgrade\r\n"
  16349. "Sec-WebSocket-Key: %s\r\n"
  16350. "Sec-WebSocket-Version: 13\r\n"
  16351. "Sec-WebSocket-Extensions: %s\r\n"
  16352. "Origin: %s\r\n"
  16353. "\r\n",
  16354. path,
  16355. host,
  16356. magic,
  16357. extensions,
  16358. origin);
  16359. } else {
  16360. i = mg_printf(conn,
  16361. "GET %s HTTP/1.1\r\n"
  16362. "Host: %s\r\n"
  16363. "Upgrade: websocket\r\n"
  16364. "Connection: Upgrade\r\n"
  16365. "Sec-WebSocket-Key: %s\r\n"
  16366. "Sec-WebSocket-Version: 13\r\n"
  16367. "Origin: %s\r\n"
  16368. "\r\n",
  16369. path,
  16370. host,
  16371. magic,
  16372. origin);
  16373. }
  16374. } else {
  16375. if (extensions != NULL) {
  16376. i = mg_printf(conn,
  16377. "GET %s HTTP/1.1\r\n"
  16378. "Host: %s\r\n"
  16379. "Upgrade: websocket\r\n"
  16380. "Connection: Upgrade\r\n"
  16381. "Sec-WebSocket-Key: %s\r\n"
  16382. "Sec-WebSocket-Version: 13\r\n"
  16383. "Sec-WebSocket-Extensions: %s\r\n"
  16384. "\r\n",
  16385. path,
  16386. host,
  16387. magic,
  16388. extensions);
  16389. } else {
  16390. i = mg_printf(conn,
  16391. "GET %s HTTP/1.1\r\n"
  16392. "Host: %s\r\n"
  16393. "Upgrade: websocket\r\n"
  16394. "Connection: Upgrade\r\n"
  16395. "Sec-WebSocket-Key: %s\r\n"
  16396. "Sec-WebSocket-Version: 13\r\n"
  16397. "\r\n",
  16398. path,
  16399. host,
  16400. magic);
  16401. }
  16402. }
  16403. if (i <= 0) {
  16404. mg_snprintf(conn,
  16405. NULL, /* No truncation check for ebuf */
  16406. error_buffer,
  16407. error_buffer_size,
  16408. "%s",
  16409. "Error sending request");
  16410. mg_close_connection(conn);
  16411. return NULL;
  16412. }
  16413. conn->data_len = 0;
  16414. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16415. mg_close_connection(conn);
  16416. return NULL;
  16417. }
  16418. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16419. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16420. #if defined(__clang__)
  16421. #pragma clang diagnostic pop
  16422. #endif
  16423. if (conn->response_info.status_code != 101) {
  16424. /* We sent an "upgrade" request. For a correct websocket
  16425. * protocol handshake, we expect a "101 Continue" response.
  16426. * Otherwise it is a protocol violation. Maybe the HTTP
  16427. * Server does not know websockets. */
  16428. if (!*error_buffer) {
  16429. /* set an error, if not yet set */
  16430. mg_snprintf(conn,
  16431. NULL, /* No truncation check for ebuf */
  16432. error_buffer,
  16433. error_buffer_size,
  16434. "Unexpected server reply");
  16435. }
  16436. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16437. mg_close_connection(conn);
  16438. return NULL;
  16439. }
  16440. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16441. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16442. if (!thread_data) {
  16443. DEBUG_TRACE("%s\r\n", "Out of memory");
  16444. mg_close_connection(conn);
  16445. return NULL;
  16446. }
  16447. thread_data->conn = conn;
  16448. thread_data->data_handler = data_func;
  16449. thread_data->close_handler = close_func;
  16450. thread_data->callback_data = user_data;
  16451. conn->phys_ctx->worker_threadids =
  16452. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16453. if (!conn->phys_ctx->worker_threadids) {
  16454. DEBUG_TRACE("%s\r\n", "Out of memory");
  16455. mg_free(thread_data);
  16456. mg_close_connection(conn);
  16457. return NULL;
  16458. }
  16459. /* Now upgrade to ws/wss client context */
  16460. conn->phys_ctx->user_data = user_data;
  16461. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16462. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16463. /* Start a thread to read the websocket client connection
  16464. * This thread will automatically stop when mg_disconnect is
  16465. * called on the client connection */
  16466. if (mg_start_thread_with_id(websocket_client_thread,
  16467. thread_data,
  16468. conn->phys_ctx->worker_threadids)
  16469. != 0) {
  16470. conn->phys_ctx->cfg_worker_threads = 0;
  16471. mg_free(thread_data);
  16472. mg_close_connection(conn);
  16473. conn = NULL;
  16474. DEBUG_TRACE("%s",
  16475. "Websocket client connect thread could not be started\r\n");
  16476. }
  16477. #else
  16478. /* Appease "unused parameter" warnings */
  16479. (void)client_options;
  16480. (void)use_ssl;
  16481. (void)error_buffer;
  16482. (void)error_buffer_size;
  16483. (void)path;
  16484. (void)origin;
  16485. (void)extensions;
  16486. (void)user_data;
  16487. (void)data_func;
  16488. (void)close_func;
  16489. #endif
  16490. return conn;
  16491. }
  16492. CIVETWEB_API struct mg_connection *
  16493. mg_connect_websocket_client(const char *host,
  16494. int port,
  16495. int use_ssl,
  16496. char *error_buffer,
  16497. size_t error_buffer_size,
  16498. const char *path,
  16499. const char *origin,
  16500. mg_websocket_data_handler data_func,
  16501. mg_websocket_close_handler close_func,
  16502. void *user_data)
  16503. {
  16504. struct mg_client_options client_options;
  16505. memset(&client_options, 0, sizeof(client_options));
  16506. client_options.host = host;
  16507. client_options.port = port;
  16508. return mg_connect_websocket_client_impl(&client_options,
  16509. use_ssl,
  16510. error_buffer,
  16511. error_buffer_size,
  16512. path,
  16513. origin,
  16514. NULL,
  16515. data_func,
  16516. close_func,
  16517. user_data);
  16518. }
  16519. CIVETWEB_API struct mg_connection *
  16520. mg_connect_websocket_client_secure(
  16521. const struct mg_client_options *client_options,
  16522. char *error_buffer,
  16523. size_t error_buffer_size,
  16524. const char *path,
  16525. const char *origin,
  16526. mg_websocket_data_handler data_func,
  16527. mg_websocket_close_handler close_func,
  16528. void *user_data)
  16529. {
  16530. if (!client_options) {
  16531. return NULL;
  16532. }
  16533. return mg_connect_websocket_client_impl(client_options,
  16534. 1,
  16535. error_buffer,
  16536. error_buffer_size,
  16537. path,
  16538. origin,
  16539. NULL,
  16540. data_func,
  16541. close_func,
  16542. user_data);
  16543. }
  16544. CIVETWEB_API struct mg_connection *
  16545. mg_connect_websocket_client_extensions(const char *host,
  16546. int port,
  16547. int use_ssl,
  16548. char *error_buffer,
  16549. size_t error_buffer_size,
  16550. const char *path,
  16551. const char *origin,
  16552. const char *extensions,
  16553. mg_websocket_data_handler data_func,
  16554. mg_websocket_close_handler close_func,
  16555. void *user_data)
  16556. {
  16557. struct mg_client_options client_options;
  16558. memset(&client_options, 0, sizeof(client_options));
  16559. client_options.host = host;
  16560. client_options.port = port;
  16561. return mg_connect_websocket_client_impl(&client_options,
  16562. use_ssl,
  16563. error_buffer,
  16564. error_buffer_size,
  16565. path,
  16566. origin,
  16567. extensions,
  16568. data_func,
  16569. close_func,
  16570. user_data);
  16571. }
  16572. CIVETWEB_API struct mg_connection *
  16573. mg_connect_websocket_client_secure_extensions(
  16574. const struct mg_client_options *client_options,
  16575. char *error_buffer,
  16576. size_t error_buffer_size,
  16577. const char *path,
  16578. const char *origin,
  16579. const char *extensions,
  16580. mg_websocket_data_handler data_func,
  16581. mg_websocket_close_handler close_func,
  16582. void *user_data)
  16583. {
  16584. if (!client_options) {
  16585. return NULL;
  16586. }
  16587. return mg_connect_websocket_client_impl(client_options,
  16588. 1,
  16589. error_buffer,
  16590. error_buffer_size,
  16591. path,
  16592. origin,
  16593. extensions,
  16594. data_func,
  16595. close_func,
  16596. user_data);
  16597. }
  16598. /* Prepare connection data structure */
  16599. static void
  16600. init_connection(struct mg_connection *conn)
  16601. {
  16602. /* Is keep alive allowed by the server */
  16603. int keep_alive_enabled =
  16604. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16605. if (!keep_alive_enabled) {
  16606. conn->must_close = 1;
  16607. }
  16608. /* Important: on new connection, reset the receiving buffer. Credit
  16609. * goes to crule42. */
  16610. conn->data_len = 0;
  16611. conn->handled_requests = 0;
  16612. conn->connection_type = CONNECTION_TYPE_INVALID;
  16613. mg_set_user_connection_data(conn, NULL);
  16614. #if defined(USE_SERVER_STATS)
  16615. conn->conn_state = 2; /* init */
  16616. #endif
  16617. /* call the init_connection callback if assigned */
  16618. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16619. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16620. void *conn_data = NULL;
  16621. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16622. mg_set_user_connection_data(conn, conn_data);
  16623. }
  16624. }
  16625. }
  16626. /* Process a connection - may handle multiple requests
  16627. * using the same connection.
  16628. * Must be called with a valid connection (conn and
  16629. * conn->phys_ctx must be valid).
  16630. */
  16631. static void
  16632. process_new_connection(struct mg_connection *conn)
  16633. {
  16634. struct mg_request_info *ri = &conn->request_info;
  16635. int keep_alive, discard_len;
  16636. char ebuf[100];
  16637. const char *hostend;
  16638. int reqerr, uri_type;
  16639. #if defined(USE_SERVER_STATS)
  16640. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16641. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16642. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16643. #endif
  16644. DEBUG_TRACE("Start processing connection from %s",
  16645. conn->request_info.remote_addr);
  16646. /* Loop over multiple requests sent using the same connection
  16647. * (while "keep alive"). */
  16648. do {
  16649. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16650. conn->handled_requests + 1);
  16651. #if defined(USE_SERVER_STATS)
  16652. conn->conn_state = 3; /* ready */
  16653. #endif
  16654. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16655. /* The request sent by the client could not be understood by
  16656. * the server, or it was incomplete or a timeout. Send an
  16657. * error message and close the connection. */
  16658. if (reqerr > 0) {
  16659. DEBUG_ASSERT(ebuf[0] != '\0');
  16660. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16661. }
  16662. } else if (strcmp(ri->http_version, "1.0")
  16663. && strcmp(ri->http_version, "1.1")) {
  16664. /* HTTP/2 is not allowed here */
  16665. mg_snprintf(conn,
  16666. NULL, /* No truncation check for ebuf */
  16667. ebuf,
  16668. sizeof(ebuf),
  16669. "Bad HTTP version: [%s]",
  16670. ri->http_version);
  16671. mg_send_http_error(conn, 505, "%s", ebuf);
  16672. }
  16673. if (ebuf[0] == '\0') {
  16674. uri_type = get_uri_type(conn->request_info.request_uri);
  16675. switch (uri_type) {
  16676. case 1:
  16677. /* Asterisk */
  16678. conn->request_info.local_uri_raw = 0;
  16679. /* TODO: Deal with '*'. */
  16680. break;
  16681. case 2:
  16682. /* relative uri */
  16683. conn->request_info.local_uri_raw =
  16684. conn->request_info.request_uri;
  16685. break;
  16686. case 3:
  16687. case 4:
  16688. /* absolute uri (with/without port) */
  16689. hostend = get_rel_url_at_current_server(
  16690. conn->request_info.request_uri, conn);
  16691. if (hostend) {
  16692. conn->request_info.local_uri_raw = hostend;
  16693. } else {
  16694. conn->request_info.local_uri_raw = NULL;
  16695. }
  16696. break;
  16697. default:
  16698. mg_snprintf(conn,
  16699. NULL, /* No truncation check for ebuf */
  16700. ebuf,
  16701. sizeof(ebuf),
  16702. "Invalid URI");
  16703. mg_send_http_error(conn, 400, "%s", ebuf);
  16704. conn->request_info.local_uri_raw = NULL;
  16705. break;
  16706. }
  16707. conn->request_info.local_uri =
  16708. (char *)conn->request_info.local_uri_raw;
  16709. }
  16710. if (ebuf[0] != '\0') {
  16711. conn->protocol_type = -1;
  16712. } else {
  16713. /* HTTP/1 allows protocol upgrade */
  16714. conn->protocol_type = should_switch_to_protocol(conn);
  16715. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16716. /* This will occur, if a HTTP/1.1 request should be upgraded
  16717. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16718. * Since most (all?) major browsers only support HTTP/2 using
  16719. * ALPN, this is hard to test and very low priority.
  16720. * Deactivate it (at least for now).
  16721. */
  16722. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16723. }
  16724. }
  16725. DEBUG_TRACE("http: %s, error: %s",
  16726. (ri->http_version ? ri->http_version : "none"),
  16727. (ebuf[0] ? ebuf : "none"));
  16728. if (ebuf[0] == '\0') {
  16729. if (conn->request_info.local_uri) {
  16730. /* handle request to local server */
  16731. handle_request_stat_log(conn);
  16732. } else {
  16733. /* TODO: handle non-local request (PROXY) */
  16734. conn->must_close = 1;
  16735. }
  16736. } else {
  16737. conn->must_close = 1;
  16738. }
  16739. /* Response complete. Free header buffer */
  16740. free_buffered_response_header_list(conn);
  16741. if (ri->remote_user != NULL) {
  16742. mg_free((void *)ri->remote_user);
  16743. /* Important! When having connections with and without auth
  16744. * would cause double free and then crash */
  16745. ri->remote_user = NULL;
  16746. }
  16747. /* NOTE(lsm): order is important here. should_keep_alive() call
  16748. * is using parsed request, which will be invalid after
  16749. * memmove's below.
  16750. * Therefore, memorize should_keep_alive() result now for later
  16751. * use in loop exit condition. */
  16752. /* Enable it only if this request is completely discardable. */
  16753. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16754. && should_keep_alive(conn) && (conn->content_len >= 0)
  16755. && (conn->request_len > 0)
  16756. && ((conn->is_chunked == 4)
  16757. || (!conn->is_chunked
  16758. && ((conn->consumed_content == conn->content_len)
  16759. || ((conn->request_len + conn->content_len)
  16760. <= conn->data_len))))
  16761. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16762. if (keep_alive) {
  16763. /* Discard all buffered data for this request */
  16764. discard_len =
  16765. ((conn->request_len + conn->content_len) < conn->data_len)
  16766. ? (int)(conn->request_len + conn->content_len)
  16767. : conn->data_len;
  16768. conn->data_len -= discard_len;
  16769. if (conn->data_len > 0) {
  16770. DEBUG_TRACE("discard_len = %d", discard_len);
  16771. memmove(conn->buf,
  16772. conn->buf + discard_len,
  16773. (size_t)conn->data_len);
  16774. }
  16775. }
  16776. DEBUG_ASSERT(conn->data_len >= 0);
  16777. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16778. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16779. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16780. (long int)conn->data_len,
  16781. (long int)conn->buf_size);
  16782. break;
  16783. }
  16784. conn->handled_requests++;
  16785. } while (keep_alive);
  16786. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16787. conn->request_info.remote_addr,
  16788. difftime(time(NULL), conn->conn_birth_time));
  16789. close_connection(conn);
  16790. #if defined(USE_SERVER_STATS)
  16791. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16792. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16793. #endif
  16794. }
  16795. #if defined(ALTERNATIVE_QUEUE)
  16796. static void
  16797. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16798. {
  16799. unsigned int i;
  16800. while (!ctx->stop_flag) {
  16801. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16802. /* find a free worker slot and signal it */
  16803. if (ctx->client_socks[i].in_use == 2) {
  16804. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16805. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16806. ctx->client_socks[i] = *sp;
  16807. ctx->client_socks[i].in_use = 1;
  16808. /* socket has been moved to the consumer */
  16809. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16810. (void)event_signal(ctx->client_wait_events[i]);
  16811. return;
  16812. }
  16813. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16814. }
  16815. }
  16816. /* queue is full */
  16817. mg_sleep(1);
  16818. }
  16819. /* must consume */
  16820. set_blocking_mode(sp->sock);
  16821. closesocket(sp->sock);
  16822. }
  16823. static int
  16824. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16825. {
  16826. DEBUG_TRACE("%s", "going idle");
  16827. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16828. ctx->client_socks[thread_index].in_use = 2;
  16829. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16830. event_wait(ctx->client_wait_events[thread_index]);
  16831. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16832. *sp = ctx->client_socks[thread_index];
  16833. if (ctx->stop_flag) {
  16834. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16835. if (sp->in_use == 1) {
  16836. /* must consume */
  16837. set_blocking_mode(sp->sock);
  16838. closesocket(sp->sock);
  16839. }
  16840. return 0;
  16841. }
  16842. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16843. if (sp->in_use == 1) {
  16844. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16845. return 1;
  16846. }
  16847. /* must not reach here */
  16848. DEBUG_ASSERT(0);
  16849. return 0;
  16850. }
  16851. #else /* ALTERNATIVE_QUEUE */
  16852. /* Worker threads take accepted socket from the queue */
  16853. static int
  16854. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16855. {
  16856. (void)thread_index;
  16857. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16858. DEBUG_TRACE("%s", "going idle");
  16859. /* If the queue is empty, wait. We're idle at this point. */
  16860. while ((ctx->sq_head == ctx->sq_tail)
  16861. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16862. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16863. }
  16864. /* If we're stopping, sq_head may be equal to sq_tail. */
  16865. if (ctx->sq_head > ctx->sq_tail) {
  16866. /* Copy socket from the queue and increment tail */
  16867. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16868. ctx->sq_tail++;
  16869. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16870. /* Wrap pointers if needed */
  16871. while (ctx->sq_tail > ctx->sq_size) {
  16872. ctx->sq_tail -= ctx->sq_size;
  16873. ctx->sq_head -= ctx->sq_size;
  16874. }
  16875. }
  16876. (void)pthread_cond_signal(&ctx->sq_empty);
  16877. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16878. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16879. }
  16880. /* Master thread adds accepted socket to a queue */
  16881. static void
  16882. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16883. {
  16884. int queue_filled;
  16885. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16886. queue_filled = ctx->sq_head - ctx->sq_tail;
  16887. /* If the queue is full, wait */
  16888. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16889. && (queue_filled >= ctx->sq_size)) {
  16890. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16891. #if defined(USE_SERVER_STATS)
  16892. if (queue_filled > ctx->sq_max_fill) {
  16893. ctx->sq_max_fill = queue_filled;
  16894. }
  16895. #endif
  16896. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16897. ctx->sq_blocked = 0; /* Not blocked now */
  16898. queue_filled = ctx->sq_head - ctx->sq_tail;
  16899. }
  16900. if (queue_filled < ctx->sq_size) {
  16901. /* Copy socket to the queue and increment head */
  16902. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16903. ctx->sq_head++;
  16904. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16905. }
  16906. queue_filled = ctx->sq_head - ctx->sq_tail;
  16907. #if defined(USE_SERVER_STATS)
  16908. if (queue_filled > ctx->sq_max_fill) {
  16909. ctx->sq_max_fill = queue_filled;
  16910. }
  16911. #endif
  16912. (void)pthread_cond_signal(&ctx->sq_full);
  16913. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16914. }
  16915. #endif /* ALTERNATIVE_QUEUE */
  16916. static void
  16917. worker_thread_run(struct mg_connection *conn)
  16918. {
  16919. struct mg_context *ctx = conn->phys_ctx;
  16920. int thread_index;
  16921. struct mg_workerTLS tls;
  16922. mg_set_thread_name("worker");
  16923. tls.is_master = 0;
  16924. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16925. #if defined(_WIN32)
  16926. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16927. #endif
  16928. /* Initialize thread local storage before calling any callback */
  16929. pthread_setspecific(sTlsKey, &tls);
  16930. /* Check if there is a user callback */
  16931. if (ctx->callbacks.init_thread) {
  16932. /* call init_thread for a worker thread (type 1), and store the
  16933. * return value */
  16934. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16935. } else {
  16936. /* No callback: set user pointer to NULL */
  16937. tls.user_ptr = NULL;
  16938. }
  16939. /* Connection structure has been pre-allocated */
  16940. thread_index = (int)(conn - ctx->worker_connections);
  16941. if ((thread_index < 0)
  16942. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16943. mg_cry_ctx_internal(ctx,
  16944. "Internal error: Invalid worker index %i",
  16945. thread_index);
  16946. return;
  16947. }
  16948. /* Request buffers are not pre-allocated. They are private to the
  16949. * request and do not contain any state information that might be
  16950. * of interest to anyone observing a server status. */
  16951. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16952. if (conn->buf == NULL) {
  16953. mg_cry_ctx_internal(
  16954. ctx,
  16955. "Out of memory: Cannot allocate buffer for worker %i",
  16956. thread_index);
  16957. return;
  16958. }
  16959. conn->buf_size = (int)ctx->max_request_size;
  16960. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16961. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16962. conn->request_info.user_data = ctx->user_data;
  16963. /* Allocate a mutex for this connection to allow communication both
  16964. * within the request handler and from elsewhere in the application
  16965. */
  16966. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16967. mg_free(conn->buf);
  16968. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16969. return;
  16970. }
  16971. #if defined(USE_SERVER_STATS)
  16972. conn->conn_state = 1; /* not consumed */
  16973. #endif
  16974. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16975. * signal sq_empty condvar to wake up the master waiting in
  16976. * produce_socket() */
  16977. while (consume_socket(ctx, &conn->client, thread_index)) {
  16978. /* New connections must start with new protocol negotiation */
  16979. tls.alpn_proto = NULL;
  16980. #if defined(USE_SERVER_STATS)
  16981. conn->conn_close_time = 0;
  16982. #endif
  16983. conn->conn_birth_time = time(NULL);
  16984. /* Fill in IP, port info early so even if SSL setup below fails,
  16985. * error handler would have the corresponding info.
  16986. * Thanks to Johannes Winkelmann for the patch.
  16987. */
  16988. conn->request_info.remote_port =
  16989. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16990. conn->request_info.server_port =
  16991. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16992. sockaddr_to_string(conn->request_info.remote_addr,
  16993. sizeof(conn->request_info.remote_addr),
  16994. &conn->client.rsa);
  16995. DEBUG_TRACE("Incomming %sconnection from %s",
  16996. (conn->client.is_ssl ? "SSL " : ""),
  16997. conn->request_info.remote_addr);
  16998. conn->request_info.is_ssl = conn->client.is_ssl;
  16999. if (conn->client.is_ssl) {
  17000. #if defined(USE_MBEDTLS)
  17001. /* HTTPS connection */
  17002. if (mbed_ssl_accept(&(conn->ssl),
  17003. conn->dom_ctx->ssl_ctx,
  17004. (int *)&(conn->client.sock),
  17005. conn->phys_ctx)
  17006. == 0) {
  17007. /* conn->dom_ctx is set in get_request */
  17008. /* process HTTPS connection */
  17009. init_connection(conn);
  17010. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17011. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17012. process_new_connection(conn);
  17013. } else {
  17014. /* make sure the connection is cleaned up on SSL failure */
  17015. close_connection(conn);
  17016. }
  17017. #elif !defined(NO_SSL)
  17018. /* HTTPS connection */
  17019. if (sslize(conn, SSL_accept, NULL)) {
  17020. /* conn->dom_ctx is set in get_request */
  17021. /* Get SSL client certificate information (if set) */
  17022. struct mg_client_cert client_cert;
  17023. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17024. conn->request_info.client_cert = &client_cert;
  17025. }
  17026. /* process HTTPS connection */
  17027. #if defined(USE_HTTP2)
  17028. if ((tls.alpn_proto != NULL)
  17029. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17030. /* process HTTPS/2 connection */
  17031. init_connection(conn);
  17032. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17033. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17034. conn->content_len =
  17035. -1; /* content length is not predefined */
  17036. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17037. process_new_http2_connection(conn);
  17038. } else
  17039. #endif
  17040. {
  17041. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17042. init_connection(conn);
  17043. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17044. /* Start with HTTP, WS will be an "upgrade" request later */
  17045. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17046. process_new_connection(conn);
  17047. }
  17048. /* Free client certificate info */
  17049. if (conn->request_info.client_cert) {
  17050. mg_free((void *)(conn->request_info.client_cert->subject));
  17051. mg_free((void *)(conn->request_info.client_cert->issuer));
  17052. mg_free((void *)(conn->request_info.client_cert->serial));
  17053. mg_free((void *)(conn->request_info.client_cert->finger));
  17054. /* Free certificate memory */
  17055. X509_free(
  17056. (X509 *)conn->request_info.client_cert->peer_cert);
  17057. conn->request_info.client_cert->peer_cert = 0;
  17058. conn->request_info.client_cert->subject = 0;
  17059. conn->request_info.client_cert->issuer = 0;
  17060. conn->request_info.client_cert->serial = 0;
  17061. conn->request_info.client_cert->finger = 0;
  17062. conn->request_info.client_cert = 0;
  17063. }
  17064. } else {
  17065. /* make sure the connection is cleaned up on SSL failure */
  17066. close_connection(conn);
  17067. }
  17068. #endif
  17069. } else {
  17070. /* process HTTP connection */
  17071. init_connection(conn);
  17072. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17073. /* Start with HTTP, WS will be an "upgrade" request later */
  17074. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17075. process_new_connection(conn);
  17076. }
  17077. DEBUG_TRACE("%s", "Connection closed");
  17078. #if defined(USE_SERVER_STATS)
  17079. conn->conn_close_time = time(NULL);
  17080. #endif
  17081. }
  17082. /* Call exit thread user callback */
  17083. if (ctx->callbacks.exit_thread) {
  17084. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17085. }
  17086. /* delete thread local storage objects */
  17087. pthread_setspecific(sTlsKey, NULL);
  17088. #if defined(_WIN32)
  17089. CloseHandle(tls.pthread_cond_helper_mutex);
  17090. #endif
  17091. pthread_mutex_destroy(&conn->mutex);
  17092. /* Free the request buffer. */
  17093. conn->buf_size = 0;
  17094. mg_free(conn->buf);
  17095. conn->buf = NULL;
  17096. /* Free cleaned URI (if any) */
  17097. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17098. mg_free((void *)conn->request_info.local_uri);
  17099. conn->request_info.local_uri = NULL;
  17100. }
  17101. #if defined(USE_SERVER_STATS)
  17102. conn->conn_state = 9; /* done */
  17103. #endif
  17104. DEBUG_TRACE("%s", "exiting");
  17105. }
  17106. /* Threads have different return types on Windows and Unix. */
  17107. #if defined(_WIN32)
  17108. static unsigned __stdcall worker_thread(void *thread_func_param)
  17109. {
  17110. worker_thread_run((struct mg_connection *)thread_func_param);
  17111. return 0;
  17112. }
  17113. #else
  17114. static void *
  17115. worker_thread(void *thread_func_param)
  17116. {
  17117. #if !defined(__ZEPHYR__)
  17118. struct sigaction sa;
  17119. /* Ignore SIGPIPE */
  17120. memset(&sa, 0, sizeof(sa));
  17121. sa.sa_handler = SIG_IGN;
  17122. sigaction(SIGPIPE, &sa, NULL);
  17123. #endif
  17124. worker_thread_run((struct mg_connection *)thread_func_param);
  17125. return NULL;
  17126. }
  17127. #endif /* _WIN32 */
  17128. /* This is an internal function, thus all arguments are expected to be
  17129. * valid - a NULL check is not required. */
  17130. static void
  17131. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17132. {
  17133. struct socket so;
  17134. char src_addr[IP_ADDR_STR_LEN];
  17135. socklen_t len = sizeof(so.rsa);
  17136. #if !defined(__ZEPHYR__)
  17137. int on = 1;
  17138. #endif
  17139. memset(&so, 0, sizeof(so));
  17140. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17141. == INVALID_SOCKET) {
  17142. } else if (check_acl(ctx, &so.rsa) != 1) {
  17143. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17144. mg_cry_ctx_internal(ctx,
  17145. "%s: %s is not allowed to connect",
  17146. __func__,
  17147. src_addr);
  17148. closesocket(so.sock);
  17149. } else {
  17150. /* Put so socket structure into the queue */
  17151. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17152. set_close_on_exec(so.sock, NULL, ctx);
  17153. so.is_ssl = listener->is_ssl;
  17154. so.ssl_redir = listener->ssl_redir;
  17155. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17156. mg_cry_ctx_internal(ctx,
  17157. "%s: getsockname() failed: %s",
  17158. __func__,
  17159. strerror(ERRNO));
  17160. }
  17161. #if !defined(__ZEPHYR__)
  17162. if ((so.lsa.sa.sa_family == AF_INET)
  17163. || (so.lsa.sa.sa_family == AF_INET6)) {
  17164. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17165. * This is needed because if HTTP-level keep-alive
  17166. * is enabled, and client resets the connection, server won't get
  17167. * TCP FIN or RST and will keep the connection open forever. With
  17168. * TCP keep-alive, next keep-alive handshake will figure out that
  17169. * the client is down and will close the server end.
  17170. * Thanks to Igor Klopov who suggested the patch. */
  17171. if (setsockopt(so.sock,
  17172. SOL_SOCKET,
  17173. SO_KEEPALIVE,
  17174. (SOCK_OPT_TYPE)&on,
  17175. sizeof(on))
  17176. != 0) {
  17177. mg_cry_ctx_internal(
  17178. ctx,
  17179. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17180. __func__,
  17181. strerror(ERRNO));
  17182. }
  17183. }
  17184. #endif
  17185. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17186. * to effectively fill up the underlying IP packet payload and
  17187. * reduce the overhead of sending lots of small buffers. However
  17188. * this hurts the server's throughput (ie. operations per second)
  17189. * when HTTP 1.1 persistent connections are used and the responses
  17190. * are relatively small (eg. less than 1400 bytes).
  17191. */
  17192. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17193. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17194. if (set_tcp_nodelay(&so, 1) != 0) {
  17195. mg_cry_ctx_internal(
  17196. ctx,
  17197. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17198. __func__,
  17199. strerror(ERRNO));
  17200. }
  17201. }
  17202. /* The "non blocking" property should already be
  17203. * inherited from the parent socket. Set it for
  17204. * non-compliant socket implementations. */
  17205. set_non_blocking_mode(so.sock);
  17206. so.in_use = 0;
  17207. produce_socket(ctx, &so);
  17208. }
  17209. }
  17210. static void
  17211. master_thread_run(struct mg_context *ctx)
  17212. {
  17213. struct mg_workerTLS tls;
  17214. struct mg_pollfd *pfd;
  17215. unsigned int i;
  17216. unsigned int workerthreadcount;
  17217. if (!ctx) {
  17218. return;
  17219. }
  17220. mg_set_thread_name("master");
  17221. /* Increase priority of the master thread */
  17222. #if defined(_WIN32)
  17223. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17224. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17225. int min_prio = sched_get_priority_min(SCHED_RR);
  17226. int max_prio = sched_get_priority_max(SCHED_RR);
  17227. if ((min_prio >= 0) && (max_prio >= 0)
  17228. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17229. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17230. struct sched_param sched_param = {0};
  17231. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17232. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17233. }
  17234. #endif
  17235. /* Initialize thread local storage */
  17236. #if defined(_WIN32)
  17237. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17238. #endif
  17239. tls.is_master = 1;
  17240. pthread_setspecific(sTlsKey, &tls);
  17241. if (ctx->callbacks.init_thread) {
  17242. /* Callback for the master thread (type 0) */
  17243. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17244. } else {
  17245. tls.user_ptr = NULL;
  17246. }
  17247. /* Lua background script "start" event */
  17248. #if defined(USE_LUA)
  17249. if (ctx->lua_background_state) {
  17250. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17251. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17252. /* call "start()" in Lua */
  17253. lua_getglobal(lstate, "start");
  17254. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17255. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17256. if (ret != 0) {
  17257. struct mg_connection fc;
  17258. lua_cry(fake_connection(&fc, ctx),
  17259. ret,
  17260. lstate,
  17261. "lua_background_script",
  17262. "start");
  17263. }
  17264. } else {
  17265. lua_pop(lstate, 1);
  17266. }
  17267. /* determine if there is a "log()" function in Lua background script */
  17268. lua_getglobal(lstate, "log");
  17269. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17270. ctx->lua_bg_log_available = 1;
  17271. }
  17272. lua_pop(lstate, 1);
  17273. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17274. }
  17275. #endif
  17276. /* Server starts *now* */
  17277. ctx->start_time = time(NULL);
  17278. /* Server accept loop */
  17279. pfd = ctx->listening_socket_fds;
  17280. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17281. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17282. pfd[i].fd = ctx->listening_sockets[i].sock;
  17283. pfd[i].events = POLLIN;
  17284. }
  17285. if (mg_poll(pfd,
  17286. ctx->num_listening_sockets,
  17287. SOCKET_TIMEOUT_QUANTUM,
  17288. &(ctx->stop_flag))
  17289. > 0) {
  17290. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17291. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17292. * successful poll, and POLLIN is defined as
  17293. * (POLLRDNORM | POLLRDBAND)
  17294. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17295. * pfd[i].revents == POLLIN. */
  17296. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17297. && (pfd[i].revents & POLLIN)) {
  17298. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17299. }
  17300. }
  17301. }
  17302. }
  17303. /* Here stop_flag is 1 - Initiate shutdown. */
  17304. DEBUG_TRACE("%s", "stopping workers");
  17305. /* Stop signal received: somebody called mg_stop. Quit. */
  17306. close_all_listening_sockets(ctx);
  17307. /* Wakeup workers that are waiting for connections to handle. */
  17308. #if defined(ALTERNATIVE_QUEUE)
  17309. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17310. event_signal(ctx->client_wait_events[i]);
  17311. }
  17312. #else
  17313. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17314. pthread_cond_broadcast(&ctx->sq_full);
  17315. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17316. #endif
  17317. /* Join all worker threads to avoid leaking threads. */
  17318. workerthreadcount = ctx->cfg_worker_threads;
  17319. for (i = 0; i < workerthreadcount; i++) {
  17320. if (ctx->worker_threadids[i] != 0) {
  17321. mg_join_thread(ctx->worker_threadids[i]);
  17322. }
  17323. }
  17324. #if defined(USE_LUA)
  17325. /* Free Lua state of lua background task */
  17326. if (ctx->lua_background_state) {
  17327. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17328. ctx->lua_bg_log_available = 0;
  17329. /* call "stop()" in Lua */
  17330. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17331. lua_getglobal(lstate, "stop");
  17332. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17333. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17334. if (ret != 0) {
  17335. struct mg_connection fc;
  17336. lua_cry(fake_connection(&fc, ctx),
  17337. ret,
  17338. lstate,
  17339. "lua_background_script",
  17340. "stop");
  17341. }
  17342. }
  17343. lua_close(lstate);
  17344. ctx->lua_background_state = 0;
  17345. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17346. }
  17347. #endif
  17348. DEBUG_TRACE("%s", "exiting");
  17349. /* call exit thread callback */
  17350. if (ctx->callbacks.exit_thread) {
  17351. /* Callback for the master thread (type 0) */
  17352. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17353. }
  17354. #if defined(_WIN32)
  17355. CloseHandle(tls.pthread_cond_helper_mutex);
  17356. #endif
  17357. pthread_setspecific(sTlsKey, NULL);
  17358. /* Signal mg_stop() that we're done.
  17359. * WARNING: This must be the very last thing this
  17360. * thread does, as ctx becomes invalid after this line. */
  17361. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17362. }
  17363. /* Threads have different return types on Windows and Unix. */
  17364. #if defined(_WIN32)
  17365. static unsigned __stdcall master_thread(void *thread_func_param)
  17366. {
  17367. master_thread_run((struct mg_context *)thread_func_param);
  17368. return 0;
  17369. }
  17370. #else
  17371. static void *
  17372. master_thread(void *thread_func_param)
  17373. {
  17374. #if !defined(__ZEPHYR__)
  17375. struct sigaction sa;
  17376. /* Ignore SIGPIPE */
  17377. memset(&sa, 0, sizeof(sa));
  17378. sa.sa_handler = SIG_IGN;
  17379. sigaction(SIGPIPE, &sa, NULL);
  17380. #endif
  17381. master_thread_run((struct mg_context *)thread_func_param);
  17382. return NULL;
  17383. }
  17384. #endif /* _WIN32 */
  17385. static void
  17386. free_context(struct mg_context *ctx)
  17387. {
  17388. int i;
  17389. struct mg_handler_info *tmp_rh;
  17390. if (ctx == NULL) {
  17391. return;
  17392. }
  17393. /* Call user callback */
  17394. if (ctx->callbacks.exit_context) {
  17395. ctx->callbacks.exit_context(ctx);
  17396. }
  17397. /* All threads exited, no sync is needed. Destroy thread mutex and
  17398. * condvars
  17399. */
  17400. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17401. #if defined(ALTERNATIVE_QUEUE)
  17402. mg_free(ctx->client_socks);
  17403. if (ctx->client_wait_events != NULL) {
  17404. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17405. event_destroy(ctx->client_wait_events[i]);
  17406. }
  17407. mg_free(ctx->client_wait_events);
  17408. }
  17409. #else
  17410. (void)pthread_cond_destroy(&ctx->sq_empty);
  17411. (void)pthread_cond_destroy(&ctx->sq_full);
  17412. mg_free(ctx->squeue);
  17413. #endif
  17414. /* Destroy other context global data structures mutex */
  17415. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17416. #if defined(USE_LUA)
  17417. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17418. #endif
  17419. /* Deallocate config parameters */
  17420. for (i = 0; i < NUM_OPTIONS; i++) {
  17421. if (ctx->dd.config[i] != NULL) {
  17422. #if defined(_MSC_VER)
  17423. #pragma warning(suppress : 6001)
  17424. #endif
  17425. mg_free(ctx->dd.config[i]);
  17426. }
  17427. }
  17428. /* Deallocate request handlers */
  17429. while (ctx->dd.handlers) {
  17430. tmp_rh = ctx->dd.handlers;
  17431. ctx->dd.handlers = tmp_rh->next;
  17432. mg_free(tmp_rh->uri);
  17433. mg_free(tmp_rh);
  17434. }
  17435. #if defined(USE_MBEDTLS)
  17436. if (ctx->dd.ssl_ctx != NULL) {
  17437. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17438. mg_free(ctx->dd.ssl_ctx);
  17439. ctx->dd.ssl_ctx = NULL;
  17440. }
  17441. #elif !defined(NO_SSL)
  17442. /* Deallocate SSL context */
  17443. if (ctx->dd.ssl_ctx != NULL) {
  17444. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17445. int callback_ret =
  17446. (ctx->callbacks.external_ssl_ctx == NULL)
  17447. ? 0
  17448. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17449. if (callback_ret == 0) {
  17450. SSL_CTX_free(ctx->dd.ssl_ctx);
  17451. }
  17452. /* else: ignore error and ommit SSL_CTX_free in case
  17453. * callback_ret is 1 */
  17454. }
  17455. #endif /* !NO_SSL */
  17456. /* Deallocate worker thread ID array */
  17457. mg_free(ctx->worker_threadids);
  17458. /* Deallocate worker thread ID array */
  17459. mg_free(ctx->worker_connections);
  17460. /* deallocate system name string */
  17461. mg_free(ctx->systemName);
  17462. /* Deallocate context itself */
  17463. mg_free(ctx);
  17464. }
  17465. CIVETWEB_API void
  17466. mg_stop(struct mg_context *ctx)
  17467. {
  17468. pthread_t mt;
  17469. if (!ctx) {
  17470. return;
  17471. }
  17472. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17473. * two threads is not allowed. */
  17474. mt = ctx->masterthreadid;
  17475. if (mt == 0) {
  17476. return;
  17477. }
  17478. ctx->masterthreadid = 0;
  17479. /* Set stop flag, so all threads know they have to exit. */
  17480. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17481. /* Join timer thread */
  17482. #if defined(USE_TIMERS)
  17483. timers_exit(ctx);
  17484. #endif
  17485. /* Wait until everything has stopped. */
  17486. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17487. (void)mg_sleep(10);
  17488. }
  17489. /* Wait to stop master thread */
  17490. mg_join_thread(mt);
  17491. /* Close remaining Lua states */
  17492. #if defined(USE_LUA)
  17493. lua_ctx_exit(ctx);
  17494. #endif
  17495. /* Free memory */
  17496. free_context(ctx);
  17497. }
  17498. static void
  17499. get_system_name(char **sysName)
  17500. {
  17501. #if defined(_WIN32)
  17502. char name[128];
  17503. DWORD dwVersion = 0;
  17504. DWORD dwMajorVersion = 0;
  17505. DWORD dwMinorVersion = 0;
  17506. DWORD dwBuild = 0;
  17507. BOOL wowRet, isWoW = FALSE;
  17508. #if defined(_MSC_VER)
  17509. #pragma warning(push)
  17510. /* GetVersion was declared deprecated */
  17511. #pragma warning(disable : 4996)
  17512. #endif
  17513. dwVersion = GetVersion();
  17514. #if defined(_MSC_VER)
  17515. #pragma warning(pop)
  17516. #endif
  17517. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17518. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17519. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17520. (void)dwBuild;
  17521. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17522. sprintf(name,
  17523. "Windows %u.%u%s",
  17524. (unsigned)dwMajorVersion,
  17525. (unsigned)dwMinorVersion,
  17526. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17527. *sysName = mg_strdup(name);
  17528. #elif defined(__ZEPHYR__)
  17529. *sysName = mg_strdup("Zephyr OS");
  17530. #else
  17531. struct utsname name;
  17532. memset(&name, 0, sizeof(name));
  17533. uname(&name);
  17534. *sysName = mg_strdup(name.sysname);
  17535. #endif
  17536. }
  17537. static void
  17538. legacy_init(const char **options)
  17539. {
  17540. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17541. if (options) {
  17542. const char **run_options = options;
  17543. const char *optname = config_options[LISTENING_PORTS].name;
  17544. /* Try to find the "listening_ports" option */
  17545. while (*run_options) {
  17546. if (!strcmp(*run_options, optname)) {
  17547. ports_option = run_options[1];
  17548. }
  17549. run_options += 2;
  17550. }
  17551. }
  17552. if (is_ssl_port_used(ports_option)) {
  17553. /* Initialize with SSL support */
  17554. mg_init_library(MG_FEATURES_TLS);
  17555. } else {
  17556. /* Initialize without SSL support */
  17557. mg_init_library(MG_FEATURES_DEFAULT);
  17558. }
  17559. }
  17560. CIVETWEB_API struct mg_context *
  17561. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17562. {
  17563. struct mg_context *ctx;
  17564. const char *name, *value, *default_value;
  17565. int idx, ok, workerthreadcount;
  17566. unsigned int i;
  17567. int itmp;
  17568. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17569. const char **options =
  17570. ((init != NULL) ? (init->configuration_options) : (NULL));
  17571. struct mg_workerTLS tls;
  17572. if (error != NULL) {
  17573. error->code = MG_ERROR_DATA_CODE_OK;
  17574. error->code_sub = 0;
  17575. if (error->text_buffer_size > 0) {
  17576. *error->text = 0;
  17577. }
  17578. }
  17579. if (mg_init_library_called == 0) {
  17580. /* Legacy INIT, if mg_start is called without mg_init_library.
  17581. * Note: This will cause a memory leak when unloading the library.
  17582. */
  17583. legacy_init(options);
  17584. }
  17585. if (mg_init_library_called == 0) {
  17586. if (error != NULL) {
  17587. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  17588. mg_snprintf(NULL,
  17589. NULL, /* No truncation check for error buffers */
  17590. error->text,
  17591. error->text_buffer_size,
  17592. "%s",
  17593. "Library uninitialized");
  17594. }
  17595. return NULL;
  17596. }
  17597. /* Allocate context and initialize reasonable general case defaults. */
  17598. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  17599. if (ctx == NULL) {
  17600. if (error != NULL) {
  17601. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17602. error->code_sub = (unsigned)sizeof(*ctx);
  17603. mg_snprintf(NULL,
  17604. NULL, /* No truncation check for error buffers */
  17605. error->text,
  17606. error->text_buffer_size,
  17607. "%s",
  17608. "Out of memory");
  17609. }
  17610. return NULL;
  17611. }
  17612. /* Random number generator will initialize at the first call */
  17613. ctx->dd.auth_nonce_mask =
  17614. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17615. /* Save started thread index to reuse in other external API calls
  17616. * For the sake of thread synchronization all non-civetweb threads
  17617. * can be considered as single external thread */
  17618. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17619. tls.is_master = -1; /* Thread calling mg_start */
  17620. tls.thread_idx = ctx->starter_thread_idx;
  17621. #if defined(_WIN32)
  17622. tls.pthread_cond_helper_mutex = NULL;
  17623. #endif
  17624. pthread_setspecific(sTlsKey, &tls);
  17625. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17626. #if !defined(ALTERNATIVE_QUEUE)
  17627. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17628. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17629. ctx->sq_blocked = 0;
  17630. #endif
  17631. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17632. #if defined(USE_LUA)
  17633. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17634. #endif
  17635. if (!ok) {
  17636. unsigned error_id = (unsigned)ERRNO;
  17637. const char *err_msg =
  17638. "Cannot initialize thread synchronization objects";
  17639. /* Fatal error - abort start. However, this situation should never
  17640. * occur in practice. */
  17641. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17642. if (error != NULL) {
  17643. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  17644. error->code_sub = error_id;
  17645. mg_snprintf(NULL,
  17646. NULL, /* No truncation check for error buffers */
  17647. error->text,
  17648. error->text_buffer_size,
  17649. "%s",
  17650. err_msg);
  17651. }
  17652. mg_free(ctx);
  17653. pthread_setspecific(sTlsKey, NULL);
  17654. return NULL;
  17655. }
  17656. if ((init != NULL) && (init->callbacks != NULL)) {
  17657. /* Set all callbacks except exit_context. */
  17658. ctx->callbacks = *init->callbacks;
  17659. exit_callback = init->callbacks->exit_context;
  17660. /* The exit callback is activated once the context is successfully
  17661. * created. It should not be called, if an incomplete context object
  17662. * is deleted during a failed initialization. */
  17663. ctx->callbacks.exit_context = 0;
  17664. }
  17665. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17666. ctx->dd.handlers = NULL;
  17667. ctx->dd.next = NULL;
  17668. #if defined(USE_LUA)
  17669. lua_ctx_init(ctx);
  17670. #endif
  17671. /* Store options */
  17672. while (options && (name = *options++) != NULL) {
  17673. idx = get_option_index(name);
  17674. if (idx == -1) {
  17675. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17676. if (error != NULL) {
  17677. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17678. error->code_sub = (unsigned)-1;
  17679. mg_snprintf(NULL,
  17680. NULL, /* No truncation check for error buffers */
  17681. error->text,
  17682. error->text_buffer_size,
  17683. "Invalid configuration option: %s",
  17684. name);
  17685. }
  17686. free_context(ctx);
  17687. pthread_setspecific(sTlsKey, NULL);
  17688. return NULL;
  17689. } else if ((value = *options++) == NULL) {
  17690. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17691. if (error != NULL) {
  17692. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17693. error->code_sub = (unsigned)idx;
  17694. mg_snprintf(NULL,
  17695. NULL, /* No truncation check for error buffers */
  17696. error->text,
  17697. error->text_buffer_size,
  17698. "Invalid configuration option value: %s",
  17699. name);
  17700. }
  17701. free_context(ctx);
  17702. pthread_setspecific(sTlsKey, NULL);
  17703. return NULL;
  17704. }
  17705. if (ctx->dd.config[idx] != NULL) {
  17706. /* A duplicate configuration option is not an error - the last
  17707. * option value will be used. */
  17708. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17709. mg_free(ctx->dd.config[idx]);
  17710. }
  17711. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17712. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17713. }
  17714. /* Set default value if needed */
  17715. for (i = 0; config_options[i].name != NULL; i++) {
  17716. default_value = config_options[i].default_value;
  17717. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17718. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17719. }
  17720. }
  17721. /* Request size option */
  17722. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17723. if (itmp < 1024) {
  17724. mg_cry_ctx_internal(ctx,
  17725. "%s too small",
  17726. config_options[MAX_REQUEST_SIZE].name);
  17727. if (error != NULL) {
  17728. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17729. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  17730. mg_snprintf(NULL,
  17731. NULL, /* No truncation check for error buffers */
  17732. error->text,
  17733. error->text_buffer_size,
  17734. "Invalid configuration option value: %s",
  17735. config_options[MAX_REQUEST_SIZE].name);
  17736. }
  17737. free_context(ctx);
  17738. pthread_setspecific(sTlsKey, NULL);
  17739. return NULL;
  17740. }
  17741. ctx->max_request_size = (unsigned)itmp;
  17742. /* Queue length */
  17743. #if !defined(ALTERNATIVE_QUEUE)
  17744. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17745. if (itmp < 1) {
  17746. mg_cry_ctx_internal(ctx,
  17747. "%s too small",
  17748. config_options[CONNECTION_QUEUE_SIZE].name);
  17749. if (error != NULL) {
  17750. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17751. error->code_sub = CONNECTION_QUEUE_SIZE;
  17752. mg_snprintf(NULL,
  17753. NULL, /* No truncation check for error buffers */
  17754. error->text,
  17755. error->text_buffer_size,
  17756. "Invalid configuration option value: %s",
  17757. config_options[CONNECTION_QUEUE_SIZE].name);
  17758. }
  17759. free_context(ctx);
  17760. pthread_setspecific(sTlsKey, NULL);
  17761. return NULL;
  17762. }
  17763. ctx->squeue =
  17764. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17765. if (ctx->squeue == NULL) {
  17766. mg_cry_ctx_internal(ctx,
  17767. "Out of memory: Cannot allocate %s",
  17768. config_options[CONNECTION_QUEUE_SIZE].name);
  17769. if (error != NULL) {
  17770. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  17771. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  17772. mg_snprintf(NULL,
  17773. NULL, /* No truncation check for error buffers */
  17774. error->text,
  17775. error->text_buffer_size,
  17776. "Out of memory: Cannot allocate %s",
  17777. config_options[CONNECTION_QUEUE_SIZE].name);
  17778. }
  17779. free_context(ctx);
  17780. pthread_setspecific(sTlsKey, NULL);
  17781. return NULL;
  17782. }
  17783. ctx->sq_size = itmp;
  17784. #endif
  17785. /* Worker thread count option */
  17786. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17787. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17788. if (workerthreadcount <= 0) {
  17789. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17790. } else {
  17791. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17792. }
  17793. if (error != NULL) {
  17794. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17795. error->code_sub = NUM_THREADS;
  17796. mg_snprintf(NULL,
  17797. NULL, /* No truncation check for error buffers */
  17798. error->text,
  17799. error->text_buffer_size,
  17800. "Invalid configuration option value: %s",
  17801. config_options[NUM_THREADS].name);
  17802. }
  17803. free_context(ctx);
  17804. pthread_setspecific(sTlsKey, NULL);
  17805. return NULL;
  17806. }
  17807. /* Document root */
  17808. #if defined(NO_FILES)
  17809. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17810. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17811. if (error != NULL) {
  17812. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  17813. error->code_sub = (unsigned)DOCUMENT_ROOT;
  17814. mg_snprintf(NULL,
  17815. NULL, /* No truncation check for error buffers */
  17816. error->text,
  17817. error->text_buffer_size,
  17818. "Invalid configuration option value: %s",
  17819. config_options[DOCUMENT_ROOT].name);
  17820. }
  17821. free_context(ctx);
  17822. pthread_setspecific(sTlsKey, NULL);
  17823. return NULL;
  17824. }
  17825. #endif
  17826. get_system_name(&ctx->systemName);
  17827. #if defined(USE_LUA)
  17828. /* If a Lua background script has been configured, start it. */
  17829. ctx->lua_bg_log_available = 0;
  17830. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17831. char ebuf[256];
  17832. struct vec opt_vec;
  17833. struct vec eq_vec;
  17834. const char *sparams;
  17835. memset(ebuf, 0, sizeof(ebuf));
  17836. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17837. /* Create a Lua state, load all standard libraries and the mg table */
  17838. lua_State *state = mg_lua_context_script_prepare(
  17839. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17840. if (!state) {
  17841. mg_cry_ctx_internal(ctx,
  17842. "lua_background_script load error: %s",
  17843. ebuf);
  17844. if (error != NULL) {
  17845. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17846. mg_snprintf(NULL,
  17847. NULL, /* No truncation check for error buffers */
  17848. error->text,
  17849. error->text_buffer_size,
  17850. "Error in script %s: %s",
  17851. config_options[LUA_BACKGROUND_SCRIPT].name,
  17852. ebuf);
  17853. }
  17854. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17855. free_context(ctx);
  17856. pthread_setspecific(sTlsKey, NULL);
  17857. return NULL;
  17858. }
  17859. /* Add a table with parameters into mg.params */
  17860. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17861. if (sparams && sparams[0]) {
  17862. lua_getglobal(state, "mg");
  17863. lua_pushstring(state, "params");
  17864. lua_newtable(state);
  17865. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17866. != NULL) {
  17867. reg_llstring(
  17868. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17869. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17870. break;
  17871. }
  17872. lua_rawset(state, -3);
  17873. lua_pop(state, 1);
  17874. }
  17875. /* Call script */
  17876. state = mg_lua_context_script_run(state,
  17877. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17878. ctx,
  17879. ebuf,
  17880. sizeof(ebuf));
  17881. if (!state) {
  17882. mg_cry_ctx_internal(ctx,
  17883. "lua_background_script start error: %s",
  17884. ebuf);
  17885. if (error != NULL) {
  17886. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  17887. mg_snprintf(NULL,
  17888. NULL, /* No truncation check for error buffers */
  17889. error->text,
  17890. error->text_buffer_size,
  17891. "Error in script %s: %s",
  17892. config_options[DOCUMENT_ROOT].name,
  17893. ebuf);
  17894. }
  17895. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17896. free_context(ctx);
  17897. pthread_setspecific(sTlsKey, NULL);
  17898. return NULL;
  17899. }
  17900. /* state remains valid */
  17901. ctx->lua_background_state = (void *)state;
  17902. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17903. } else {
  17904. ctx->lua_background_state = 0;
  17905. }
  17906. #endif
  17907. /* Step by step initialization of ctx - depending on build options */
  17908. #if !defined(NO_FILESYSTEMS)
  17909. if (!set_gpass_option(ctx, NULL)) {
  17910. const char *err_msg = "Invalid global password file";
  17911. /* Fatal error - abort start. */
  17912. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17913. if (error != NULL) {
  17914. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  17915. mg_snprintf(NULL,
  17916. NULL, /* No truncation check for error buffers */
  17917. error->text,
  17918. error->text_buffer_size,
  17919. "%s",
  17920. err_msg);
  17921. }
  17922. free_context(ctx);
  17923. pthread_setspecific(sTlsKey, NULL);
  17924. return NULL;
  17925. }
  17926. #endif
  17927. #if defined(USE_MBEDTLS)
  17928. if (!mg_sslctx_init(ctx, NULL)) {
  17929. const char *err_msg = "Error initializing SSL context";
  17930. /* Fatal error - abort start. */
  17931. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17932. if (error != NULL) {
  17933. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  17934. mg_snprintf(NULL,
  17935. NULL, /* No truncation check for error buffers */
  17936. error->text,
  17937. error->text_buffer_size,
  17938. "%s",
  17939. err_msg);
  17940. }
  17941. free_context(ctx);
  17942. pthread_setspecific(sTlsKey, NULL);
  17943. return NULL;
  17944. }
  17945. #elif !defined(NO_SSL)
  17946. if (!init_ssl_ctx(ctx, NULL)) {
  17947. const char *err_msg = "Error initializing SSL context";
  17948. /* Fatal error - abort start. */
  17949. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17950. if (error != NULL) {
  17951. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  17952. mg_snprintf(NULL,
  17953. NULL, /* No truncation check for error buffers */
  17954. error->text,
  17955. error->text_buffer_size,
  17956. "%s",
  17957. err_msg);
  17958. }
  17959. free_context(ctx);
  17960. pthread_setspecific(sTlsKey, NULL);
  17961. return NULL;
  17962. }
  17963. #endif
  17964. if (!set_ports_option(ctx)) {
  17965. const char *err_msg = "Failed to setup server ports";
  17966. /* Fatal error - abort start. */
  17967. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17968. if (error != NULL) {
  17969. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  17970. mg_snprintf(NULL,
  17971. NULL, /* No truncation check for error buffers */
  17972. error->text,
  17973. error->text_buffer_size,
  17974. "%s",
  17975. err_msg);
  17976. }
  17977. free_context(ctx);
  17978. pthread_setspecific(sTlsKey, NULL);
  17979. return NULL;
  17980. }
  17981. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17982. if (!set_uid_option(ctx)) {
  17983. const char *err_msg = "Failed to run as configured user";
  17984. /* Fatal error - abort start. */
  17985. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17986. if (error != NULL) {
  17987. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  17988. mg_snprintf(NULL,
  17989. NULL, /* No truncation check for error buffers */
  17990. error->text,
  17991. error->text_buffer_size,
  17992. "%s",
  17993. err_msg);
  17994. }
  17995. free_context(ctx);
  17996. pthread_setspecific(sTlsKey, NULL);
  17997. return NULL;
  17998. }
  17999. #endif
  18000. if (!set_acl_option(ctx)) {
  18001. const char *err_msg = "Failed to setup access control list";
  18002. /* Fatal error - abort start. */
  18003. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18004. if (error != NULL) {
  18005. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18006. mg_snprintf(NULL,
  18007. NULL, /* No truncation check for error buffers */
  18008. error->text,
  18009. error->text_buffer_size,
  18010. "%s",
  18011. err_msg);
  18012. }
  18013. free_context(ctx);
  18014. pthread_setspecific(sTlsKey, NULL);
  18015. return NULL;
  18016. }
  18017. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  18018. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18019. sizeof(pthread_t),
  18020. ctx);
  18021. if (ctx->worker_threadids == NULL) {
  18022. const char *err_msg = "Not enough memory for worker thread ID array";
  18023. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18024. if (error != NULL) {
  18025. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18026. error->code_sub =
  18027. (unsigned)ctx->cfg_worker_threads * (unsigned)sizeof(pthread_t);
  18028. mg_snprintf(NULL,
  18029. NULL, /* No truncation check for error buffers */
  18030. error->text,
  18031. error->text_buffer_size,
  18032. "%s",
  18033. err_msg);
  18034. }
  18035. free_context(ctx);
  18036. pthread_setspecific(sTlsKey, NULL);
  18037. return NULL;
  18038. }
  18039. ctx->worker_connections =
  18040. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18041. sizeof(struct mg_connection),
  18042. ctx);
  18043. if (ctx->worker_connections == NULL) {
  18044. const char *err_msg =
  18045. "Not enough memory for worker thread connection array";
  18046. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18047. if (error != NULL) {
  18048. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18049. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18050. * (unsigned)sizeof(struct mg_connection);
  18051. mg_snprintf(NULL,
  18052. NULL, /* No truncation check for error buffers */
  18053. error->text,
  18054. error->text_buffer_size,
  18055. "%s",
  18056. err_msg);
  18057. }
  18058. free_context(ctx);
  18059. pthread_setspecific(sTlsKey, NULL);
  18060. return NULL;
  18061. }
  18062. #if defined(ALTERNATIVE_QUEUE)
  18063. ctx->client_wait_events =
  18064. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  18065. sizeof(ctx->client_wait_events[0]),
  18066. ctx);
  18067. if (ctx->client_wait_events == NULL) {
  18068. const char *err_msg = "Not enough memory for worker event array";
  18069. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18070. mg_free(ctx->worker_threadids);
  18071. if (error != NULL) {
  18072. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18073. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18074. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18075. mg_snprintf(NULL,
  18076. NULL, /* No truncation check for error buffers */
  18077. error->text,
  18078. error->text_buffer_size,
  18079. "%s",
  18080. err_msg);
  18081. }
  18082. free_context(ctx);
  18083. pthread_setspecific(sTlsKey, NULL);
  18084. return NULL;
  18085. }
  18086. ctx->client_socks =
  18087. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  18088. sizeof(ctx->client_socks[0]),
  18089. ctx);
  18090. if (ctx->client_socks == NULL) {
  18091. const char *err_msg = "Not enough memory for worker socket array";
  18092. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18093. mg_free(ctx->client_wait_events);
  18094. mg_free(ctx->worker_threadids);
  18095. if (error != NULL) {
  18096. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18097. error->code_sub = (unsigned)ctx->cfg_worker_threads
  18098. * (unsigned)sizeof(ctx->client_socks[0]);
  18099. mg_snprintf(NULL,
  18100. NULL, /* No truncation check for error buffers */
  18101. error->text,
  18102. error->text_buffer_size,
  18103. "%s",
  18104. err_msg);
  18105. }
  18106. free_context(ctx);
  18107. pthread_setspecific(sTlsKey, NULL);
  18108. return NULL;
  18109. }
  18110. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  18111. ctx->client_wait_events[i] = event_create();
  18112. if (ctx->client_wait_events[i] == 0) {
  18113. const char *err_msg = "Error creating worker event %i";
  18114. mg_cry_ctx_internal(ctx, err_msg, i);
  18115. while (i > 0) {
  18116. i--;
  18117. event_destroy(ctx->client_wait_events[i]);
  18118. }
  18119. mg_free(ctx->client_socks);
  18120. mg_free(ctx->client_wait_events);
  18121. mg_free(ctx->worker_threadids);
  18122. if (error != NULL) {
  18123. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18124. error->code_sub = ERRNO;
  18125. mg_snprintf(NULL,
  18126. NULL, /* No truncation check for error buffers */
  18127. error->text,
  18128. error->text_buffer_size,
  18129. err_msg,
  18130. i);
  18131. }
  18132. free_context(ctx);
  18133. pthread_setspecific(sTlsKey, NULL);
  18134. return NULL;
  18135. }
  18136. }
  18137. #endif
  18138. #if defined(USE_TIMERS)
  18139. if (timers_init(ctx) != 0) {
  18140. const char *err_msg = "Error creating timers";
  18141. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18142. if (error != NULL) {
  18143. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18144. error->code_sub = ERRNO;
  18145. mg_snprintf(NULL,
  18146. NULL, /* No truncation check for error buffers */
  18147. error->text,
  18148. error->text_buffer_size,
  18149. "%s",
  18150. err_msg);
  18151. }
  18152. free_context(ctx);
  18153. pthread_setspecific(sTlsKey, NULL);
  18154. return NULL;
  18155. }
  18156. #endif
  18157. /* Context has been created - init user libraries */
  18158. if (ctx->callbacks.init_context) {
  18159. ctx->callbacks.init_context(ctx);
  18160. }
  18161. /* From now, the context is successfully created.
  18162. * When it is destroyed, the exit callback should be called. */
  18163. ctx->callbacks.exit_context = exit_callback;
  18164. ctx->context_type = CONTEXT_SERVER; /* server context */
  18165. /* Start worker threads */
  18166. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  18167. /* worker_thread sets up the other fields */
  18168. ctx->worker_connections[i].phys_ctx = ctx;
  18169. if (mg_start_thread_with_id(worker_thread,
  18170. &ctx->worker_connections[i],
  18171. &ctx->worker_threadids[i])
  18172. != 0) {
  18173. long error_no = (long)ERRNO;
  18174. /* thread was not created */
  18175. if (i > 0) {
  18176. /* If the second, third, ... thread cannot be created, set a
  18177. * warning, but keep running. */
  18178. mg_cry_ctx_internal(ctx,
  18179. "Cannot start worker thread %i: error %ld",
  18180. i + 1,
  18181. error_no);
  18182. /* If the server initialization should stop here, all
  18183. * threads that have already been created must be stopped
  18184. * first, before any free_context(ctx) call.
  18185. */
  18186. } else {
  18187. /* If the first worker thread cannot be created, stop
  18188. * initialization and free the entire server context. */
  18189. mg_cry_ctx_internal(ctx,
  18190. "Cannot create threads: error %ld",
  18191. error_no);
  18192. if (error != NULL) {
  18193. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18194. error->code_sub = (unsigned)error_no;
  18195. mg_snprintf(
  18196. NULL,
  18197. NULL, /* No truncation check for error buffers */
  18198. error->text,
  18199. error->text_buffer_size,
  18200. "Cannot create first worker thread: error %ld",
  18201. error_no);
  18202. }
  18203. free_context(ctx);
  18204. pthread_setspecific(sTlsKey, NULL);
  18205. return NULL;
  18206. }
  18207. break;
  18208. }
  18209. }
  18210. /* Start master (listening) thread */
  18211. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18212. pthread_setspecific(sTlsKey, NULL);
  18213. return ctx;
  18214. }
  18215. CIVETWEB_API struct mg_context *
  18216. mg_start(const struct mg_callbacks *callbacks,
  18217. void *user_data,
  18218. const char **options)
  18219. {
  18220. struct mg_init_data init = {0};
  18221. init.callbacks = callbacks;
  18222. init.user_data = user_data;
  18223. init.configuration_options = options;
  18224. return mg_start2(&init, NULL);
  18225. }
  18226. /* Add an additional domain to an already running web server. */
  18227. CIVETWEB_API int
  18228. mg_start_domain2(struct mg_context *ctx,
  18229. const char **options,
  18230. struct mg_error_data *error)
  18231. {
  18232. const char *name;
  18233. const char *value;
  18234. const char *default_value;
  18235. struct mg_domain_context *new_dom;
  18236. struct mg_domain_context *dom;
  18237. int idx, i;
  18238. if (error != NULL) {
  18239. error->code = MG_ERROR_DATA_CODE_OK;
  18240. error->code_sub = 0;
  18241. if (error->text_buffer_size > 0) {
  18242. *error->text = 0;
  18243. }
  18244. }
  18245. if ((ctx == NULL) || (options == NULL)) {
  18246. if (error != NULL) {
  18247. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18248. mg_snprintf(NULL,
  18249. NULL, /* No truncation check for error buffers */
  18250. error->text,
  18251. error->text_buffer_size,
  18252. "%s",
  18253. "Invalid parameters");
  18254. }
  18255. return -1;
  18256. }
  18257. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18258. if (error != NULL) {
  18259. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18260. mg_snprintf(NULL,
  18261. NULL, /* No truncation check for error buffers */
  18262. error->text,
  18263. error->text_buffer_size,
  18264. "%s",
  18265. "Server already stopped");
  18266. }
  18267. return -7;
  18268. }
  18269. new_dom = (struct mg_domain_context *)
  18270. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18271. if (!new_dom) {
  18272. /* Out of memory */
  18273. if (error != NULL) {
  18274. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18275. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18276. mg_snprintf(NULL,
  18277. NULL, /* No truncation check for error buffers */
  18278. error->text,
  18279. error->text_buffer_size,
  18280. "%s",
  18281. "Out or memory");
  18282. }
  18283. return -6;
  18284. }
  18285. /* Store options - TODO: unite duplicate code */
  18286. while (options && (name = *options++) != NULL) {
  18287. idx = get_option_index(name);
  18288. if (idx == -1) {
  18289. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18290. if (error != NULL) {
  18291. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18292. error->code_sub = (unsigned)-1;
  18293. mg_snprintf(NULL,
  18294. NULL, /* No truncation check for error buffers */
  18295. error->text,
  18296. error->text_buffer_size,
  18297. "Invalid option: %s",
  18298. name);
  18299. }
  18300. mg_free(new_dom);
  18301. return -2;
  18302. } else if ((value = *options++) == NULL) {
  18303. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18304. if (error != NULL) {
  18305. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18306. error->code_sub = idx;
  18307. mg_snprintf(NULL,
  18308. NULL, /* No truncation check for error buffers */
  18309. error->text,
  18310. error->text_buffer_size,
  18311. "Invalid option value: %s",
  18312. name);
  18313. }
  18314. mg_free(new_dom);
  18315. return -2;
  18316. }
  18317. if (new_dom->config[idx] != NULL) {
  18318. /* Duplicate option: Later values overwrite earlier ones. */
  18319. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18320. mg_free(new_dom->config[idx]);
  18321. }
  18322. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18323. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18324. }
  18325. /* Authentication domain is mandatory */
  18326. /* TODO: Maybe use a new option hostname? */
  18327. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18328. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18329. if (error != NULL) {
  18330. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18331. error->code_sub = AUTHENTICATION_DOMAIN;
  18332. mg_snprintf(NULL,
  18333. NULL, /* No truncation check for error buffers */
  18334. error->text,
  18335. error->text_buffer_size,
  18336. "Mandatory option %s missing",
  18337. config_options[AUTHENTICATION_DOMAIN].name);
  18338. }
  18339. mg_free(new_dom);
  18340. return -4;
  18341. }
  18342. /* Set default value if needed. Take the config value from
  18343. * ctx as a default value. */
  18344. for (i = 0; config_options[i].name != NULL; i++) {
  18345. default_value = ctx->dd.config[i];
  18346. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18347. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18348. }
  18349. }
  18350. new_dom->handlers = NULL;
  18351. new_dom->next = NULL;
  18352. new_dom->nonce_count = 0;
  18353. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18354. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18355. new_dom->shared_lua_websockets = NULL;
  18356. #endif
  18357. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18358. if (!init_ssl_ctx(ctx, new_dom)) {
  18359. /* Init SSL failed */
  18360. if (error != NULL) {
  18361. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18362. mg_snprintf(NULL,
  18363. NULL, /* No truncation check for error buffers */
  18364. error->text,
  18365. error->text_buffer_size,
  18366. "%s",
  18367. "Initializing SSL context failed");
  18368. }
  18369. mg_free(new_dom);
  18370. return -3;
  18371. }
  18372. #endif
  18373. /* Add element to linked list. */
  18374. mg_lock_context(ctx);
  18375. idx = 0;
  18376. dom = &(ctx->dd);
  18377. for (;;) {
  18378. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18379. dom->config[AUTHENTICATION_DOMAIN])) {
  18380. /* Domain collision */
  18381. mg_cry_ctx_internal(ctx,
  18382. "domain %s already in use",
  18383. new_dom->config[AUTHENTICATION_DOMAIN]);
  18384. if (error != NULL) {
  18385. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18386. mg_snprintf(NULL,
  18387. NULL, /* No truncation check for error buffers */
  18388. error->text,
  18389. error->text_buffer_size,
  18390. "Domain %s specified by %s is already in use",
  18391. new_dom->config[AUTHENTICATION_DOMAIN],
  18392. config_options[AUTHENTICATION_DOMAIN].name);
  18393. }
  18394. mg_free(new_dom);
  18395. mg_unlock_context(ctx);
  18396. return -5;
  18397. }
  18398. /* Count number of domains */
  18399. idx++;
  18400. if (dom->next == NULL) {
  18401. dom->next = new_dom;
  18402. break;
  18403. }
  18404. dom = dom->next;
  18405. }
  18406. mg_unlock_context(ctx);
  18407. /* Return domain number */
  18408. return idx;
  18409. }
  18410. CIVETWEB_API int
  18411. mg_start_domain(struct mg_context *ctx, const char **options)
  18412. {
  18413. return mg_start_domain2(ctx, options, NULL);
  18414. }
  18415. /* Feature check API function */
  18416. CIVETWEB_API unsigned
  18417. mg_check_feature(unsigned feature)
  18418. {
  18419. static const unsigned feature_set = 0
  18420. /* Set bits for available features according to API documentation.
  18421. * This bit mask is created at compile time, according to the active
  18422. * preprocessor defines. It is a single const value at runtime. */
  18423. #if !defined(NO_FILES)
  18424. | MG_FEATURES_FILES
  18425. #endif
  18426. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18427. | MG_FEATURES_SSL
  18428. #endif
  18429. #if !defined(NO_CGI)
  18430. | MG_FEATURES_CGI
  18431. #endif
  18432. #if defined(USE_IPV6)
  18433. | MG_FEATURES_IPV6
  18434. #endif
  18435. #if defined(USE_WEBSOCKET)
  18436. | MG_FEATURES_WEBSOCKET
  18437. #endif
  18438. #if defined(USE_LUA)
  18439. | MG_FEATURES_LUA
  18440. #endif
  18441. #if defined(USE_DUKTAPE)
  18442. | MG_FEATURES_SSJS
  18443. #endif
  18444. #if !defined(NO_CACHING)
  18445. | MG_FEATURES_CACHE
  18446. #endif
  18447. #if defined(USE_SERVER_STATS)
  18448. | MG_FEATURES_STATS
  18449. #endif
  18450. #if defined(USE_ZLIB)
  18451. | MG_FEATURES_COMPRESSION
  18452. #endif
  18453. #if defined(USE_HTTP2)
  18454. | MG_FEATURES_HTTP2
  18455. #endif
  18456. #if defined(USE_X_DOM_SOCKET)
  18457. | MG_FEATURES_X_DOMAIN_SOCKET
  18458. #endif
  18459. /* Set some extra bits not defined in the API documentation.
  18460. * These bits may change without further notice. */
  18461. #if defined(MG_LEGACY_INTERFACE)
  18462. | 0x80000000u
  18463. #endif
  18464. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18465. | 0x40000000u
  18466. #endif
  18467. #if !defined(NO_RESPONSE_BUFFERING)
  18468. | 0x20000000u
  18469. #endif
  18470. #if defined(MEMORY_DEBUGGING)
  18471. | 0x10000000u
  18472. #endif
  18473. ;
  18474. return (feature & feature_set);
  18475. }
  18476. static size_t
  18477. mg_str_append(char **dst, char *end, const char *src)
  18478. {
  18479. size_t len = strlen(src);
  18480. if (*dst != end) {
  18481. /* Append src if enough space, or close dst. */
  18482. if ((size_t)(end - *dst) > len) {
  18483. strcpy(*dst, src);
  18484. *dst += len;
  18485. } else {
  18486. *dst = end;
  18487. }
  18488. }
  18489. return len;
  18490. }
  18491. /* Get system information. It can be printed or stored by the caller.
  18492. * Return the size of available information. */
  18493. CIVETWEB_API int
  18494. mg_get_system_info(char *buffer, int buflen)
  18495. {
  18496. char *end, *append_eoobj = NULL, block[256];
  18497. size_t system_info_length = 0;
  18498. #if defined(_WIN32)
  18499. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18500. #else
  18501. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18502. #endif
  18503. if ((buffer == NULL) || (buflen < 1)) {
  18504. buflen = 0;
  18505. end = buffer;
  18506. } else {
  18507. *buffer = 0;
  18508. end = buffer + buflen;
  18509. }
  18510. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18511. /* has enough space to append eoobj */
  18512. append_eoobj = buffer;
  18513. if (end) {
  18514. end -= sizeof(eoobj) - 1;
  18515. }
  18516. }
  18517. system_info_length += mg_str_append(&buffer, end, "{");
  18518. /* Server version */
  18519. {
  18520. const char *version = mg_version();
  18521. mg_snprintf(NULL,
  18522. NULL,
  18523. block,
  18524. sizeof(block),
  18525. "%s\"version\" : \"%s\"",
  18526. eol,
  18527. version);
  18528. system_info_length += mg_str_append(&buffer, end, block);
  18529. }
  18530. /* System info */
  18531. {
  18532. #if defined(_WIN32)
  18533. DWORD dwVersion = 0;
  18534. DWORD dwMajorVersion = 0;
  18535. DWORD dwMinorVersion = 0;
  18536. SYSTEM_INFO si;
  18537. GetSystemInfo(&si);
  18538. #if defined(_MSC_VER)
  18539. #pragma warning(push)
  18540. /* GetVersion was declared deprecated */
  18541. #pragma warning(disable : 4996)
  18542. #endif
  18543. dwVersion = GetVersion();
  18544. #if defined(_MSC_VER)
  18545. #pragma warning(pop)
  18546. #endif
  18547. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18548. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18549. mg_snprintf(NULL,
  18550. NULL,
  18551. block,
  18552. sizeof(block),
  18553. ",%s\"os\" : \"Windows %u.%u\"",
  18554. eol,
  18555. (unsigned)dwMajorVersion,
  18556. (unsigned)dwMinorVersion);
  18557. system_info_length += mg_str_append(&buffer, end, block);
  18558. mg_snprintf(NULL,
  18559. NULL,
  18560. block,
  18561. sizeof(block),
  18562. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18563. eol,
  18564. (unsigned)si.wProcessorArchitecture,
  18565. (unsigned)si.dwNumberOfProcessors,
  18566. (unsigned)si.dwActiveProcessorMask);
  18567. system_info_length += mg_str_append(&buffer, end, block);
  18568. #elif defined(__ZEPHYR__)
  18569. mg_snprintf(NULL,
  18570. NULL,
  18571. block,
  18572. sizeof(block),
  18573. ",%s\"os\" : \"%s %s\"",
  18574. eol,
  18575. "Zephyr OS",
  18576. ZEPHYR_VERSION);
  18577. system_info_length += mg_str_append(&buffer, end, block);
  18578. #else
  18579. struct utsname name;
  18580. memset(&name, 0, sizeof(name));
  18581. uname(&name);
  18582. mg_snprintf(NULL,
  18583. NULL,
  18584. block,
  18585. sizeof(block),
  18586. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18587. eol,
  18588. name.sysname,
  18589. name.version,
  18590. name.release,
  18591. name.machine);
  18592. system_info_length += mg_str_append(&buffer, end, block);
  18593. #endif
  18594. }
  18595. /* Features */
  18596. {
  18597. mg_snprintf(NULL,
  18598. NULL,
  18599. block,
  18600. sizeof(block),
  18601. ",%s\"features\" : %lu"
  18602. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18603. eol,
  18604. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18605. eol,
  18606. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18607. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18608. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18609. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18610. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18611. : "",
  18612. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18613. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18614. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18615. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18616. system_info_length += mg_str_append(&buffer, end, block);
  18617. #if defined(USE_LUA)
  18618. mg_snprintf(NULL,
  18619. NULL,
  18620. block,
  18621. sizeof(block),
  18622. ",%s\"lua_version\" : \"%u (%s)\"",
  18623. eol,
  18624. (unsigned)LUA_VERSION_NUM,
  18625. LUA_RELEASE);
  18626. system_info_length += mg_str_append(&buffer, end, block);
  18627. #endif
  18628. #if defined(USE_DUKTAPE)
  18629. mg_snprintf(NULL,
  18630. NULL,
  18631. block,
  18632. sizeof(block),
  18633. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18634. eol,
  18635. (unsigned)DUK_VERSION / 10000,
  18636. ((unsigned)DUK_VERSION / 100) % 100,
  18637. (unsigned)DUK_VERSION % 100);
  18638. system_info_length += mg_str_append(&buffer, end, block);
  18639. #endif
  18640. }
  18641. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18642. {
  18643. #if defined(BUILD_DATE)
  18644. const char *bd = BUILD_DATE;
  18645. #else
  18646. #if defined(GCC_DIAGNOSTIC)
  18647. #if GCC_VERSION >= 40900
  18648. #pragma GCC diagnostic push
  18649. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18650. * does not work in some versions. If "BUILD_DATE" is defined to some
  18651. * string, it is used instead of __DATE__. */
  18652. #pragma GCC diagnostic ignored "-Wdate-time"
  18653. #endif
  18654. #endif
  18655. const char *bd = __DATE__;
  18656. #if defined(GCC_DIAGNOSTIC)
  18657. #if GCC_VERSION >= 40900
  18658. #pragma GCC diagnostic pop
  18659. #endif
  18660. #endif
  18661. #endif
  18662. mg_snprintf(
  18663. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18664. system_info_length += mg_str_append(&buffer, end, block);
  18665. }
  18666. /* Compiler information */
  18667. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18668. {
  18669. #if defined(_MSC_VER)
  18670. mg_snprintf(NULL,
  18671. NULL,
  18672. block,
  18673. sizeof(block),
  18674. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18675. eol,
  18676. (unsigned)_MSC_VER,
  18677. (unsigned)_MSC_FULL_VER);
  18678. system_info_length += mg_str_append(&buffer, end, block);
  18679. #elif defined(__MINGW64__)
  18680. mg_snprintf(NULL,
  18681. NULL,
  18682. block,
  18683. sizeof(block),
  18684. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18685. eol,
  18686. (unsigned)__MINGW64_VERSION_MAJOR,
  18687. (unsigned)__MINGW64_VERSION_MINOR);
  18688. system_info_length += mg_str_append(&buffer, end, block);
  18689. mg_snprintf(NULL,
  18690. NULL,
  18691. block,
  18692. sizeof(block),
  18693. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18694. eol,
  18695. (unsigned)__MINGW32_MAJOR_VERSION,
  18696. (unsigned)__MINGW32_MINOR_VERSION);
  18697. system_info_length += mg_str_append(&buffer, end, block);
  18698. #elif defined(__MINGW32__)
  18699. mg_snprintf(NULL,
  18700. NULL,
  18701. block,
  18702. sizeof(block),
  18703. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18704. eol,
  18705. (unsigned)__MINGW32_MAJOR_VERSION,
  18706. (unsigned)__MINGW32_MINOR_VERSION);
  18707. system_info_length += mg_str_append(&buffer, end, block);
  18708. #elif defined(__clang__)
  18709. mg_snprintf(NULL,
  18710. NULL,
  18711. block,
  18712. sizeof(block),
  18713. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18714. eol,
  18715. __clang_major__,
  18716. __clang_minor__,
  18717. __clang_patchlevel__,
  18718. __clang_version__);
  18719. system_info_length += mg_str_append(&buffer, end, block);
  18720. #elif defined(__GNUC__)
  18721. mg_snprintf(NULL,
  18722. NULL,
  18723. block,
  18724. sizeof(block),
  18725. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18726. eol,
  18727. (unsigned)__GNUC__,
  18728. (unsigned)__GNUC_MINOR__,
  18729. (unsigned)__GNUC_PATCHLEVEL__);
  18730. system_info_length += mg_str_append(&buffer, end, block);
  18731. #elif defined(__INTEL_COMPILER)
  18732. mg_snprintf(NULL,
  18733. NULL,
  18734. block,
  18735. sizeof(block),
  18736. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18737. eol,
  18738. (unsigned)__INTEL_COMPILER);
  18739. system_info_length += mg_str_append(&buffer, end, block);
  18740. #elif defined(__BORLANDC__)
  18741. mg_snprintf(NULL,
  18742. NULL,
  18743. block,
  18744. sizeof(block),
  18745. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18746. eol,
  18747. (unsigned)__BORLANDC__);
  18748. system_info_length += mg_str_append(&buffer, end, block);
  18749. #elif defined(__SUNPRO_C)
  18750. mg_snprintf(NULL,
  18751. NULL,
  18752. block,
  18753. sizeof(block),
  18754. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18755. eol,
  18756. (unsigned)__SUNPRO_C);
  18757. system_info_length += mg_str_append(&buffer, end, block);
  18758. #else
  18759. mg_snprintf(NULL,
  18760. NULL,
  18761. block,
  18762. sizeof(block),
  18763. ",%s\"compiler\" : \"other\"",
  18764. eol);
  18765. system_info_length += mg_str_append(&buffer, end, block);
  18766. #endif
  18767. }
  18768. /* Determine 32/64 bit data mode.
  18769. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18770. {
  18771. mg_snprintf(NULL,
  18772. NULL,
  18773. block,
  18774. sizeof(block),
  18775. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18776. "char:%u/%u, "
  18777. "ptr:%u, size:%u, time:%u\"",
  18778. eol,
  18779. (unsigned)sizeof(short),
  18780. (unsigned)sizeof(int),
  18781. (unsigned)sizeof(long),
  18782. (unsigned)sizeof(long long),
  18783. (unsigned)sizeof(float),
  18784. (unsigned)sizeof(double),
  18785. (unsigned)sizeof(long double),
  18786. (unsigned)sizeof(char),
  18787. (unsigned)sizeof(wchar_t),
  18788. (unsigned)sizeof(void *),
  18789. (unsigned)sizeof(size_t),
  18790. (unsigned)sizeof(time_t));
  18791. system_info_length += mg_str_append(&buffer, end, block);
  18792. }
  18793. /* Terminate string */
  18794. if (append_eoobj) {
  18795. strcat(append_eoobj, eoobj);
  18796. }
  18797. system_info_length += sizeof(eoobj) - 1;
  18798. return (int)system_info_length;
  18799. }
  18800. /* Get context information. It can be printed or stored by the caller.
  18801. * Return the size of available information. */
  18802. CIVETWEB_API int
  18803. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18804. {
  18805. #if defined(USE_SERVER_STATS)
  18806. char *end, *append_eoobj = NULL, block[256];
  18807. size_t context_info_length = 0;
  18808. #if defined(_WIN32)
  18809. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18810. #else
  18811. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18812. #endif
  18813. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18814. if ((buffer == NULL) || (buflen < 1)) {
  18815. buflen = 0;
  18816. end = buffer;
  18817. } else {
  18818. *buffer = 0;
  18819. end = buffer + buflen;
  18820. }
  18821. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18822. /* has enough space to append eoobj */
  18823. append_eoobj = buffer;
  18824. end -= sizeof(eoobj) - 1;
  18825. }
  18826. context_info_length += mg_str_append(&buffer, end, "{");
  18827. if (ms) { /* <-- should be always true */
  18828. /* Memory information */
  18829. int blockCount = (int)ms->blockCount;
  18830. int64_t totalMemUsed = ms->totalMemUsed;
  18831. int64_t maxMemUsed = ms->maxMemUsed;
  18832. if (totalMemUsed > maxMemUsed) {
  18833. maxMemUsed = totalMemUsed;
  18834. }
  18835. mg_snprintf(NULL,
  18836. NULL,
  18837. block,
  18838. sizeof(block),
  18839. "%s\"memory\" : {%s"
  18840. "\"blocks\" : %i,%s"
  18841. "\"used\" : %" INT64_FMT ",%s"
  18842. "\"maxUsed\" : %" INT64_FMT "%s"
  18843. "}",
  18844. eol,
  18845. eol,
  18846. blockCount,
  18847. eol,
  18848. totalMemUsed,
  18849. eol,
  18850. maxMemUsed,
  18851. eol);
  18852. context_info_length += mg_str_append(&buffer, end, block);
  18853. }
  18854. if (ctx) {
  18855. /* Declare all variables at begin of the block, to comply
  18856. * with old C standards. */
  18857. char start_time_str[64] = {0};
  18858. char now_str[64] = {0};
  18859. time_t start_time = ctx->start_time;
  18860. time_t now = time(NULL);
  18861. int64_t total_data_read, total_data_written;
  18862. int active_connections = (int)ctx->active_connections;
  18863. int max_active_connections = (int)ctx->max_active_connections;
  18864. int total_connections = (int)ctx->total_connections;
  18865. if (active_connections > max_active_connections) {
  18866. max_active_connections = active_connections;
  18867. }
  18868. if (active_connections > total_connections) {
  18869. total_connections = active_connections;
  18870. }
  18871. /* Connections information */
  18872. mg_snprintf(NULL,
  18873. NULL,
  18874. block,
  18875. sizeof(block),
  18876. ",%s\"connections\" : {%s"
  18877. "\"active\" : %i,%s"
  18878. "\"maxActive\" : %i,%s"
  18879. "\"total\" : %i%s"
  18880. "}",
  18881. eol,
  18882. eol,
  18883. active_connections,
  18884. eol,
  18885. max_active_connections,
  18886. eol,
  18887. total_connections,
  18888. eol);
  18889. context_info_length += mg_str_append(&buffer, end, block);
  18890. /* Queue information */
  18891. #if !defined(ALTERNATIVE_QUEUE)
  18892. mg_snprintf(NULL,
  18893. NULL,
  18894. block,
  18895. sizeof(block),
  18896. ",%s\"queue\" : {%s"
  18897. "\"length\" : %i,%s"
  18898. "\"filled\" : %i,%s"
  18899. "\"maxFilled\" : %i,%s"
  18900. "\"full\" : %s%s"
  18901. "}",
  18902. eol,
  18903. eol,
  18904. ctx->sq_size,
  18905. eol,
  18906. ctx->sq_head - ctx->sq_tail,
  18907. eol,
  18908. ctx->sq_max_fill,
  18909. eol,
  18910. (ctx->sq_blocked ? "true" : "false"),
  18911. eol);
  18912. context_info_length += mg_str_append(&buffer, end, block);
  18913. #endif
  18914. /* Requests information */
  18915. mg_snprintf(NULL,
  18916. NULL,
  18917. block,
  18918. sizeof(block),
  18919. ",%s\"requests\" : {%s"
  18920. "\"total\" : %lu%s"
  18921. "}",
  18922. eol,
  18923. eol,
  18924. (unsigned long)ctx->total_requests,
  18925. eol);
  18926. context_info_length += mg_str_append(&buffer, end, block);
  18927. /* Data information */
  18928. total_data_read =
  18929. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18930. total_data_written =
  18931. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18932. mg_snprintf(NULL,
  18933. NULL,
  18934. block,
  18935. sizeof(block),
  18936. ",%s\"data\" : {%s"
  18937. "\"read\" : %" INT64_FMT ",%s"
  18938. "\"written\" : %" INT64_FMT "%s"
  18939. "}",
  18940. eol,
  18941. eol,
  18942. total_data_read,
  18943. eol,
  18944. total_data_written,
  18945. eol);
  18946. context_info_length += mg_str_append(&buffer, end, block);
  18947. /* Execution time information */
  18948. gmt_time_string(start_time_str,
  18949. sizeof(start_time_str) - 1,
  18950. &start_time);
  18951. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18952. mg_snprintf(NULL,
  18953. NULL,
  18954. block,
  18955. sizeof(block),
  18956. ",%s\"time\" : {%s"
  18957. "\"uptime\" : %.0f,%s"
  18958. "\"start\" : \"%s\",%s"
  18959. "\"now\" : \"%s\"%s"
  18960. "}",
  18961. eol,
  18962. eol,
  18963. difftime(now, start_time),
  18964. eol,
  18965. start_time_str,
  18966. eol,
  18967. now_str,
  18968. eol);
  18969. context_info_length += mg_str_append(&buffer, end, block);
  18970. }
  18971. /* Terminate string */
  18972. if (append_eoobj) {
  18973. strcat(append_eoobj, eoobj);
  18974. }
  18975. context_info_length += sizeof(eoobj) - 1;
  18976. return (int)context_info_length;
  18977. #else
  18978. (void)ctx;
  18979. if ((buffer != NULL) && (buflen > 0)) {
  18980. *buffer = 0;
  18981. }
  18982. return 0;
  18983. #endif
  18984. }
  18985. CIVETWEB_API void
  18986. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18987. {
  18988. /* https://github.com/civetweb/civetweb/issues/727 */
  18989. if (conn != NULL) {
  18990. conn->must_close = 1;
  18991. }
  18992. }
  18993. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18994. /* Get connection information. It can be printed or stored by the caller.
  18995. * Return the size of available information. */
  18996. CIVETWEB_API int
  18997. mg_get_connection_info(const struct mg_context *ctx,
  18998. int idx,
  18999. char *buffer,
  19000. int buflen)
  19001. {
  19002. const struct mg_connection *conn;
  19003. const struct mg_request_info *ri;
  19004. char *end, *append_eoobj = NULL, block[256];
  19005. size_t connection_info_length = 0;
  19006. int state = 0;
  19007. const char *state_str = "unknown";
  19008. #if defined(_WIN32)
  19009. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19010. #else
  19011. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19012. #endif
  19013. if ((buffer == NULL) || (buflen < 1)) {
  19014. buflen = 0;
  19015. end = buffer;
  19016. } else {
  19017. *buffer = 0;
  19018. end = buffer + buflen;
  19019. }
  19020. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19021. /* has enough space to append eoobj */
  19022. append_eoobj = buffer;
  19023. end -= sizeof(eoobj) - 1;
  19024. }
  19025. if ((ctx == NULL) || (idx < 0)) {
  19026. /* Parameter error */
  19027. return 0;
  19028. }
  19029. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  19030. /* Out of range */
  19031. return 0;
  19032. }
  19033. /* Take connection [idx]. This connection is not locked in
  19034. * any way, so some other thread might use it. */
  19035. conn = (ctx->worker_connections) + idx;
  19036. /* Initialize output string */
  19037. connection_info_length += mg_str_append(&buffer, end, "{");
  19038. /* Init variables */
  19039. ri = &(conn->request_info);
  19040. #if defined(USE_SERVER_STATS)
  19041. state = conn->conn_state;
  19042. /* State as string */
  19043. switch (state) {
  19044. case 0:
  19045. state_str = "undefined";
  19046. break;
  19047. case 1:
  19048. state_str = "not used";
  19049. break;
  19050. case 2:
  19051. state_str = "init";
  19052. break;
  19053. case 3:
  19054. state_str = "ready";
  19055. break;
  19056. case 4:
  19057. state_str = "processing";
  19058. break;
  19059. case 5:
  19060. state_str = "processed";
  19061. break;
  19062. case 6:
  19063. state_str = "to close";
  19064. break;
  19065. case 7:
  19066. state_str = "closing";
  19067. break;
  19068. case 8:
  19069. state_str = "closed";
  19070. break;
  19071. case 9:
  19072. state_str = "done";
  19073. break;
  19074. }
  19075. #endif
  19076. /* Connection info */
  19077. if ((state >= 3) && (state < 9)) {
  19078. mg_snprintf(NULL,
  19079. NULL,
  19080. block,
  19081. sizeof(block),
  19082. "%s\"connection\" : {%s"
  19083. "\"remote\" : {%s"
  19084. "\"protocol\" : \"%s\",%s"
  19085. "\"addr\" : \"%s\",%s"
  19086. "\"port\" : %u%s"
  19087. "},%s"
  19088. "\"handled_requests\" : %u%s"
  19089. "}",
  19090. eol,
  19091. eol,
  19092. eol,
  19093. get_proto_name(conn),
  19094. eol,
  19095. ri->remote_addr,
  19096. eol,
  19097. ri->remote_port,
  19098. eol,
  19099. eol,
  19100. conn->handled_requests,
  19101. eol);
  19102. connection_info_length += mg_str_append(&buffer, end, block);
  19103. }
  19104. /* Request info */
  19105. if ((state >= 4) && (state < 6)) {
  19106. mg_snprintf(NULL,
  19107. NULL,
  19108. block,
  19109. sizeof(block),
  19110. "%s%s\"request_info\" : {%s"
  19111. "\"method\" : \"%s\",%s"
  19112. "\"uri\" : \"%s\",%s"
  19113. "\"query\" : %s%s%s%s"
  19114. "}",
  19115. (connection_info_length > 1 ? "," : ""),
  19116. eol,
  19117. eol,
  19118. ri->request_method,
  19119. eol,
  19120. ri->request_uri,
  19121. eol,
  19122. ri->query_string ? "\"" : "",
  19123. ri->query_string ? ri->query_string : "null",
  19124. ri->query_string ? "\"" : "",
  19125. eol);
  19126. connection_info_length += mg_str_append(&buffer, end, block);
  19127. }
  19128. /* Execution time information */
  19129. if ((state >= 2) && (state < 9)) {
  19130. char start_time_str[64] = {0};
  19131. char close_time_str[64] = {0};
  19132. time_t start_time = conn->conn_birth_time;
  19133. time_t close_time = 0;
  19134. double time_diff;
  19135. gmt_time_string(start_time_str,
  19136. sizeof(start_time_str) - 1,
  19137. &start_time);
  19138. #if defined(USE_SERVER_STATS)
  19139. close_time = conn->conn_close_time;
  19140. #endif
  19141. if (close_time != 0) {
  19142. time_diff = difftime(close_time, start_time);
  19143. gmt_time_string(close_time_str,
  19144. sizeof(close_time_str) - 1,
  19145. &close_time);
  19146. } else {
  19147. time_t now = time(NULL);
  19148. time_diff = difftime(now, start_time);
  19149. close_time_str[0] = 0; /* or use "now" ? */
  19150. }
  19151. mg_snprintf(NULL,
  19152. NULL,
  19153. block,
  19154. sizeof(block),
  19155. "%s%s\"time\" : {%s"
  19156. "\"uptime\" : %.0f,%s"
  19157. "\"start\" : \"%s\",%s"
  19158. "\"closed\" : \"%s\"%s"
  19159. "}",
  19160. (connection_info_length > 1 ? "," : ""),
  19161. eol,
  19162. eol,
  19163. time_diff,
  19164. eol,
  19165. start_time_str,
  19166. eol,
  19167. close_time_str,
  19168. eol);
  19169. connection_info_length += mg_str_append(&buffer, end, block);
  19170. }
  19171. /* Remote user name */
  19172. if ((ri->remote_user) && (state < 9)) {
  19173. mg_snprintf(NULL,
  19174. NULL,
  19175. block,
  19176. sizeof(block),
  19177. "%s%s\"user\" : {%s"
  19178. "\"name\" : \"%s\",%s"
  19179. "}",
  19180. (connection_info_length > 1 ? "," : ""),
  19181. eol,
  19182. eol,
  19183. ri->remote_user,
  19184. eol);
  19185. connection_info_length += mg_str_append(&buffer, end, block);
  19186. }
  19187. /* Data block */
  19188. if (state >= 3) {
  19189. mg_snprintf(NULL,
  19190. NULL,
  19191. block,
  19192. sizeof(block),
  19193. "%s%s\"data\" : {%s"
  19194. "\"read\" : %" INT64_FMT ",%s"
  19195. "\"written\" : %" INT64_FMT "%s"
  19196. "}",
  19197. (connection_info_length > 1 ? "," : ""),
  19198. eol,
  19199. eol,
  19200. conn->consumed_content,
  19201. eol,
  19202. conn->num_bytes_sent,
  19203. eol);
  19204. connection_info_length += mg_str_append(&buffer, end, block);
  19205. }
  19206. /* State */
  19207. mg_snprintf(NULL,
  19208. NULL,
  19209. block,
  19210. sizeof(block),
  19211. "%s%s\"state\" : \"%s\"",
  19212. (connection_info_length > 1 ? "," : ""),
  19213. eol,
  19214. state_str);
  19215. connection_info_length += mg_str_append(&buffer, end, block);
  19216. /* Terminate string */
  19217. if (append_eoobj) {
  19218. strcat(append_eoobj, eoobj);
  19219. }
  19220. connection_info_length += sizeof(eoobj) - 1;
  19221. return (int)connection_info_length;
  19222. }
  19223. #if 0
  19224. /* Get handler information. It can be printed or stored by the caller.
  19225. * Return the size of available information. */
  19226. CIVETWEB_API int
  19227. mg_get_handler_info(struct mg_context *ctx,
  19228. char *buffer,
  19229. int buflen)
  19230. {
  19231. int handler_info_len = 0;
  19232. struct mg_handler_info *tmp_rh;
  19233. mg_lock_context(ctx);
  19234. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19235. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19236. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19237. }
  19238. handler_info_len += tmp_rh->uri_len;
  19239. switch (tmp_rh->handler_type) {
  19240. case REQUEST_HANDLER:
  19241. (void)tmp_rh->handler;
  19242. break;
  19243. case WEBSOCKET_HANDLER:
  19244. (void)tmp_rh->connect_handler;
  19245. (void) tmp_rh->ready_handler;
  19246. (void) tmp_rh->data_handler;
  19247. (void) tmp_rh->close_handler;
  19248. break;
  19249. case AUTH_HANDLER:
  19250. (void) tmp_rh->auth_handler;
  19251. break;
  19252. }
  19253. (void)cbdata;
  19254. }
  19255. mg_unlock_context(ctx);
  19256. return handler_info_len;
  19257. }
  19258. #endif
  19259. #endif
  19260. /* Initialize this library. This function does not need to be thread safe.
  19261. */
  19262. CIVETWEB_API unsigned
  19263. mg_init_library(unsigned features)
  19264. {
  19265. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19266. unsigned features_inited = features_to_init;
  19267. if (mg_init_library_called <= 0) {
  19268. /* Not initialized yet */
  19269. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19270. return 0;
  19271. }
  19272. }
  19273. mg_global_lock();
  19274. if (mg_init_library_called <= 0) {
  19275. int i, len;
  19276. #if defined(_WIN32)
  19277. int file_mutex_init = 1;
  19278. int wsa = 1;
  19279. #else
  19280. int mutexattr_init = 1;
  19281. #endif
  19282. int failed = 1;
  19283. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19284. if (key_create == 0) {
  19285. #if defined(_WIN32)
  19286. file_mutex_init =
  19287. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19288. if (file_mutex_init == 0) {
  19289. /* Start WinSock */
  19290. WSADATA data;
  19291. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19292. }
  19293. #else
  19294. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19295. if (mutexattr_init == 0) {
  19296. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19297. PTHREAD_MUTEX_RECURSIVE);
  19298. }
  19299. #endif
  19300. }
  19301. if (failed) {
  19302. #if defined(_WIN32)
  19303. if (wsa == 0) {
  19304. (void)WSACleanup();
  19305. }
  19306. if (file_mutex_init == 0) {
  19307. (void)pthread_mutex_destroy(&global_log_file_lock);
  19308. }
  19309. #else
  19310. if (mutexattr_init == 0) {
  19311. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19312. }
  19313. #endif
  19314. if (key_create == 0) {
  19315. (void)pthread_key_delete(sTlsKey);
  19316. }
  19317. mg_global_unlock();
  19318. (void)pthread_mutex_destroy(&global_lock_mutex);
  19319. return 0;
  19320. }
  19321. #if defined(USE_LUA)
  19322. lua_init_optional_libraries();
  19323. #endif
  19324. len = 1;
  19325. for (i = 0; http_methods[i].name != NULL; i++) {
  19326. size_t sl = strlen(http_methods[i].name);
  19327. len += (int)sl;
  19328. if (i > 0) {
  19329. len += 2;
  19330. }
  19331. }
  19332. all_methods = mg_malloc(len);
  19333. if (!all_methods) {
  19334. /* Must never happen */
  19335. return 0;
  19336. }
  19337. all_methods[0] = 0;
  19338. for (i = 0; http_methods[i].name != NULL; i++) {
  19339. if (i > 0) {
  19340. strcat(all_methods, ", ");
  19341. strcat(all_methods, http_methods[i].name);
  19342. } else {
  19343. strcpy(all_methods, http_methods[i].name);
  19344. }
  19345. }
  19346. }
  19347. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19348. || defined(OPENSSL_API_3_0)) \
  19349. && !defined(NO_SSL)
  19350. if (features_to_init & MG_FEATURES_SSL) {
  19351. if (!mg_openssl_initialized) {
  19352. char ebuf[128];
  19353. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19354. mg_openssl_initialized = 1;
  19355. } else {
  19356. (void)ebuf;
  19357. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19358. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19359. }
  19360. } else {
  19361. /* ssl already initialized */
  19362. }
  19363. }
  19364. #endif
  19365. if (mg_init_library_called <= 0) {
  19366. mg_init_library_called = 1;
  19367. } else {
  19368. mg_init_library_called++;
  19369. }
  19370. mg_global_unlock();
  19371. return features_inited;
  19372. }
  19373. /* Un-initialize this library. */
  19374. CIVETWEB_API unsigned
  19375. mg_exit_library(void)
  19376. {
  19377. if (mg_init_library_called <= 0) {
  19378. return 0;
  19379. }
  19380. mg_global_lock();
  19381. mg_init_library_called--;
  19382. if (mg_init_library_called == 0) {
  19383. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19384. if (mg_openssl_initialized) {
  19385. uninitialize_openssl();
  19386. mg_openssl_initialized = 0;
  19387. }
  19388. #endif
  19389. #if defined(_WIN32)
  19390. (void)WSACleanup();
  19391. (void)pthread_mutex_destroy(&global_log_file_lock);
  19392. #else
  19393. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19394. #endif
  19395. (void)pthread_key_delete(sTlsKey);
  19396. #if defined(USE_LUA)
  19397. lua_exit_optional_libraries();
  19398. #endif
  19399. mg_free(all_methods);
  19400. all_methods = NULL;
  19401. mg_global_unlock();
  19402. (void)pthread_mutex_destroy(&global_lock_mutex);
  19403. return 1;
  19404. }
  19405. mg_global_unlock();
  19406. return 1;
  19407. }
  19408. /* End of civetweb.c */