civetweb.c 586 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115
  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. #define qsort_r(base, num, with, comp, arg) \
  486. qsort_s(base, \
  487. num, \
  488. with, \
  489. (int(__cdecl *)(void *, const void *, const void *))comp, \
  490. arg)
  491. #endif /* _MSC_VER */
  492. #define ERRNO ((int)(GetLastError()))
  493. #define NO_SOCKLEN_T
  494. #if defined(_WIN64) || defined(__MINGW64__)
  495. #if !defined(SSL_LIB)
  496. #if defined(OPENSSL_API_3_0)
  497. #define SSL_LIB "libssl-3-x64.dll"
  498. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  499. #endif
  500. #if defined(OPENSSL_API_1_1)
  501. #define SSL_LIB "libssl-1_1-x64.dll"
  502. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  503. #endif /* OPENSSL_API_1_1 */
  504. #if defined(OPENSSL_API_1_0)
  505. #define SSL_LIB "ssleay64.dll"
  506. #define CRYPTO_LIB "libeay64.dll"
  507. #endif /* OPENSSL_API_1_0 */
  508. #endif
  509. #else /* defined(_WIN64) || defined(__MINGW64__) */
  510. #if !defined(SSL_LIB)
  511. #if defined(OPENSSL_API_3_0)
  512. #define SSL_LIB "libssl-3.dll"
  513. #define CRYPTO_LIB "libcrypto-3.dll"
  514. #endif
  515. #if defined(OPENSSL_API_1_1)
  516. #define SSL_LIB "libssl-1_1.dll"
  517. #define CRYPTO_LIB "libcrypto-1_1.dll"
  518. #endif /* OPENSSL_API_1_1 */
  519. #if defined(OPENSSL_API_1_0)
  520. #define SSL_LIB "ssleay32.dll"
  521. #define CRYPTO_LIB "libeay32.dll"
  522. #endif /* OPENSSL_API_1_0 */
  523. #endif /* SSL_LIB */
  524. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  525. #define O_NONBLOCK (0)
  526. #if !defined(W_OK)
  527. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  528. #endif
  529. #define _POSIX_
  530. #define INT64_FMT "I64d"
  531. #define UINT64_FMT "I64u"
  532. #define WINCDECL __cdecl
  533. #define vsnprintf_impl _vsnprintf
  534. #define access _access
  535. #define mg_sleep(x) (Sleep(x))
  536. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  537. #if !defined(popen)
  538. #define popen(x, y) (_popen(x, y))
  539. #endif
  540. #if !defined(pclose)
  541. #define pclose(x) (_pclose(x))
  542. #endif
  543. #define close(x) (_close(x))
  544. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  545. #define RTLD_LAZY (0)
  546. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  547. #define fdopen(x, y) (_fdopen((x), (y)))
  548. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  549. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  550. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  551. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  552. #define sleep(x) (Sleep((x)*1000))
  553. #define rmdir(x) (_rmdir(x))
  554. #if defined(_WIN64) || !defined(__MINGW32__)
  555. /* Only MinGW 32 bit is missing this function */
  556. #define timegm(x) (_mkgmtime(x))
  557. #else
  558. time_t timegm(struct tm *tm);
  559. #define NEED_TIMEGM
  560. #endif
  561. #if !defined(fileno)
  562. #define fileno(x) (_fileno(x))
  563. #endif /* !fileno MINGW #defines fileno */
  564. typedef struct {
  565. CRITICAL_SECTION sec; /* Immovable */
  566. } pthread_mutex_t;
  567. typedef DWORD pthread_key_t;
  568. typedef HANDLE pthread_t;
  569. typedef struct {
  570. pthread_mutex_t threadIdSec;
  571. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  572. } pthread_cond_t;
  573. #if !defined(__clockid_t_defined)
  574. typedef DWORD clockid_t;
  575. #endif
  576. #if !defined(CLOCK_MONOTONIC)
  577. #define CLOCK_MONOTONIC (1)
  578. #endif
  579. #if !defined(CLOCK_REALTIME)
  580. #define CLOCK_REALTIME (2)
  581. #endif
  582. #if !defined(CLOCK_THREAD)
  583. #define CLOCK_THREAD (3)
  584. #endif
  585. #if !defined(CLOCK_PROCESS)
  586. #define CLOCK_PROCESS (4)
  587. #endif
  588. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  589. #define _TIMESPEC_DEFINED
  590. #endif
  591. #if !defined(_TIMESPEC_DEFINED)
  592. struct timespec {
  593. time_t tv_sec; /* seconds */
  594. long tv_nsec; /* nanoseconds */
  595. };
  596. #endif
  597. #if !defined(WIN_PTHREADS_TIME_H)
  598. #define MUST_IMPLEMENT_CLOCK_GETTIME
  599. #endif
  600. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  601. #define clock_gettime mg_clock_gettime
  602. static int
  603. clock_gettime(clockid_t clk_id, struct timespec *tp)
  604. {
  605. FILETIME ft;
  606. ULARGE_INTEGER li, li2;
  607. BOOL ok = FALSE;
  608. double d;
  609. static double perfcnt_per_sec = 0.0;
  610. static BOOL initialized = FALSE;
  611. if (!initialized) {
  612. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  613. perfcnt_per_sec = 1.0 / li.QuadPart;
  614. initialized = TRUE;
  615. }
  616. if (tp) {
  617. memset(tp, 0, sizeof(*tp));
  618. if (clk_id == CLOCK_REALTIME) {
  619. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  620. GetSystemTimeAsFileTime(&ft);
  621. li.LowPart = ft.dwLowDateTime;
  622. li.HighPart = ft.dwHighDateTime;
  623. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  624. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  625. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  626. ok = TRUE;
  627. /* END: CLOCK_REALTIME */
  628. } else if (clk_id == CLOCK_MONOTONIC) {
  629. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  630. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  631. d = li.QuadPart * perfcnt_per_sec;
  632. tp->tv_sec = (time_t)d;
  633. d -= (double)tp->tv_sec;
  634. tp->tv_nsec = (long)(d * 1.0E9);
  635. ok = TRUE;
  636. /* END: CLOCK_MONOTONIC */
  637. } else if (clk_id == CLOCK_THREAD) {
  638. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  639. FILETIME t_create, t_exit, t_kernel, t_user;
  640. if (GetThreadTimes(GetCurrentThread(),
  641. &t_create,
  642. &t_exit,
  643. &t_kernel,
  644. &t_user)) {
  645. li.LowPart = t_user.dwLowDateTime;
  646. li.HighPart = t_user.dwHighDateTime;
  647. li2.LowPart = t_kernel.dwLowDateTime;
  648. li2.HighPart = t_kernel.dwHighDateTime;
  649. li.QuadPart += li2.QuadPart;
  650. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  651. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  652. ok = TRUE;
  653. }
  654. /* END: CLOCK_THREAD */
  655. } else if (clk_id == CLOCK_PROCESS) {
  656. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  657. FILETIME t_create, t_exit, t_kernel, t_user;
  658. if (GetProcessTimes(GetCurrentProcess(),
  659. &t_create,
  660. &t_exit,
  661. &t_kernel,
  662. &t_user)) {
  663. li.LowPart = t_user.dwLowDateTime;
  664. li.HighPart = t_user.dwHighDateTime;
  665. li2.LowPart = t_kernel.dwLowDateTime;
  666. li2.HighPart = t_kernel.dwHighDateTime;
  667. li.QuadPart += li2.QuadPart;
  668. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  669. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  670. ok = TRUE;
  671. }
  672. /* END: CLOCK_PROCESS */
  673. } else {
  674. /* BEGIN: unknown clock */
  675. /* ok = FALSE; already set by init */
  676. /* END: unknown clock */
  677. }
  678. }
  679. return ok ? 0 : -1;
  680. }
  681. #endif
  682. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  683. static int pthread_mutex_lock(pthread_mutex_t *);
  684. static int pthread_mutex_unlock(pthread_mutex_t *);
  685. static void path_to_unicode(const struct mg_connection *conn,
  686. const char *path,
  687. wchar_t *wbuf,
  688. size_t wbuf_len);
  689. /* All file operations need to be rewritten to solve #246. */
  690. struct mg_file;
  691. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  692. /* POSIX dirent interface */
  693. struct dirent {
  694. char d_name[UTF8_PATH_MAX];
  695. };
  696. typedef struct DIR {
  697. HANDLE handle;
  698. WIN32_FIND_DATAW info;
  699. struct dirent result;
  700. } DIR;
  701. #if defined(HAVE_POLL)
  702. #define mg_pollfd pollfd
  703. #else
  704. struct mg_pollfd {
  705. SOCKET fd;
  706. short events;
  707. short revents;
  708. };
  709. #endif
  710. /* Mark required libraries */
  711. #if defined(_MSC_VER)
  712. #pragma comment(lib, "Ws2_32.lib")
  713. #endif
  714. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  715. #include <inttypes.h>
  716. /* Linux & co. internally use UTF8 */
  717. #define UTF8_PATH_MAX (PATH_MAX)
  718. typedef const void *SOCK_OPT_TYPE;
  719. #if defined(ANDROID)
  720. typedef unsigned short int in_port_t;
  721. #endif
  722. #if !defined(__ZEPHYR__)
  723. #include <arpa/inet.h>
  724. #include <ctype.h>
  725. #include <dirent.h>
  726. #include <grp.h>
  727. #include <limits.h>
  728. #include <netdb.h>
  729. #include <netinet/in.h>
  730. #include <netinet/tcp.h>
  731. #include <pthread.h>
  732. #include <pwd.h>
  733. #include <stdarg.h>
  734. #include <stddef.h>
  735. #include <stdio.h>
  736. #include <stdlib.h>
  737. #include <string.h>
  738. #include <sys/poll.h>
  739. #include <sys/socket.h>
  740. #include <sys/time.h>
  741. #include <sys/utsname.h>
  742. #include <sys/wait.h>
  743. #include <time.h>
  744. #include <unistd.h>
  745. #if defined(USE_X_DOM_SOCKET)
  746. #include <sys/un.h>
  747. #endif
  748. #endif
  749. #define vsnprintf_impl vsnprintf
  750. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  751. #include <dlfcn.h>
  752. #endif
  753. #if defined(__MACH__)
  754. #define SSL_LIB "libssl.dylib"
  755. #define CRYPTO_LIB "libcrypto.dylib"
  756. #else
  757. #if !defined(SSL_LIB)
  758. #define SSL_LIB "libssl.so"
  759. #endif
  760. #if !defined(CRYPTO_LIB)
  761. #define CRYPTO_LIB "libcrypto.so"
  762. #endif
  763. #endif
  764. #if !defined(O_BINARY)
  765. #define O_BINARY (0)
  766. #endif /* O_BINARY */
  767. #define closesocket(a) (close(a))
  768. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  769. #define mg_remove(conn, x) (remove(x))
  770. #define mg_sleep(x) (usleep((x)*1000))
  771. #define mg_opendir(conn, x) (opendir(x))
  772. #define mg_closedir(x) (closedir(x))
  773. #define mg_readdir(x) (readdir(x))
  774. #define ERRNO (errno)
  775. #define INVALID_SOCKET (-1)
  776. #define INT64_FMT PRId64
  777. #define UINT64_FMT PRIu64
  778. typedef int SOCKET;
  779. #define WINCDECL
  780. #if defined(__hpux)
  781. /* HPUX 11 does not have monotonic, fall back to realtime */
  782. #if !defined(CLOCK_MONOTONIC)
  783. #define CLOCK_MONOTONIC CLOCK_REALTIME
  784. #endif
  785. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  786. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  787. * the prototypes use int* rather than socklen_t* which matches the
  788. * actual library expectation. When called with the wrong size arg
  789. * accept() returns a zero client inet addr and check_acl() always
  790. * fails. Since socklen_t is widely used below, just force replace
  791. * their typedef with int. - DTL
  792. */
  793. #define socklen_t int
  794. #endif /* hpux */
  795. #define mg_pollfd pollfd
  796. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  797. /* In case our C library is missing "timegm", provide an implementation */
  798. #if defined(NEED_TIMEGM)
  799. static inline int
  800. is_leap(int y)
  801. {
  802. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  803. }
  804. static inline int
  805. count_leap(int y)
  806. {
  807. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  808. }
  809. time_t
  810. timegm(struct tm *tm)
  811. {
  812. static const unsigned short ydays[] = {
  813. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  814. int year = tm->tm_year + 1900;
  815. int mon = tm->tm_mon;
  816. int mday = tm->tm_mday - 1;
  817. int hour = tm->tm_hour;
  818. int min = tm->tm_min;
  819. int sec = tm->tm_sec;
  820. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  821. || (mday >= ydays[mon + 1] - ydays[mon]
  822. + (mon == 1 && is_leap(year) ? 1 : 0))
  823. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  824. return -1;
  825. time_t res = year - 1970;
  826. res *= 365;
  827. res += mday;
  828. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  829. res += count_leap(year);
  830. res *= 24;
  831. res += hour;
  832. res *= 60;
  833. res += min;
  834. res *= 60;
  835. res += sec;
  836. return res;
  837. }
  838. #endif /* NEED_TIMEGM */
  839. /* va_copy should always be a macro, C99 and C++11 - DTL */
  840. #if !defined(va_copy)
  841. #define va_copy(x, y) ((x) = (y))
  842. #endif
  843. #if defined(_WIN32)
  844. /* Create substitutes for POSIX functions in Win32. */
  845. #if defined(GCC_DIAGNOSTIC)
  846. /* Show no warning in case system functions are not used. */
  847. #pragma GCC diagnostic push
  848. #pragma GCC diagnostic ignored "-Wunused-function"
  849. #endif
  850. static pthread_mutex_t global_log_file_lock;
  851. FUNCTION_MAY_BE_UNUSED
  852. static DWORD
  853. pthread_self(void)
  854. {
  855. return GetCurrentThreadId();
  856. }
  857. FUNCTION_MAY_BE_UNUSED
  858. static int
  859. pthread_key_create(
  860. pthread_key_t *key,
  861. void (*_ignored)(void *) /* destructor not supported for Windows */
  862. )
  863. {
  864. (void)_ignored;
  865. if ((key != 0)) {
  866. *key = TlsAlloc();
  867. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  868. }
  869. return -2;
  870. }
  871. FUNCTION_MAY_BE_UNUSED
  872. static int
  873. pthread_key_delete(pthread_key_t key)
  874. {
  875. return TlsFree(key) ? 0 : 1;
  876. }
  877. FUNCTION_MAY_BE_UNUSED
  878. static int
  879. pthread_setspecific(pthread_key_t key, void *value)
  880. {
  881. return TlsSetValue(key, value) ? 0 : 1;
  882. }
  883. FUNCTION_MAY_BE_UNUSED
  884. static void *
  885. pthread_getspecific(pthread_key_t key)
  886. {
  887. return TlsGetValue(key);
  888. }
  889. #if defined(GCC_DIAGNOSTIC)
  890. /* Enable unused function warning again */
  891. #pragma GCC diagnostic pop
  892. #endif
  893. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  894. #else
  895. static pthread_mutexattr_t pthread_mutex_attr;
  896. #endif /* _WIN32 */
  897. #if defined(GCC_DIAGNOSTIC)
  898. /* Show no warning in case system functions are not used. */
  899. #pragma GCC diagnostic push
  900. #pragma GCC diagnostic ignored "-Wunused-function"
  901. #endif /* defined(GCC_DIAGNOSTIC) */
  902. #if defined(__clang__)
  903. /* Show no warning in case system functions are not used. */
  904. #pragma clang diagnostic push
  905. #pragma clang diagnostic ignored "-Wunused-function"
  906. #endif
  907. static pthread_mutex_t global_lock_mutex;
  908. FUNCTION_MAY_BE_UNUSED
  909. static void
  910. mg_global_lock(void)
  911. {
  912. (void)pthread_mutex_lock(&global_lock_mutex);
  913. }
  914. FUNCTION_MAY_BE_UNUSED
  915. static void
  916. mg_global_unlock(void)
  917. {
  918. (void)pthread_mutex_unlock(&global_lock_mutex);
  919. }
  920. #if defined(_WIN64)
  921. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  922. #elif defined(_WIN32)
  923. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  924. #endif
  925. /* Atomic functions working on ptrdiff_t ("signed size_t").
  926. * Operations: Increment, Decrement, Add, Maximum.
  927. * Up to size_t, they do not an atomic "load" operation.
  928. */
  929. FUNCTION_MAY_BE_UNUSED
  930. static ptrdiff_t
  931. mg_atomic_inc(volatile ptrdiff_t *addr)
  932. {
  933. ptrdiff_t ret;
  934. #if defined(_WIN64) && !defined(NO_ATOMICS)
  935. ret = InterlockedIncrement64(addr);
  936. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  937. ret = InterlockedIncrement(addr);
  938. #elif defined(__GNUC__) \
  939. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  940. && !defined(NO_ATOMICS)
  941. ret = __sync_add_and_fetch(addr, 1);
  942. #else
  943. mg_global_lock();
  944. ret = (++(*addr));
  945. mg_global_unlock();
  946. #endif
  947. return ret;
  948. }
  949. FUNCTION_MAY_BE_UNUSED
  950. static ptrdiff_t
  951. mg_atomic_dec(volatile ptrdiff_t *addr)
  952. {
  953. ptrdiff_t ret;
  954. #if defined(_WIN64) && !defined(NO_ATOMICS)
  955. ret = InterlockedDecrement64(addr);
  956. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  957. ret = InterlockedDecrement(addr);
  958. #elif defined(__GNUC__) \
  959. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  960. && !defined(NO_ATOMICS)
  961. ret = __sync_sub_and_fetch(addr, 1);
  962. #else
  963. mg_global_lock();
  964. ret = (--(*addr));
  965. mg_global_unlock();
  966. #endif
  967. return ret;
  968. }
  969. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  970. static ptrdiff_t
  971. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  972. {
  973. ptrdiff_t ret;
  974. #if defined(_WIN64) && !defined(NO_ATOMICS)
  975. ret = InterlockedAdd64(addr, value);
  976. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  977. ret = InterlockedExchangeAdd(addr, value) + value;
  978. #elif defined(__GNUC__) \
  979. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  980. && !defined(NO_ATOMICS)
  981. ret = __sync_add_and_fetch(addr, value);
  982. #else
  983. mg_global_lock();
  984. *addr += value;
  985. ret = (*addr);
  986. mg_global_unlock();
  987. #endif
  988. return ret;
  989. }
  990. FUNCTION_MAY_BE_UNUSED
  991. static ptrdiff_t
  992. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  993. ptrdiff_t oldval,
  994. ptrdiff_t newval)
  995. {
  996. ptrdiff_t ret;
  997. #if defined(_WIN64) && !defined(NO_ATOMICS)
  998. ret = InterlockedCompareExchange64(addr, newval, oldval);
  999. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1000. ret = InterlockedCompareExchange(addr, newval, oldval);
  1001. #elif defined(__GNUC__) \
  1002. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1003. && !defined(NO_ATOMICS)
  1004. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1005. #else
  1006. mg_global_lock();
  1007. ret = *addr;
  1008. if ((ret != newval) && (ret == oldval)) {
  1009. *addr = newval;
  1010. }
  1011. mg_global_unlock();
  1012. #endif
  1013. return ret;
  1014. }
  1015. static void
  1016. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1017. {
  1018. register ptrdiff_t tmp = *addr;
  1019. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1020. while (tmp < value) {
  1021. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1022. }
  1023. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1024. while (tmp < value) {
  1025. tmp = InterlockedCompareExchange(addr, value, tmp);
  1026. }
  1027. #elif defined(__GNUC__) \
  1028. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1029. && !defined(NO_ATOMICS)
  1030. while (tmp < value) {
  1031. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1032. }
  1033. #else
  1034. mg_global_lock();
  1035. if (*addr < value) {
  1036. *addr = value;
  1037. }
  1038. mg_global_unlock();
  1039. #endif
  1040. }
  1041. static int64_t
  1042. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1043. {
  1044. int64_t ret;
  1045. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1046. ret = InterlockedAdd64(addr, value);
  1047. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1048. ret = InterlockedExchangeAdd64(addr, value) + value;
  1049. #elif defined(__GNUC__) \
  1050. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1051. && !defined(NO_ATOMICS)
  1052. ret = __sync_add_and_fetch(addr, value);
  1053. #else
  1054. mg_global_lock();
  1055. *addr += value;
  1056. ret = (*addr);
  1057. mg_global_unlock();
  1058. #endif
  1059. return ret;
  1060. }
  1061. #endif
  1062. #if defined(GCC_DIAGNOSTIC)
  1063. /* Show no warning in case system functions are not used. */
  1064. #pragma GCC diagnostic pop
  1065. #endif /* defined(GCC_DIAGNOSTIC) */
  1066. #if defined(__clang__)
  1067. /* Show no warning in case system functions are not used. */
  1068. #pragma clang diagnostic pop
  1069. #endif
  1070. #if defined(USE_SERVER_STATS)
  1071. struct mg_memory_stat {
  1072. volatile ptrdiff_t totalMemUsed;
  1073. volatile ptrdiff_t maxMemUsed;
  1074. volatile ptrdiff_t blockCount;
  1075. };
  1076. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1077. static void *
  1078. mg_malloc_ex(size_t size,
  1079. struct mg_context *ctx,
  1080. const char *file,
  1081. unsigned line)
  1082. {
  1083. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1084. void *memory = 0;
  1085. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1086. #if defined(MEMORY_DEBUGGING)
  1087. char mallocStr[256];
  1088. #else
  1089. (void)file;
  1090. (void)line;
  1091. #endif
  1092. if (data) {
  1093. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1094. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1095. mg_atomic_inc(&mstat->blockCount);
  1096. ((uintptr_t *)data)[0] = size;
  1097. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1098. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1099. }
  1100. #if defined(MEMORY_DEBUGGING)
  1101. sprintf(mallocStr,
  1102. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1103. memory,
  1104. (unsigned long)size,
  1105. (unsigned long)mstat->totalMemUsed,
  1106. (unsigned long)mstat->blockCount,
  1107. file,
  1108. line);
  1109. DEBUG_TRACE("%s", mallocStr);
  1110. #endif
  1111. return memory;
  1112. }
  1113. static void *
  1114. mg_calloc_ex(size_t count,
  1115. size_t size,
  1116. struct mg_context *ctx,
  1117. const char *file,
  1118. unsigned line)
  1119. {
  1120. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1121. if (data) {
  1122. memset(data, 0, size * count);
  1123. }
  1124. return data;
  1125. }
  1126. static void
  1127. mg_free_ex(void *memory, const char *file, unsigned line)
  1128. {
  1129. #if defined(MEMORY_DEBUGGING)
  1130. char mallocStr[256];
  1131. #else
  1132. (void)file;
  1133. (void)line;
  1134. #endif
  1135. if (memory) {
  1136. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1137. uintptr_t size = ((uintptr_t *)data)[0];
  1138. struct mg_memory_stat *mstat =
  1139. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1140. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1141. mg_atomic_dec(&mstat->blockCount);
  1142. #if defined(MEMORY_DEBUGGING)
  1143. sprintf(mallocStr,
  1144. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1145. memory,
  1146. (unsigned long)size,
  1147. (unsigned long)mstat->totalMemUsed,
  1148. (unsigned long)mstat->blockCount,
  1149. file,
  1150. line);
  1151. DEBUG_TRACE("%s", mallocStr);
  1152. #endif
  1153. free(data);
  1154. }
  1155. }
  1156. static void *
  1157. mg_realloc_ex(void *memory,
  1158. size_t newsize,
  1159. struct mg_context *ctx,
  1160. const char *file,
  1161. unsigned line)
  1162. {
  1163. void *data;
  1164. void *_realloc;
  1165. uintptr_t oldsize;
  1166. #if defined(MEMORY_DEBUGGING)
  1167. char mallocStr[256];
  1168. #else
  1169. (void)file;
  1170. (void)line;
  1171. #endif
  1172. if (newsize) {
  1173. if (memory) {
  1174. /* Reallocate existing block */
  1175. struct mg_memory_stat *mstat;
  1176. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1177. oldsize = ((uintptr_t *)data)[0];
  1178. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1179. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1180. if (_realloc) {
  1181. data = _realloc;
  1182. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1183. #if defined(MEMORY_DEBUGGING)
  1184. sprintf(mallocStr,
  1185. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1186. memory,
  1187. (unsigned long)oldsize,
  1188. (unsigned long)mstat->totalMemUsed,
  1189. (unsigned long)mstat->blockCount,
  1190. file,
  1191. line);
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1195. #if defined(MEMORY_DEBUGGING)
  1196. sprintf(mallocStr,
  1197. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1198. memory,
  1199. (unsigned long)newsize,
  1200. (unsigned long)mstat->totalMemUsed,
  1201. (unsigned long)mstat->blockCount,
  1202. file,
  1203. line);
  1204. DEBUG_TRACE("%s", mallocStr);
  1205. #endif
  1206. *(uintptr_t *)data = newsize;
  1207. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1208. } else {
  1209. #if defined(MEMORY_DEBUGGING)
  1210. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1211. #endif
  1212. return _realloc;
  1213. }
  1214. } else {
  1215. /* Allocate new block */
  1216. data = mg_malloc_ex(newsize, ctx, file, line);
  1217. }
  1218. } else {
  1219. /* Free existing block */
  1220. data = 0;
  1221. mg_free_ex(memory, file, line);
  1222. }
  1223. return data;
  1224. }
  1225. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1226. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1227. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1228. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1229. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1230. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1231. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1232. #else /* USE_SERVER_STATS */
  1233. static __inline void *
  1234. mg_malloc(size_t a)
  1235. {
  1236. return malloc(a);
  1237. }
  1238. static __inline void *
  1239. mg_calloc(size_t a, size_t b)
  1240. {
  1241. return calloc(a, b);
  1242. }
  1243. static __inline void *
  1244. mg_realloc(void *a, size_t b)
  1245. {
  1246. return realloc(a, b);
  1247. }
  1248. static __inline void
  1249. mg_free(void *a)
  1250. {
  1251. free(a);
  1252. }
  1253. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1254. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1255. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1256. #define mg_free_ctx(a, c) mg_free(a)
  1257. #endif /* USE_SERVER_STATS */
  1258. static void mg_vsnprintf(const struct mg_connection *conn,
  1259. int *truncated,
  1260. char *buf,
  1261. size_t buflen,
  1262. const char *fmt,
  1263. va_list ap);
  1264. static void mg_snprintf(const struct mg_connection *conn,
  1265. int *truncated,
  1266. char *buf,
  1267. size_t buflen,
  1268. PRINTF_FORMAT_STRING(const char *fmt),
  1269. ...) PRINTF_ARGS(5, 6);
  1270. /* This following lines are just meant as a reminder to use the mg-functions
  1271. * for memory management */
  1272. #if defined(malloc)
  1273. #undef malloc
  1274. #endif
  1275. #if defined(calloc)
  1276. #undef calloc
  1277. #endif
  1278. #if defined(realloc)
  1279. #undef realloc
  1280. #endif
  1281. #if defined(free)
  1282. #undef free
  1283. #endif
  1284. #if defined(snprintf)
  1285. #undef snprintf
  1286. #endif
  1287. #if defined(vsnprintf)
  1288. #undef vsnprintf
  1289. #endif
  1290. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1291. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1292. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1293. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1294. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1295. #if defined(_WIN32)
  1296. /* vsnprintf must not be used in any system,
  1297. * but this define only works well for Windows. */
  1298. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1299. #endif
  1300. /* mg_init_library counter */
  1301. static int mg_init_library_called = 0;
  1302. #if !defined(NO_SSL)
  1303. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1304. || defined(OPENSSL_API_3_0)
  1305. static int mg_openssl_initialized = 0;
  1306. #endif
  1307. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1308. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1309. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1310. #endif
  1311. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1312. && defined(OPENSSL_API_3_0)
  1313. #error "Multiple OPENSSL_API versions defined"
  1314. #endif
  1315. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1316. || defined(OPENSSL_API_3_0)) \
  1317. && defined(USE_MBEDTLS)
  1318. #error "Multiple SSL libraries defined"
  1319. #endif
  1320. #endif
  1321. static pthread_key_t sTlsKey; /* Thread local storage index */
  1322. static volatile ptrdiff_t thread_idx_max = 0;
  1323. #if defined(MG_LEGACY_INTERFACE)
  1324. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1325. #endif
  1326. struct mg_workerTLS {
  1327. int is_master;
  1328. unsigned long thread_idx;
  1329. void *user_ptr;
  1330. #if defined(_WIN32)
  1331. HANDLE pthread_cond_helper_mutex;
  1332. struct mg_workerTLS *next_waiting_thread;
  1333. #endif
  1334. const char *alpn_proto;
  1335. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1336. char txtbuf[4];
  1337. #endif
  1338. };
  1339. #if defined(GCC_DIAGNOSTIC)
  1340. /* Show no warning in case system functions are not used. */
  1341. #pragma GCC diagnostic push
  1342. #pragma GCC diagnostic ignored "-Wunused-function"
  1343. #endif /* defined(GCC_DIAGNOSTIC) */
  1344. #if defined(__clang__)
  1345. /* Show no warning in case system functions are not used. */
  1346. #pragma clang diagnostic push
  1347. #pragma clang diagnostic ignored "-Wunused-function"
  1348. #endif
  1349. /* Get a unique thread ID as unsigned long, independent from the data type
  1350. * of thread IDs defined by the operating system API.
  1351. * If two calls to mg_current_thread_id return the same value, they calls
  1352. * are done from the same thread. If they return different values, they are
  1353. * done from different threads. (Provided this function is used in the same
  1354. * process context and threads are not repeatedly created and deleted, but
  1355. * CivetWeb does not do that).
  1356. * This function must match the signature required for SSL id callbacks:
  1357. * CRYPTO_set_id_callback
  1358. */
  1359. FUNCTION_MAY_BE_UNUSED
  1360. static unsigned long
  1361. mg_current_thread_id(void)
  1362. {
  1363. #if defined(_WIN32)
  1364. return GetCurrentThreadId();
  1365. #else
  1366. #if defined(__clang__)
  1367. #pragma clang diagnostic push
  1368. #pragma clang diagnostic ignored "-Wunreachable-code"
  1369. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1370. * or not, so one of the two conditions will be unreachable by construction.
  1371. * Unfortunately the C standard does not define a way to check this at
  1372. * compile time, since the #if preprocessor conditions can not use the
  1373. * sizeof operator as an argument. */
  1374. #endif
  1375. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1376. /* This is the problematic case for CRYPTO_set_id_callback:
  1377. * The OS pthread_t can not be cast to unsigned long. */
  1378. struct mg_workerTLS *tls =
  1379. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1380. if (tls == NULL) {
  1381. /* SSL called from an unknown thread: Create some thread index.
  1382. */
  1383. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1384. tls->is_master = -2; /* -2 means "3rd party thread" */
  1385. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1386. pthread_setspecific(sTlsKey, tls);
  1387. }
  1388. return tls->thread_idx;
  1389. } else {
  1390. /* pthread_t may be any data type, so a simple cast to unsigned long
  1391. * can rise a warning/error, depending on the platform.
  1392. * Here memcpy is used as an anything-to-anything cast. */
  1393. unsigned long ret = 0;
  1394. pthread_t t = pthread_self();
  1395. memcpy(&ret, &t, sizeof(pthread_t));
  1396. return ret;
  1397. }
  1398. #if defined(__clang__)
  1399. #pragma clang diagnostic pop
  1400. #endif
  1401. #endif
  1402. }
  1403. FUNCTION_MAY_BE_UNUSED
  1404. static uint64_t
  1405. mg_get_current_time_ns(void)
  1406. {
  1407. struct timespec tsnow;
  1408. clock_gettime(CLOCK_REALTIME, &tsnow);
  1409. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1410. }
  1411. #if defined(GCC_DIAGNOSTIC)
  1412. /* Show no warning in case system functions are not used. */
  1413. #pragma GCC diagnostic pop
  1414. #endif /* defined(GCC_DIAGNOSTIC) */
  1415. #if defined(__clang__)
  1416. /* Show no warning in case system functions are not used. */
  1417. #pragma clang diagnostic pop
  1418. #endif
  1419. #if defined(NEED_DEBUG_TRACE_FUNC)
  1420. static void
  1421. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1422. {
  1423. va_list args;
  1424. struct timespec tsnow;
  1425. /* Get some operating system independent thread id */
  1426. unsigned long thread_id = mg_current_thread_id();
  1427. clock_gettime(CLOCK_REALTIME, &tsnow);
  1428. flockfile(DEBUG_TRACE_STREAM);
  1429. fprintf(DEBUG_TRACE_STREAM,
  1430. "*** %lu.%09lu %lu %s:%u: ",
  1431. (unsigned long)tsnow.tv_sec,
  1432. (unsigned long)tsnow.tv_nsec,
  1433. thread_id,
  1434. func,
  1435. line);
  1436. va_start(args, fmt);
  1437. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1438. va_end(args);
  1439. putc('\n', DEBUG_TRACE_STREAM);
  1440. fflush(DEBUG_TRACE_STREAM);
  1441. funlockfile(DEBUG_TRACE_STREAM);
  1442. }
  1443. #endif /* NEED_DEBUG_TRACE_FUNC */
  1444. #define MD5_STATIC static
  1445. #include "md5.inl"
  1446. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1447. #if defined(NO_SOCKLEN_T)
  1448. typedef int socklen_t;
  1449. #endif /* NO_SOCKLEN_T */
  1450. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1451. #if !defined(MSG_NOSIGNAL)
  1452. #define MSG_NOSIGNAL (0)
  1453. #endif
  1454. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1455. #if defined(USE_MBEDTLS)
  1456. /* mbedTLS */
  1457. #include "mod_mbedtls.inl"
  1458. #elif defined(NO_SSL)
  1459. /* no SSL */
  1460. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1461. typedef struct SSL_CTX SSL_CTX;
  1462. #elif defined(NO_SSL_DL)
  1463. /* OpenSSL without dynamic loading */
  1464. #include <openssl/bn.h>
  1465. #include <openssl/conf.h>
  1466. #include <openssl/crypto.h>
  1467. #include <openssl/dh.h>
  1468. #include <openssl/engine.h>
  1469. #include <openssl/err.h>
  1470. #include <openssl/opensslv.h>
  1471. #include <openssl/pem.h>
  1472. #include <openssl/ssl.h>
  1473. #include <openssl/tls1.h>
  1474. #include <openssl/x509.h>
  1475. #if defined(WOLFSSL_VERSION)
  1476. /* Additional defines for WolfSSL, see
  1477. * https://github.com/civetweb/civetweb/issues/583 */
  1478. #include "wolfssl_extras.inl"
  1479. #endif
  1480. #if defined(OPENSSL_IS_BORINGSSL)
  1481. /* From boringssl/src/include/openssl/mem.h:
  1482. *
  1483. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1484. * However, that was written in a time before Valgrind and ASAN. Since we now
  1485. * have those tools, the OpenSSL allocation functions are simply macros around
  1486. * the standard memory functions.
  1487. *
  1488. * #define OPENSSL_free free */
  1489. #define free free
  1490. // disable for boringssl
  1491. #define CONF_modules_unload(a) ((void)0)
  1492. #define ENGINE_cleanup() ((void)0)
  1493. #endif
  1494. /* If OpenSSL headers are included, automatically select the API version */
  1495. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1496. #if !defined(OPENSSL_API_3_0)
  1497. #define OPENSSL_API_3_0
  1498. #endif
  1499. #define OPENSSL_REMOVE_THREAD_STATE()
  1500. #else
  1501. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1502. #if !defined(OPENSSL_API_1_1)
  1503. #define OPENSSL_API_1_1
  1504. #endif
  1505. #define OPENSSL_REMOVE_THREAD_STATE()
  1506. #else
  1507. #if !defined(OPENSSL_API_1_0)
  1508. #define OPENSSL_API_1_0
  1509. #endif
  1510. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1511. #endif
  1512. #endif
  1513. #else
  1514. /* SSL loaded dynamically from DLL / shared object */
  1515. /* Add all prototypes here, to be independent from OpenSSL source
  1516. * installation. */
  1517. #include "openssl_dl.inl"
  1518. #endif /* Various SSL bindings */
  1519. #if !defined(NO_CACHING)
  1520. static const char month_names[][4] = {"Jan",
  1521. "Feb",
  1522. "Mar",
  1523. "Apr",
  1524. "May",
  1525. "Jun",
  1526. "Jul",
  1527. "Aug",
  1528. "Sep",
  1529. "Oct",
  1530. "Nov",
  1531. "Dec"};
  1532. #endif /* !NO_CACHING */
  1533. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1534. * the union u. */
  1535. union usa {
  1536. struct sockaddr sa;
  1537. struct sockaddr_in sin;
  1538. #if defined(USE_IPV6)
  1539. struct sockaddr_in6 sin6;
  1540. #endif
  1541. #if defined(USE_X_DOM_SOCKET)
  1542. struct sockaddr_un sun;
  1543. #endif
  1544. };
  1545. #if defined(USE_X_DOM_SOCKET)
  1546. static unsigned short
  1547. USA_IN_PORT_UNSAFE(union usa *s)
  1548. {
  1549. if (s->sa.sa_family == AF_INET)
  1550. return s->sin.sin_port;
  1551. #if defined(USE_IPV6)
  1552. if (s->sa.sa_family == AF_INET6)
  1553. return s->sin6.sin6_port;
  1554. #endif
  1555. return 0;
  1556. }
  1557. #endif
  1558. #if defined(USE_IPV6)
  1559. #define USA_IN_PORT_UNSAFE(s) \
  1560. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1561. #else
  1562. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1563. #endif
  1564. /* Describes a string (chunk of memory). */
  1565. struct vec {
  1566. const char *ptr;
  1567. size_t len;
  1568. };
  1569. struct mg_file_stat {
  1570. /* File properties filled by mg_stat: */
  1571. uint64_t size;
  1572. time_t last_modified;
  1573. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1574. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1575. * case we need a "Content-Eencoding: gzip" header */
  1576. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1577. };
  1578. struct mg_file_access {
  1579. /* File properties filled by mg_fopen: */
  1580. FILE *fp;
  1581. };
  1582. struct mg_file {
  1583. struct mg_file_stat stat;
  1584. struct mg_file_access access;
  1585. };
  1586. #define STRUCT_FILE_INITIALIZER \
  1587. { \
  1588. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1589. { \
  1590. (FILE *)NULL \
  1591. } \
  1592. }
  1593. /* Describes listening socket, or socket which was accept()-ed by the master
  1594. * thread and queued for future handling by the worker thread. */
  1595. struct socket {
  1596. SOCKET sock; /* Listening socket */
  1597. union usa lsa; /* Local socket address */
  1598. union usa rsa; /* Remote socket address */
  1599. unsigned char is_ssl; /* Is port SSL-ed */
  1600. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1601. * port */
  1602. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1603. };
  1604. /* Enum const for all options must be in sync with
  1605. * static struct mg_option config_options[]
  1606. * This is tested in the unit test (test/private.c)
  1607. * "Private Config Options"
  1608. */
  1609. enum {
  1610. /* Once for each server */
  1611. LISTENING_PORTS,
  1612. NUM_THREADS,
  1613. RUN_AS_USER,
  1614. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1615. * socket option typedef TCP_NODELAY. */
  1616. MAX_REQUEST_SIZE,
  1617. LINGER_TIMEOUT,
  1618. CONNECTION_QUEUE_SIZE,
  1619. LISTEN_BACKLOG_SIZE,
  1620. #if defined(__linux__)
  1621. ALLOW_SENDFILE_CALL,
  1622. #endif
  1623. #if defined(_WIN32)
  1624. CASE_SENSITIVE_FILES,
  1625. #endif
  1626. THROTTLE,
  1627. ENABLE_KEEP_ALIVE,
  1628. REQUEST_TIMEOUT,
  1629. KEEP_ALIVE_TIMEOUT,
  1630. #if defined(USE_WEBSOCKET)
  1631. WEBSOCKET_TIMEOUT,
  1632. ENABLE_WEBSOCKET_PING_PONG,
  1633. #endif
  1634. DECODE_URL,
  1635. DECODE_QUERY_STRING,
  1636. #if defined(USE_LUA)
  1637. LUA_BACKGROUND_SCRIPT,
  1638. LUA_BACKGROUND_SCRIPT_PARAMS,
  1639. #endif
  1640. #if defined(USE_HTTP2)
  1641. ENABLE_HTTP2,
  1642. #endif
  1643. /* Once for each domain */
  1644. DOCUMENT_ROOT,
  1645. ACCESS_LOG_FILE,
  1646. ERROR_LOG_FILE,
  1647. CGI_EXTENSIONS,
  1648. CGI_ENVIRONMENT,
  1649. CGI_INTERPRETER,
  1650. CGI_INTERPRETER_ARGS,
  1651. #if defined(USE_TIMERS)
  1652. CGI_TIMEOUT,
  1653. #endif
  1654. CGI2_EXTENSIONS,
  1655. CGI2_ENVIRONMENT,
  1656. CGI2_INTERPRETER,
  1657. CGI2_INTERPRETER_ARGS,
  1658. #if defined(USE_TIMERS)
  1659. CGI2_TIMEOUT,
  1660. #endif
  1661. #if defined(USE_4_CGI)
  1662. CGI3_EXTENSIONS,
  1663. CGI3_ENVIRONMENT,
  1664. CGI3_INTERPRETER,
  1665. CGI3_INTERPRETER_ARGS,
  1666. #if defined(USE_TIMERS)
  1667. CGI3_TIMEOUT,
  1668. #endif
  1669. CGI4_EXTENSIONS,
  1670. CGI4_ENVIRONMENT,
  1671. CGI4_INTERPRETER,
  1672. CGI4_INTERPRETER_ARGS,
  1673. #if defined(USE_TIMERS)
  1674. CGI4_TIMEOUT,
  1675. #endif
  1676. #endif
  1677. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1678. PROTECT_URI,
  1679. AUTHENTICATION_DOMAIN,
  1680. ENABLE_AUTH_DOMAIN_CHECK,
  1681. SSI_EXTENSIONS,
  1682. ENABLE_DIRECTORY_LISTING,
  1683. GLOBAL_PASSWORDS_FILE,
  1684. INDEX_FILES,
  1685. ACCESS_CONTROL_LIST,
  1686. EXTRA_MIME_TYPES,
  1687. SSL_CERTIFICATE,
  1688. SSL_CERTIFICATE_CHAIN,
  1689. URL_REWRITE_PATTERN,
  1690. HIDE_FILES,
  1691. SSL_DO_VERIFY_PEER,
  1692. SSL_CACHE_TIMEOUT,
  1693. SSL_CA_PATH,
  1694. SSL_CA_FILE,
  1695. SSL_VERIFY_DEPTH,
  1696. SSL_DEFAULT_VERIFY_PATHS,
  1697. SSL_CIPHER_LIST,
  1698. SSL_PROTOCOL_VERSION,
  1699. SSL_SHORT_TRUST,
  1700. #if defined(USE_LUA)
  1701. LUA_PRELOAD_FILE,
  1702. LUA_SCRIPT_EXTENSIONS,
  1703. LUA_SERVER_PAGE_EXTENSIONS,
  1704. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1705. LUA_DEBUG_PARAMS,
  1706. #endif
  1707. #endif
  1708. #if defined(USE_DUKTAPE)
  1709. DUKTAPE_SCRIPT_EXTENSIONS,
  1710. #endif
  1711. #if defined(USE_WEBSOCKET)
  1712. WEBSOCKET_ROOT,
  1713. #endif
  1714. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1715. LUA_WEBSOCKET_EXTENSIONS,
  1716. #endif
  1717. ACCESS_CONTROL_ALLOW_ORIGIN,
  1718. ACCESS_CONTROL_ALLOW_METHODS,
  1719. ACCESS_CONTROL_ALLOW_HEADERS,
  1720. ERROR_PAGES,
  1721. #if !defined(NO_CACHING)
  1722. STATIC_FILE_MAX_AGE,
  1723. STATIC_FILE_CACHE_CONTROL,
  1724. #endif
  1725. #if !defined(NO_SSL)
  1726. STRICT_HTTPS_MAX_AGE,
  1727. #endif
  1728. ADDITIONAL_HEADER,
  1729. ALLOW_INDEX_SCRIPT_SUB_RES,
  1730. NUM_OPTIONS
  1731. };
  1732. /* Config option name, config types, default value.
  1733. * Must be in the same order as the enum const above.
  1734. */
  1735. static const struct mg_option config_options[] = {
  1736. /* Once for each server */
  1737. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1738. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1739. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1740. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1741. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1742. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1743. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1744. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1745. #if defined(__linux__)
  1746. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1747. #endif
  1748. #if defined(_WIN32)
  1749. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1750. #endif
  1751. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1752. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1753. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1754. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1755. #if defined(USE_WEBSOCKET)
  1756. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1757. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1758. #endif
  1759. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1760. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1761. #if defined(USE_LUA)
  1762. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1763. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1764. #endif
  1765. #if defined(USE_HTTP2)
  1766. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1767. #endif
  1768. /* Once for each domain */
  1769. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1770. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1771. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1772. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1773. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1774. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1775. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1776. #if defined(USE_TIMERS)
  1777. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1778. #endif
  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. #if defined(USE_4_CGI)
  1787. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1788. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1789. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1790. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1791. #if defined(USE_TIMERS)
  1792. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1793. #endif
  1794. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1795. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1796. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1797. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1798. #if defined(USE_TIMERS)
  1799. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1800. #endif
  1801. #endif
  1802. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1803. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1804. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1805. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1806. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1807. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1808. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1809. {"index_files",
  1810. MG_CONFIG_TYPE_STRING_LIST,
  1811. #if defined(USE_LUA)
  1812. "index.xhtml,index.html,index.htm,"
  1813. "index.lp,index.lsp,index.lua,index.cgi,"
  1814. "index.shtml,index.php"},
  1815. #else
  1816. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1817. #endif
  1818. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1819. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1820. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1821. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1822. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1823. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1824. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1825. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1826. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1827. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1828. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1829. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1830. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1831. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1832. * as a minimum in 2020 */
  1833. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1834. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1835. #if defined(USE_LUA)
  1836. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1837. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1838. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1839. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1840. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1841. #endif
  1842. #endif
  1843. #if defined(USE_DUKTAPE)
  1844. /* The support for duktape is still in alpha version state.
  1845. * The name of this config option might change. */
  1846. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1847. #endif
  1848. #if defined(USE_WEBSOCKET)
  1849. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1850. #endif
  1851. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1852. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1853. #endif
  1854. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1855. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1856. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1857. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1858. #if !defined(NO_CACHING)
  1859. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1860. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1861. #endif
  1862. #if !defined(NO_SSL)
  1863. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1864. #endif
  1865. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1866. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1867. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1868. /* Check if the config_options and the corresponding enum have compatible
  1869. * sizes. */
  1870. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1871. == (NUM_OPTIONS + 1),
  1872. "config_options and enum not sync");
  1873. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1874. struct mg_handler_info {
  1875. /* Name/Pattern of the URI. */
  1876. char *uri;
  1877. size_t uri_len;
  1878. /* handler type */
  1879. int handler_type;
  1880. /* Handler for http/https or requests. */
  1881. mg_request_handler handler;
  1882. unsigned int refcount;
  1883. int removing;
  1884. /* Handler for ws/wss (websocket) requests. */
  1885. mg_websocket_connect_handler connect_handler;
  1886. mg_websocket_ready_handler ready_handler;
  1887. mg_websocket_data_handler data_handler;
  1888. mg_websocket_close_handler close_handler;
  1889. /* accepted subprotocols for ws/wss requests. */
  1890. struct mg_websocket_subprotocols *subprotocols;
  1891. /* Handler for authorization requests */
  1892. mg_authorization_handler auth_handler;
  1893. /* User supplied argument for the handler function. */
  1894. void *cbdata;
  1895. /* next handler in a linked list */
  1896. struct mg_handler_info *next;
  1897. };
  1898. enum {
  1899. CONTEXT_INVALID,
  1900. CONTEXT_SERVER,
  1901. CONTEXT_HTTP_CLIENT,
  1902. CONTEXT_WS_CLIENT
  1903. };
  1904. struct mg_domain_context {
  1905. SSL_CTX *ssl_ctx; /* SSL context */
  1906. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1907. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1908. int64_t ssl_cert_last_mtime;
  1909. /* Server nonce */
  1910. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1911. unsigned long nonce_count; /* Used nonces, used for authentication */
  1912. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1913. /* linked list of shared lua websockets */
  1914. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1915. #endif
  1916. /* Linked list of domains */
  1917. struct mg_domain_context *next;
  1918. };
  1919. /* Stop flag can be "volatile" or require a lock.
  1920. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1921. * states a read operation for int is always atomic. */
  1922. #if defined(STOP_FLAG_NEEDS_LOCK)
  1923. typedef ptrdiff_t volatile stop_flag_t;
  1924. static int
  1925. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1926. {
  1927. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1928. return (sf == 0);
  1929. }
  1930. static int
  1931. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1932. {
  1933. stop_flag_t sf = mg_atomic_add(f, 0);
  1934. return (sf == 2);
  1935. }
  1936. static void
  1937. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1938. {
  1939. stop_flag_t sf;
  1940. do {
  1941. sf = mg_atomic_compare_and_swap(f, *f, v);
  1942. } while (sf != v);
  1943. }
  1944. #else /* STOP_FLAG_NEEDS_LOCK */
  1945. typedef int volatile stop_flag_t;
  1946. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1947. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1948. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1949. #endif /* STOP_FLAG_NEEDS_LOCK */
  1950. #if !defined(NUM_WEBDAV_LOCKS)
  1951. #define NUM_WEBDAV_LOCKS 10
  1952. #endif
  1953. #if !defined(LOCK_DURATION_S)
  1954. #define LOCK_DURATION_S 60
  1955. #endif
  1956. struct twebdav_lock {
  1957. uint64_t locktime;
  1958. char token[33];
  1959. char path[UTF8_PATH_MAX * 2];
  1960. char user[UTF8_PATH_MAX * 2];
  1961. };
  1962. struct mg_context {
  1963. /* Part 1 - Physical context:
  1964. * This holds threads, ports, timeouts, ...
  1965. * set for the entire server, independent from the
  1966. * addressed hostname.
  1967. */
  1968. /* Connection related */
  1969. int context_type; /* See CONTEXT_* above */
  1970. struct socket *listening_sockets;
  1971. struct mg_pollfd *listening_socket_fds;
  1972. unsigned int num_listening_sockets;
  1973. struct mg_connection *worker_connections; /* The connection struct, pre-
  1974. * allocated for each worker */
  1975. #if defined(USE_SERVER_STATS)
  1976. volatile ptrdiff_t active_connections;
  1977. volatile ptrdiff_t max_active_connections;
  1978. volatile ptrdiff_t total_connections;
  1979. volatile ptrdiff_t total_requests;
  1980. volatile int64_t total_data_read;
  1981. volatile int64_t total_data_written;
  1982. #endif
  1983. /* Thread related */
  1984. stop_flag_t stop_flag; /* Should we stop event loop */
  1985. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1986. pthread_t masterthreadid; /* The master thread ID */
  1987. unsigned int
  1988. cfg_worker_threads; /* The number of configured worker threads. */
  1989. pthread_t *worker_threadids; /* The worker thread IDs */
  1990. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1991. /* Connection to thread dispatching */
  1992. #if defined(ALTERNATIVE_QUEUE)
  1993. struct socket *client_socks;
  1994. void **client_wait_events;
  1995. #else
  1996. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  1997. worker thread */
  1998. volatile int sq_head; /* Head of the socket queue */
  1999. volatile int sq_tail; /* Tail of the socket queue */
  2000. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2001. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2002. volatile int sq_blocked; /* Status information: sq is full */
  2003. int sq_size; /* No of elements in socket queue */
  2004. #if defined(USE_SERVER_STATS)
  2005. int sq_max_fill;
  2006. #endif /* USE_SERVER_STATS */
  2007. #endif /* ALTERNATIVE_QUEUE */
  2008. /* Memory related */
  2009. unsigned int max_request_size; /* The max request size */
  2010. #if defined(USE_SERVER_STATS)
  2011. struct mg_memory_stat ctx_memory;
  2012. #endif
  2013. /* WebDAV lock structures */
  2014. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2015. /* Operating system related */
  2016. char *systemName; /* What operating system is running */
  2017. time_t start_time; /* Server start time, used for authentication
  2018. * and for diagnstics. */
  2019. #if defined(USE_TIMERS)
  2020. struct ttimers *timers;
  2021. #endif
  2022. /* Lua specific: Background operations and shared websockets */
  2023. #if defined(USE_LUA)
  2024. void *lua_background_state; /* lua_State (here as void *) */
  2025. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2026. int lua_bg_log_available; /* Use Lua background state for access log */
  2027. #endif
  2028. /* Server nonce */
  2029. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2030. * ssl_cert_last_mtime, nonce_count, and
  2031. * next (linked list) */
  2032. /* Server callbacks */
  2033. struct mg_callbacks callbacks; /* User-defined callback function */
  2034. void *user_data; /* User-defined data */
  2035. /* Part 2 - Logical domain:
  2036. * This holds hostname, TLS certificate, document root, ...
  2037. * set for a domain hosted at the server.
  2038. * There may be multiple domains hosted at one physical server.
  2039. * The default domain "dd" is the first element of a list of
  2040. * domains.
  2041. */
  2042. struct mg_domain_context dd; /* default domain */
  2043. };
  2044. #if defined(USE_SERVER_STATS)
  2045. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2046. static struct mg_memory_stat *
  2047. get_memory_stat(struct mg_context *ctx)
  2048. {
  2049. if (ctx) {
  2050. return &(ctx->ctx_memory);
  2051. }
  2052. return &mg_common_memory;
  2053. }
  2054. #endif
  2055. enum {
  2056. CONNECTION_TYPE_INVALID = 0,
  2057. CONNECTION_TYPE_REQUEST = 1,
  2058. CONNECTION_TYPE_RESPONSE = 2
  2059. };
  2060. enum {
  2061. PROTOCOL_TYPE_HTTP1 = 0,
  2062. PROTOCOL_TYPE_WEBSOCKET = 1,
  2063. PROTOCOL_TYPE_HTTP2 = 2
  2064. };
  2065. #if defined(USE_HTTP2)
  2066. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2067. #define HTTP2_DYN_TABLE_SIZE (256)
  2068. #endif
  2069. struct mg_http2_connection {
  2070. uint32_t stream_id;
  2071. uint32_t dyn_table_size;
  2072. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2073. };
  2074. #endif
  2075. struct mg_connection {
  2076. int connection_type; /* see CONNECTION_TYPE_* above */
  2077. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2078. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2079. fully sent */
  2080. #if defined(USE_HTTP2)
  2081. struct mg_http2_connection http2;
  2082. #endif
  2083. struct mg_request_info request_info;
  2084. struct mg_response_info response_info;
  2085. struct mg_context *phys_ctx;
  2086. struct mg_domain_context *dom_ctx;
  2087. #if defined(USE_SERVER_STATS)
  2088. int conn_state; /* 0 = undef, numerical value may change in different
  2089. * versions. For the current definition, see
  2090. * mg_get_connection_info_impl */
  2091. #endif
  2092. SSL *ssl; /* SSL descriptor */
  2093. struct socket client; /* Connected client */
  2094. time_t conn_birth_time; /* Time (wall clock) when connection was
  2095. * established */
  2096. #if defined(USE_SERVER_STATS)
  2097. time_t conn_close_time; /* Time (wall clock) when connection was
  2098. * closed (or 0 if still open) */
  2099. double processing_time; /* Procesing time for one request. */
  2100. #endif
  2101. struct timespec req_time; /* Time (since system start) when the request
  2102. * was received */
  2103. int64_t num_bytes_sent; /* Total bytes sent to client */
  2104. int64_t content_len; /* How many bytes of content can be read
  2105. * !is_chunked: Content-Length header value
  2106. * or -1 (until connection closed,
  2107. * not allowed for a request)
  2108. * is_chunked: >= 0, appended gradually
  2109. */
  2110. int64_t consumed_content; /* How many bytes of content have been read */
  2111. int is_chunked; /* Transfer-Encoding is chunked:
  2112. * 0 = not chunked,
  2113. * 1 = chunked, not yet, or some data read,
  2114. * 2 = chunked, has error,
  2115. * 3 = chunked, all data read except trailer,
  2116. * 4 = chunked, all data read
  2117. */
  2118. char *buf; /* Buffer for received data */
  2119. char *path_info; /* PATH_INFO part of the URL */
  2120. int must_close; /* 1 if connection must be closed */
  2121. int accept_gzip; /* 1 if gzip encoding is accepted */
  2122. int in_error_handler; /* 1 if in handler for user defined error
  2123. * pages */
  2124. #if defined(USE_WEBSOCKET)
  2125. int in_websocket_handling; /* 1 if in read_websocket */
  2126. #endif
  2127. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2128. && defined(MG_EXPERIMENTAL_INTERFACES)
  2129. /* Parameters for websocket data compression according to rfc7692 */
  2130. int websocket_deflate_server_max_windows_bits;
  2131. int websocket_deflate_client_max_windows_bits;
  2132. int websocket_deflate_server_no_context_takeover;
  2133. int websocket_deflate_client_no_context_takeover;
  2134. int websocket_deflate_initialized;
  2135. int websocket_deflate_flush;
  2136. z_stream websocket_deflate_state;
  2137. z_stream websocket_inflate_state;
  2138. #endif
  2139. int handled_requests; /* Number of requests handled by this connection
  2140. */
  2141. int buf_size; /* Buffer size */
  2142. int request_len; /* Size of the request + headers in a buffer */
  2143. int data_len; /* Total size of data in a buffer */
  2144. int status_code; /* HTTP reply status code, e.g. 200 */
  2145. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2146. * throttle */
  2147. time_t last_throttle_time; /* Last time throttled data was sent */
  2148. int last_throttle_bytes; /* Bytes sent this second */
  2149. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2150. * atomic transmissions for websockets */
  2151. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2152. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2153. #endif
  2154. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2155. * for quick access */
  2156. };
  2157. /* Directory entry */
  2158. struct de {
  2159. char *file_name;
  2160. struct mg_file_stat file;
  2161. };
  2162. #define mg_cry_internal(conn, fmt, ...) \
  2163. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2164. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2165. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2166. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2167. struct mg_context *ctx,
  2168. const char *func,
  2169. unsigned line,
  2170. const char *fmt,
  2171. ...) PRINTF_ARGS(5, 6);
  2172. #if !defined(NO_THREAD_NAME)
  2173. #if defined(_WIN32) && defined(_MSC_VER)
  2174. /* Set the thread name for debugging purposes in Visual Studio
  2175. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2176. */
  2177. #pragma pack(push, 8)
  2178. typedef struct tagTHREADNAME_INFO {
  2179. DWORD dwType; /* Must be 0x1000. */
  2180. LPCSTR szName; /* Pointer to name (in user addr space). */
  2181. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2182. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2183. } THREADNAME_INFO;
  2184. #pragma pack(pop)
  2185. #elif defined(__linux__)
  2186. #include <sys/prctl.h>
  2187. #include <sys/sendfile.h>
  2188. #if defined(ALTERNATIVE_QUEUE)
  2189. #include <sys/eventfd.h>
  2190. #endif /* ALTERNATIVE_QUEUE */
  2191. #if defined(ALTERNATIVE_QUEUE)
  2192. static void *
  2193. event_create(void)
  2194. {
  2195. int evhdl = eventfd(0, EFD_CLOEXEC);
  2196. int *ret;
  2197. if (evhdl == -1) {
  2198. /* Linux uses -1 on error, Windows NULL. */
  2199. /* However, Linux does not return 0 on success either. */
  2200. return 0;
  2201. }
  2202. ret = (int *)mg_malloc(sizeof(int));
  2203. if (ret) {
  2204. *ret = evhdl;
  2205. } else {
  2206. (void)close(evhdl);
  2207. }
  2208. return (void *)ret;
  2209. }
  2210. static int
  2211. event_wait(void *eventhdl)
  2212. {
  2213. uint64_t u;
  2214. int evhdl, s;
  2215. if (!eventhdl) {
  2216. /* error */
  2217. return 0;
  2218. }
  2219. evhdl = *(int *)eventhdl;
  2220. s = (int)read(evhdl, &u, sizeof(u));
  2221. if (s != sizeof(u)) {
  2222. /* error */
  2223. return 0;
  2224. }
  2225. (void)u; /* the value is not required */
  2226. return 1;
  2227. }
  2228. static int
  2229. event_signal(void *eventhdl)
  2230. {
  2231. uint64_t u = 1;
  2232. int evhdl, s;
  2233. if (!eventhdl) {
  2234. /* error */
  2235. return 0;
  2236. }
  2237. evhdl = *(int *)eventhdl;
  2238. s = (int)write(evhdl, &u, sizeof(u));
  2239. if (s != sizeof(u)) {
  2240. /* error */
  2241. return 0;
  2242. }
  2243. return 1;
  2244. }
  2245. static void
  2246. event_destroy(void *eventhdl)
  2247. {
  2248. int evhdl;
  2249. if (!eventhdl) {
  2250. /* error */
  2251. return;
  2252. }
  2253. evhdl = *(int *)eventhdl;
  2254. close(evhdl);
  2255. mg_free(eventhdl);
  2256. }
  2257. #endif
  2258. #endif
  2259. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2260. struct posix_event {
  2261. pthread_mutex_t mutex;
  2262. pthread_cond_t cond;
  2263. int signaled;
  2264. };
  2265. static void *
  2266. event_create(void)
  2267. {
  2268. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2269. if (ret == 0) {
  2270. /* out of memory */
  2271. return 0;
  2272. }
  2273. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2274. /* pthread mutex not available */
  2275. mg_free(ret);
  2276. return 0;
  2277. }
  2278. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2279. /* pthread cond not available */
  2280. pthread_mutex_destroy(&(ret->mutex));
  2281. mg_free(ret);
  2282. return 0;
  2283. }
  2284. ret->signaled = 0;
  2285. return (void *)ret;
  2286. }
  2287. static int
  2288. event_wait(void *eventhdl)
  2289. {
  2290. struct posix_event *ev = (struct posix_event *)eventhdl;
  2291. pthread_mutex_lock(&(ev->mutex));
  2292. while (!ev->signaled) {
  2293. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2294. }
  2295. ev->signaled = 0;
  2296. pthread_mutex_unlock(&(ev->mutex));
  2297. return 1;
  2298. }
  2299. static int
  2300. event_signal(void *eventhdl)
  2301. {
  2302. struct posix_event *ev = (struct posix_event *)eventhdl;
  2303. pthread_mutex_lock(&(ev->mutex));
  2304. pthread_cond_signal(&(ev->cond));
  2305. ev->signaled = 1;
  2306. pthread_mutex_unlock(&(ev->mutex));
  2307. return 1;
  2308. }
  2309. static void
  2310. event_destroy(void *eventhdl)
  2311. {
  2312. struct posix_event *ev = (struct posix_event *)eventhdl;
  2313. pthread_cond_destroy(&(ev->cond));
  2314. pthread_mutex_destroy(&(ev->mutex));
  2315. mg_free(ev);
  2316. }
  2317. #endif
  2318. static void
  2319. mg_set_thread_name(const char *name)
  2320. {
  2321. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2322. mg_snprintf(
  2323. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2324. #if defined(_WIN32)
  2325. #if defined(_MSC_VER)
  2326. /* Windows and Visual Studio Compiler */
  2327. __try {
  2328. THREADNAME_INFO info;
  2329. info.dwType = 0x1000;
  2330. info.szName = threadName;
  2331. info.dwThreadID = ~0U;
  2332. info.dwFlags = 0;
  2333. RaiseException(0x406D1388,
  2334. 0,
  2335. sizeof(info) / sizeof(ULONG_PTR),
  2336. (ULONG_PTR *)&info);
  2337. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2338. }
  2339. #elif defined(__MINGW32__)
  2340. /* No option known to set thread name for MinGW known */
  2341. #endif
  2342. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2343. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2344. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2345. #if defined(__MACH__)
  2346. /* OS X only current thread name can be changed */
  2347. (void)pthread_setname_np(threadName);
  2348. #else
  2349. (void)pthread_setname_np(pthread_self(), threadName);
  2350. #endif
  2351. #elif defined(__linux__)
  2352. /* On Linux we can use the prctl function.
  2353. * When building for Linux Standard Base (LSB) use
  2354. * NO_THREAD_NAME. However, thread names are a big
  2355. * help for debugging, so the stadard is to set them.
  2356. */
  2357. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2358. #endif
  2359. }
  2360. #else /* !defined(NO_THREAD_NAME) */
  2361. void
  2362. mg_set_thread_name(const char *threadName)
  2363. {
  2364. }
  2365. #endif
  2366. const struct mg_option *
  2367. mg_get_valid_options(void)
  2368. {
  2369. return config_options;
  2370. }
  2371. /* Do not open file (unused) */
  2372. #define MG_FOPEN_MODE_NONE (0)
  2373. /* Open file for read only access */
  2374. #define MG_FOPEN_MODE_READ (1)
  2375. /* Open file for writing, create and overwrite */
  2376. #define MG_FOPEN_MODE_WRITE (2)
  2377. /* Open file for writing, create and append */
  2378. #define MG_FOPEN_MODE_APPEND (4)
  2379. static int
  2380. is_file_opened(const struct mg_file_access *fileacc)
  2381. {
  2382. if (!fileacc) {
  2383. return 0;
  2384. }
  2385. return (fileacc->fp != NULL);
  2386. }
  2387. #if !defined(NO_FILESYSTEMS)
  2388. static int mg_stat(const struct mg_connection *conn,
  2389. const char *path,
  2390. struct mg_file_stat *filep);
  2391. /* Reject files with special characters (for Windows) */
  2392. static int
  2393. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2394. {
  2395. const uint8_t *c = (const uint8_t *)path;
  2396. (void)conn; /* not used */
  2397. if ((c == NULL) || (c[0] == 0)) {
  2398. /* Null pointer or empty path --> suspicious */
  2399. return 1;
  2400. }
  2401. #if defined(_WIN32)
  2402. while (*c) {
  2403. if (*c < 32) {
  2404. /* Control character */
  2405. return 1;
  2406. }
  2407. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2408. /* stdin/stdout redirection character */
  2409. return 1;
  2410. }
  2411. if ((*c == '*') || (*c == '?')) {
  2412. /* Wildcard character */
  2413. return 1;
  2414. }
  2415. if (*c == '"') {
  2416. /* Windows quotation */
  2417. return 1;
  2418. }
  2419. c++;
  2420. }
  2421. #endif
  2422. /* Nothing suspicious found */
  2423. return 0;
  2424. }
  2425. /* mg_fopen will open a file either in memory or on the disk.
  2426. * The input parameter path is a string in UTF-8 encoding.
  2427. * The input parameter mode is MG_FOPEN_MODE_*
  2428. * On success, fp will be set in the output struct mg_file.
  2429. * All status members will also be set.
  2430. * The function returns 1 on success, 0 on error. */
  2431. static int
  2432. mg_fopen(const struct mg_connection *conn,
  2433. const char *path,
  2434. int mode,
  2435. struct mg_file *filep)
  2436. {
  2437. int found;
  2438. if (!filep) {
  2439. return 0;
  2440. }
  2441. filep->access.fp = NULL;
  2442. if (mg_path_suspicious(conn, path)) {
  2443. return 0;
  2444. }
  2445. /* filep is initialized in mg_stat: all fields with memset to,
  2446. * some fields like size and modification date with values */
  2447. found = mg_stat(conn, path, &(filep->stat));
  2448. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2449. /* file does not exist and will not be created */
  2450. return 0;
  2451. }
  2452. #if defined(_WIN32)
  2453. {
  2454. wchar_t wbuf[UTF16_PATH_MAX];
  2455. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2456. switch (mode) {
  2457. case MG_FOPEN_MODE_READ:
  2458. filep->access.fp = _wfopen(wbuf, L"rb");
  2459. break;
  2460. case MG_FOPEN_MODE_WRITE:
  2461. filep->access.fp = _wfopen(wbuf, L"wb");
  2462. break;
  2463. case MG_FOPEN_MODE_APPEND:
  2464. filep->access.fp = _wfopen(wbuf, L"ab");
  2465. break;
  2466. }
  2467. }
  2468. #else
  2469. /* Linux et al already use unicode. No need to convert. */
  2470. switch (mode) {
  2471. case MG_FOPEN_MODE_READ:
  2472. filep->access.fp = fopen(path, "r");
  2473. break;
  2474. case MG_FOPEN_MODE_WRITE:
  2475. filep->access.fp = fopen(path, "w");
  2476. break;
  2477. case MG_FOPEN_MODE_APPEND:
  2478. filep->access.fp = fopen(path, "a");
  2479. break;
  2480. }
  2481. #endif
  2482. if (!found) {
  2483. /* File did not exist before fopen was called.
  2484. * Maybe it has been created now. Get stat info
  2485. * like creation time now. */
  2486. found = mg_stat(conn, path, &(filep->stat));
  2487. (void)found;
  2488. }
  2489. /* return OK if file is opened */
  2490. return (filep->access.fp != NULL);
  2491. }
  2492. /* return 0 on success, just like fclose */
  2493. static int
  2494. mg_fclose(struct mg_file_access *fileacc)
  2495. {
  2496. int ret = -1;
  2497. if (fileacc != NULL) {
  2498. if (fileacc->fp != NULL) {
  2499. ret = fclose(fileacc->fp);
  2500. }
  2501. /* reset all members of fileacc */
  2502. memset(fileacc, 0, sizeof(*fileacc));
  2503. }
  2504. return ret;
  2505. }
  2506. #endif /* NO_FILESYSTEMS */
  2507. static void
  2508. mg_strlcpy(char *dst, const char *src, size_t n)
  2509. {
  2510. for (; *src != '\0' && n > 1; n--) {
  2511. *dst++ = *src++;
  2512. }
  2513. *dst = '\0';
  2514. }
  2515. static int
  2516. lowercase(const char *s)
  2517. {
  2518. return tolower((unsigned char)*s);
  2519. }
  2520. int
  2521. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2522. {
  2523. int diff = 0;
  2524. if (len > 0) {
  2525. do {
  2526. diff = lowercase(s1++) - lowercase(s2++);
  2527. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2528. }
  2529. return diff;
  2530. }
  2531. int
  2532. mg_strcasecmp(const char *s1, const char *s2)
  2533. {
  2534. int diff;
  2535. do {
  2536. diff = lowercase(s1++) - lowercase(s2++);
  2537. } while (diff == 0 && s1[-1] != '\0');
  2538. return diff;
  2539. }
  2540. static char *
  2541. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2542. {
  2543. char *p;
  2544. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2545. * defined */
  2546. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2547. mg_strlcpy(p, ptr, len + 1);
  2548. }
  2549. return p;
  2550. }
  2551. static char *
  2552. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2553. {
  2554. return mg_strndup_ctx(str, strlen(str), ctx);
  2555. }
  2556. static char *
  2557. mg_strdup(const char *str)
  2558. {
  2559. return mg_strndup_ctx(str, strlen(str), NULL);
  2560. }
  2561. static const char *
  2562. mg_strcasestr(const char *big_str, const char *small_str)
  2563. {
  2564. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2565. if (big_len >= small_len) {
  2566. for (i = 0; i <= (big_len - small_len); i++) {
  2567. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2568. return big_str + i;
  2569. }
  2570. }
  2571. }
  2572. return NULL;
  2573. }
  2574. /* Return null terminated string of given maximum length.
  2575. * Report errors if length is exceeded. */
  2576. static void
  2577. mg_vsnprintf(const struct mg_connection *conn,
  2578. int *truncated,
  2579. char *buf,
  2580. size_t buflen,
  2581. const char *fmt,
  2582. va_list ap)
  2583. {
  2584. int n, ok;
  2585. if (buflen == 0) {
  2586. if (truncated) {
  2587. *truncated = 1;
  2588. }
  2589. return;
  2590. }
  2591. #if defined(__clang__)
  2592. #pragma clang diagnostic push
  2593. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2594. /* Using fmt as a non-literal is intended here, since it is mostly called
  2595. * indirectly by mg_snprintf */
  2596. #endif
  2597. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2598. ok = (n >= 0) && ((size_t)n < buflen);
  2599. #if defined(__clang__)
  2600. #pragma clang diagnostic pop
  2601. #endif
  2602. if (ok) {
  2603. if (truncated) {
  2604. *truncated = 0;
  2605. }
  2606. } else {
  2607. if (truncated) {
  2608. *truncated = 1;
  2609. }
  2610. mg_cry_internal(conn,
  2611. "truncating vsnprintf buffer: [%.*s]",
  2612. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2613. buf);
  2614. n = (int)buflen - 1;
  2615. }
  2616. buf[n] = '\0';
  2617. }
  2618. static void
  2619. mg_snprintf(const struct mg_connection *conn,
  2620. int *truncated,
  2621. char *buf,
  2622. size_t buflen,
  2623. const char *fmt,
  2624. ...)
  2625. {
  2626. va_list ap;
  2627. va_start(ap, fmt);
  2628. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2629. va_end(ap);
  2630. }
  2631. static int
  2632. get_option_index(const char *name)
  2633. {
  2634. int i;
  2635. for (i = 0; config_options[i].name != NULL; i++) {
  2636. if (strcmp(config_options[i].name, name) == 0) {
  2637. return i;
  2638. }
  2639. }
  2640. return -1;
  2641. }
  2642. const char *
  2643. mg_get_option(const struct mg_context *ctx, const char *name)
  2644. {
  2645. int i;
  2646. if ((i = get_option_index(name)) == -1) {
  2647. return NULL;
  2648. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2649. return "";
  2650. } else {
  2651. return ctx->dd.config[i];
  2652. }
  2653. }
  2654. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2655. struct mg_context *
  2656. mg_get_context(const struct mg_connection *conn)
  2657. {
  2658. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2659. }
  2660. void *
  2661. mg_get_user_data(const struct mg_context *ctx)
  2662. {
  2663. return (ctx == NULL) ? NULL : ctx->user_data;
  2664. }
  2665. void *
  2666. mg_get_user_context_data(const struct mg_connection *conn)
  2667. {
  2668. return mg_get_user_data(mg_get_context(conn));
  2669. }
  2670. void *
  2671. mg_get_thread_pointer(const struct mg_connection *conn)
  2672. {
  2673. /* both methods should return the same pointer */
  2674. if (conn) {
  2675. /* quick access, in case conn is known */
  2676. return conn->tls_user_ptr;
  2677. } else {
  2678. /* otherwise get pointer from thread local storage (TLS) */
  2679. struct mg_workerTLS *tls =
  2680. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2681. return tls->user_ptr;
  2682. }
  2683. }
  2684. void
  2685. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2686. {
  2687. if (const_conn != NULL) {
  2688. /* Const cast, since "const struct mg_connection *" does not mean
  2689. * the connection object is not modified. Here "const" is used,
  2690. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2691. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2692. conn->request_info.conn_data = data;
  2693. }
  2694. }
  2695. void *
  2696. mg_get_user_connection_data(const struct mg_connection *conn)
  2697. {
  2698. if (conn != NULL) {
  2699. return conn->request_info.conn_data;
  2700. }
  2701. return NULL;
  2702. }
  2703. int
  2704. mg_get_server_ports(const struct mg_context *ctx,
  2705. int size,
  2706. struct mg_server_port *ports)
  2707. {
  2708. int i, cnt = 0;
  2709. if (size <= 0) {
  2710. return -1;
  2711. }
  2712. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2713. if (!ctx) {
  2714. return -1;
  2715. }
  2716. if (!ctx->listening_sockets) {
  2717. return -1;
  2718. }
  2719. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2720. ports[cnt].port =
  2721. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2722. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2723. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2724. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2725. /* IPv4 */
  2726. ports[cnt].protocol = 1;
  2727. cnt++;
  2728. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2729. /* IPv6 */
  2730. ports[cnt].protocol = 3;
  2731. cnt++;
  2732. }
  2733. }
  2734. return cnt;
  2735. }
  2736. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2737. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2738. #endif
  2739. static void
  2740. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2741. {
  2742. buf[0] = '\0';
  2743. if (!usa) {
  2744. return;
  2745. }
  2746. if (usa->sa.sa_family == AF_INET) {
  2747. getnameinfo(&usa->sa,
  2748. sizeof(usa->sin),
  2749. buf,
  2750. (unsigned)len,
  2751. NULL,
  2752. 0,
  2753. NI_NUMERICHOST);
  2754. }
  2755. #if defined(USE_IPV6)
  2756. else if (usa->sa.sa_family == AF_INET6) {
  2757. getnameinfo(&usa->sa,
  2758. sizeof(usa->sin6),
  2759. buf,
  2760. (unsigned)len,
  2761. NULL,
  2762. 0,
  2763. NI_NUMERICHOST);
  2764. }
  2765. #endif
  2766. #if defined(USE_X_DOM_SOCKET)
  2767. else if (usa->sa.sa_family == AF_UNIX) {
  2768. /* TODO: Define a remote address for unix domain sockets.
  2769. * This code will always return "localhost", identical to http+tcp:
  2770. getnameinfo(&usa->sa,
  2771. sizeof(usa->sun),
  2772. buf,
  2773. (unsigned)len,
  2774. NULL,
  2775. 0,
  2776. NI_NUMERICHOST);
  2777. */
  2778. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2779. buf[len] = 0;
  2780. }
  2781. #endif
  2782. }
  2783. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2784. * included in all responses other than 100, 101, 5xx. */
  2785. static void
  2786. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2787. {
  2788. #if !defined(REENTRANT_TIME)
  2789. struct tm *tm;
  2790. tm = ((t != NULL) ? gmtime(t) : NULL);
  2791. if (tm != NULL) {
  2792. #else
  2793. struct tm _tm;
  2794. struct tm *tm = &_tm;
  2795. if (t != NULL) {
  2796. gmtime_r(t, tm);
  2797. #endif
  2798. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2799. } else {
  2800. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2801. buf[buf_len - 1] = '\0';
  2802. }
  2803. }
  2804. /* difftime for struct timespec. Return value is in seconds. */
  2805. static double
  2806. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2807. {
  2808. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2809. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2810. }
  2811. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2812. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2813. const char *func,
  2814. unsigned line,
  2815. const char *fmt,
  2816. va_list ap);
  2817. #include "external_mg_cry_internal_impl.inl"
  2818. #elif !defined(NO_FILESYSTEMS)
  2819. /* Print error message to the opened error log stream. */
  2820. static void
  2821. mg_cry_internal_impl(const struct mg_connection *conn,
  2822. const char *func,
  2823. unsigned line,
  2824. const char *fmt,
  2825. va_list ap)
  2826. {
  2827. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2828. struct mg_file fi;
  2829. time_t timestamp;
  2830. /* Unused, in the RELEASE build */
  2831. (void)func;
  2832. (void)line;
  2833. #if defined(GCC_DIAGNOSTIC)
  2834. #pragma GCC diagnostic push
  2835. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2836. #endif
  2837. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2838. #if defined(GCC_DIAGNOSTIC)
  2839. #pragma GCC diagnostic pop
  2840. #endif
  2841. buf[sizeof(buf) - 1] = 0;
  2842. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2843. if (!conn) {
  2844. puts(buf);
  2845. return;
  2846. }
  2847. /* Do not lock when getting the callback value, here and below.
  2848. * I suppose this is fine, since function cannot disappear in the
  2849. * same way string option can. */
  2850. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2851. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2852. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2853. if (mg_fopen(conn,
  2854. conn->dom_ctx->config[ERROR_LOG_FILE],
  2855. MG_FOPEN_MODE_APPEND,
  2856. &fi)
  2857. == 0) {
  2858. fi.access.fp = NULL;
  2859. }
  2860. } else {
  2861. fi.access.fp = NULL;
  2862. }
  2863. if (fi.access.fp != NULL) {
  2864. flockfile(fi.access.fp);
  2865. timestamp = time(NULL);
  2866. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2867. fprintf(fi.access.fp,
  2868. "[%010lu] [error] [client %s] ",
  2869. (unsigned long)timestamp,
  2870. src_addr);
  2871. if (conn->request_info.request_method != NULL) {
  2872. fprintf(fi.access.fp,
  2873. "%s %s: ",
  2874. conn->request_info.request_method,
  2875. conn->request_info.request_uri
  2876. ? conn->request_info.request_uri
  2877. : "");
  2878. }
  2879. fprintf(fi.access.fp, "%s", buf);
  2880. fputc('\n', fi.access.fp);
  2881. fflush(fi.access.fp);
  2882. funlockfile(fi.access.fp);
  2883. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2884. * mg_cry here anyway ;-) */
  2885. }
  2886. }
  2887. }
  2888. #else
  2889. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2890. #endif /* Externally provided function */
  2891. /* Construct fake connection structure. Used for logging, if connection
  2892. * is not applicable at the moment of logging. */
  2893. static struct mg_connection *
  2894. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2895. {
  2896. static const struct mg_connection conn_zero = {0};
  2897. *fc = conn_zero;
  2898. fc->phys_ctx = ctx;
  2899. fc->dom_ctx = &(ctx->dd);
  2900. return fc;
  2901. }
  2902. static void
  2903. mg_cry_internal_wrap(const struct mg_connection *conn,
  2904. struct mg_context *ctx,
  2905. const char *func,
  2906. unsigned line,
  2907. const char *fmt,
  2908. ...)
  2909. {
  2910. va_list ap;
  2911. va_start(ap, fmt);
  2912. if (!conn && ctx) {
  2913. struct mg_connection fc;
  2914. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2915. } else {
  2916. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2917. }
  2918. va_end(ap);
  2919. }
  2920. void
  2921. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2922. {
  2923. va_list ap;
  2924. va_start(ap, fmt);
  2925. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2926. va_end(ap);
  2927. }
  2928. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2929. const char *
  2930. mg_version(void)
  2931. {
  2932. return CIVETWEB_VERSION;
  2933. }
  2934. const struct mg_request_info *
  2935. mg_get_request_info(const struct mg_connection *conn)
  2936. {
  2937. if (!conn) {
  2938. return NULL;
  2939. }
  2940. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2941. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2942. char txt[16];
  2943. struct mg_workerTLS *tls =
  2944. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2945. sprintf(txt, "%03i", conn->response_info.status_code);
  2946. if (strlen(txt) == 3) {
  2947. memcpy(tls->txtbuf, txt, 4);
  2948. } else {
  2949. strcpy(tls->txtbuf, "ERR");
  2950. }
  2951. ((struct mg_connection *)conn)->request_info.local_uri =
  2952. tls->txtbuf; /* use thread safe buffer */
  2953. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2954. tls->txtbuf; /* use the same thread safe buffer */
  2955. ((struct mg_connection *)conn)->request_info.request_uri =
  2956. tls->txtbuf; /* use the same thread safe buffer */
  2957. ((struct mg_connection *)conn)->request_info.num_headers =
  2958. conn->response_info.num_headers;
  2959. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2960. conn->response_info.http_headers,
  2961. sizeof(conn->response_info.http_headers));
  2962. } else
  2963. #endif
  2964. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2965. return NULL;
  2966. }
  2967. return &conn->request_info;
  2968. }
  2969. const struct mg_response_info *
  2970. mg_get_response_info(const struct mg_connection *conn)
  2971. {
  2972. if (!conn) {
  2973. return NULL;
  2974. }
  2975. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2976. return NULL;
  2977. }
  2978. return &conn->response_info;
  2979. }
  2980. static const char *
  2981. get_proto_name(const struct mg_connection *conn)
  2982. {
  2983. #if defined(__clang__)
  2984. #pragma clang diagnostic push
  2985. #pragma clang diagnostic ignored "-Wunreachable-code"
  2986. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2987. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2988. * unreachable, but splitting into four different #ifdef clauses here is
  2989. * more complicated.
  2990. */
  2991. #endif
  2992. const struct mg_request_info *ri = &conn->request_info;
  2993. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2994. ? (ri->is_ssl ? "wss" : "ws")
  2995. : (ri->is_ssl ? "https" : "http"));
  2996. return proto;
  2997. #if defined(__clang__)
  2998. #pragma clang diagnostic pop
  2999. #endif
  3000. }
  3001. static int
  3002. mg_construct_local_link(const struct mg_connection *conn,
  3003. char *buf,
  3004. size_t buflen,
  3005. const char *define_proto,
  3006. int define_port,
  3007. const char *define_uri)
  3008. {
  3009. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3010. return -1;
  3011. } else {
  3012. int truncated = 0;
  3013. const struct mg_request_info *ri = &conn->request_info;
  3014. const char *proto =
  3015. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3016. const char *uri =
  3017. (define_uri != NULL)
  3018. ? define_uri
  3019. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3020. int port = (define_port > 0) ? define_port : ri->server_port;
  3021. int default_port = 80;
  3022. if (uri == NULL) {
  3023. return -1;
  3024. }
  3025. #if defined(USE_X_DOM_SOCKET)
  3026. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3027. /* TODO: Define and document a link for UNIX domain sockets. */
  3028. /* There seems to be no official standard for this.
  3029. * Common uses seem to be "httpunix://", "http.unix://" or
  3030. * "http+unix://" as a protocol definition string, followed by
  3031. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3032. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3033. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3034. * "" (completely skipping the server name part). In any case, the
  3035. * last part is the server local path. */
  3036. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3037. mg_snprintf(conn,
  3038. &truncated,
  3039. buf,
  3040. buflen,
  3041. "%s.unix://%s%s",
  3042. proto,
  3043. server_name,
  3044. ri->local_uri);
  3045. default_port = 0;
  3046. return 0;
  3047. }
  3048. #endif
  3049. if (define_proto) {
  3050. /* If we got a protocol name, use the default port accordingly. */
  3051. if ((0 == strcmp(define_proto, "https"))
  3052. || (0 == strcmp(define_proto, "wss"))) {
  3053. default_port = 443;
  3054. }
  3055. } else if (ri->is_ssl) {
  3056. /* If we did not get a protocol name, use TLS as default if it is
  3057. * already used. */
  3058. default_port = 443;
  3059. }
  3060. {
  3061. #if defined(USE_IPV6)
  3062. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3063. #endif
  3064. int auth_domain_check_enabled =
  3065. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3066. && (!mg_strcasecmp(
  3067. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3068. const char *server_domain =
  3069. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3070. char portstr[16];
  3071. char server_ip[48];
  3072. if (port != default_port) {
  3073. sprintf(portstr, ":%u", (unsigned)port);
  3074. } else {
  3075. portstr[0] = 0;
  3076. }
  3077. if (!auth_domain_check_enabled || !server_domain) {
  3078. sockaddr_to_string(server_ip,
  3079. sizeof(server_ip),
  3080. &conn->client.lsa);
  3081. server_domain = server_ip;
  3082. }
  3083. mg_snprintf(conn,
  3084. &truncated,
  3085. buf,
  3086. buflen,
  3087. #if defined(USE_IPV6)
  3088. "%s://%s%s%s%s%s",
  3089. proto,
  3090. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3091. server_domain,
  3092. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3093. #else
  3094. "%s://%s%s%s",
  3095. proto,
  3096. server_domain,
  3097. #endif
  3098. portstr,
  3099. ri->local_uri);
  3100. if (truncated) {
  3101. return -1;
  3102. }
  3103. return 0;
  3104. }
  3105. }
  3106. }
  3107. int
  3108. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3109. {
  3110. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3111. }
  3112. /* Skip the characters until one of the delimiters characters found.
  3113. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3114. * Advance pointer to buffer to the next word. Return found 0-terminated
  3115. * word.
  3116. * Delimiters can be quoted with quotechar. */
  3117. static char *
  3118. skip_quoted(char **buf,
  3119. const char *delimiters,
  3120. const char *whitespace,
  3121. char quotechar)
  3122. {
  3123. char *p, *begin_word, *end_word, *end_whitespace;
  3124. begin_word = *buf;
  3125. end_word = begin_word + strcspn(begin_word, delimiters);
  3126. /* Check for quotechar */
  3127. if (end_word > begin_word) {
  3128. p = end_word - 1;
  3129. while (*p == quotechar) {
  3130. /* While the delimiter is quoted, look for the next delimiter.
  3131. */
  3132. /* This happens, e.g., in calls from parse_auth_header,
  3133. * if the user name contains a " character. */
  3134. /* If there is anything beyond end_word, copy it. */
  3135. if (*end_word != '\0') {
  3136. size_t end_off = strcspn(end_word + 1, delimiters);
  3137. memmove(p, end_word, end_off + 1);
  3138. p += end_off; /* p must correspond to end_word - 1 */
  3139. end_word += end_off + 1;
  3140. } else {
  3141. *p = '\0';
  3142. break;
  3143. }
  3144. }
  3145. for (p++; p < end_word; p++) {
  3146. *p = '\0';
  3147. }
  3148. }
  3149. if (*end_word == '\0') {
  3150. *buf = end_word;
  3151. } else {
  3152. #if defined(GCC_DIAGNOSTIC)
  3153. /* Disable spurious conversion warning for GCC */
  3154. #pragma GCC diagnostic push
  3155. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3156. #endif /* defined(GCC_DIAGNOSTIC) */
  3157. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3158. #if defined(GCC_DIAGNOSTIC)
  3159. #pragma GCC diagnostic pop
  3160. #endif /* defined(GCC_DIAGNOSTIC) */
  3161. for (p = end_word; p < end_whitespace; p++) {
  3162. *p = '\0';
  3163. }
  3164. *buf = end_whitespace;
  3165. }
  3166. return begin_word;
  3167. }
  3168. /* Return HTTP header value, or NULL if not found. */
  3169. static const char *
  3170. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3171. {
  3172. int i;
  3173. for (i = 0; i < num_hdr; i++) {
  3174. if (!mg_strcasecmp(name, hdr[i].name)) {
  3175. return hdr[i].value;
  3176. }
  3177. }
  3178. return NULL;
  3179. }
  3180. #if defined(USE_WEBSOCKET)
  3181. /* Retrieve requested HTTP header multiple values, and return the number of
  3182. * found occurrences */
  3183. static int
  3184. get_req_headers(const struct mg_request_info *ri,
  3185. const char *name,
  3186. const char **output,
  3187. int output_max_size)
  3188. {
  3189. int i;
  3190. int cnt = 0;
  3191. if (ri) {
  3192. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3193. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3194. output[cnt++] = ri->http_headers[i].value;
  3195. }
  3196. }
  3197. }
  3198. return cnt;
  3199. }
  3200. #endif
  3201. const char *
  3202. mg_get_header(const struct mg_connection *conn, const char *name)
  3203. {
  3204. if (!conn) {
  3205. return NULL;
  3206. }
  3207. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3208. return get_header(conn->request_info.http_headers,
  3209. conn->request_info.num_headers,
  3210. name);
  3211. }
  3212. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3213. return get_header(conn->response_info.http_headers,
  3214. conn->response_info.num_headers,
  3215. name);
  3216. }
  3217. return NULL;
  3218. }
  3219. static const char *
  3220. get_http_version(const struct mg_connection *conn)
  3221. {
  3222. if (!conn) {
  3223. return NULL;
  3224. }
  3225. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3226. return conn->request_info.http_version;
  3227. }
  3228. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3229. return conn->response_info.http_version;
  3230. }
  3231. return NULL;
  3232. }
  3233. /* A helper function for traversing a comma separated list of values.
  3234. * It returns a list pointer shifted to the next value, or NULL if the end
  3235. * of the list found.
  3236. * Value is stored in val vector. If value has form "x=y", then eq_val
  3237. * vector is initialized to point to the "y" part, and val vector length
  3238. * is adjusted to point only to "x". */
  3239. static const char *
  3240. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3241. {
  3242. int end;
  3243. reparse:
  3244. if (val == NULL || list == NULL || *list == '\0') {
  3245. /* End of the list */
  3246. return NULL;
  3247. }
  3248. /* Skip over leading LWS */
  3249. while (*list == ' ' || *list == '\t')
  3250. list++;
  3251. val->ptr = list;
  3252. if ((list = strchr(val->ptr, ',')) != NULL) {
  3253. /* Comma found. Store length and shift the list ptr */
  3254. val->len = ((size_t)(list - val->ptr));
  3255. list++;
  3256. } else {
  3257. /* This value is the last one */
  3258. list = val->ptr + strlen(val->ptr);
  3259. val->len = ((size_t)(list - val->ptr));
  3260. }
  3261. /* Adjust length for trailing LWS */
  3262. end = (int)val->len - 1;
  3263. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3264. end--;
  3265. val->len = (size_t)(end) + (size_t)(1);
  3266. if (val->len == 0) {
  3267. /* Ignore any empty entries. */
  3268. goto reparse;
  3269. }
  3270. if (eq_val != NULL) {
  3271. /* Value has form "x=y", adjust pointers and lengths
  3272. * so that val points to "x", and eq_val points to "y". */
  3273. eq_val->len = 0;
  3274. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3275. if (eq_val->ptr != NULL) {
  3276. eq_val->ptr++; /* Skip over '=' character */
  3277. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3278. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3279. }
  3280. }
  3281. return list;
  3282. }
  3283. /* A helper function for checking if a comma separated list of values
  3284. * contains
  3285. * the given option (case insensitvely).
  3286. * 'header' can be NULL, in which case false is returned. */
  3287. static int
  3288. header_has_option(const char *header, const char *option)
  3289. {
  3290. struct vec opt_vec;
  3291. struct vec eq_vec;
  3292. DEBUG_ASSERT(option != NULL);
  3293. DEBUG_ASSERT(option[0] != '\0');
  3294. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3295. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3296. return 1;
  3297. }
  3298. return 0;
  3299. }
  3300. /* Perform case-insensitive match of string against pattern */
  3301. static ptrdiff_t
  3302. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3303. {
  3304. const char *or_str;
  3305. ptrdiff_t i, j, len, res;
  3306. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3307. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3308. return (res > 0) ? res
  3309. : match_prefix(or_str + 1,
  3310. (size_t)((pattern + pattern_len)
  3311. - (or_str + 1)),
  3312. str);
  3313. }
  3314. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3315. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3316. continue;
  3317. } else if (pattern[i] == '$') {
  3318. return (str[j] == '\0') ? j : -1;
  3319. } else if (pattern[i] == '*') {
  3320. i++;
  3321. if (pattern[i] == '*') {
  3322. i++;
  3323. len = (ptrdiff_t)strlen(str + j);
  3324. } else {
  3325. len = (ptrdiff_t)strcspn(str + j, "/");
  3326. }
  3327. if (i == (ptrdiff_t)pattern_len) {
  3328. return j + len;
  3329. }
  3330. do {
  3331. res = match_prefix(pattern + i,
  3332. (pattern_len - (size_t)i),
  3333. str + j + len);
  3334. } while (res == -1 && len-- > 0);
  3335. return (res == -1) ? -1 : j + res + len;
  3336. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3337. return -1;
  3338. }
  3339. }
  3340. return (ptrdiff_t)j;
  3341. }
  3342. static ptrdiff_t
  3343. match_prefix_strlen(const char *pattern, const char *str)
  3344. {
  3345. if (pattern == NULL) {
  3346. return -1;
  3347. }
  3348. return match_prefix(pattern, strlen(pattern), str);
  3349. }
  3350. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3351. * This function must tolerate situations when connection info is not
  3352. * set up, for example if request parsing failed. */
  3353. static int
  3354. should_keep_alive(const struct mg_connection *conn)
  3355. {
  3356. const char *http_version;
  3357. const char *header;
  3358. /* First satisfy needs of the server */
  3359. if ((conn == NULL) || conn->must_close) {
  3360. /* Close, if civetweb framework needs to close */
  3361. return 0;
  3362. }
  3363. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3364. /* Close, if keep alive is not enabled */
  3365. return 0;
  3366. }
  3367. /* Check explicit wish of the client */
  3368. header = mg_get_header(conn, "Connection");
  3369. if (header) {
  3370. /* If there is a connection header from the client, obey */
  3371. if (header_has_option(header, "keep-alive")) {
  3372. return 1;
  3373. }
  3374. return 0;
  3375. }
  3376. /* Use default of the standard */
  3377. http_version = get_http_version(conn);
  3378. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3379. /* HTTP 1.1 default is keep alive */
  3380. return 1;
  3381. }
  3382. /* HTTP 1.0 (and earlier) default is to close the connection */
  3383. return 0;
  3384. }
  3385. static int
  3386. should_decode_url(const struct mg_connection *conn)
  3387. {
  3388. if (!conn || !conn->dom_ctx) {
  3389. return 0;
  3390. }
  3391. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3392. }
  3393. static int
  3394. should_decode_query_string(const struct mg_connection *conn)
  3395. {
  3396. if (!conn || !conn->dom_ctx) {
  3397. return 0;
  3398. }
  3399. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3400. == 0);
  3401. }
  3402. static const char *
  3403. suggest_connection_header(const struct mg_connection *conn)
  3404. {
  3405. return should_keep_alive(conn) ? "keep-alive" : "close";
  3406. }
  3407. #include "response.inl"
  3408. static void
  3409. send_no_cache_header(struct mg_connection *conn)
  3410. {
  3411. /* Send all current and obsolete cache opt-out directives. */
  3412. mg_response_header_add(conn,
  3413. "Cache-Control",
  3414. "no-cache, no-store, "
  3415. "must-revalidate, private, max-age=0",
  3416. -1);
  3417. mg_response_header_add(conn, "Expires", "0", -1);
  3418. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3419. /* Obsolete, but still send it for HTTP/1.0 */
  3420. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3421. }
  3422. }
  3423. static void
  3424. send_static_cache_header(struct mg_connection *conn)
  3425. {
  3426. #if !defined(NO_CACHING)
  3427. int max_age;
  3428. char val[64];
  3429. const char *cache_control =
  3430. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3431. /* If there is a full cache-control option configured,0 use it */
  3432. if (cache_control != NULL) {
  3433. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3434. return;
  3435. }
  3436. /* Read the server config to check how long a file may be cached.
  3437. * The configuration is in seconds. */
  3438. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3439. if (max_age <= 0) {
  3440. /* 0 means "do not cache". All values <0 are reserved
  3441. * and may be used differently in the future. */
  3442. /* If a file should not be cached, do not only send
  3443. * max-age=0, but also pragmas and Expires headers. */
  3444. send_no_cache_header(conn);
  3445. return;
  3446. }
  3447. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3448. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3449. /* See also https://www.mnot.net/cache_docs/ */
  3450. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3451. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3452. * leap
  3453. * year to 31622400 seconds. For the moment, we just send whatever has
  3454. * been configured, still the behavior for >1 year should be considered
  3455. * as undefined. */
  3456. mg_snprintf(
  3457. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3458. mg_response_header_add(conn, "Cache-Control", val, -1);
  3459. #else /* NO_CACHING */
  3460. send_no_cache_header(conn);
  3461. #endif /* !NO_CACHING */
  3462. }
  3463. static void
  3464. send_additional_header(struct mg_connection *conn)
  3465. {
  3466. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3467. #if !defined(NO_SSL)
  3468. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3469. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3470. if (max_age >= 0) {
  3471. char val[64];
  3472. mg_snprintf(conn,
  3473. NULL,
  3474. val,
  3475. sizeof(val),
  3476. "max-age=%lu",
  3477. (unsigned long)max_age);
  3478. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3479. }
  3480. }
  3481. #endif
  3482. if (header && header[0]) {
  3483. mg_response_header_add_lines(conn, header);
  3484. }
  3485. }
  3486. static void
  3487. send_cors_header(struct mg_connection *conn)
  3488. {
  3489. const char *origin_hdr = mg_get_header(conn, "Origin");
  3490. const char *cors_orig_cfg =
  3491. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3492. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3493. /* Cross-origin resource sharing (CORS), see
  3494. * http://www.html5rocks.com/en/tutorials/cors/,
  3495. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3496. * CORS preflight is not supported for files. */
  3497. mg_response_header_add(conn,
  3498. "Access-Control-Allow-Origin",
  3499. cors_orig_cfg,
  3500. -1);
  3501. }
  3502. }
  3503. #if !defined(NO_FILESYSTEMS)
  3504. static void handle_file_based_request(struct mg_connection *conn,
  3505. const char *path,
  3506. struct mg_file *filep);
  3507. #endif /* NO_FILESYSTEMS */
  3508. const char *
  3509. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3510. {
  3511. /* See IANA HTTP status code assignment:
  3512. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3513. */
  3514. switch (response_code) {
  3515. /* RFC2616 Section 10.1 - Informational 1xx */
  3516. case 100:
  3517. return "Continue"; /* RFC2616 Section 10.1.1 */
  3518. case 101:
  3519. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3520. case 102:
  3521. return "Processing"; /* RFC2518 Section 10.1 */
  3522. /* RFC2616 Section 10.2 - Successful 2xx */
  3523. case 200:
  3524. return "OK"; /* RFC2616 Section 10.2.1 */
  3525. case 201:
  3526. return "Created"; /* RFC2616 Section 10.2.2 */
  3527. case 202:
  3528. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3529. case 203:
  3530. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3531. case 204:
  3532. return "No Content"; /* RFC2616 Section 10.2.5 */
  3533. case 205:
  3534. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3535. case 206:
  3536. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3537. case 207:
  3538. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3539. */
  3540. case 208:
  3541. return "Already Reported"; /* RFC5842 Section 7.1 */
  3542. case 226:
  3543. return "IM used"; /* RFC3229 Section 10.4.1 */
  3544. /* RFC2616 Section 10.3 - Redirection 3xx */
  3545. case 300:
  3546. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3547. case 301:
  3548. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3549. case 302:
  3550. return "Found"; /* RFC2616 Section 10.3.3 */
  3551. case 303:
  3552. return "See Other"; /* RFC2616 Section 10.3.4 */
  3553. case 304:
  3554. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3555. case 305:
  3556. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3557. case 307:
  3558. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3559. case 308:
  3560. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3561. /* RFC2616 Section 10.4 - Client Error 4xx */
  3562. case 400:
  3563. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3564. case 401:
  3565. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3566. case 402:
  3567. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3568. case 403:
  3569. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3570. case 404:
  3571. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3572. case 405:
  3573. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3574. case 406:
  3575. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3576. case 407:
  3577. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3578. case 408:
  3579. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3580. case 409:
  3581. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3582. case 410:
  3583. return "Gone"; /* RFC2616 Section 10.4.11 */
  3584. case 411:
  3585. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3586. case 412:
  3587. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3588. case 413:
  3589. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3590. case 414:
  3591. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3592. case 415:
  3593. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3594. case 416:
  3595. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3596. */
  3597. case 417:
  3598. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3599. case 421:
  3600. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3601. case 422:
  3602. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3603. * Section 11.2 */
  3604. case 423:
  3605. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3606. case 424:
  3607. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3608. * Section 11.4 */
  3609. case 426:
  3610. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3611. case 428:
  3612. return "Precondition Required"; /* RFC 6585, Section 3 */
  3613. case 429:
  3614. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3615. case 431:
  3616. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3617. case 451:
  3618. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3619. * Section 3 */
  3620. /* RFC2616 Section 10.5 - Server Error 5xx */
  3621. case 500:
  3622. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3623. case 501:
  3624. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3625. case 502:
  3626. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3627. case 503:
  3628. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3629. case 504:
  3630. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3631. case 505:
  3632. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3633. case 506:
  3634. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3635. case 507:
  3636. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3637. * Section 11.5 */
  3638. case 508:
  3639. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3640. case 510:
  3641. return "Not Extended"; /* RFC 2774, Section 7 */
  3642. case 511:
  3643. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3644. /* Other status codes, not shown in the IANA HTTP status code
  3645. * assignment.
  3646. * E.g., "de facto" standards due to common use, ... */
  3647. case 418:
  3648. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3649. case 419:
  3650. return "Authentication Timeout"; /* common use */
  3651. case 420:
  3652. return "Enhance Your Calm"; /* common use */
  3653. case 440:
  3654. return "Login Timeout"; /* common use */
  3655. case 509:
  3656. return "Bandwidth Limit Exceeded"; /* common use */
  3657. default:
  3658. /* This error code is unknown. This should not happen. */
  3659. if (conn) {
  3660. mg_cry_internal(conn,
  3661. "Unknown HTTP response code: %u",
  3662. response_code);
  3663. }
  3664. /* Return at least a category according to RFC 2616 Section 10. */
  3665. if (response_code >= 100 && response_code < 200) {
  3666. /* Unknown informational status code */
  3667. return "Information";
  3668. }
  3669. if (response_code >= 200 && response_code < 300) {
  3670. /* Unknown success code */
  3671. return "Success";
  3672. }
  3673. if (response_code >= 300 && response_code < 400) {
  3674. /* Unknown redirection code */
  3675. return "Redirection";
  3676. }
  3677. if (response_code >= 400 && response_code < 500) {
  3678. /* Unknown request error code */
  3679. return "Client Error";
  3680. }
  3681. if (response_code >= 500 && response_code < 600) {
  3682. /* Unknown server error code */
  3683. return "Server Error";
  3684. }
  3685. /* Response code not even within reasonable range */
  3686. return "";
  3687. }
  3688. }
  3689. static int
  3690. mg_send_http_error_impl(struct mg_connection *conn,
  3691. int status,
  3692. const char *fmt,
  3693. va_list args)
  3694. {
  3695. char errmsg_buf[MG_BUF_LEN];
  3696. va_list ap;
  3697. int has_body;
  3698. #if !defined(NO_FILESYSTEMS)
  3699. char path_buf[UTF8_PATH_MAX];
  3700. int len, i, page_handler_found, scope, truncated;
  3701. const char *error_handler = NULL;
  3702. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3703. const char *error_page_file_ext, *tstr;
  3704. #endif /* NO_FILESYSTEMS */
  3705. int handled_by_callback = 0;
  3706. if ((conn == NULL) || (fmt == NULL)) {
  3707. return -2;
  3708. }
  3709. /* Set status (for log) */
  3710. conn->status_code = status;
  3711. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3712. has_body = ((status > 199) && (status != 204) && (status != 304));
  3713. /* Prepare message in buf, if required */
  3714. if (has_body
  3715. || (!conn->in_error_handler
  3716. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3717. /* Store error message in errmsg_buf */
  3718. va_copy(ap, args);
  3719. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3720. va_end(ap);
  3721. /* In a debug build, print all html errors */
  3722. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3723. }
  3724. /* If there is a http_error callback, call it.
  3725. * But don't do it recursively, if callback calls mg_send_http_error again.
  3726. */
  3727. if (!conn->in_error_handler
  3728. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3729. /* Mark in_error_handler to avoid recursion and call user callback. */
  3730. conn->in_error_handler = 1;
  3731. handled_by_callback =
  3732. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3733. == 0);
  3734. conn->in_error_handler = 0;
  3735. }
  3736. if (!handled_by_callback) {
  3737. /* Check for recursion */
  3738. if (conn->in_error_handler) {
  3739. DEBUG_TRACE(
  3740. "Recursion when handling error %u - fall back to default",
  3741. status);
  3742. #if !defined(NO_FILESYSTEMS)
  3743. } else {
  3744. /* Send user defined error pages, if defined */
  3745. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3746. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3747. page_handler_found = 0;
  3748. if (error_handler != NULL) {
  3749. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3750. switch (scope) {
  3751. case 1: /* Handler for specific error, e.g. 404 error */
  3752. mg_snprintf(conn,
  3753. &truncated,
  3754. path_buf,
  3755. sizeof(path_buf) - 32,
  3756. "%serror%03u.",
  3757. error_handler,
  3758. status);
  3759. break;
  3760. case 2: /* Handler for error group, e.g., 5xx error
  3761. * handler
  3762. * for all server errors (500-599) */
  3763. mg_snprintf(conn,
  3764. &truncated,
  3765. path_buf,
  3766. sizeof(path_buf) - 32,
  3767. "%serror%01uxx.",
  3768. error_handler,
  3769. status / 100);
  3770. break;
  3771. default: /* Handler for all errors */
  3772. mg_snprintf(conn,
  3773. &truncated,
  3774. path_buf,
  3775. sizeof(path_buf) - 32,
  3776. "%serror.",
  3777. error_handler);
  3778. break;
  3779. }
  3780. /* String truncation in buf may only occur if
  3781. * error_handler is too long. This string is
  3782. * from the config, not from a client. */
  3783. (void)truncated;
  3784. /* The following code is redundant, but it should avoid
  3785. * false positives in static source code analyzers and
  3786. * vulnerability scanners.
  3787. */
  3788. path_buf[sizeof(path_buf) - 32] = 0;
  3789. len = (int)strlen(path_buf);
  3790. if (len > (int)sizeof(path_buf) - 32) {
  3791. len = (int)sizeof(path_buf) - 32;
  3792. }
  3793. /* Start with the file extenstion from the configuration. */
  3794. tstr = strchr(error_page_file_ext, '.');
  3795. while (tstr) {
  3796. for (i = 1;
  3797. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3798. i++) {
  3799. /* buffer overrun is not possible here, since
  3800. * (i < 32) && (len < sizeof(path_buf) - 32)
  3801. * ==> (i + len) < sizeof(path_buf) */
  3802. path_buf[len + i - 1] = tstr[i];
  3803. }
  3804. /* buffer overrun is not possible here, since
  3805. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3806. * ==> (i + len) <= sizeof(path_buf) */
  3807. path_buf[len + i - 1] = 0;
  3808. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3809. DEBUG_TRACE("Check error page %s - found",
  3810. path_buf);
  3811. page_handler_found = 1;
  3812. break;
  3813. }
  3814. DEBUG_TRACE("Check error page %s - not found",
  3815. path_buf);
  3816. /* Continue with the next file extenstion from the
  3817. * configuration (if there is a next one). */
  3818. tstr = strchr(tstr + i, '.');
  3819. }
  3820. }
  3821. }
  3822. if (page_handler_found) {
  3823. conn->in_error_handler = 1;
  3824. handle_file_based_request(conn, path_buf, &error_page_file);
  3825. conn->in_error_handler = 0;
  3826. return 0;
  3827. }
  3828. #endif /* NO_FILESYSTEMS */
  3829. }
  3830. /* No custom error page. Send default error page. */
  3831. conn->must_close = 1;
  3832. mg_response_header_start(conn, status);
  3833. send_no_cache_header(conn);
  3834. send_additional_header(conn);
  3835. send_cors_header(conn);
  3836. if (has_body) {
  3837. mg_response_header_add(conn,
  3838. "Content-Type",
  3839. "text/plain; charset=utf-8",
  3840. -1);
  3841. }
  3842. mg_response_header_send(conn);
  3843. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3844. if (has_body) {
  3845. /* For other errors, send a generic error message. */
  3846. const char *status_text = mg_get_response_code_text(conn, status);
  3847. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3848. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3849. } else {
  3850. /* No body allowed. Close the connection. */
  3851. DEBUG_TRACE("Error %i", status);
  3852. }
  3853. }
  3854. return 0;
  3855. }
  3856. int
  3857. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3858. {
  3859. va_list ap;
  3860. int ret;
  3861. va_start(ap, fmt);
  3862. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3863. va_end(ap);
  3864. return ret;
  3865. }
  3866. int
  3867. mg_send_http_ok(struct mg_connection *conn,
  3868. const char *mime_type,
  3869. long long content_length)
  3870. {
  3871. if ((mime_type == NULL) || (*mime_type == 0)) {
  3872. /* No content type defined: default to text/html */
  3873. mime_type = "text/html";
  3874. }
  3875. mg_response_header_start(conn, 200);
  3876. send_no_cache_header(conn);
  3877. send_additional_header(conn);
  3878. send_cors_header(conn);
  3879. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3880. if (content_length < 0) {
  3881. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3882. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3883. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3884. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3885. }
  3886. } else {
  3887. char len[32];
  3888. int trunc = 0;
  3889. mg_snprintf(conn,
  3890. &trunc,
  3891. len,
  3892. sizeof(len),
  3893. "%" UINT64_FMT,
  3894. (uint64_t)content_length);
  3895. if (!trunc) {
  3896. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3897. * !trunc is always true */
  3898. mg_response_header_add(conn, "Content-Length", len, -1);
  3899. }
  3900. }
  3901. mg_response_header_send(conn);
  3902. return 0;
  3903. }
  3904. int
  3905. mg_send_http_redirect(struct mg_connection *conn,
  3906. const char *target_url,
  3907. int redirect_code)
  3908. {
  3909. /* Send a 30x redirect response.
  3910. *
  3911. * Redirect types (status codes):
  3912. *
  3913. * Status | Perm/Temp | Method | Version
  3914. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3915. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3916. * 303 | temporary | always use GET | HTTP/1.1
  3917. * 307 | temporary | always keep method | HTTP/1.1
  3918. * 308 | permanent | always keep method | HTTP/1.1
  3919. */
  3920. #if defined(MG_SEND_REDIRECT_BODY)
  3921. char redirect_body[MG_BUF_LEN];
  3922. size_t content_len = 0;
  3923. char content_len_text[32];
  3924. #endif
  3925. /* In case redirect_code=0, use 307. */
  3926. if (redirect_code == 0) {
  3927. redirect_code = 307;
  3928. }
  3929. /* In case redirect_code is none of the above, return error. */
  3930. if ((redirect_code != 301) && (redirect_code != 302)
  3931. && (redirect_code != 303) && (redirect_code != 307)
  3932. && (redirect_code != 308)) {
  3933. /* Parameter error */
  3934. return -2;
  3935. }
  3936. /* If target_url is not defined, redirect to "/". */
  3937. if ((target_url == NULL) || (*target_url == 0)) {
  3938. target_url = "/";
  3939. }
  3940. #if defined(MG_SEND_REDIRECT_BODY)
  3941. /* TODO: condition name? */
  3942. /* Prepare a response body with a hyperlink.
  3943. *
  3944. * According to RFC2616 (and RFC1945 before):
  3945. * Unless the request method was HEAD, the entity of the
  3946. * response SHOULD contain a short hypertext note with a hyperlink to
  3947. * the new URI(s).
  3948. *
  3949. * However, this response body is not useful in M2M communication.
  3950. * Probably the original reason in the RFC was, clients not supporting
  3951. * a 30x HTTP redirect could still show the HTML page and let the user
  3952. * press the link. Since current browsers support 30x HTTP, the additional
  3953. * HTML body does not seem to make sense anymore.
  3954. *
  3955. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3956. * but it only notes:
  3957. * The server's response payload usually contains a short
  3958. * hypertext note with a hyperlink to the new URI(s).
  3959. *
  3960. * Deactivated by default. If you need the 30x body, set the define.
  3961. */
  3962. mg_snprintf(
  3963. conn,
  3964. NULL /* ignore truncation */,
  3965. redirect_body,
  3966. sizeof(redirect_body),
  3967. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3968. redirect_text,
  3969. target_url,
  3970. target_url);
  3971. content_len = strlen(reply);
  3972. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  3973. #endif
  3974. /* Send all required headers */
  3975. mg_response_header_start(conn, redirect_code);
  3976. mg_response_header_add(conn, "Location", target_url, -1);
  3977. if ((redirect_code == 301) || (redirect_code == 308)) {
  3978. /* Permanent redirect */
  3979. send_static_cache_header(conn);
  3980. } else {
  3981. /* Temporary redirect */
  3982. send_no_cache_header(conn);
  3983. }
  3984. send_additional_header(conn);
  3985. send_cors_header(conn);
  3986. #if defined(MG_SEND_REDIRECT_BODY)
  3987. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  3988. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  3989. #else
  3990. mg_response_header_add(conn, "Content-Length", "0", 1);
  3991. #endif
  3992. mg_response_header_send(conn);
  3993. #if defined(MG_SEND_REDIRECT_BODY)
  3994. /* Send response body */
  3995. /* ... unless it is a HEAD request */
  3996. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3997. ret = mg_write(conn, redirect_body, content_len);
  3998. }
  3999. #endif
  4000. return 1;
  4001. }
  4002. #if defined(_WIN32)
  4003. /* Create substitutes for POSIX functions in Win32. */
  4004. #if defined(GCC_DIAGNOSTIC)
  4005. /* Show no warning in case system functions are not used. */
  4006. #pragma GCC diagnostic push
  4007. #pragma GCC diagnostic ignored "-Wunused-function"
  4008. #endif
  4009. static int
  4010. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4011. {
  4012. (void)unused;
  4013. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4014. InitializeCriticalSection(&mutex->sec);
  4015. return 0;
  4016. }
  4017. static int
  4018. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4019. {
  4020. DeleteCriticalSection(&mutex->sec);
  4021. return 0;
  4022. }
  4023. static int
  4024. pthread_mutex_lock(pthread_mutex_t *mutex)
  4025. {
  4026. EnterCriticalSection(&mutex->sec);
  4027. return 0;
  4028. }
  4029. static int
  4030. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4031. {
  4032. LeaveCriticalSection(&mutex->sec);
  4033. return 0;
  4034. }
  4035. FUNCTION_MAY_BE_UNUSED
  4036. static int
  4037. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4038. {
  4039. (void)unused;
  4040. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4041. cv->waiting_thread = NULL;
  4042. return 0;
  4043. }
  4044. FUNCTION_MAY_BE_UNUSED
  4045. static int
  4046. pthread_cond_timedwait(pthread_cond_t *cv,
  4047. pthread_mutex_t *mutex,
  4048. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4049. {
  4050. struct mg_workerTLS **ptls,
  4051. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4052. int ok;
  4053. uint64_t nsnow, nswaitabs;
  4054. int64_t nswaitrel;
  4055. DWORD mswaitrel;
  4056. pthread_mutex_lock(&cv->threadIdSec);
  4057. /* Add this thread to cv's waiting list */
  4058. ptls = &cv->waiting_thread;
  4059. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4060. ;
  4061. tls->next_waiting_thread = NULL;
  4062. *ptls = tls;
  4063. pthread_mutex_unlock(&cv->threadIdSec);
  4064. if (abstime) {
  4065. nsnow = mg_get_current_time_ns();
  4066. nswaitabs =
  4067. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4068. nswaitrel = nswaitabs - nsnow;
  4069. if (nswaitrel < 0) {
  4070. nswaitrel = 0;
  4071. }
  4072. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4073. } else {
  4074. mswaitrel = (DWORD)INFINITE;
  4075. }
  4076. pthread_mutex_unlock(mutex);
  4077. ok = (WAIT_OBJECT_0
  4078. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4079. if (!ok) {
  4080. ok = 1;
  4081. pthread_mutex_lock(&cv->threadIdSec);
  4082. ptls = &cv->waiting_thread;
  4083. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4084. if (*ptls == tls) {
  4085. *ptls = tls->next_waiting_thread;
  4086. ok = 0;
  4087. break;
  4088. }
  4089. }
  4090. pthread_mutex_unlock(&cv->threadIdSec);
  4091. if (ok) {
  4092. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4093. (DWORD)INFINITE);
  4094. }
  4095. }
  4096. /* This thread has been removed from cv's waiting list */
  4097. pthread_mutex_lock(mutex);
  4098. return ok ? 0 : -1;
  4099. }
  4100. FUNCTION_MAY_BE_UNUSED
  4101. static int
  4102. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4103. {
  4104. return pthread_cond_timedwait(cv, mutex, NULL);
  4105. }
  4106. FUNCTION_MAY_BE_UNUSED
  4107. static int
  4108. pthread_cond_signal(pthread_cond_t *cv)
  4109. {
  4110. HANDLE wkup = NULL;
  4111. BOOL ok = FALSE;
  4112. pthread_mutex_lock(&cv->threadIdSec);
  4113. if (cv->waiting_thread) {
  4114. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4115. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4116. ok = SetEvent(wkup);
  4117. DEBUG_ASSERT(ok);
  4118. }
  4119. pthread_mutex_unlock(&cv->threadIdSec);
  4120. return ok ? 0 : 1;
  4121. }
  4122. FUNCTION_MAY_BE_UNUSED
  4123. static int
  4124. pthread_cond_broadcast(pthread_cond_t *cv)
  4125. {
  4126. pthread_mutex_lock(&cv->threadIdSec);
  4127. while (cv->waiting_thread) {
  4128. pthread_cond_signal(cv);
  4129. }
  4130. pthread_mutex_unlock(&cv->threadIdSec);
  4131. return 0;
  4132. }
  4133. FUNCTION_MAY_BE_UNUSED
  4134. static int
  4135. pthread_cond_destroy(pthread_cond_t *cv)
  4136. {
  4137. pthread_mutex_lock(&cv->threadIdSec);
  4138. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4139. pthread_mutex_unlock(&cv->threadIdSec);
  4140. pthread_mutex_destroy(&cv->threadIdSec);
  4141. return 0;
  4142. }
  4143. #if defined(ALTERNATIVE_QUEUE)
  4144. FUNCTION_MAY_BE_UNUSED
  4145. static void *
  4146. event_create(void)
  4147. {
  4148. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4149. }
  4150. FUNCTION_MAY_BE_UNUSED
  4151. static int
  4152. event_wait(void *eventhdl)
  4153. {
  4154. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4155. return (res == WAIT_OBJECT_0);
  4156. }
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static int
  4159. event_signal(void *eventhdl)
  4160. {
  4161. return (int)SetEvent((HANDLE)eventhdl);
  4162. }
  4163. FUNCTION_MAY_BE_UNUSED
  4164. static void
  4165. event_destroy(void *eventhdl)
  4166. {
  4167. CloseHandle((HANDLE)eventhdl);
  4168. }
  4169. #endif
  4170. #if defined(GCC_DIAGNOSTIC)
  4171. /* Enable unused function warning again */
  4172. #pragma GCC diagnostic pop
  4173. #endif
  4174. /* For Windows, change all slashes to backslashes in path names. */
  4175. static void
  4176. change_slashes_to_backslashes(char *path)
  4177. {
  4178. int i;
  4179. for (i = 0; path[i] != '\0'; i++) {
  4180. if (path[i] == '/') {
  4181. path[i] = '\\';
  4182. }
  4183. /* remove double backslash (check i > 0 to preserve UNC paths,
  4184. * like \\server\file.txt) */
  4185. if ((i > 0) && (path[i] == '\\')) {
  4186. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4187. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4188. }
  4189. }
  4190. }
  4191. }
  4192. static int
  4193. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4194. {
  4195. int diff;
  4196. do {
  4197. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4198. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4199. s1++;
  4200. s2++;
  4201. } while ((diff == 0) && (s1[-1] != L'\0'));
  4202. return diff;
  4203. }
  4204. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4205. * wbuf and wbuf_len is a target buffer and its length. */
  4206. static void
  4207. path_to_unicode(const struct mg_connection *conn,
  4208. const char *path,
  4209. wchar_t *wbuf,
  4210. size_t wbuf_len)
  4211. {
  4212. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4213. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4214. DWORD long_len, err;
  4215. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4216. mg_strlcpy(buf, path, sizeof(buf));
  4217. change_slashes_to_backslashes(buf);
  4218. /* Convert to Unicode and back. If doubly-converted string does not
  4219. * match the original, something is fishy, reject. */
  4220. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4221. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4222. WideCharToMultiByte(
  4223. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4224. if (strcmp(buf, buf2) != 0) {
  4225. wbuf[0] = L'\0';
  4226. }
  4227. /* Windows file systems are not case sensitive, but you can still use
  4228. * uppercase and lowercase letters (on all modern file systems).
  4229. * The server can check if the URI uses the same upper/lowercase
  4230. * letters an the file system, effectively making Windows servers
  4231. * case sensitive (like Linux servers are). It is still not possible
  4232. * to use two files with the same name in different cases on Windows
  4233. * (like /a and /A) - this would be possible in Linux.
  4234. * As a default, Windows is not case sensitive, but the case sensitive
  4235. * file name check can be activated by an additional configuration. */
  4236. if (conn) {
  4237. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4238. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4239. "yes")) {
  4240. /* Use case sensitive compare function */
  4241. fcompare = wcscmp;
  4242. }
  4243. }
  4244. (void)conn; /* conn is currently unused */
  4245. /* Only accept a full file path, not a Windows short (8.3) path. */
  4246. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4247. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4248. if (long_len == 0) {
  4249. err = GetLastError();
  4250. if (err == ERROR_FILE_NOT_FOUND) {
  4251. /* File does not exist. This is not always a problem here. */
  4252. return;
  4253. }
  4254. }
  4255. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4256. /* Short name is used. */
  4257. wbuf[0] = L'\0';
  4258. }
  4259. }
  4260. #if !defined(NO_FILESYSTEMS)
  4261. /* Get file information, return 1 if file exists, 0 if not */
  4262. static int
  4263. mg_stat(const struct mg_connection *conn,
  4264. const char *path,
  4265. struct mg_file_stat *filep)
  4266. {
  4267. wchar_t wbuf[UTF16_PATH_MAX];
  4268. WIN32_FILE_ATTRIBUTE_DATA info;
  4269. time_t creation_time;
  4270. size_t len;
  4271. if (!filep) {
  4272. return 0;
  4273. }
  4274. memset(filep, 0, sizeof(*filep));
  4275. if (mg_path_suspicious(conn, path)) {
  4276. return 0;
  4277. }
  4278. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4279. /* Windows happily opens files with some garbage at the end of file name.
  4280. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4281. * "a.cgi", despite one would expect an error back. */
  4282. len = strlen(path);
  4283. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4284. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4285. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4286. filep->last_modified =
  4287. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4288. info.ftLastWriteTime.dwHighDateTime);
  4289. /* On Windows, the file creation time can be higher than the
  4290. * modification time, e.g. when a file is copied.
  4291. * Since the Last-Modified timestamp is used for caching
  4292. * it should be based on the most recent timestamp. */
  4293. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4294. info.ftCreationTime.dwHighDateTime);
  4295. if (creation_time > filep->last_modified) {
  4296. filep->last_modified = creation_time;
  4297. }
  4298. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4299. return 1;
  4300. }
  4301. return 0;
  4302. }
  4303. #endif
  4304. static int
  4305. mg_remove(const struct mg_connection *conn, const char *path)
  4306. {
  4307. wchar_t wbuf[UTF16_PATH_MAX];
  4308. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4309. return DeleteFileW(wbuf) ? 0 : -1;
  4310. }
  4311. static int
  4312. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4313. {
  4314. wchar_t wbuf[UTF16_PATH_MAX];
  4315. (void)mode;
  4316. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4317. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4318. }
  4319. /* Create substitutes for POSIX functions in Win32. */
  4320. #if defined(GCC_DIAGNOSTIC)
  4321. /* Show no warning in case system functions are not used. */
  4322. #pragma GCC diagnostic push
  4323. #pragma GCC diagnostic ignored "-Wunused-function"
  4324. #endif
  4325. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4326. FUNCTION_MAY_BE_UNUSED
  4327. static DIR *
  4328. mg_opendir(const struct mg_connection *conn, const char *name)
  4329. {
  4330. DIR *dir = NULL;
  4331. wchar_t wpath[UTF16_PATH_MAX];
  4332. DWORD attrs;
  4333. if (name == NULL) {
  4334. SetLastError(ERROR_BAD_ARGUMENTS);
  4335. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4336. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4337. } else {
  4338. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4339. attrs = GetFileAttributesW(wpath);
  4340. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4341. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4342. (void)wcscat(wpath, L"\\*");
  4343. dir->handle = FindFirstFileW(wpath, &dir->info);
  4344. dir->result.d_name[0] = '\0';
  4345. } else {
  4346. mg_free(dir);
  4347. dir = NULL;
  4348. }
  4349. }
  4350. return dir;
  4351. }
  4352. FUNCTION_MAY_BE_UNUSED
  4353. static int
  4354. mg_closedir(DIR *dir)
  4355. {
  4356. int result = 0;
  4357. if (dir != NULL) {
  4358. if (dir->handle != INVALID_HANDLE_VALUE)
  4359. result = FindClose(dir->handle) ? 0 : -1;
  4360. mg_free(dir);
  4361. } else {
  4362. result = -1;
  4363. SetLastError(ERROR_BAD_ARGUMENTS);
  4364. }
  4365. return result;
  4366. }
  4367. FUNCTION_MAY_BE_UNUSED
  4368. static struct dirent *
  4369. mg_readdir(DIR *dir)
  4370. {
  4371. struct dirent *result = 0;
  4372. if (dir) {
  4373. if (dir->handle != INVALID_HANDLE_VALUE) {
  4374. result = &dir->result;
  4375. (void)WideCharToMultiByte(CP_UTF8,
  4376. 0,
  4377. dir->info.cFileName,
  4378. -1,
  4379. result->d_name,
  4380. sizeof(result->d_name),
  4381. NULL,
  4382. NULL);
  4383. if (!FindNextFileW(dir->handle, &dir->info)) {
  4384. (void)FindClose(dir->handle);
  4385. dir->handle = INVALID_HANDLE_VALUE;
  4386. }
  4387. } else {
  4388. SetLastError(ERROR_FILE_NOT_FOUND);
  4389. }
  4390. } else {
  4391. SetLastError(ERROR_BAD_ARGUMENTS);
  4392. }
  4393. return result;
  4394. }
  4395. #if !defined(HAVE_POLL)
  4396. #undef POLLIN
  4397. #undef POLLPRI
  4398. #undef POLLOUT
  4399. #undef POLLERR
  4400. #define POLLIN (1) /* Data ready - read will not block. */
  4401. #define POLLPRI (2) /* Priority data ready. */
  4402. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4403. #define POLLERR (8) /* Error event */
  4404. FUNCTION_MAY_BE_UNUSED
  4405. static int
  4406. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4407. {
  4408. struct timeval tv;
  4409. fd_set rset;
  4410. fd_set wset;
  4411. fd_set eset;
  4412. unsigned int i;
  4413. int result;
  4414. SOCKET maxfd = 0;
  4415. memset(&tv, 0, sizeof(tv));
  4416. tv.tv_sec = milliseconds / 1000;
  4417. tv.tv_usec = (milliseconds % 1000) * 1000;
  4418. FD_ZERO(&rset);
  4419. FD_ZERO(&wset);
  4420. FD_ZERO(&eset);
  4421. for (i = 0; i < n; i++) {
  4422. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4423. if (pfd[i].events & POLLIN) {
  4424. FD_SET(pfd[i].fd, &rset);
  4425. }
  4426. if (pfd[i].events & POLLOUT) {
  4427. FD_SET(pfd[i].fd, &wset);
  4428. }
  4429. /* Check for errors for any FD in the set */
  4430. FD_SET(pfd[i].fd, &eset);
  4431. }
  4432. pfd[i].revents = 0;
  4433. if (pfd[i].fd > maxfd) {
  4434. maxfd = pfd[i].fd;
  4435. }
  4436. }
  4437. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4438. for (i = 0; i < n; i++) {
  4439. if (FD_ISSET(pfd[i].fd, &rset)) {
  4440. pfd[i].revents |= POLLIN;
  4441. }
  4442. if (FD_ISSET(pfd[i].fd, &wset)) {
  4443. pfd[i].revents |= POLLOUT;
  4444. }
  4445. if (FD_ISSET(pfd[i].fd, &eset)) {
  4446. pfd[i].revents |= POLLERR;
  4447. }
  4448. }
  4449. }
  4450. /* We should subtract the time used in select from remaining
  4451. * "milliseconds", in particular if called from mg_poll with a
  4452. * timeout quantum.
  4453. * Unfortunately, the remaining time is not stored in "tv" in all
  4454. * implementations, so the result in "tv" must be considered undefined.
  4455. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4456. return result;
  4457. }
  4458. #endif /* HAVE_POLL */
  4459. #if defined(GCC_DIAGNOSTIC)
  4460. /* Enable unused function warning again */
  4461. #pragma GCC diagnostic pop
  4462. #endif
  4463. static void
  4464. set_close_on_exec(SOCKET sock,
  4465. const struct mg_connection *conn /* may be null */,
  4466. struct mg_context *ctx /* may be null */)
  4467. {
  4468. (void)conn; /* Unused. */
  4469. (void)ctx;
  4470. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4471. }
  4472. int
  4473. mg_start_thread(mg_thread_func_t f, void *p)
  4474. {
  4475. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4476. /* Compile-time option to control stack size, e.g.
  4477. * -DUSE_STACK_SIZE=16384
  4478. */
  4479. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4480. == ((uintptr_t)(-1L)))
  4481. ? -1
  4482. : 0);
  4483. #else
  4484. return (
  4485. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4486. ? -1
  4487. : 0);
  4488. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4489. }
  4490. /* Start a thread storing the thread context. */
  4491. static int
  4492. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4493. void *p,
  4494. pthread_t *threadidptr)
  4495. {
  4496. uintptr_t uip;
  4497. HANDLE threadhandle;
  4498. int result = -1;
  4499. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4500. threadhandle = (HANDLE)uip;
  4501. if ((uip != 0) && (threadidptr != NULL)) {
  4502. *threadidptr = threadhandle;
  4503. result = 0;
  4504. }
  4505. return result;
  4506. }
  4507. /* Wait for a thread to finish. */
  4508. static int
  4509. mg_join_thread(pthread_t threadid)
  4510. {
  4511. int result;
  4512. DWORD dwevent;
  4513. result = -1;
  4514. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4515. if (dwevent == WAIT_FAILED) {
  4516. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4517. } else {
  4518. if (dwevent == WAIT_OBJECT_0) {
  4519. CloseHandle(threadid);
  4520. result = 0;
  4521. }
  4522. }
  4523. return result;
  4524. }
  4525. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4526. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4527. /* Create substitutes for POSIX functions in Win32. */
  4528. #if defined(GCC_DIAGNOSTIC)
  4529. /* Show no warning in case system functions are not used. */
  4530. #pragma GCC diagnostic push
  4531. #pragma GCC diagnostic ignored "-Wunused-function"
  4532. #endif
  4533. FUNCTION_MAY_BE_UNUSED
  4534. static HANDLE
  4535. dlopen(const char *dll_name, int flags)
  4536. {
  4537. wchar_t wbuf[UTF16_PATH_MAX];
  4538. (void)flags;
  4539. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4540. return LoadLibraryW(wbuf);
  4541. }
  4542. FUNCTION_MAY_BE_UNUSED
  4543. static int
  4544. dlclose(void *handle)
  4545. {
  4546. int result;
  4547. if (FreeLibrary((HMODULE)handle) != 0) {
  4548. result = 0;
  4549. } else {
  4550. result = -1;
  4551. }
  4552. return result;
  4553. }
  4554. #if defined(GCC_DIAGNOSTIC)
  4555. /* Enable unused function warning again */
  4556. #pragma GCC diagnostic pop
  4557. #endif
  4558. #endif
  4559. #if !defined(NO_CGI)
  4560. #define SIGKILL (0)
  4561. static int
  4562. kill(pid_t pid, int sig_num)
  4563. {
  4564. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4565. (void)CloseHandle((HANDLE)pid);
  4566. return 0;
  4567. }
  4568. #if !defined(WNOHANG)
  4569. #define WNOHANG (1)
  4570. #endif
  4571. static pid_t
  4572. waitpid(pid_t pid, int *status, int flags)
  4573. {
  4574. DWORD timeout = INFINITE;
  4575. DWORD waitres;
  4576. (void)status; /* Currently not used by any client here */
  4577. if ((flags | WNOHANG) == WNOHANG) {
  4578. timeout = 0;
  4579. }
  4580. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4581. if (waitres == WAIT_OBJECT_0) {
  4582. return pid;
  4583. }
  4584. if (waitres == WAIT_TIMEOUT) {
  4585. return 0;
  4586. }
  4587. return (pid_t)-1;
  4588. }
  4589. static void
  4590. trim_trailing_whitespaces(char *s)
  4591. {
  4592. char *e = s + strlen(s);
  4593. while ((e > s) && isspace((unsigned char)e[-1])) {
  4594. *(--e) = '\0';
  4595. }
  4596. }
  4597. static pid_t
  4598. spawn_process(struct mg_connection *conn,
  4599. const char *prog,
  4600. char *envblk,
  4601. char *envp[],
  4602. int fdin[2],
  4603. int fdout[2],
  4604. int fderr[2],
  4605. const char *dir,
  4606. unsigned char cgi_config_idx)
  4607. {
  4608. HANDLE me;
  4609. char *interp;
  4610. char *interp_arg = 0;
  4611. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4612. int truncated;
  4613. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4614. STARTUPINFOA si;
  4615. PROCESS_INFORMATION pi = {0};
  4616. (void)envp;
  4617. memset(&si, 0, sizeof(si));
  4618. si.cb = sizeof(si);
  4619. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4620. si.wShowWindow = SW_HIDE;
  4621. me = GetCurrentProcess();
  4622. DuplicateHandle(me,
  4623. (HANDLE)_get_osfhandle(fdin[0]),
  4624. me,
  4625. &si.hStdInput,
  4626. 0,
  4627. TRUE,
  4628. DUPLICATE_SAME_ACCESS);
  4629. DuplicateHandle(me,
  4630. (HANDLE)_get_osfhandle(fdout[1]),
  4631. me,
  4632. &si.hStdOutput,
  4633. 0,
  4634. TRUE,
  4635. DUPLICATE_SAME_ACCESS);
  4636. DuplicateHandle(me,
  4637. (HANDLE)_get_osfhandle(fderr[1]),
  4638. me,
  4639. &si.hStdError,
  4640. 0,
  4641. TRUE,
  4642. DUPLICATE_SAME_ACCESS);
  4643. /* Mark handles that should not be inherited. See
  4644. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4645. */
  4646. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4647. HANDLE_FLAG_INHERIT,
  4648. 0);
  4649. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4650. HANDLE_FLAG_INHERIT,
  4651. 0);
  4652. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4653. HANDLE_FLAG_INHERIT,
  4654. 0);
  4655. /* First check, if there is a CGI interpreter configured for all CGI
  4656. * scripts. */
  4657. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4658. if (interp != NULL) {
  4659. /* If there is a configured interpreter, check for additional arguments
  4660. */
  4661. interp_arg =
  4662. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4663. } else {
  4664. /* Otherwise, the interpreter must be stated in the first line of the
  4665. * CGI script file, after a #! (shebang) mark. */
  4666. buf[0] = buf[1] = '\0';
  4667. /* Get the full script path */
  4668. mg_snprintf(
  4669. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4670. if (truncated) {
  4671. pi.hProcess = (pid_t)-1;
  4672. goto spawn_cleanup;
  4673. }
  4674. /* Open the script file, to read the first line */
  4675. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4676. /* Read the first line of the script into the buffer */
  4677. mg_fgets(buf, sizeof(buf), &file);
  4678. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4679. buf[sizeof(buf) - 1] = '\0';
  4680. }
  4681. if ((buf[0] == '#') && (buf[1] == '!')) {
  4682. trim_trailing_whitespaces(buf + 2);
  4683. } else {
  4684. buf[2] = '\0';
  4685. }
  4686. interp = buf + 2;
  4687. }
  4688. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4689. if (interp[0] != '\0') {
  4690. /* This is an interpreted script file. We must call the interpreter. */
  4691. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4692. mg_snprintf(conn,
  4693. &truncated,
  4694. cmdline,
  4695. sizeof(cmdline),
  4696. "\"%s\" %s \"%s\\%s\"",
  4697. interp,
  4698. interp_arg,
  4699. full_dir,
  4700. prog);
  4701. } else {
  4702. mg_snprintf(conn,
  4703. &truncated,
  4704. cmdline,
  4705. sizeof(cmdline),
  4706. "\"%s\" \"%s\\%s\"",
  4707. interp,
  4708. full_dir,
  4709. prog);
  4710. }
  4711. } else {
  4712. /* This is (probably) a compiled program. We call it directly. */
  4713. mg_snprintf(conn,
  4714. &truncated,
  4715. cmdline,
  4716. sizeof(cmdline),
  4717. "\"%s\\%s\"",
  4718. full_dir,
  4719. prog);
  4720. }
  4721. if (truncated) {
  4722. pi.hProcess = (pid_t)-1;
  4723. goto spawn_cleanup;
  4724. }
  4725. DEBUG_TRACE("Running [%s]", cmdline);
  4726. if (CreateProcessA(NULL,
  4727. cmdline,
  4728. NULL,
  4729. NULL,
  4730. TRUE,
  4731. CREATE_NEW_PROCESS_GROUP,
  4732. envblk,
  4733. NULL,
  4734. &si,
  4735. &pi)
  4736. == 0) {
  4737. mg_cry_internal(
  4738. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4739. pi.hProcess = (pid_t)-1;
  4740. /* goto spawn_cleanup; */
  4741. }
  4742. spawn_cleanup:
  4743. (void)CloseHandle(si.hStdOutput);
  4744. (void)CloseHandle(si.hStdError);
  4745. (void)CloseHandle(si.hStdInput);
  4746. if (pi.hThread != NULL) {
  4747. (void)CloseHandle(pi.hThread);
  4748. }
  4749. return (pid_t)pi.hProcess;
  4750. }
  4751. #endif /* !NO_CGI */
  4752. static int
  4753. set_blocking_mode(SOCKET sock)
  4754. {
  4755. unsigned long non_blocking = 0;
  4756. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4757. }
  4758. static int
  4759. set_non_blocking_mode(SOCKET sock)
  4760. {
  4761. unsigned long non_blocking = 1;
  4762. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4763. }
  4764. #else
  4765. #if !defined(NO_FILESYSTEMS)
  4766. static int
  4767. mg_stat(const struct mg_connection *conn,
  4768. const char *path,
  4769. struct mg_file_stat *filep)
  4770. {
  4771. struct stat st;
  4772. if (!filep) {
  4773. return 0;
  4774. }
  4775. memset(filep, 0, sizeof(*filep));
  4776. if (mg_path_suspicious(conn, path)) {
  4777. return 0;
  4778. }
  4779. if (0 == stat(path, &st)) {
  4780. filep->size = (uint64_t)(st.st_size);
  4781. filep->last_modified = st.st_mtime;
  4782. filep->is_directory = S_ISDIR(st.st_mode);
  4783. return 1;
  4784. }
  4785. return 0;
  4786. }
  4787. #endif /* NO_FILESYSTEMS */
  4788. static void
  4789. set_close_on_exec(int fd,
  4790. const struct mg_connection *conn /* may be null */,
  4791. struct mg_context *ctx /* may be null */)
  4792. {
  4793. #if defined(__ZEPHYR__)
  4794. (void)fd;
  4795. (void)conn;
  4796. (void)ctx;
  4797. #else
  4798. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4799. if (conn || ctx) {
  4800. struct mg_connection fc;
  4801. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4802. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4803. __func__,
  4804. strerror(ERRNO));
  4805. }
  4806. }
  4807. #endif
  4808. }
  4809. int
  4810. mg_start_thread(mg_thread_func_t func, void *param)
  4811. {
  4812. pthread_t thread_id;
  4813. pthread_attr_t attr;
  4814. int result;
  4815. (void)pthread_attr_init(&attr);
  4816. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4817. #if defined(__ZEPHYR__)
  4818. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4819. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4820. /* Compile-time option to control stack size,
  4821. * e.g. -DUSE_STACK_SIZE=16384 */
  4822. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4823. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4824. result = pthread_create(&thread_id, &attr, func, param);
  4825. pthread_attr_destroy(&attr);
  4826. return result;
  4827. }
  4828. /* Start a thread storing the thread context. */
  4829. static int
  4830. mg_start_thread_with_id(mg_thread_func_t func,
  4831. void *param,
  4832. pthread_t *threadidptr)
  4833. {
  4834. pthread_t thread_id;
  4835. pthread_attr_t attr;
  4836. int result;
  4837. (void)pthread_attr_init(&attr);
  4838. #if defined(__ZEPHYR__)
  4839. pthread_attr_setstack(&attr,
  4840. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4841. ZEPHYR_STACK_SIZE);
  4842. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4843. /* Compile-time option to control stack size,
  4844. * e.g. -DUSE_STACK_SIZE=16384 */
  4845. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4846. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4847. result = pthread_create(&thread_id, &attr, func, param);
  4848. pthread_attr_destroy(&attr);
  4849. if ((result == 0) && (threadidptr != NULL)) {
  4850. *threadidptr = thread_id;
  4851. }
  4852. return result;
  4853. }
  4854. /* Wait for a thread to finish. */
  4855. static int
  4856. mg_join_thread(pthread_t threadid)
  4857. {
  4858. int result;
  4859. result = pthread_join(threadid, NULL);
  4860. return result;
  4861. }
  4862. #if !defined(NO_CGI)
  4863. static pid_t
  4864. spawn_process(struct mg_connection *conn,
  4865. const char *prog,
  4866. char *envblk,
  4867. char *envp[],
  4868. int fdin[2],
  4869. int fdout[2],
  4870. int fderr[2],
  4871. const char *dir,
  4872. unsigned char cgi_config_idx)
  4873. {
  4874. pid_t pid;
  4875. const char *interp;
  4876. (void)envblk;
  4877. if ((pid = fork()) == -1) {
  4878. /* Parent */
  4879. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4880. } else if (pid != 0) {
  4881. /* Make sure children close parent-side descriptors.
  4882. * The caller will close the child-side immediately. */
  4883. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4884. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4885. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4886. } else {
  4887. /* Child */
  4888. if (chdir(dir) != 0) {
  4889. mg_cry_internal(
  4890. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4891. } else if (dup2(fdin[0], 0) == -1) {
  4892. mg_cry_internal(conn,
  4893. "%s: dup2(%d, 0): %s",
  4894. __func__,
  4895. fdin[0],
  4896. strerror(ERRNO));
  4897. } else if (dup2(fdout[1], 1) == -1) {
  4898. mg_cry_internal(conn,
  4899. "%s: dup2(%d, 1): %s",
  4900. __func__,
  4901. fdout[1],
  4902. strerror(ERRNO));
  4903. } else if (dup2(fderr[1], 2) == -1) {
  4904. mg_cry_internal(conn,
  4905. "%s: dup2(%d, 2): %s",
  4906. __func__,
  4907. fderr[1],
  4908. strerror(ERRNO));
  4909. } else {
  4910. struct sigaction sa;
  4911. /* Keep stderr and stdout in two different pipes.
  4912. * Stdout will be sent back to the client,
  4913. * stderr should go into a server error log. */
  4914. (void)close(fdin[0]);
  4915. (void)close(fdout[1]);
  4916. (void)close(fderr[1]);
  4917. /* Close write end fdin and read end fdout and fderr */
  4918. (void)close(fdin[1]);
  4919. (void)close(fdout[0]);
  4920. (void)close(fderr[0]);
  4921. /* After exec, all signal handlers are restored to their default
  4922. * values, with one exception of SIGCHLD. According to
  4923. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4924. * will leave unchanged after exec if it was set to be ignored.
  4925. * Restore it to default action. */
  4926. memset(&sa, 0, sizeof(sa));
  4927. sa.sa_handler = SIG_DFL;
  4928. sigaction(SIGCHLD, &sa, NULL);
  4929. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4930. if (interp == NULL) {
  4931. /* no interpreter configured, call the programm directly */
  4932. (void)execle(prog, prog, NULL, envp);
  4933. mg_cry_internal(conn,
  4934. "%s: execle(%s): %s",
  4935. __func__,
  4936. prog,
  4937. strerror(ERRNO));
  4938. } else {
  4939. /* call the configured interpreter */
  4940. const char *interp_args =
  4941. conn->dom_ctx
  4942. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4943. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4944. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4945. } else {
  4946. (void)execle(interp, interp, prog, NULL, envp);
  4947. }
  4948. mg_cry_internal(conn,
  4949. "%s: execle(%s %s): %s",
  4950. __func__,
  4951. interp,
  4952. prog,
  4953. strerror(ERRNO));
  4954. }
  4955. }
  4956. exit(EXIT_FAILURE);
  4957. }
  4958. return pid;
  4959. }
  4960. #endif /* !NO_CGI */
  4961. static int
  4962. set_non_blocking_mode(SOCKET sock)
  4963. {
  4964. int flags = fcntl(sock, F_GETFL, 0);
  4965. if (flags < 0) {
  4966. return -1;
  4967. }
  4968. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4969. return -1;
  4970. }
  4971. return 0;
  4972. }
  4973. static int
  4974. set_blocking_mode(SOCKET sock)
  4975. {
  4976. int flags = fcntl(sock, F_GETFL, 0);
  4977. if (flags < 0) {
  4978. return -1;
  4979. }
  4980. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4981. return -1;
  4982. }
  4983. return 0;
  4984. }
  4985. #endif /* _WIN32 / else */
  4986. /* End of initial operating system specific define block. */
  4987. /* Get a random number (independent of C rand function) */
  4988. static uint64_t
  4989. get_random(void)
  4990. {
  4991. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4992. static uint64_t lcg = 0; /* Linear congruential generator */
  4993. uint64_t now = mg_get_current_time_ns();
  4994. if (lfsr == 0) {
  4995. /* lfsr will be only 0 if has not been initialized,
  4996. * so this code is called only once. */
  4997. lfsr = mg_get_current_time_ns();
  4998. lcg = mg_get_current_time_ns();
  4999. } else {
  5000. /* Get the next step of both random number generators. */
  5001. lfsr = (lfsr >> 1)
  5002. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5003. << 63);
  5004. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5005. }
  5006. /* Combining two pseudo-random number generators and a high resolution
  5007. * part
  5008. * of the current server time will make it hard (impossible?) to guess
  5009. * the
  5010. * next number. */
  5011. return (lfsr ^ lcg ^ now);
  5012. }
  5013. static int
  5014. mg_poll(struct mg_pollfd *pfd,
  5015. unsigned int n,
  5016. int milliseconds,
  5017. const stop_flag_t *stop_flag)
  5018. {
  5019. /* Call poll, but only for a maximum time of a few seconds.
  5020. * This will allow to stop the server after some seconds, instead
  5021. * of having to wait for a long socket timeout. */
  5022. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5023. int check_pollerr = 0;
  5024. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5025. /* If we wait for only one file descriptor, wait on error as well */
  5026. pfd[0].events |= POLLERR;
  5027. check_pollerr = 1;
  5028. }
  5029. do {
  5030. int result;
  5031. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5032. /* Shut down signal */
  5033. return -2;
  5034. }
  5035. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5036. ms_now = milliseconds;
  5037. }
  5038. result = poll(pfd, n, ms_now);
  5039. if (result != 0) {
  5040. /* Poll returned either success (1) or error (-1).
  5041. * Forward both to the caller. */
  5042. if ((check_pollerr)
  5043. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5044. == POLLERR)) {
  5045. /* One and only file descriptor returned error */
  5046. return -1;
  5047. }
  5048. return result;
  5049. }
  5050. /* Poll returned timeout (0). */
  5051. if (milliseconds > 0) {
  5052. milliseconds -= ms_now;
  5053. }
  5054. } while (milliseconds > 0);
  5055. /* timeout: return 0 */
  5056. return 0;
  5057. }
  5058. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5059. * descriptor.
  5060. * Return value:
  5061. * >=0 .. number of bytes successfully written
  5062. * -1 .. timeout
  5063. * -2 .. error
  5064. */
  5065. static int
  5066. push_inner(struct mg_context *ctx,
  5067. FILE *fp,
  5068. SOCKET sock,
  5069. SSL *ssl,
  5070. const char *buf,
  5071. int len,
  5072. double timeout)
  5073. {
  5074. uint64_t start = 0, now = 0, timeout_ns = 0;
  5075. int n, err;
  5076. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5077. #if defined(_WIN32)
  5078. typedef int len_t;
  5079. #else
  5080. typedef size_t len_t;
  5081. #endif
  5082. if (timeout > 0) {
  5083. now = mg_get_current_time_ns();
  5084. start = now;
  5085. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5086. }
  5087. if (ctx == NULL) {
  5088. return -2;
  5089. }
  5090. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5091. if (ssl) {
  5092. return -2;
  5093. }
  5094. #endif
  5095. /* Try to read until it succeeds, fails, times out, or the server
  5096. * shuts down. */
  5097. for (;;) {
  5098. #if defined(USE_MBEDTLS)
  5099. if (ssl != NULL) {
  5100. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5101. if (n <= 0) {
  5102. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5103. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5104. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5105. n = 0;
  5106. } else {
  5107. fprintf(stderr, "SSL write failed, error %d\n", n);
  5108. return -2;
  5109. }
  5110. } else {
  5111. err = 0;
  5112. }
  5113. } else
  5114. #elif !defined(NO_SSL)
  5115. if (ssl != NULL) {
  5116. ERR_clear_error();
  5117. n = SSL_write(ssl, buf, len);
  5118. if (n <= 0) {
  5119. err = SSL_get_error(ssl, n);
  5120. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5121. err = ERRNO;
  5122. } else if ((err == SSL_ERROR_WANT_READ)
  5123. || (err == SSL_ERROR_WANT_WRITE)) {
  5124. n = 0;
  5125. } else {
  5126. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5127. ERR_clear_error();
  5128. return -2;
  5129. }
  5130. ERR_clear_error();
  5131. } else {
  5132. err = 0;
  5133. }
  5134. } else
  5135. #endif
  5136. if (fp != NULL) {
  5137. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5138. if (ferror(fp)) {
  5139. n = -1;
  5140. err = ERRNO;
  5141. } else {
  5142. err = 0;
  5143. }
  5144. } else {
  5145. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5146. err = (n < 0) ? ERRNO : 0;
  5147. #if defined(_WIN32)
  5148. if (err == WSAEWOULDBLOCK) {
  5149. err = 0;
  5150. n = 0;
  5151. }
  5152. #else
  5153. if (ERROR_TRY_AGAIN(err)) {
  5154. err = 0;
  5155. n = 0;
  5156. }
  5157. #endif
  5158. if (n < 0) {
  5159. /* shutdown of the socket at client side */
  5160. return -2;
  5161. }
  5162. }
  5163. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5164. return -2;
  5165. }
  5166. if ((n > 0) || ((n == 0) && (len == 0))) {
  5167. /* some data has been read, or no data was requested */
  5168. return n;
  5169. }
  5170. if (n < 0) {
  5171. /* socket error - check errno */
  5172. DEBUG_TRACE("send() failed, error %d", err);
  5173. /* TODO (mid): error handling depending on the error code.
  5174. * These codes are different between Windows and Linux.
  5175. * Currently there is no problem with failing send calls,
  5176. * if there is a reproducible situation, it should be
  5177. * investigated in detail.
  5178. */
  5179. return -2;
  5180. }
  5181. /* Only in case n=0 (timeout), repeat calling the write function */
  5182. /* If send failed, wait before retry */
  5183. if (fp != NULL) {
  5184. /* For files, just wait a fixed time.
  5185. * Maybe it helps, maybe not. */
  5186. mg_sleep(5);
  5187. } else {
  5188. /* For sockets, wait for the socket using poll */
  5189. struct mg_pollfd pfd[1];
  5190. int pollres;
  5191. pfd[0].fd = sock;
  5192. pfd[0].events = POLLOUT;
  5193. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5194. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5195. return -2;
  5196. }
  5197. if (pollres > 0) {
  5198. continue;
  5199. }
  5200. }
  5201. if (timeout > 0) {
  5202. now = mg_get_current_time_ns();
  5203. if ((now - start) > timeout_ns) {
  5204. /* Timeout */
  5205. break;
  5206. }
  5207. }
  5208. }
  5209. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5210. used */
  5211. return -1;
  5212. }
  5213. static int
  5214. push_all(struct mg_context *ctx,
  5215. FILE *fp,
  5216. SOCKET sock,
  5217. SSL *ssl,
  5218. const char *buf,
  5219. int len)
  5220. {
  5221. double timeout = -1.0;
  5222. int n, nwritten = 0;
  5223. if (ctx == NULL) {
  5224. return -1;
  5225. }
  5226. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5227. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5228. }
  5229. if (timeout <= 0.0) {
  5230. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5231. / 1000.0;
  5232. }
  5233. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5234. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5235. if (n < 0) {
  5236. if (nwritten == 0) {
  5237. nwritten = -1; /* Propagate the error */
  5238. }
  5239. break;
  5240. } else if (n == 0) {
  5241. break; /* No more data to write */
  5242. } else {
  5243. nwritten += n;
  5244. len -= n;
  5245. }
  5246. }
  5247. return nwritten;
  5248. }
  5249. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5250. * Return value:
  5251. * >=0 .. number of bytes successfully read
  5252. * -1 .. timeout
  5253. * -2 .. error
  5254. */
  5255. static int
  5256. pull_inner(FILE *fp,
  5257. struct mg_connection *conn,
  5258. char *buf,
  5259. int len,
  5260. double timeout)
  5261. {
  5262. int nread, err = 0;
  5263. #if defined(_WIN32)
  5264. typedef int len_t;
  5265. #else
  5266. typedef size_t len_t;
  5267. #endif
  5268. /* We need an additional wait loop around this, because in some cases
  5269. * with TLSwe may get data from the socket but not from SSL_read.
  5270. * In this case we need to repeat at least once.
  5271. */
  5272. if (fp != NULL) {
  5273. /* Use read() instead of fread(), because if we're reading from the
  5274. * CGI pipe, fread() may block until IO buffer is filled up. We
  5275. * cannot afford to block and must pass all read bytes immediately
  5276. * to the client. */
  5277. nread = (int)read(fileno(fp), buf, (size_t)len);
  5278. err = (nread < 0) ? ERRNO : 0;
  5279. if ((nread == 0) && (len > 0)) {
  5280. /* Should get data, but got EOL */
  5281. return -2;
  5282. }
  5283. #if defined(USE_MBEDTLS)
  5284. } else if (conn->ssl != NULL) {
  5285. struct mg_pollfd pfd[1];
  5286. int to_read;
  5287. int pollres;
  5288. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5289. if (to_read > 0) {
  5290. /* We already know there is no more data buffered in conn->buf
  5291. * but there is more available in the SSL layer. So don't poll
  5292. * conn->client.sock yet. */
  5293. pollres = 1;
  5294. if (to_read > len)
  5295. to_read = len;
  5296. } else {
  5297. pfd[0].fd = conn->client.sock;
  5298. pfd[0].events = POLLIN;
  5299. to_read = len;
  5300. pollres = mg_poll(pfd,
  5301. 1,
  5302. (int)(timeout * 1000.0),
  5303. &(conn->phys_ctx->stop_flag));
  5304. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5305. return -2;
  5306. }
  5307. }
  5308. if (pollres > 0) {
  5309. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5310. if (nread <= 0) {
  5311. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5312. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5313. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5314. nread = 0;
  5315. } else {
  5316. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5317. return -2;
  5318. }
  5319. } else {
  5320. err = 0;
  5321. }
  5322. } else if (pollres < 0) {
  5323. /* Error */
  5324. return -2;
  5325. } else {
  5326. /* pollres = 0 means timeout */
  5327. nread = 0;
  5328. }
  5329. #elif !defined(NO_SSL)
  5330. } else if (conn->ssl != NULL) {
  5331. int ssl_pending;
  5332. struct mg_pollfd pfd[1];
  5333. int pollres;
  5334. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5335. /* We already know there is no more data buffered in conn->buf
  5336. * but there is more available in the SSL layer. So don't poll
  5337. * conn->client.sock yet. */
  5338. if (ssl_pending > len) {
  5339. ssl_pending = len;
  5340. }
  5341. pollres = 1;
  5342. } else {
  5343. pfd[0].fd = conn->client.sock;
  5344. pfd[0].events = POLLIN;
  5345. pollres = mg_poll(pfd,
  5346. 1,
  5347. (int)(timeout * 1000.0),
  5348. &(conn->phys_ctx->stop_flag));
  5349. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5350. return -2;
  5351. }
  5352. }
  5353. if (pollres > 0) {
  5354. ERR_clear_error();
  5355. nread =
  5356. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5357. if (nread <= 0) {
  5358. err = SSL_get_error(conn->ssl, nread);
  5359. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5360. err = ERRNO;
  5361. } else if ((err == SSL_ERROR_WANT_READ)
  5362. || (err == SSL_ERROR_WANT_WRITE)) {
  5363. nread = 0;
  5364. } else {
  5365. /* All errors should return -2 */
  5366. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5367. ERR_clear_error();
  5368. return -2;
  5369. }
  5370. ERR_clear_error();
  5371. } else {
  5372. err = 0;
  5373. }
  5374. } else if (pollres < 0) {
  5375. /* Error */
  5376. return -2;
  5377. } else {
  5378. /* pollres = 0 means timeout */
  5379. nread = 0;
  5380. }
  5381. #endif
  5382. } else {
  5383. struct mg_pollfd pfd[1];
  5384. int pollres;
  5385. pfd[0].fd = conn->client.sock;
  5386. pfd[0].events = POLLIN;
  5387. pollres = mg_poll(pfd,
  5388. 1,
  5389. (int)(timeout * 1000.0),
  5390. &(conn->phys_ctx->stop_flag));
  5391. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5392. return -2;
  5393. }
  5394. if (pollres > 0) {
  5395. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5396. err = (nread < 0) ? ERRNO : 0;
  5397. if (nread <= 0) {
  5398. /* shutdown of the socket at client side */
  5399. return -2;
  5400. }
  5401. } else if (pollres < 0) {
  5402. /* error callint poll */
  5403. return -2;
  5404. } else {
  5405. /* pollres = 0 means timeout */
  5406. nread = 0;
  5407. }
  5408. }
  5409. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5410. return -2;
  5411. }
  5412. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5413. /* some data has been read, or no data was requested */
  5414. return nread;
  5415. }
  5416. if (nread < 0) {
  5417. /* socket error - check errno */
  5418. #if defined(_WIN32)
  5419. if (err == WSAEWOULDBLOCK) {
  5420. /* TODO (low): check if this is still required */
  5421. /* standard case if called from close_socket_gracefully */
  5422. return -2;
  5423. } else if (err == WSAETIMEDOUT) {
  5424. /* TODO (low): check if this is still required */
  5425. /* timeout is handled by the while loop */
  5426. return 0;
  5427. } else if (err == WSAECONNABORTED) {
  5428. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5429. return -2;
  5430. } else {
  5431. DEBUG_TRACE("recv() failed, error %d", err);
  5432. return -2;
  5433. }
  5434. #else
  5435. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5436. * if the timeout is reached and if the socket was set to non-
  5437. * blocking in close_socket_gracefully, so we can not distinguish
  5438. * here. We have to wait for the timeout in both cases for now.
  5439. */
  5440. if (ERROR_TRY_AGAIN(err)) {
  5441. /* TODO (low): check if this is still required */
  5442. /* EAGAIN/EWOULDBLOCK:
  5443. * standard case if called from close_socket_gracefully
  5444. * => should return -1 */
  5445. /* or timeout occurred
  5446. * => the code must stay in the while loop */
  5447. /* EINTR can be generated on a socket with a timeout set even
  5448. * when SA_RESTART is effective for all relevant signals
  5449. * (see signal(7)).
  5450. * => stay in the while loop */
  5451. } else {
  5452. DEBUG_TRACE("recv() failed, error %d", err);
  5453. return -2;
  5454. }
  5455. #endif
  5456. }
  5457. /* Timeout occurred, but no data available. */
  5458. return -1;
  5459. }
  5460. static int
  5461. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5462. {
  5463. int n, nread = 0;
  5464. double timeout = -1.0;
  5465. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5466. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5467. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5468. }
  5469. if (timeout <= 0.0) {
  5470. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5471. / 1000.0;
  5472. }
  5473. start_time = mg_get_current_time_ns();
  5474. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5475. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5476. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5477. if (n == -2) {
  5478. if (nread == 0) {
  5479. nread = -1; /* Propagate the error */
  5480. }
  5481. break;
  5482. } else if (n == -1) {
  5483. /* timeout */
  5484. if (timeout >= 0.0) {
  5485. now = mg_get_current_time_ns();
  5486. if ((now - start_time) <= timeout_ns) {
  5487. continue;
  5488. }
  5489. }
  5490. break;
  5491. } else if (n == 0) {
  5492. break; /* No more data to read */
  5493. } else {
  5494. nread += n;
  5495. len -= n;
  5496. }
  5497. }
  5498. return nread;
  5499. }
  5500. static void
  5501. discard_unread_request_data(struct mg_connection *conn)
  5502. {
  5503. char buf[MG_BUF_LEN];
  5504. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5505. ;
  5506. }
  5507. static int
  5508. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5509. {
  5510. int64_t content_len, n, buffered_len, nread;
  5511. int64_t len64 =
  5512. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5513. * int, we may not read more
  5514. * bytes */
  5515. const char *body;
  5516. if (conn == NULL) {
  5517. return 0;
  5518. }
  5519. /* If Content-Length is not set for a response with body data,
  5520. * we do not know in advance how much data should be read. */
  5521. content_len = conn->content_len;
  5522. if (content_len < 0) {
  5523. /* The body data is completed when the connection is closed. */
  5524. content_len = INT64_MAX;
  5525. }
  5526. nread = 0;
  5527. if (conn->consumed_content < content_len) {
  5528. /* Adjust number of bytes to read. */
  5529. int64_t left_to_read = content_len - conn->consumed_content;
  5530. if (left_to_read < len64) {
  5531. /* Do not read more than the total content length of the
  5532. * request.
  5533. */
  5534. len64 = left_to_read;
  5535. }
  5536. /* Return buffered data */
  5537. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5538. - conn->consumed_content;
  5539. if (buffered_len > 0) {
  5540. if (len64 < buffered_len) {
  5541. buffered_len = len64;
  5542. }
  5543. body = conn->buf + conn->request_len + conn->consumed_content;
  5544. memcpy(buf, body, (size_t)buffered_len);
  5545. len64 -= buffered_len;
  5546. conn->consumed_content += buffered_len;
  5547. nread += buffered_len;
  5548. buf = (char *)buf + buffered_len;
  5549. }
  5550. /* We have returned all buffered data. Read new data from the remote
  5551. * socket.
  5552. */
  5553. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5554. conn->consumed_content += n;
  5555. nread += n;
  5556. } else {
  5557. nread = ((nread > 0) ? nread : n);
  5558. }
  5559. }
  5560. return (int)nread;
  5561. }
  5562. /* Forward declarations */
  5563. static void handle_request(struct mg_connection *);
  5564. static void log_access(const struct mg_connection *);
  5565. /* Handle request, update statistics and call access log */
  5566. static void
  5567. handle_request_stat_log(struct mg_connection *conn)
  5568. {
  5569. #if defined(USE_SERVER_STATS)
  5570. struct timespec tnow;
  5571. conn->conn_state = 4; /* processing */
  5572. #endif
  5573. handle_request(conn);
  5574. #if defined(USE_SERVER_STATS)
  5575. conn->conn_state = 5; /* processed */
  5576. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5577. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5578. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5579. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5580. conn->num_bytes_sent);
  5581. #endif
  5582. DEBUG_TRACE("%s", "handle_request done");
  5583. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5584. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5585. DEBUG_TRACE("%s", "end_request callback done");
  5586. }
  5587. log_access(conn);
  5588. }
  5589. #if defined(USE_HTTP2)
  5590. #if defined(NO_SSL)
  5591. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5592. #endif
  5593. #define USE_ALPN
  5594. #include "http2.inl"
  5595. /* Not supported with HTTP/2 */
  5596. #define HTTP1_only \
  5597. { \
  5598. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5599. http2_must_use_http1(conn); \
  5600. return; \
  5601. } \
  5602. }
  5603. #else
  5604. #define HTTP1_only
  5605. #endif
  5606. int
  5607. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5608. {
  5609. if (len > INT_MAX) {
  5610. len = INT_MAX;
  5611. }
  5612. if (conn == NULL) {
  5613. return 0;
  5614. }
  5615. if (conn->is_chunked) {
  5616. size_t all_read = 0;
  5617. while (len > 0) {
  5618. if (conn->is_chunked >= 3) {
  5619. /* No more data left to read */
  5620. return 0;
  5621. }
  5622. if (conn->is_chunked != 1) {
  5623. /* Has error */
  5624. return -1;
  5625. }
  5626. if (conn->consumed_content != conn->content_len) {
  5627. /* copy from the current chunk */
  5628. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5629. if (read_ret < 1) {
  5630. /* read error */
  5631. conn->is_chunked = 2;
  5632. return -1;
  5633. }
  5634. all_read += (size_t)read_ret;
  5635. len -= (size_t)read_ret;
  5636. if (conn->consumed_content == conn->content_len) {
  5637. /* Add data bytes in the current chunk have been read,
  5638. * so we are expecting \r\n now. */
  5639. char x[2];
  5640. conn->content_len += 2;
  5641. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5642. || (x[1] != '\n')) {
  5643. /* Protocol violation */
  5644. conn->is_chunked = 2;
  5645. return -1;
  5646. }
  5647. }
  5648. } else {
  5649. /* fetch a new chunk */
  5650. size_t i;
  5651. char lenbuf[64];
  5652. char *end = NULL;
  5653. unsigned long chunkSize = 0;
  5654. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5655. conn->content_len++;
  5656. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5657. lenbuf[i] = 0;
  5658. }
  5659. if ((i > 0) && (lenbuf[i] == '\r')
  5660. && (lenbuf[i - 1] != '\r')) {
  5661. continue;
  5662. }
  5663. if ((i > 1) && (lenbuf[i] == '\n')
  5664. && (lenbuf[i - 1] == '\r')) {
  5665. lenbuf[i + 1] = 0;
  5666. chunkSize = strtoul(lenbuf, &end, 16);
  5667. if (chunkSize == 0) {
  5668. /* regular end of content */
  5669. conn->is_chunked = 3;
  5670. }
  5671. break;
  5672. }
  5673. if (!isxdigit((unsigned char)lenbuf[i])) {
  5674. /* illegal character for chunk length */
  5675. conn->is_chunked = 2;
  5676. return -1;
  5677. }
  5678. }
  5679. if ((end == NULL) || (*end != '\r')) {
  5680. /* chunksize not set correctly */
  5681. conn->is_chunked = 2;
  5682. return -1;
  5683. }
  5684. if (chunkSize == 0) {
  5685. /* try discarding trailer for keep-alive */
  5686. conn->content_len += 2;
  5687. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5688. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5689. conn->is_chunked = 4;
  5690. }
  5691. break;
  5692. }
  5693. /* append a new chunk */
  5694. conn->content_len += (int64_t)chunkSize;
  5695. }
  5696. }
  5697. return (int)all_read;
  5698. }
  5699. return mg_read_inner(conn, buf, len);
  5700. }
  5701. int
  5702. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5703. {
  5704. time_t now;
  5705. int n, total, allowed;
  5706. if (conn == NULL) {
  5707. return 0;
  5708. }
  5709. if (len > INT_MAX) {
  5710. return -1;
  5711. }
  5712. /* Mark connection as "data sent" */
  5713. conn->request_state = 10;
  5714. #if defined(USE_HTTP2)
  5715. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5716. http2_data_frame_head(conn, len, 0);
  5717. }
  5718. #endif
  5719. if (conn->throttle > 0) {
  5720. if ((now = time(NULL)) != conn->last_throttle_time) {
  5721. conn->last_throttle_time = now;
  5722. conn->last_throttle_bytes = 0;
  5723. }
  5724. allowed = conn->throttle - conn->last_throttle_bytes;
  5725. if (allowed > (int)len) {
  5726. allowed = (int)len;
  5727. }
  5728. total = push_all(conn->phys_ctx,
  5729. NULL,
  5730. conn->client.sock,
  5731. conn->ssl,
  5732. (const char *)buf,
  5733. allowed);
  5734. if (total == allowed) {
  5735. buf = (const char *)buf + total;
  5736. conn->last_throttle_bytes += total;
  5737. while ((total < (int)len)
  5738. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5739. allowed = (conn->throttle > ((int)len - total))
  5740. ? (int)len - total
  5741. : conn->throttle;
  5742. n = push_all(conn->phys_ctx,
  5743. NULL,
  5744. conn->client.sock,
  5745. conn->ssl,
  5746. (const char *)buf,
  5747. allowed);
  5748. if (n != allowed) {
  5749. break;
  5750. }
  5751. sleep(1);
  5752. conn->last_throttle_bytes = allowed;
  5753. conn->last_throttle_time = time(NULL);
  5754. buf = (const char *)buf + n;
  5755. total += n;
  5756. }
  5757. }
  5758. } else {
  5759. total = push_all(conn->phys_ctx,
  5760. NULL,
  5761. conn->client.sock,
  5762. conn->ssl,
  5763. (const char *)buf,
  5764. (int)len);
  5765. }
  5766. if (total > 0) {
  5767. conn->num_bytes_sent += total;
  5768. }
  5769. return total;
  5770. }
  5771. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5772. int
  5773. mg_send_chunk(struct mg_connection *conn,
  5774. const char *chunk,
  5775. unsigned int chunk_len)
  5776. {
  5777. char lenbuf[16];
  5778. size_t lenbuf_len;
  5779. int ret;
  5780. int t;
  5781. /* First store the length information in a text buffer. */
  5782. sprintf(lenbuf, "%x\r\n", chunk_len);
  5783. lenbuf_len = strlen(lenbuf);
  5784. /* Then send length information, chunk and terminating \r\n. */
  5785. ret = mg_write(conn, lenbuf, lenbuf_len);
  5786. if (ret != (int)lenbuf_len) {
  5787. return -1;
  5788. }
  5789. t = ret;
  5790. ret = mg_write(conn, chunk, chunk_len);
  5791. if (ret != (int)chunk_len) {
  5792. return -1;
  5793. }
  5794. t += ret;
  5795. ret = mg_write(conn, "\r\n", 2);
  5796. if (ret != 2) {
  5797. return -1;
  5798. }
  5799. t += ret;
  5800. return t;
  5801. }
  5802. #if defined(GCC_DIAGNOSTIC)
  5803. /* This block forwards format strings to printf implementations,
  5804. * so we need to disable the format-nonliteral warning. */
  5805. #pragma GCC diagnostic push
  5806. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5807. #endif
  5808. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5809. static int
  5810. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5811. {
  5812. va_list ap_copy;
  5813. size_t size = MG_BUF_LEN / 4;
  5814. int len = -1;
  5815. *buf = NULL;
  5816. while (len < 0) {
  5817. if (*buf) {
  5818. mg_free(*buf);
  5819. }
  5820. size *= 4;
  5821. *buf = (char *)mg_malloc(size);
  5822. if (!*buf) {
  5823. break;
  5824. }
  5825. va_copy(ap_copy, ap);
  5826. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5827. va_end(ap_copy);
  5828. (*buf)[size - 1] = 0;
  5829. }
  5830. return len;
  5831. }
  5832. /* Print message to buffer. If buffer is large enough to hold the message,
  5833. * return buffer. If buffer is to small, allocate large enough buffer on
  5834. * heap,
  5835. * and return allocated buffer. */
  5836. static int
  5837. alloc_vprintf(char **out_buf,
  5838. char *prealloc_buf,
  5839. size_t prealloc_size,
  5840. const char *fmt,
  5841. va_list ap)
  5842. {
  5843. va_list ap_copy;
  5844. int len;
  5845. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5846. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5847. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5848. * Therefore, we make two passes: on first pass, get required message
  5849. * length.
  5850. * On second pass, actually print the message. */
  5851. va_copy(ap_copy, ap);
  5852. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5853. va_end(ap_copy);
  5854. if (len < 0) {
  5855. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5856. * Switch to alternative code path that uses incremental
  5857. * allocations.
  5858. */
  5859. va_copy(ap_copy, ap);
  5860. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5861. va_end(ap_copy);
  5862. } else if ((size_t)(len) >= prealloc_size) {
  5863. /* The pre-allocated buffer not large enough. */
  5864. /* Allocate a new buffer. */
  5865. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5866. if (!*out_buf) {
  5867. /* Allocation failed. Return -1 as "out of memory" error. */
  5868. return -1;
  5869. }
  5870. /* Buffer allocation successful. Store the string there. */
  5871. va_copy(ap_copy, ap);
  5872. IGNORE_UNUSED_RESULT(
  5873. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5874. va_end(ap_copy);
  5875. } else {
  5876. /* The pre-allocated buffer is large enough.
  5877. * Use it to store the string and return the address. */
  5878. va_copy(ap_copy, ap);
  5879. IGNORE_UNUSED_RESULT(
  5880. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5881. va_end(ap_copy);
  5882. *out_buf = prealloc_buf;
  5883. }
  5884. return len;
  5885. }
  5886. static int
  5887. alloc_printf(char **out_buf, const char *fmt, ...)
  5888. {
  5889. va_list ap;
  5890. int result;
  5891. va_start(ap, fmt);
  5892. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  5893. va_end(ap);
  5894. return result;
  5895. }
  5896. #if defined(GCC_DIAGNOSTIC)
  5897. /* Enable format-nonliteral warning again. */
  5898. #pragma GCC diagnostic pop
  5899. #endif
  5900. static int
  5901. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5902. {
  5903. char mem[MG_BUF_LEN];
  5904. char *buf = NULL;
  5905. int len;
  5906. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5907. len = mg_write(conn, buf, (size_t)len);
  5908. }
  5909. if (buf != mem) {
  5910. mg_free(buf);
  5911. }
  5912. return len;
  5913. }
  5914. int
  5915. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5916. {
  5917. va_list ap;
  5918. int result;
  5919. va_start(ap, fmt);
  5920. result = mg_vprintf(conn, fmt, ap);
  5921. va_end(ap);
  5922. return result;
  5923. }
  5924. int
  5925. mg_url_decode(const char *src,
  5926. int src_len,
  5927. char *dst,
  5928. int dst_len,
  5929. int is_form_url_encoded)
  5930. {
  5931. int i, j, a, b;
  5932. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5933. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5934. if ((i < src_len - 2) && (src[i] == '%')
  5935. && isxdigit((unsigned char)src[i + 1])
  5936. && isxdigit((unsigned char)src[i + 2])) {
  5937. a = tolower((unsigned char)src[i + 1]);
  5938. b = tolower((unsigned char)src[i + 2]);
  5939. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5940. i += 2;
  5941. } else if (is_form_url_encoded && (src[i] == '+')) {
  5942. dst[j] = ' ';
  5943. } else {
  5944. dst[j] = src[i];
  5945. }
  5946. }
  5947. dst[j] = '\0'; /* Null-terminate the destination */
  5948. return (i >= src_len) ? j : -1;
  5949. }
  5950. /* form url decoding of an entire string */
  5951. static void
  5952. url_decode_in_place(char *buf)
  5953. {
  5954. int len = (int)strlen(buf);
  5955. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5956. }
  5957. int
  5958. mg_get_var(const char *data,
  5959. size_t data_len,
  5960. const char *name,
  5961. char *dst,
  5962. size_t dst_len)
  5963. {
  5964. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5965. }
  5966. int
  5967. mg_get_var2(const char *data,
  5968. size_t data_len,
  5969. const char *name,
  5970. char *dst,
  5971. size_t dst_len,
  5972. size_t occurrence)
  5973. {
  5974. const char *p, *e, *s;
  5975. size_t name_len;
  5976. int len;
  5977. if ((dst == NULL) || (dst_len == 0)) {
  5978. len = -2;
  5979. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5980. len = -1;
  5981. dst[0] = '\0';
  5982. } else {
  5983. name_len = strlen(name);
  5984. e = data + data_len;
  5985. len = -1;
  5986. dst[0] = '\0';
  5987. /* data is "var1=val1&var2=val2...". Find variable first */
  5988. for (p = data; p + name_len < e; p++) {
  5989. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5990. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5991. /* Point p to variable value */
  5992. p += name_len + 1;
  5993. /* Point s to the end of the value */
  5994. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5995. if (s == NULL) {
  5996. s = e;
  5997. }
  5998. DEBUG_ASSERT(s >= p);
  5999. if (s < p) {
  6000. return -3;
  6001. }
  6002. /* Decode variable into destination buffer */
  6003. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6004. /* Redirect error code from -1 to -2 (destination buffer too
  6005. * small). */
  6006. if (len == -1) {
  6007. len = -2;
  6008. }
  6009. break;
  6010. }
  6011. }
  6012. }
  6013. return len;
  6014. }
  6015. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6016. int
  6017. mg_split_form_urlencoded(char *data,
  6018. struct mg_header *form_fields,
  6019. unsigned num_form_fields)
  6020. {
  6021. char *b;
  6022. int i;
  6023. int num = 0;
  6024. if (data == NULL) {
  6025. /* parameter error */
  6026. return -1;
  6027. }
  6028. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6029. /* determine the number of expected fields */
  6030. if (data[0] == 0) {
  6031. return 0;
  6032. }
  6033. /* count number of & to return the number of key-value-pairs */
  6034. num = 1;
  6035. while (*data) {
  6036. if (*data == '&') {
  6037. num++;
  6038. }
  6039. data++;
  6040. }
  6041. return num;
  6042. }
  6043. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6044. /* parameter error */
  6045. return -1;
  6046. }
  6047. for (i = 0; i < (int)num_form_fields; i++) {
  6048. /* extract key-value pairs from input data */
  6049. while ((*data == ' ') || (*data == '\t')) {
  6050. /* skip initial spaces */
  6051. data++;
  6052. }
  6053. if (*data == 0) {
  6054. /* end of string reached */
  6055. break;
  6056. }
  6057. form_fields[num].name = data;
  6058. /* find & or = */
  6059. b = data;
  6060. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6061. b++;
  6062. }
  6063. if (*b == 0) {
  6064. /* last key without value */
  6065. form_fields[num].value = NULL;
  6066. } else if (*b == '&') {
  6067. /* mid key without value */
  6068. form_fields[num].value = NULL;
  6069. } else {
  6070. /* terminate string */
  6071. *b = 0;
  6072. /* value starts after '=' */
  6073. data = b + 1;
  6074. form_fields[num].value = data;
  6075. }
  6076. /* new field is stored */
  6077. num++;
  6078. /* find a next key */
  6079. b = strchr(data, '&');
  6080. if (b == 0) {
  6081. /* no more data */
  6082. break;
  6083. } else {
  6084. /* terminate value of last field at '&' */
  6085. *b = 0;
  6086. /* next key-value-pairs starts after '&' */
  6087. data = b + 1;
  6088. }
  6089. }
  6090. /* Decode all values */
  6091. for (i = 0; i < num; i++) {
  6092. if (form_fields[i].name) {
  6093. url_decode_in_place((char *)form_fields[i].name);
  6094. }
  6095. if (form_fields[i].value) {
  6096. url_decode_in_place((char *)form_fields[i].value);
  6097. }
  6098. }
  6099. /* return number of fields found */
  6100. return num;
  6101. }
  6102. /* HCP24: some changes to compare whole var_name */
  6103. int
  6104. mg_get_cookie(const char *cookie_header,
  6105. const char *var_name,
  6106. char *dst,
  6107. size_t dst_size)
  6108. {
  6109. const char *s, *p, *end;
  6110. int name_len, len = -1;
  6111. if ((dst == NULL) || (dst_size == 0)) {
  6112. return -2;
  6113. }
  6114. dst[0] = '\0';
  6115. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6116. return -1;
  6117. }
  6118. name_len = (int)strlen(var_name);
  6119. end = s + strlen(s);
  6120. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6121. if (s[name_len] == '=') {
  6122. /* HCP24: now check is it a substring or a full cookie name */
  6123. if ((s == cookie_header) || (s[-1] == ' ')) {
  6124. s += name_len + 1;
  6125. if ((p = strchr(s, ' ')) == NULL) {
  6126. p = end;
  6127. }
  6128. if (p[-1] == ';') {
  6129. p--;
  6130. }
  6131. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6132. s++;
  6133. p--;
  6134. }
  6135. if ((size_t)(p - s) < dst_size) {
  6136. len = (int)(p - s);
  6137. mg_strlcpy(dst, s, (size_t)len + 1);
  6138. } else {
  6139. len = -3;
  6140. }
  6141. break;
  6142. }
  6143. }
  6144. }
  6145. return len;
  6146. }
  6147. int
  6148. mg_base64_encode(const unsigned char *src,
  6149. size_t src_len,
  6150. char *dst,
  6151. size_t *dst_len)
  6152. {
  6153. static const char *b64 =
  6154. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6155. size_t i, j;
  6156. int a, b, c;
  6157. if (dst_len != NULL) {
  6158. /* Expected length including 0 termination: */
  6159. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6160. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6161. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6162. if (*dst_len < expected_len) {
  6163. if (*dst_len > 0) {
  6164. dst[0] = '\0';
  6165. }
  6166. *dst_len = expected_len;
  6167. return 0;
  6168. }
  6169. }
  6170. for (i = j = 0; i < src_len; i += 3) {
  6171. a = src[i];
  6172. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6173. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6174. dst[j++] = b64[a >> 2];
  6175. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6176. if (i + 1 < src_len) {
  6177. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6178. }
  6179. if (i + 2 < src_len) {
  6180. dst[j++] = b64[c & 63];
  6181. }
  6182. }
  6183. while (j % 4 != 0) {
  6184. dst[j++] = '=';
  6185. }
  6186. dst[j++] = '\0';
  6187. if (dst_len != NULL) {
  6188. *dst_len = (size_t)j;
  6189. }
  6190. /* Return -1 for "OK" */
  6191. return -1;
  6192. }
  6193. static unsigned char
  6194. b64reverse(char letter)
  6195. {
  6196. if ((letter >= 'A') && (letter <= 'Z')) {
  6197. return letter - 'A';
  6198. }
  6199. if ((letter >= 'a') && (letter <= 'z')) {
  6200. return letter - 'a' + 26;
  6201. }
  6202. if ((letter >= '0') && (letter <= '9')) {
  6203. return letter - '0' + 52;
  6204. }
  6205. if (letter == '+') {
  6206. return 62;
  6207. }
  6208. if (letter == '/') {
  6209. return 63;
  6210. }
  6211. if (letter == '=') {
  6212. return 255; /* normal end */
  6213. }
  6214. return 254; /* error */
  6215. }
  6216. int
  6217. mg_base64_decode(const char *src,
  6218. size_t src_len,
  6219. unsigned char *dst,
  6220. size_t *dst_len)
  6221. {
  6222. size_t i;
  6223. unsigned char a, b, c, d;
  6224. size_t dst_len_limit = (size_t)-1;
  6225. size_t dst_len_used = 0;
  6226. if (dst_len != NULL) {
  6227. dst_len_limit = *dst_len;
  6228. *dst_len = 0;
  6229. }
  6230. for (i = 0; i < src_len; i += 4) {
  6231. /* Read 4 characters from BASE64 string */
  6232. a = b64reverse(src[i]);
  6233. if (a >= 254) {
  6234. return i;
  6235. }
  6236. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6237. if (b >= 254) {
  6238. return i + 1;
  6239. }
  6240. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6241. if (c == 254) {
  6242. return i + 2;
  6243. }
  6244. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6245. if (d == 254) {
  6246. return i + 3;
  6247. }
  6248. /* Add first (of 3) decoded character */
  6249. if (dst_len_used < dst_len_limit) {
  6250. dst[dst_len_used] = (a << 2) + (b >> 4);
  6251. }
  6252. dst_len_used++;
  6253. if (c != 255) {
  6254. if (dst_len_used < dst_len_limit) {
  6255. dst[dst_len_used] = (b << 4) + (c >> 2);
  6256. }
  6257. dst_len_used++;
  6258. if (d != 255) {
  6259. if (dst_len_used < dst_len_limit) {
  6260. dst[dst_len_used] = (c << 6) + d;
  6261. }
  6262. dst_len_used++;
  6263. }
  6264. }
  6265. }
  6266. /* Add terminating zero */
  6267. if (dst_len_used < dst_len_limit) {
  6268. dst[dst_len_used] = '\0';
  6269. }
  6270. dst_len_used++;
  6271. if (dst_len != NULL) {
  6272. *dst_len = dst_len_used;
  6273. }
  6274. if (dst_len_used > dst_len_limit) {
  6275. /* Out of memory */
  6276. return 0;
  6277. }
  6278. /* Return -1 for "OK" */
  6279. return -1;
  6280. }
  6281. static int
  6282. is_put_or_delete_method(const struct mg_connection *conn)
  6283. {
  6284. if (conn) {
  6285. const char *s = conn->request_info.request_method;
  6286. if (s != NULL) {
  6287. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6288. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6289. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6290. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6291. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6292. || !strcmp(s, "COPY"));
  6293. }
  6294. }
  6295. return 0;
  6296. }
  6297. static int
  6298. is_civetweb_webdav_method(const struct mg_connection *conn)
  6299. {
  6300. /* Note: Here we only have to identify the WebDav methods that need special
  6301. * handling in the CivetWeb code - not all methods used in WebDav. In
  6302. * particular, methods used on directories (when using Windows Explorer as
  6303. * WebDav client).
  6304. */
  6305. if (conn) {
  6306. const char *s = conn->request_info.request_method;
  6307. if (s != NULL) {
  6308. /* These are the civetweb builtin DAV methods */
  6309. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6310. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6311. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6312. }
  6313. }
  6314. return 0;
  6315. }
  6316. #if !defined(NO_FILES)
  6317. static int
  6318. extention_matches_script(
  6319. struct mg_connection *conn, /* in: request (must be valid) */
  6320. const char *filename /* in: filename (must be valid) */
  6321. )
  6322. {
  6323. #if !defined(NO_CGI)
  6324. unsigned char cgi_config_idx, inc, max;
  6325. #endif
  6326. #if defined(USE_LUA)
  6327. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6328. filename)
  6329. > 0) {
  6330. return 1;
  6331. }
  6332. #endif
  6333. #if defined(USE_DUKTAPE)
  6334. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6335. filename)
  6336. > 0) {
  6337. return 1;
  6338. }
  6339. #endif
  6340. #if !defined(NO_CGI)
  6341. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6342. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6343. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6344. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6345. && (match_prefix_strlen(
  6346. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6347. filename)
  6348. > 0)) {
  6349. return 1;
  6350. }
  6351. }
  6352. #endif
  6353. /* filename and conn could be unused, if all preocessor conditions
  6354. * are false (no script language supported). */
  6355. (void)filename;
  6356. (void)conn;
  6357. return 0;
  6358. }
  6359. static int
  6360. extention_matches_template_text(
  6361. struct mg_connection *conn, /* in: request (must be valid) */
  6362. const char *filename /* in: filename (must be valid) */
  6363. )
  6364. {
  6365. #if defined(USE_LUA)
  6366. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6367. filename)
  6368. > 0) {
  6369. return 1;
  6370. }
  6371. #endif
  6372. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6373. > 0) {
  6374. return 1;
  6375. }
  6376. return 0;
  6377. }
  6378. /* For given directory path, substitute it to valid index file.
  6379. * Return 1 if index file has been found, 0 if not found.
  6380. * If the file is found, it's stats is returned in stp. */
  6381. static int
  6382. substitute_index_file(struct mg_connection *conn,
  6383. char *path,
  6384. size_t path_len,
  6385. struct mg_file_stat *filestat)
  6386. {
  6387. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6388. struct vec filename_vec;
  6389. size_t n = strlen(path);
  6390. int found = 0;
  6391. /* The 'path' given to us points to the directory. Remove all trailing
  6392. * directory separator characters from the end of the path, and
  6393. * then append single directory separator character. */
  6394. while ((n > 0) && (path[n - 1] == '/')) {
  6395. n--;
  6396. }
  6397. path[n] = '/';
  6398. /* Traverse index files list. For each entry, append it to the given
  6399. * path and see if the file exists. If it exists, break the loop */
  6400. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6401. /* Ignore too long entries that may overflow path buffer */
  6402. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6403. continue;
  6404. }
  6405. /* Prepare full path to the index file */
  6406. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6407. /* Does it exist? */
  6408. if (mg_stat(conn, path, filestat)) {
  6409. /* Yes it does, break the loop */
  6410. found = 1;
  6411. break;
  6412. }
  6413. }
  6414. /* If no index file exists, restore directory path */
  6415. if (!found) {
  6416. path[n] = '\0';
  6417. }
  6418. return found;
  6419. }
  6420. #endif
  6421. static void
  6422. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6423. char *filename, /* out: filename */
  6424. size_t filename_buf_len, /* in: size of filename buffer */
  6425. struct mg_file_stat *filestat, /* out: file status structure */
  6426. int *is_found, /* out: file found (directly) */
  6427. int *is_script_resource, /* out: handled by a script? */
  6428. int *is_websocket_request, /* out: websocket connetion? */
  6429. int *is_put_or_delete_request, /* out: put/delete a file? */
  6430. int *is_webdav_request, /* out: webdav request? */
  6431. int *is_template_text /* out: SSI file or LSP file? */
  6432. )
  6433. {
  6434. char const *accept_encoding;
  6435. #if !defined(NO_FILES)
  6436. const char *uri = conn->request_info.local_uri;
  6437. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6438. const char *rewrite;
  6439. struct vec a, b;
  6440. ptrdiff_t match_len;
  6441. char gz_path[UTF8_PATH_MAX];
  6442. int truncated;
  6443. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6444. char *tmp_str;
  6445. size_t tmp_str_len, sep_pos;
  6446. int allow_substitute_script_subresources;
  6447. #endif
  6448. #else
  6449. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6450. #endif
  6451. /* Step 1: Set all initially unknown outputs to zero */
  6452. memset(filestat, 0, sizeof(*filestat));
  6453. *filename = 0;
  6454. *is_found = 0;
  6455. *is_script_resource = 0;
  6456. *is_template_text = 0;
  6457. /* Step 2: Classify the request method */
  6458. /* Step 2a: Check if the request attempts to modify the file system */
  6459. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6460. /* Step 2b: Check if the request uses WebDav method that requires special
  6461. * handling */
  6462. *is_webdav_request = is_civetweb_webdav_method(conn);
  6463. /* Step 3: Check if it is a websocket request, and modify the document
  6464. * root if required */
  6465. #if defined(USE_WEBSOCKET)
  6466. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6467. #if !defined(NO_FILES)
  6468. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6469. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6470. }
  6471. #endif /* !NO_FILES */
  6472. #else /* USE_WEBSOCKET */
  6473. *is_websocket_request = 0;
  6474. #endif /* USE_WEBSOCKET */
  6475. /* Step 4: Check if gzip encoded response is allowed */
  6476. conn->accept_gzip = 0;
  6477. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6478. if (strstr(accept_encoding, "gzip") != NULL) {
  6479. conn->accept_gzip = 1;
  6480. }
  6481. }
  6482. #if !defined(NO_FILES)
  6483. /* Step 5: If there is no root directory, don't look for files. */
  6484. /* Note that root == NULL is a regular use case here. This occurs,
  6485. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6486. * config is not required. */
  6487. if (root == NULL) {
  6488. /* all file related outputs have already been set to 0, just return
  6489. */
  6490. return;
  6491. }
  6492. /* Step 6: Determine the local file path from the root path and the
  6493. * request uri. */
  6494. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6495. * part of the path one byte on the right. */
  6496. truncated = 0;
  6497. mg_snprintf(
  6498. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6499. if (truncated) {
  6500. goto interpret_cleanup;
  6501. }
  6502. /* Step 7: URI rewriting */
  6503. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6504. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6505. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6506. mg_snprintf(conn,
  6507. &truncated,
  6508. filename,
  6509. filename_buf_len - 1,
  6510. "%.*s%s",
  6511. (int)b.len,
  6512. b.ptr,
  6513. uri + match_len);
  6514. break;
  6515. }
  6516. }
  6517. if (truncated) {
  6518. goto interpret_cleanup;
  6519. }
  6520. /* Step 8: Check if the file exists at the server */
  6521. /* Local file path and name, corresponding to requested URI
  6522. * is now stored in "filename" variable. */
  6523. if (mg_stat(conn, filename, filestat)) {
  6524. int uri_len = (int)strlen(uri);
  6525. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6526. /* 8.1: File exists. */
  6527. *is_found = 1;
  6528. /* 8.2: Check if it is a script type. */
  6529. if (extention_matches_script(conn, filename)) {
  6530. /* The request addresses a CGI resource, Lua script or
  6531. * server-side javascript.
  6532. * The URI corresponds to the script itself (like
  6533. * /path/script.cgi), and there is no additional resource
  6534. * path (like /path/script.cgi/something).
  6535. * Requests that modify (replace or delete) a resource, like
  6536. * PUT and DELETE requests, should replace/delete the script
  6537. * file.
  6538. * Requests that read or write from/to a resource, like GET and
  6539. * POST requests, should call the script and return the
  6540. * generated response. */
  6541. *is_script_resource = (!*is_put_or_delete_request);
  6542. }
  6543. /* 8.3: Check for SSI and LSP files */
  6544. if (extention_matches_template_text(conn, filename)) {
  6545. /* Same as above, but for *.lsp and *.shtml files. */
  6546. /* A "template text" is a file delivered directly to the client,
  6547. * but with some text tags replaced by dynamic content.
  6548. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6549. * (LP, LSP) file. */
  6550. *is_template_text = (!*is_put_or_delete_request);
  6551. }
  6552. /* 8.4: If the request target is a directory, there could be
  6553. * a substitute file (index.html, index.cgi, ...). */
  6554. /* But do not substitute a directory for a WebDav request */
  6555. if (filestat->is_directory && is_uri_end_slash
  6556. && (!*is_webdav_request)) {
  6557. /* Use a local copy here, since substitute_index_file will
  6558. * change the content of the file status */
  6559. struct mg_file_stat tmp_filestat;
  6560. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6561. if (substitute_index_file(
  6562. conn, filename, filename_buf_len, &tmp_filestat)) {
  6563. /* Substitute file found. Copy stat to the output, then
  6564. * check if the file is a script file */
  6565. *filestat = tmp_filestat;
  6566. if (extention_matches_script(conn, filename)) {
  6567. /* Substitute file is a script file */
  6568. *is_script_resource = 1;
  6569. } else if (extention_matches_template_text(conn, filename)) {
  6570. /* Substitute file is a LSP or SSI file */
  6571. *is_template_text = 1;
  6572. } else {
  6573. /* Substitute file is a regular file */
  6574. *is_script_resource = 0;
  6575. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6576. }
  6577. }
  6578. /* If there is no substitute file, the server could return
  6579. * a directory listing in a later step */
  6580. }
  6581. return;
  6582. }
  6583. /* Step 9: Check for zipped files: */
  6584. /* If we can't find the actual file, look for the file
  6585. * with the same name but a .gz extension. If we find it,
  6586. * use that and set the gzipped flag in the file struct
  6587. * to indicate that the response need to have the content-
  6588. * encoding: gzip header.
  6589. * We can only do this if the browser declares support. */
  6590. if (conn->accept_gzip) {
  6591. mg_snprintf(
  6592. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6593. if (truncated) {
  6594. goto interpret_cleanup;
  6595. }
  6596. if (mg_stat(conn, gz_path, filestat)) {
  6597. if (filestat) {
  6598. filestat->is_gzipped = 1;
  6599. *is_found = 1;
  6600. }
  6601. /* Currently gz files can not be scripts. */
  6602. return;
  6603. }
  6604. }
  6605. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6606. /* Step 10: Script resources may handle sub-resources */
  6607. /* Support PATH_INFO for CGI scripts. */
  6608. tmp_str_len = strlen(filename);
  6609. tmp_str =
  6610. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6611. if (!tmp_str) {
  6612. /* Out of memory */
  6613. goto interpret_cleanup;
  6614. }
  6615. memcpy(tmp_str, filename, tmp_str_len + 1);
  6616. /* Check config, if index scripts may have sub-resources */
  6617. allow_substitute_script_subresources =
  6618. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6619. "yes");
  6620. if (*is_webdav_request) {
  6621. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6622. * PROPFIND fo their subresources? */
  6623. /* allow_substitute_script_subresources = 0; */
  6624. }
  6625. sep_pos = tmp_str_len;
  6626. while (sep_pos > 0) {
  6627. sep_pos--;
  6628. if (tmp_str[sep_pos] == '/') {
  6629. int is_script = 0, does_exist = 0;
  6630. tmp_str[sep_pos] = 0;
  6631. if (tmp_str[0]) {
  6632. is_script = extention_matches_script(conn, tmp_str);
  6633. does_exist = mg_stat(conn, tmp_str, filestat);
  6634. }
  6635. if (does_exist && is_script) {
  6636. filename[sep_pos] = 0;
  6637. memmove(filename + sep_pos + 2,
  6638. filename + sep_pos + 1,
  6639. strlen(filename + sep_pos + 1) + 1);
  6640. conn->path_info = filename + sep_pos + 1;
  6641. filename[sep_pos + 1] = '/';
  6642. *is_script_resource = 1;
  6643. *is_found = 1;
  6644. break;
  6645. }
  6646. if (allow_substitute_script_subresources) {
  6647. if (substitute_index_file(
  6648. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6649. /* some intermediate directory has an index file */
  6650. if (extention_matches_script(conn, tmp_str)) {
  6651. size_t script_name_len = strlen(tmp_str);
  6652. /* subres_name read before this memory locatio will be
  6653. overwritten */
  6654. char *subres_name = filename + sep_pos;
  6655. size_t subres_name_len = strlen(subres_name);
  6656. DEBUG_TRACE("Substitute script %s serving path %s",
  6657. tmp_str,
  6658. filename);
  6659. /* this index file is a script */
  6660. if ((script_name_len + subres_name_len + 2)
  6661. >= filename_buf_len) {
  6662. mg_free(tmp_str);
  6663. goto interpret_cleanup;
  6664. }
  6665. conn->path_info =
  6666. filename + script_name_len + 1; /* new target */
  6667. memmove(conn->path_info, subres_name, subres_name_len);
  6668. conn->path_info[subres_name_len] = 0;
  6669. memcpy(filename, tmp_str, script_name_len + 1);
  6670. *is_script_resource = 1;
  6671. *is_found = 1;
  6672. break;
  6673. } else {
  6674. DEBUG_TRACE("Substitute file %s serving path %s",
  6675. tmp_str,
  6676. filename);
  6677. /* non-script files will not have sub-resources */
  6678. filename[sep_pos] = 0;
  6679. conn->path_info = 0;
  6680. *is_script_resource = 0;
  6681. *is_found = 0;
  6682. break;
  6683. }
  6684. }
  6685. }
  6686. tmp_str[sep_pos] = '/';
  6687. }
  6688. }
  6689. mg_free(tmp_str);
  6690. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6691. #endif /* !defined(NO_FILES) */
  6692. return;
  6693. #if !defined(NO_FILES)
  6694. /* Reset all outputs */
  6695. interpret_cleanup:
  6696. memset(filestat, 0, sizeof(*filestat));
  6697. *filename = 0;
  6698. *is_found = 0;
  6699. *is_script_resource = 0;
  6700. *is_websocket_request = 0;
  6701. *is_put_or_delete_request = 0;
  6702. #endif /* !defined(NO_FILES) */
  6703. }
  6704. /* Check whether full request is buffered. Return:
  6705. * -1 if request or response is malformed
  6706. * 0 if request or response is not yet fully buffered
  6707. * >0 actual request length, including last \r\n\r\n */
  6708. static int
  6709. get_http_header_len(const char *buf, int buflen)
  6710. {
  6711. int i;
  6712. for (i = 0; i < buflen; i++) {
  6713. /* Do an unsigned comparison in some conditions below */
  6714. const unsigned char c = (unsigned char)buf[i];
  6715. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6716. && !isprint(c)) {
  6717. /* abort scan as soon as one malformed character is found */
  6718. return -1;
  6719. }
  6720. if (i < buflen - 1) {
  6721. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6722. /* Two newline, no carriage return - not standard compliant,
  6723. * but it should be accepted */
  6724. return i + 2;
  6725. }
  6726. }
  6727. if (i < buflen - 3) {
  6728. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6729. && (buf[i + 3] == '\n')) {
  6730. /* Two \r\n - standard compliant */
  6731. return i + 4;
  6732. }
  6733. }
  6734. }
  6735. return 0;
  6736. }
  6737. #if !defined(NO_CACHING)
  6738. /* Convert month to the month number. Return -1 on error, or month number */
  6739. static int
  6740. get_month_index(const char *s)
  6741. {
  6742. size_t i;
  6743. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6744. if (!strcmp(s, month_names[i])) {
  6745. return (int)i;
  6746. }
  6747. }
  6748. return -1;
  6749. }
  6750. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6751. static time_t
  6752. parse_date_string(const char *datetime)
  6753. {
  6754. char month_str[32] = {0};
  6755. int second, minute, hour, day, month, year;
  6756. time_t result = (time_t)0;
  6757. struct tm tm;
  6758. if ((sscanf(datetime,
  6759. "%d/%3s/%d %d:%d:%d",
  6760. &day,
  6761. month_str,
  6762. &year,
  6763. &hour,
  6764. &minute,
  6765. &second)
  6766. == 6)
  6767. || (sscanf(datetime,
  6768. "%d %3s %d %d:%d:%d",
  6769. &day,
  6770. month_str,
  6771. &year,
  6772. &hour,
  6773. &minute,
  6774. &second)
  6775. == 6)
  6776. || (sscanf(datetime,
  6777. "%*3s, %d %3s %d %d:%d:%d",
  6778. &day,
  6779. month_str,
  6780. &year,
  6781. &hour,
  6782. &minute,
  6783. &second)
  6784. == 6)
  6785. || (sscanf(datetime,
  6786. "%d-%3s-%d %d:%d:%d",
  6787. &day,
  6788. month_str,
  6789. &year,
  6790. &hour,
  6791. &minute,
  6792. &second)
  6793. == 6)) {
  6794. month = get_month_index(month_str);
  6795. if ((month >= 0) && (year >= 1970)) {
  6796. memset(&tm, 0, sizeof(tm));
  6797. tm.tm_year = year - 1900;
  6798. tm.tm_mon = month;
  6799. tm.tm_mday = day;
  6800. tm.tm_hour = hour;
  6801. tm.tm_min = minute;
  6802. tm.tm_sec = second;
  6803. result = timegm(&tm);
  6804. }
  6805. }
  6806. return result;
  6807. }
  6808. #endif /* !NO_CACHING */
  6809. /* Pre-process URIs according to RFC + protect against directory disclosure
  6810. * attacks by removing '..', excessive '/' and '\' characters */
  6811. static void
  6812. remove_dot_segments(char *inout)
  6813. {
  6814. /* Windows backend protection
  6815. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6816. * in URI by slash */
  6817. char *out_end = inout;
  6818. char *in = inout;
  6819. if (!in) {
  6820. /* Param error. */
  6821. return;
  6822. }
  6823. while (*in) {
  6824. if (*in == '\\') {
  6825. *in = '/';
  6826. }
  6827. in++;
  6828. }
  6829. /* Algorithm "remove_dot_segments" from
  6830. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6831. /* Step 1:
  6832. * The input buffer is initialized.
  6833. * The output buffer is initialized to the empty string.
  6834. */
  6835. in = inout;
  6836. /* Step 2:
  6837. * While the input buffer is not empty, loop as follows:
  6838. */
  6839. /* Less than out_end of the inout buffer is used as output, so keep
  6840. * condition: out_end <= in */
  6841. while (*in) {
  6842. /* Step 2a:
  6843. * If the input buffer begins with a prefix of "../" or "./",
  6844. * then remove that prefix from the input buffer;
  6845. */
  6846. if (!strncmp(in, "../", 3)) {
  6847. in += 3;
  6848. } else if (!strncmp(in, "./", 2)) {
  6849. in += 2;
  6850. }
  6851. /* otherwise */
  6852. /* Step 2b:
  6853. * if the input buffer begins with a prefix of "/./" or "/.",
  6854. * where "." is a complete path segment, then replace that
  6855. * prefix with "/" in the input buffer;
  6856. */
  6857. else if (!strncmp(in, "/./", 3)) {
  6858. in += 2;
  6859. } else if (!strcmp(in, "/.")) {
  6860. in[1] = 0;
  6861. }
  6862. /* otherwise */
  6863. /* Step 2c:
  6864. * if the input buffer begins with a prefix of "/../" or "/..",
  6865. * where ".." is a complete path segment, then replace that
  6866. * prefix with "/" in the input buffer and remove the last
  6867. * segment and its preceding "/" (if any) from the output
  6868. * buffer;
  6869. */
  6870. else if (!strncmp(in, "/../", 4)) {
  6871. in += 3;
  6872. if (inout != out_end) {
  6873. /* remove last segment */
  6874. do {
  6875. out_end--;
  6876. } while ((inout != out_end) && (*out_end != '/'));
  6877. }
  6878. } else if (!strcmp(in, "/..")) {
  6879. in[1] = 0;
  6880. if (inout != out_end) {
  6881. /* remove last segment */
  6882. do {
  6883. out_end--;
  6884. } while ((inout != out_end) && (*out_end != '/'));
  6885. }
  6886. }
  6887. /* otherwise */
  6888. /* Step 2d:
  6889. * if the input buffer consists only of "." or "..", then remove
  6890. * that from the input buffer;
  6891. */
  6892. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6893. *in = 0;
  6894. }
  6895. /* otherwise */
  6896. /* Step 2e:
  6897. * move the first path segment in the input buffer to the end of
  6898. * the output buffer, including the initial "/" character (if
  6899. * any) and any subsequent characters up to, but not including,
  6900. * the next "/" character or the end of the input buffer.
  6901. */
  6902. else {
  6903. do {
  6904. *out_end = *in;
  6905. out_end++;
  6906. in++;
  6907. } while ((*in != 0) && (*in != '/'));
  6908. }
  6909. }
  6910. /* Step 3:
  6911. * Finally, the output buffer is returned as the result of
  6912. * remove_dot_segments.
  6913. */
  6914. /* Terminate output */
  6915. *out_end = 0;
  6916. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6917. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6918. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6919. * or "//" anymore.
  6920. */
  6921. out_end = in = inout;
  6922. while (*in) {
  6923. if (*in == '.') {
  6924. /* remove . at the end or preceding of / */
  6925. char *in_ahead = in;
  6926. do {
  6927. in_ahead++;
  6928. } while (*in_ahead == '.');
  6929. if (*in_ahead == '/') {
  6930. in = in_ahead;
  6931. if ((out_end != inout) && (out_end[-1] == '/')) {
  6932. /* remove generated // */
  6933. out_end--;
  6934. }
  6935. } else if (*in_ahead == 0) {
  6936. in = in_ahead;
  6937. } else {
  6938. do {
  6939. *out_end++ = '.';
  6940. in++;
  6941. } while (in != in_ahead);
  6942. }
  6943. } else if (*in == '/') {
  6944. /* replace // by / */
  6945. *out_end++ = '/';
  6946. do {
  6947. in++;
  6948. } while (*in == '/');
  6949. } else {
  6950. *out_end++ = *in;
  6951. in++;
  6952. }
  6953. }
  6954. *out_end = 0;
  6955. }
  6956. static const struct {
  6957. const char *extension;
  6958. size_t ext_len;
  6959. const char *mime_type;
  6960. } builtin_mime_types[] = {
  6961. /* IANA registered MIME types
  6962. * (http://www.iana.org/assignments/media-types)
  6963. * application types */
  6964. {".bin", 4, "application/octet-stream"},
  6965. {".deb", 4, "application/octet-stream"},
  6966. {".dmg", 4, "application/octet-stream"},
  6967. {".dll", 4, "application/octet-stream"},
  6968. {".doc", 4, "application/msword"},
  6969. {".eps", 4, "application/postscript"},
  6970. {".exe", 4, "application/octet-stream"},
  6971. {".iso", 4, "application/octet-stream"},
  6972. {".js", 3, "application/javascript"},
  6973. {".json", 5, "application/json"},
  6974. {".msi", 4, "application/octet-stream"},
  6975. {".pdf", 4, "application/pdf"},
  6976. {".ps", 3, "application/postscript"},
  6977. {".rtf", 4, "application/rtf"},
  6978. {".xhtml", 6, "application/xhtml+xml"},
  6979. {".xsl", 4, "application/xml"},
  6980. {".xslt", 5, "application/xml"},
  6981. /* fonts */
  6982. {".ttf", 4, "application/font-sfnt"},
  6983. {".cff", 4, "application/font-sfnt"},
  6984. {".otf", 4, "application/font-sfnt"},
  6985. {".aat", 4, "application/font-sfnt"},
  6986. {".sil", 4, "application/font-sfnt"},
  6987. {".pfr", 4, "application/font-tdpfr"},
  6988. {".woff", 5, "application/font-woff"},
  6989. {".woff2", 6, "application/font-woff2"},
  6990. /* audio */
  6991. {".mp3", 4, "audio/mpeg"},
  6992. {".oga", 4, "audio/ogg"},
  6993. {".ogg", 4, "audio/ogg"},
  6994. /* image */
  6995. {".gif", 4, "image/gif"},
  6996. {".ief", 4, "image/ief"},
  6997. {".jpeg", 5, "image/jpeg"},
  6998. {".jpg", 4, "image/jpeg"},
  6999. {".jpm", 4, "image/jpm"},
  7000. {".jpx", 4, "image/jpx"},
  7001. {".png", 4, "image/png"},
  7002. {".svg", 4, "image/svg+xml"},
  7003. {".tif", 4, "image/tiff"},
  7004. {".tiff", 5, "image/tiff"},
  7005. /* model */
  7006. {".wrl", 4, "model/vrml"},
  7007. /* text */
  7008. {".css", 4, "text/css"},
  7009. {".csv", 4, "text/csv"},
  7010. {".htm", 4, "text/html"},
  7011. {".html", 5, "text/html"},
  7012. {".sgm", 4, "text/sgml"},
  7013. {".shtm", 5, "text/html"},
  7014. {".shtml", 6, "text/html"},
  7015. {".txt", 4, "text/plain"},
  7016. {".xml", 4, "text/xml"},
  7017. /* video */
  7018. {".mov", 4, "video/quicktime"},
  7019. {".mp4", 4, "video/mp4"},
  7020. {".mpeg", 5, "video/mpeg"},
  7021. {".mpg", 4, "video/mpeg"},
  7022. {".ogv", 4, "video/ogg"},
  7023. {".qt", 3, "video/quicktime"},
  7024. /* not registered types
  7025. * (http://reference.sitepoint.com/html/mime-types-full,
  7026. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7027. {".arj", 4, "application/x-arj-compressed"},
  7028. {".gz", 3, "application/x-gunzip"},
  7029. {".rar", 4, "application/x-arj-compressed"},
  7030. {".swf", 4, "application/x-shockwave-flash"},
  7031. {".tar", 4, "application/x-tar"},
  7032. {".tgz", 4, "application/x-tar-gz"},
  7033. {".torrent", 8, "application/x-bittorrent"},
  7034. {".ppt", 4, "application/x-mspowerpoint"},
  7035. {".xls", 4, "application/x-msexcel"},
  7036. {".zip", 4, "application/x-zip-compressed"},
  7037. {".aac",
  7038. 4,
  7039. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7040. {".flac", 5, "audio/flac"},
  7041. {".aif", 4, "audio/x-aif"},
  7042. {".m3u", 4, "audio/x-mpegurl"},
  7043. {".mid", 4, "audio/x-midi"},
  7044. {".ra", 3, "audio/x-pn-realaudio"},
  7045. {".ram", 4, "audio/x-pn-realaudio"},
  7046. {".wav", 4, "audio/x-wav"},
  7047. {".bmp", 4, "image/bmp"},
  7048. {".ico", 4, "image/x-icon"},
  7049. {".pct", 4, "image/x-pct"},
  7050. {".pict", 5, "image/pict"},
  7051. {".rgb", 4, "image/x-rgb"},
  7052. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7053. {".asf", 4, "video/x-ms-asf"},
  7054. {".avi", 4, "video/x-msvideo"},
  7055. {".m4v", 4, "video/x-m4v"},
  7056. {NULL, 0, NULL}};
  7057. const char *
  7058. mg_get_builtin_mime_type(const char *path)
  7059. {
  7060. const char *ext;
  7061. size_t i, path_len;
  7062. path_len = strlen(path);
  7063. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7064. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7065. if ((path_len > builtin_mime_types[i].ext_len)
  7066. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7067. return builtin_mime_types[i].mime_type;
  7068. }
  7069. }
  7070. return "text/plain";
  7071. }
  7072. /* Look at the "path" extension and figure what mime type it has.
  7073. * Store mime type in the vector. */
  7074. static void
  7075. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7076. {
  7077. struct vec ext_vec, mime_vec;
  7078. const char *list, *ext;
  7079. size_t path_len;
  7080. path_len = strlen(path);
  7081. if ((conn == NULL) || (vec == NULL)) {
  7082. if (vec != NULL) {
  7083. memset(vec, '\0', sizeof(struct vec));
  7084. }
  7085. return;
  7086. }
  7087. /* Scan user-defined mime types first, in case user wants to
  7088. * override default mime types. */
  7089. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7090. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7091. /* ext now points to the path suffix */
  7092. ext = path + path_len - ext_vec.len;
  7093. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7094. *vec = mime_vec;
  7095. return;
  7096. }
  7097. }
  7098. vec->ptr = mg_get_builtin_mime_type(path);
  7099. vec->len = strlen(vec->ptr);
  7100. }
  7101. /* Stringify binary data. Output buffer must be twice as big as input,
  7102. * because each byte takes 2 bytes in string representation */
  7103. static void
  7104. bin2str(char *to, const unsigned char *p, size_t len)
  7105. {
  7106. static const char *hex = "0123456789abcdef";
  7107. for (; len--; p++) {
  7108. *to++ = hex[p[0] >> 4];
  7109. *to++ = hex[p[0] & 0x0f];
  7110. }
  7111. *to = '\0';
  7112. }
  7113. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7114. */
  7115. char *
  7116. mg_md5(char buf[33], ...)
  7117. {
  7118. md5_byte_t hash[16];
  7119. const char *p;
  7120. va_list ap;
  7121. md5_state_t ctx;
  7122. md5_init(&ctx);
  7123. va_start(ap, buf);
  7124. while ((p = va_arg(ap, const char *)) != NULL) {
  7125. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7126. }
  7127. va_end(ap);
  7128. md5_finish(&ctx, hash);
  7129. bin2str(buf, hash, sizeof(hash));
  7130. return buf;
  7131. }
  7132. /* Check the user's password, return 1 if OK */
  7133. static int
  7134. check_password(const char *method,
  7135. const char *ha1,
  7136. const char *uri,
  7137. const char *nonce,
  7138. const char *nc,
  7139. const char *cnonce,
  7140. const char *qop,
  7141. const char *response)
  7142. {
  7143. char ha2[32 + 1], expected_response[32 + 1];
  7144. /* Some of the parameters may be NULL */
  7145. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7146. || (qop == NULL) || (response == NULL)) {
  7147. return 0;
  7148. }
  7149. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7150. if (strlen(response) != 32) {
  7151. return 0;
  7152. }
  7153. mg_md5(ha2, method, ":", uri, NULL);
  7154. mg_md5(expected_response,
  7155. ha1,
  7156. ":",
  7157. nonce,
  7158. ":",
  7159. nc,
  7160. ":",
  7161. cnonce,
  7162. ":",
  7163. qop,
  7164. ":",
  7165. ha2,
  7166. NULL);
  7167. return mg_strcasecmp(response, expected_response) == 0;
  7168. }
  7169. #if !defined(NO_FILESYSTEMS)
  7170. /* Use the global passwords file, if specified by auth_gpass option,
  7171. * or search for .htpasswd in the requested directory. */
  7172. static void
  7173. open_auth_file(struct mg_connection *conn,
  7174. const char *path,
  7175. struct mg_file *filep)
  7176. {
  7177. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7178. char name[UTF8_PATH_MAX];
  7179. const char *p, *e,
  7180. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7181. int truncated;
  7182. if (gpass != NULL) {
  7183. /* Use global passwords file */
  7184. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7185. #if defined(DEBUG)
  7186. /* Use mg_cry_internal here, since gpass has been
  7187. * configured. */
  7188. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7189. #endif
  7190. }
  7191. /* Important: using local struct mg_file to test path for
  7192. * is_directory flag. If filep is used, mg_stat() makes it
  7193. * appear as if auth file was opened.
  7194. * TODO(mid): Check if this is still required after rewriting
  7195. * mg_stat */
  7196. } else if (mg_stat(conn, path, &filep->stat)
  7197. && filep->stat.is_directory) {
  7198. mg_snprintf(conn,
  7199. &truncated,
  7200. name,
  7201. sizeof(name),
  7202. "%s/%s",
  7203. path,
  7204. PASSWORDS_FILE_NAME);
  7205. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7206. #if defined(DEBUG)
  7207. /* Don't use mg_cry_internal here, but only a trace, since
  7208. * this is a typical case. It will occur for every directory
  7209. * without a password file. */
  7210. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7211. #endif
  7212. }
  7213. } else {
  7214. /* Try to find .htpasswd in requested directory. */
  7215. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7216. if (e[0] == '/') {
  7217. break;
  7218. }
  7219. }
  7220. mg_snprintf(conn,
  7221. &truncated,
  7222. name,
  7223. sizeof(name),
  7224. "%.*s/%s",
  7225. (int)(e - p),
  7226. p,
  7227. PASSWORDS_FILE_NAME);
  7228. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7229. #if defined(DEBUG)
  7230. /* Don't use mg_cry_internal here, but only a trace, since
  7231. * this is a typical case. It will occur for every directory
  7232. * without a password file. */
  7233. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7234. #endif
  7235. }
  7236. }
  7237. }
  7238. }
  7239. #endif /* NO_FILESYSTEMS */
  7240. /* Parsed Authorization header */
  7241. struct ah {
  7242. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7243. };
  7244. /* Return 1 on success. Always initializes the ah structure. */
  7245. static int
  7246. parse_auth_header(struct mg_connection *conn,
  7247. char *buf,
  7248. size_t buf_size,
  7249. struct ah *ah)
  7250. {
  7251. char *name, *value, *s;
  7252. const char *auth_header;
  7253. uint64_t nonce;
  7254. if (!ah || !conn) {
  7255. return 0;
  7256. }
  7257. (void)memset(ah, 0, sizeof(*ah));
  7258. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7259. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7260. return 0;
  7261. }
  7262. /* Make modifiable copy of the auth header */
  7263. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7264. s = buf;
  7265. /* Parse authorization header */
  7266. for (;;) {
  7267. /* Gobble initial spaces */
  7268. while (isspace((unsigned char)*s)) {
  7269. s++;
  7270. }
  7271. name = skip_quoted(&s, "=", " ", 0);
  7272. /* Value is either quote-delimited, or ends at first comma or space.
  7273. */
  7274. if (s[0] == '\"') {
  7275. s++;
  7276. value = skip_quoted(&s, "\"", " ", '\\');
  7277. if (s[0] == ',') {
  7278. s++;
  7279. }
  7280. } else {
  7281. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7282. * uses spaces */
  7283. }
  7284. if (*name == '\0') {
  7285. break;
  7286. }
  7287. if (!strcmp(name, "username")) {
  7288. ah->user = value;
  7289. } else if (!strcmp(name, "cnonce")) {
  7290. ah->cnonce = value;
  7291. } else if (!strcmp(name, "response")) {
  7292. ah->response = value;
  7293. } else if (!strcmp(name, "uri")) {
  7294. ah->uri = value;
  7295. } else if (!strcmp(name, "qop")) {
  7296. ah->qop = value;
  7297. } else if (!strcmp(name, "nc")) {
  7298. ah->nc = value;
  7299. } else if (!strcmp(name, "nonce")) {
  7300. ah->nonce = value;
  7301. }
  7302. }
  7303. #if !defined(NO_NONCE_CHECK)
  7304. /* Read the nonce from the response. */
  7305. if (ah->nonce == NULL) {
  7306. return 0;
  7307. }
  7308. s = NULL;
  7309. nonce = strtoull(ah->nonce, &s, 10);
  7310. if ((s == NULL) || (*s != 0)) {
  7311. return 0;
  7312. }
  7313. /* Convert the nonce from the client to a number. */
  7314. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7315. /* The converted number corresponds to the time the nounce has been
  7316. * created. This should not be earlier than the server start. */
  7317. /* Server side nonce check is valuable in all situations but one:
  7318. * if the server restarts frequently, but the client should not see
  7319. * that, so the server should accept nonces from previous starts. */
  7320. /* However, the reasonable default is to not accept a nonce from a
  7321. * previous start, so if anyone changed the access rights between
  7322. * two restarts, a new login is required. */
  7323. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7324. /* nonce is from a previous start of the server and no longer valid
  7325. * (replay attack?) */
  7326. return 0;
  7327. }
  7328. /* Check if the nonce is too high, so it has not (yet) been used by the
  7329. * server. */
  7330. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7331. + conn->dom_ctx->nonce_count)) {
  7332. return 0;
  7333. }
  7334. #else
  7335. (void)nonce;
  7336. #endif
  7337. /* CGI needs it as REMOTE_USER */
  7338. if (ah->user != NULL) {
  7339. conn->request_info.remote_user =
  7340. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7341. } else {
  7342. return 0;
  7343. }
  7344. return 1;
  7345. }
  7346. static const char *
  7347. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7348. {
  7349. if (!filep) {
  7350. return NULL;
  7351. }
  7352. if (filep->access.fp != NULL) {
  7353. return fgets(buf, (int)size, filep->access.fp);
  7354. } else {
  7355. return NULL;
  7356. }
  7357. }
  7358. /* Define the initial recursion depth for procesesing htpasswd files that
  7359. * include other htpasswd
  7360. * (or even the same) files. It is not difficult to provide a file or files
  7361. * s.t. they force civetweb
  7362. * to infinitely recurse and then crash.
  7363. */
  7364. #define INITIAL_DEPTH 9
  7365. #if INITIAL_DEPTH <= 0
  7366. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7367. #endif
  7368. #if !defined(NO_FILESYSTEMS)
  7369. struct read_auth_file_struct {
  7370. struct mg_connection *conn;
  7371. struct ah ah;
  7372. const char *domain;
  7373. char buf[256 + 256 + 40];
  7374. const char *f_user;
  7375. const char *f_domain;
  7376. const char *f_ha1;
  7377. };
  7378. static int
  7379. read_auth_file(struct mg_file *filep,
  7380. struct read_auth_file_struct *workdata,
  7381. int depth)
  7382. {
  7383. int is_authorized = 0;
  7384. struct mg_file fp;
  7385. size_t l;
  7386. if (!filep || !workdata || (0 == depth)) {
  7387. return 0;
  7388. }
  7389. /* Loop over passwords file */
  7390. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7391. l = strlen(workdata->buf);
  7392. while (l > 0) {
  7393. if (isspace((unsigned char)workdata->buf[l - 1])
  7394. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7395. l--;
  7396. workdata->buf[l] = 0;
  7397. } else
  7398. break;
  7399. }
  7400. if (l < 1) {
  7401. continue;
  7402. }
  7403. workdata->f_user = workdata->buf;
  7404. if (workdata->f_user[0] == ':') {
  7405. /* user names may not contain a ':' and may not be empty,
  7406. * so lines starting with ':' may be used for a special purpose
  7407. */
  7408. if (workdata->f_user[1] == '#') {
  7409. /* :# is a comment */
  7410. continue;
  7411. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7412. if (mg_fopen(workdata->conn,
  7413. workdata->f_user + 9,
  7414. MG_FOPEN_MODE_READ,
  7415. &fp)) {
  7416. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7417. (void)mg_fclose(
  7418. &fp.access); /* ignore error on read only file */
  7419. /* No need to continue processing files once we have a
  7420. * match, since nothing will reset it back
  7421. * to 0.
  7422. */
  7423. if (is_authorized) {
  7424. return is_authorized;
  7425. }
  7426. } else {
  7427. mg_cry_internal(workdata->conn,
  7428. "%s: cannot open authorization file: %s",
  7429. __func__,
  7430. workdata->buf);
  7431. }
  7432. continue;
  7433. }
  7434. /* everything is invalid for the moment (might change in the
  7435. * future) */
  7436. mg_cry_internal(workdata->conn,
  7437. "%s: syntax error in authorization file: %s",
  7438. __func__,
  7439. workdata->buf);
  7440. continue;
  7441. }
  7442. workdata->f_domain = strchr(workdata->f_user, ':');
  7443. if (workdata->f_domain == NULL) {
  7444. mg_cry_internal(workdata->conn,
  7445. "%s: syntax error in authorization file: %s",
  7446. __func__,
  7447. workdata->buf);
  7448. continue;
  7449. }
  7450. *(char *)(workdata->f_domain) = 0;
  7451. (workdata->f_domain)++;
  7452. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7453. if (workdata->f_ha1 == NULL) {
  7454. mg_cry_internal(workdata->conn,
  7455. "%s: syntax error in authorization file: %s",
  7456. __func__,
  7457. workdata->buf);
  7458. continue;
  7459. }
  7460. *(char *)(workdata->f_ha1) = 0;
  7461. (workdata->f_ha1)++;
  7462. if (!strcmp(workdata->ah.user, workdata->f_user)
  7463. && !strcmp(workdata->domain, workdata->f_domain)) {
  7464. return check_password(workdata->conn->request_info.request_method,
  7465. workdata->f_ha1,
  7466. workdata->ah.uri,
  7467. workdata->ah.nonce,
  7468. workdata->ah.nc,
  7469. workdata->ah.cnonce,
  7470. workdata->ah.qop,
  7471. workdata->ah.response);
  7472. }
  7473. }
  7474. return is_authorized;
  7475. }
  7476. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7477. static int
  7478. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7479. {
  7480. struct read_auth_file_struct workdata;
  7481. char buf[MG_BUF_LEN];
  7482. if (!conn || !conn->dom_ctx) {
  7483. return 0;
  7484. }
  7485. memset(&workdata, 0, sizeof(workdata));
  7486. workdata.conn = conn;
  7487. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7488. return 0;
  7489. }
  7490. if (realm) {
  7491. workdata.domain = realm;
  7492. } else {
  7493. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7494. }
  7495. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7496. }
  7497. /* Public function to check http digest authentication header */
  7498. int
  7499. mg_check_digest_access_authentication(struct mg_connection *conn,
  7500. const char *realm,
  7501. const char *filename)
  7502. {
  7503. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7504. int auth;
  7505. if (!conn || !filename) {
  7506. return -1;
  7507. }
  7508. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7509. return -2;
  7510. }
  7511. auth = authorize(conn, &file, realm);
  7512. mg_fclose(&file.access);
  7513. return auth;
  7514. }
  7515. #endif /* NO_FILESYSTEMS */
  7516. /* Return 1 if request is authorised, 0 otherwise. */
  7517. static int
  7518. check_authorization(struct mg_connection *conn, const char *path)
  7519. {
  7520. #if !defined(NO_FILESYSTEMS)
  7521. char fname[UTF8_PATH_MAX];
  7522. struct vec uri_vec, filename_vec;
  7523. const char *list;
  7524. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7525. int authorized = 1, truncated;
  7526. if (!conn || !conn->dom_ctx) {
  7527. return 0;
  7528. }
  7529. list = conn->dom_ctx->config[PROTECT_URI];
  7530. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7531. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7532. mg_snprintf(conn,
  7533. &truncated,
  7534. fname,
  7535. sizeof(fname),
  7536. "%.*s",
  7537. (int)filename_vec.len,
  7538. filename_vec.ptr);
  7539. if (truncated
  7540. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7541. mg_cry_internal(conn,
  7542. "%s: cannot open %s: %s",
  7543. __func__,
  7544. fname,
  7545. strerror(errno));
  7546. }
  7547. break;
  7548. }
  7549. }
  7550. if (!is_file_opened(&file.access)) {
  7551. open_auth_file(conn, path, &file);
  7552. }
  7553. if (is_file_opened(&file.access)) {
  7554. authorized = authorize(conn, &file, NULL);
  7555. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7556. }
  7557. return authorized;
  7558. #else
  7559. (void)conn;
  7560. (void)path;
  7561. return 1;
  7562. #endif /* NO_FILESYSTEMS */
  7563. }
  7564. /* Internal function. Assumes conn is valid */
  7565. static void
  7566. send_authorization_request(struct mg_connection *conn, const char *realm)
  7567. {
  7568. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7569. int trunc = 0;
  7570. char buf[128];
  7571. if (!realm) {
  7572. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7573. }
  7574. mg_lock_context(conn->phys_ctx);
  7575. nonce += conn->dom_ctx->nonce_count;
  7576. ++conn->dom_ctx->nonce_count;
  7577. mg_unlock_context(conn->phys_ctx);
  7578. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7579. conn->must_close = 1;
  7580. /* Create 401 response */
  7581. mg_response_header_start(conn, 401);
  7582. send_no_cache_header(conn);
  7583. send_additional_header(conn);
  7584. mg_response_header_add(conn, "Content-Length", "0", -1);
  7585. /* Content for "WWW-Authenticate" header */
  7586. mg_snprintf(conn,
  7587. &trunc,
  7588. buf,
  7589. sizeof(buf),
  7590. "Digest qop=\"auth\", realm=\"%s\", "
  7591. "nonce=\"%" UINT64_FMT "\"",
  7592. realm,
  7593. nonce);
  7594. if (!trunc) {
  7595. /* !trunc should always be true */
  7596. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7597. }
  7598. /* Send all headers */
  7599. mg_response_header_send(conn);
  7600. }
  7601. /* Interface function. Parameters are provided by the user, so do
  7602. * at least some basic checks.
  7603. */
  7604. int
  7605. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7606. const char *realm)
  7607. {
  7608. if (conn && conn->dom_ctx) {
  7609. send_authorization_request(conn, realm);
  7610. return 0;
  7611. }
  7612. return -1;
  7613. }
  7614. #if !defined(NO_FILES)
  7615. static int
  7616. is_authorized_for_put(struct mg_connection *conn)
  7617. {
  7618. if (conn) {
  7619. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7620. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7621. int ret = 0;
  7622. if (passfile != NULL
  7623. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7624. ret = authorize(conn, &file, NULL);
  7625. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7626. }
  7627. return ret;
  7628. }
  7629. return 0;
  7630. }
  7631. #endif
  7632. int
  7633. mg_modify_passwords_file_ha1(const char *fname,
  7634. const char *domain,
  7635. const char *user,
  7636. const char *ha1)
  7637. {
  7638. int found = 0, i, result = 1;
  7639. char line[512], u[256], d[256], h[256];
  7640. struct stat st = {0};
  7641. FILE *fp = NULL;
  7642. char *temp_file = NULL;
  7643. int temp_file_offs = 0;
  7644. /* Regard empty password as no password - remove user record. */
  7645. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7646. ha1 = NULL;
  7647. }
  7648. /* Other arguments must not be empty */
  7649. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7650. return 0;
  7651. }
  7652. /* Using the given file format, user name and domain must not contain
  7653. * the ':' character */
  7654. if (strchr(user, ':') != NULL) {
  7655. return 0;
  7656. }
  7657. if (strchr(domain, ':') != NULL) {
  7658. return 0;
  7659. }
  7660. /* Do not allow control characters like newline in user name and domain.
  7661. * Do not allow excessively long names either. */
  7662. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7663. if (iscntrl((unsigned char)user[i])) {
  7664. return 0;
  7665. }
  7666. }
  7667. if (user[i]) {
  7668. return 0; /* user name too long */
  7669. }
  7670. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7671. if (iscntrl((unsigned char)domain[i])) {
  7672. return 0;
  7673. }
  7674. }
  7675. if (domain[i]) {
  7676. return 0; /* domain name too long */
  7677. }
  7678. /* The maximum length of the path to the password file is limited */
  7679. if (strlen(fname) >= UTF8_PATH_MAX) {
  7680. return 0;
  7681. }
  7682. /* Check if the file exists, and get file size */
  7683. if (0 == stat(fname, &st)) {
  7684. int temp_buf_len = (int)st.st_size + 1024;
  7685. /* Allocate memory (instead of using a temporary file) */
  7686. temp_file = (char *)mg_calloc(temp_buf_len, 1);
  7687. if (!temp_file) {
  7688. /* Out of memory */
  7689. return 0;
  7690. }
  7691. /* File exists. Read it into a memory buffer. */
  7692. fp = fopen(fname, "r");
  7693. if (fp == NULL) {
  7694. /* Cannot read file. No permission? */
  7695. mg_free(temp_file);
  7696. return 0;
  7697. }
  7698. /* Read content and store in memory */
  7699. while ((fgets(line, sizeof(line), fp) != NULL)
  7700. && ((temp_file_offs + 600) < temp_buf_len)) {
  7701. /* file format is "user:domain:hash\n" */
  7702. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7703. continue;
  7704. }
  7705. u[255] = 0;
  7706. d[255] = 0;
  7707. h[255] = 0;
  7708. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7709. /* Found the user: change the password hash or drop the user
  7710. */
  7711. if ((ha1 != NULL) && (!found)) {
  7712. i = sprintf(temp_file + temp_file_offs,
  7713. "%s:%s:%s\n",
  7714. user,
  7715. domain,
  7716. ha1);
  7717. if (i < 1) {
  7718. fclose(fp);
  7719. mg_free(temp_file);
  7720. return 0;
  7721. }
  7722. temp_file_offs += i;
  7723. }
  7724. found = 1;
  7725. } else {
  7726. /* Copy existing user, including password hash */
  7727. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7728. if (i < 1) {
  7729. fclose(fp);
  7730. mg_free(temp_file);
  7731. return 0;
  7732. }
  7733. temp_file_offs += i;
  7734. }
  7735. }
  7736. fclose(fp);
  7737. }
  7738. /* Create new file */
  7739. fp = fopen(fname, "w");
  7740. if (!fp) {
  7741. mg_free(temp_file);
  7742. return 0;
  7743. }
  7744. #if !defined(_WIN32)
  7745. /* On Linux & co., restrict file read/write permissions to the owner */
  7746. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7747. result = 0;
  7748. }
  7749. #endif
  7750. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7751. /* Store buffered content of old file */
  7752. if (fwrite(temp_file, 1, temp_file_offs, fp)
  7753. != (size_t)temp_file_offs) {
  7754. result = 0;
  7755. }
  7756. }
  7757. /* If new user, just add it */
  7758. if ((ha1 != NULL) && (!found)) {
  7759. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7760. result = 0;
  7761. }
  7762. }
  7763. /* All data written */
  7764. if (fclose(fp) != 0) {
  7765. result = 0;
  7766. }
  7767. mg_free(temp_file);
  7768. return result;
  7769. }
  7770. int
  7771. mg_modify_passwords_file(const char *fname,
  7772. const char *domain,
  7773. const char *user,
  7774. const char *pass)
  7775. {
  7776. char ha1buf[33];
  7777. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7778. return 0;
  7779. }
  7780. if ((pass == NULL) || (pass[0] == 0)) {
  7781. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  7782. }
  7783. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  7784. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  7785. }
  7786. static int
  7787. is_valid_port(unsigned long port)
  7788. {
  7789. return (port <= 0xffff);
  7790. }
  7791. static int
  7792. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7793. {
  7794. struct addrinfo hints, *res, *ressave;
  7795. int func_ret = 0;
  7796. int gai_ret;
  7797. memset(&hints, 0, sizeof(struct addrinfo));
  7798. hints.ai_family = af;
  7799. if (!resolve_src) {
  7800. hints.ai_flags = AI_NUMERICHOST;
  7801. }
  7802. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7803. if (gai_ret != 0) {
  7804. /* gai_strerror could be used to convert gai_ret to a string */
  7805. /* POSIX return values: see
  7806. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7807. */
  7808. /* Windows return values: see
  7809. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7810. */
  7811. return 0;
  7812. }
  7813. ressave = res;
  7814. while (res) {
  7815. if ((dstlen >= (size_t)res->ai_addrlen)
  7816. && (res->ai_addr->sa_family == af)) {
  7817. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7818. func_ret = 1;
  7819. }
  7820. res = res->ai_next;
  7821. }
  7822. freeaddrinfo(ressave);
  7823. return func_ret;
  7824. }
  7825. static int
  7826. connect_socket(
  7827. struct mg_context *ctx /* may be NULL */,
  7828. const char *host,
  7829. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7830. int use_ssl, /* 0 or 1 */
  7831. char *ebuf,
  7832. size_t ebuf_len,
  7833. SOCKET *sock /* output: socket, must not be NULL */,
  7834. union usa *sa /* output: socket address, must not be NULL */
  7835. )
  7836. {
  7837. int ip_ver = 0;
  7838. int conn_ret = -1;
  7839. int sockerr = 0;
  7840. *sock = INVALID_SOCKET;
  7841. memset(sa, 0, sizeof(*sa));
  7842. if (ebuf_len > 0) {
  7843. *ebuf = 0;
  7844. }
  7845. if (host == NULL) {
  7846. mg_snprintf(NULL,
  7847. NULL, /* No truncation check for ebuf */
  7848. ebuf,
  7849. ebuf_len,
  7850. "%s",
  7851. "NULL host");
  7852. return 0;
  7853. }
  7854. #if defined(USE_X_DOM_SOCKET)
  7855. if (port == -99) {
  7856. /* Unix domain socket */
  7857. size_t hostlen = strlen(host);
  7858. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7859. mg_snprintf(NULL,
  7860. NULL, /* No truncation check for ebuf */
  7861. ebuf,
  7862. ebuf_len,
  7863. "%s",
  7864. "host length exceeds limit");
  7865. return 0;
  7866. }
  7867. } else
  7868. #endif
  7869. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7870. mg_snprintf(NULL,
  7871. NULL, /* No truncation check for ebuf */
  7872. ebuf,
  7873. ebuf_len,
  7874. "%s",
  7875. "invalid port");
  7876. return 0;
  7877. }
  7878. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7879. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7880. if (use_ssl && (TLS_client_method == NULL)) {
  7881. mg_snprintf(NULL,
  7882. NULL, /* No truncation check for ebuf */
  7883. ebuf,
  7884. ebuf_len,
  7885. "%s",
  7886. "SSL is not initialized");
  7887. return 0;
  7888. }
  7889. #else
  7890. if (use_ssl && (SSLv23_client_method == NULL)) {
  7891. mg_snprintf(NULL,
  7892. NULL, /* No truncation check for ebuf */
  7893. ebuf,
  7894. ebuf_len,
  7895. "%s",
  7896. "SSL is not initialized");
  7897. return 0;
  7898. }
  7899. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7900. #else
  7901. (void)use_ssl;
  7902. #endif /* NO SSL */
  7903. #if defined(USE_X_DOM_SOCKET)
  7904. if (port == -99) {
  7905. size_t hostlen = strlen(host);
  7906. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7907. ip_ver = -99;
  7908. sa->sun.sun_family = AF_UNIX;
  7909. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7910. memcpy(sa->sun.sun_path, host, hostlen);
  7911. } else
  7912. #endif
  7913. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7914. sa->sin.sin_port = htons((uint16_t)port);
  7915. ip_ver = 4;
  7916. #if defined(USE_IPV6)
  7917. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7918. sa->sin6.sin6_port = htons((uint16_t)port);
  7919. ip_ver = 6;
  7920. } else if (host[0] == '[') {
  7921. /* While getaddrinfo on Windows will work with [::1],
  7922. * getaddrinfo on Linux only works with ::1 (without []). */
  7923. size_t l = strlen(host + 1);
  7924. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7925. if (h) {
  7926. h[l - 1] = 0;
  7927. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7928. sa->sin6.sin6_port = htons((uint16_t)port);
  7929. ip_ver = 6;
  7930. }
  7931. mg_free(h);
  7932. }
  7933. #endif
  7934. }
  7935. if (ip_ver == 0) {
  7936. mg_snprintf(NULL,
  7937. NULL, /* No truncation check for ebuf */
  7938. ebuf,
  7939. ebuf_len,
  7940. "%s",
  7941. "host not found");
  7942. return 0;
  7943. }
  7944. if (ip_ver == 4) {
  7945. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7946. }
  7947. #if defined(USE_IPV6)
  7948. else if (ip_ver == 6) {
  7949. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7950. }
  7951. #endif
  7952. #if defined(USE_X_DOM_SOCKET)
  7953. else if (ip_ver == -99) {
  7954. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7955. }
  7956. #endif
  7957. if (*sock == INVALID_SOCKET) {
  7958. mg_snprintf(NULL,
  7959. NULL, /* No truncation check for ebuf */
  7960. ebuf,
  7961. ebuf_len,
  7962. "socket(): %s",
  7963. strerror(ERRNO));
  7964. return 0;
  7965. }
  7966. if (0 != set_non_blocking_mode(*sock)) {
  7967. mg_snprintf(NULL,
  7968. NULL, /* No truncation check for ebuf */
  7969. ebuf,
  7970. ebuf_len,
  7971. "Cannot set socket to non-blocking: %s",
  7972. strerror(ERRNO));
  7973. closesocket(*sock);
  7974. *sock = INVALID_SOCKET;
  7975. return 0;
  7976. }
  7977. set_close_on_exec(*sock, NULL, ctx);
  7978. if (ip_ver == 4) {
  7979. /* connected with IPv4 */
  7980. conn_ret = connect(*sock,
  7981. (struct sockaddr *)((void *)&sa->sin),
  7982. sizeof(sa->sin));
  7983. }
  7984. #if defined(USE_IPV6)
  7985. else if (ip_ver == 6) {
  7986. /* connected with IPv6 */
  7987. conn_ret = connect(*sock,
  7988. (struct sockaddr *)((void *)&sa->sin6),
  7989. sizeof(sa->sin6));
  7990. }
  7991. #endif
  7992. #if defined(USE_X_DOM_SOCKET)
  7993. else if (ip_ver == -99) {
  7994. /* connected to domain socket */
  7995. conn_ret = connect(*sock,
  7996. (struct sockaddr *)((void *)&sa->sun),
  7997. sizeof(sa->sun));
  7998. }
  7999. #endif
  8000. if (conn_ret != 0) {
  8001. sockerr = ERRNO;
  8002. }
  8003. #if defined(_WIN32)
  8004. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8005. #else
  8006. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8007. #endif
  8008. /* Data for getsockopt */
  8009. void *psockerr = &sockerr;
  8010. int ret;
  8011. #if defined(_WIN32)
  8012. int len = (int)sizeof(sockerr);
  8013. #else
  8014. socklen_t len = (socklen_t)sizeof(sockerr);
  8015. #endif
  8016. /* Data for poll */
  8017. struct mg_pollfd pfd[1];
  8018. int pollres;
  8019. int ms_wait = 10000; /* 10 second timeout */
  8020. stop_flag_t nonstop;
  8021. STOP_FLAG_ASSIGN(&nonstop, 0);
  8022. /* For a non-blocking socket, the connect sequence is:
  8023. * 1) call connect (will not block)
  8024. * 2) wait until the socket is ready for writing (select or poll)
  8025. * 3) check connection state with getsockopt
  8026. */
  8027. pfd[0].fd = *sock;
  8028. pfd[0].events = POLLOUT;
  8029. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8030. if (pollres != 1) {
  8031. /* Not connected */
  8032. mg_snprintf(NULL,
  8033. NULL, /* No truncation check for ebuf */
  8034. ebuf,
  8035. ebuf_len,
  8036. "connect(%s:%d): timeout",
  8037. host,
  8038. port);
  8039. closesocket(*sock);
  8040. *sock = INVALID_SOCKET;
  8041. return 0;
  8042. }
  8043. #if defined(_WIN32)
  8044. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8045. #else
  8046. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8047. #endif
  8048. if ((ret == 0) && (sockerr == 0)) {
  8049. conn_ret = 0;
  8050. }
  8051. }
  8052. if (conn_ret != 0) {
  8053. /* Not connected */
  8054. mg_snprintf(NULL,
  8055. NULL, /* No truncation check for ebuf */
  8056. ebuf,
  8057. ebuf_len,
  8058. "connect(%s:%d): error %s",
  8059. host,
  8060. port,
  8061. strerror(sockerr));
  8062. closesocket(*sock);
  8063. *sock = INVALID_SOCKET;
  8064. return 0;
  8065. }
  8066. return 1;
  8067. }
  8068. int
  8069. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8070. {
  8071. static const char *dont_escape = "._-$,;~()";
  8072. static const char *hex = "0123456789abcdef";
  8073. char *pos = dst;
  8074. const char *end = dst + dst_len - 1;
  8075. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8076. if (isalnum((unsigned char)*src)
  8077. || (strchr(dont_escape, *src) != NULL)) {
  8078. *pos = *src;
  8079. } else if (pos + 2 < end) {
  8080. pos[0] = '%';
  8081. pos[1] = hex[(unsigned char)*src >> 4];
  8082. pos[2] = hex[(unsigned char)*src & 0xf];
  8083. pos += 2;
  8084. } else {
  8085. break;
  8086. }
  8087. }
  8088. *pos = '\0';
  8089. return (*src == '\0') ? (int)(pos - dst) : -1;
  8090. }
  8091. /* Return 0 on success, non-zero if an error occurs. */
  8092. static int
  8093. print_dir_entry(struct mg_connection *conn, struct de *de)
  8094. {
  8095. size_t namesize, escsize, i;
  8096. char *href, *esc, *p;
  8097. char size[64], mod[64];
  8098. #if defined(REENTRANT_TIME)
  8099. struct tm _tm;
  8100. struct tm *tm = &_tm;
  8101. #else
  8102. struct tm *tm;
  8103. #endif
  8104. /* Estimate worst case size for encoding and escaping */
  8105. namesize = strlen(de->file_name) + 1;
  8106. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8107. href = (char *)mg_malloc(namesize * 3 + escsize);
  8108. if (href == NULL) {
  8109. return -1;
  8110. }
  8111. mg_url_encode(de->file_name, href, namesize * 3);
  8112. esc = NULL;
  8113. if (escsize > 0) {
  8114. /* HTML escaping needed */
  8115. esc = href + namesize * 3;
  8116. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8117. mg_strlcpy(p, de->file_name + i, 2);
  8118. if (*p == '&') {
  8119. strcpy(p, "&amp;");
  8120. } else if (*p == '<') {
  8121. strcpy(p, "&lt;");
  8122. } else if (*p == '>') {
  8123. strcpy(p, "&gt;");
  8124. }
  8125. }
  8126. }
  8127. if (de->file.is_directory) {
  8128. mg_snprintf(conn,
  8129. NULL, /* Buffer is big enough */
  8130. size,
  8131. sizeof(size),
  8132. "%s",
  8133. "[DIRECTORY]");
  8134. } else {
  8135. /* We use (signed) cast below because MSVC 6 compiler cannot
  8136. * convert unsigned __int64 to double. Sigh. */
  8137. if (de->file.size < 1024) {
  8138. mg_snprintf(conn,
  8139. NULL, /* Buffer is big enough */
  8140. size,
  8141. sizeof(size),
  8142. "%d",
  8143. (int)de->file.size);
  8144. } else if (de->file.size < 0x100000) {
  8145. mg_snprintf(conn,
  8146. NULL, /* Buffer is big enough */
  8147. size,
  8148. sizeof(size),
  8149. "%.1fk",
  8150. (double)de->file.size / 1024.0);
  8151. } else if (de->file.size < 0x40000000) {
  8152. mg_snprintf(conn,
  8153. NULL, /* Buffer is big enough */
  8154. size,
  8155. sizeof(size),
  8156. "%.1fM",
  8157. (double)de->file.size / 1048576);
  8158. } else {
  8159. mg_snprintf(conn,
  8160. NULL, /* Buffer is big enough */
  8161. size,
  8162. sizeof(size),
  8163. "%.1fG",
  8164. (double)de->file.size / 1073741824);
  8165. }
  8166. }
  8167. /* Note: mg_snprintf will not cause a buffer overflow above.
  8168. * So, string truncation checks are not required here. */
  8169. #if defined(REENTRANT_TIME)
  8170. localtime_r(&de->file.last_modified, tm);
  8171. #else
  8172. tm = localtime(&de->file.last_modified);
  8173. #endif
  8174. if (tm != NULL) {
  8175. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8176. } else {
  8177. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8178. mod[sizeof(mod) - 1] = '\0';
  8179. }
  8180. mg_printf(conn,
  8181. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8182. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8183. href,
  8184. de->file.is_directory ? "/" : "",
  8185. esc ? esc : de->file_name,
  8186. de->file.is_directory ? "/" : "",
  8187. mod,
  8188. size);
  8189. mg_free(href);
  8190. return 0;
  8191. }
  8192. /* This function is called from send_directory() and used for
  8193. * sorting directory entries by size, or name, or modification time.
  8194. * On windows, __cdecl specification is needed in case if project is built
  8195. * with __stdcall convention. qsort always requires __cdels callback. */
  8196. static int WINCDECL
  8197. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8198. {
  8199. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8200. if (p1 && p2) {
  8201. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8202. int cmp_result = 0;
  8203. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8204. query_string = "n";
  8205. }
  8206. if (a->file.is_directory && !b->file.is_directory) {
  8207. return -1; /* Always put directories on top */
  8208. } else if (!a->file.is_directory && b->file.is_directory) {
  8209. return 1; /* Always put directories on top */
  8210. } else if (*query_string == 'n') {
  8211. cmp_result = strcmp(a->file_name, b->file_name);
  8212. } else if (*query_string == 's') {
  8213. cmp_result = (a->file.size == b->file.size)
  8214. ? 0
  8215. : ((a->file.size > b->file.size) ? 1 : -1);
  8216. } else if (*query_string == 'd') {
  8217. cmp_result =
  8218. (a->file.last_modified == b->file.last_modified)
  8219. ? 0
  8220. : ((a->file.last_modified > b->file.last_modified) ? 1
  8221. : -1);
  8222. }
  8223. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8224. }
  8225. return 0;
  8226. }
  8227. static int
  8228. must_hide_file(struct mg_connection *conn, const char *path)
  8229. {
  8230. if (conn && conn->dom_ctx) {
  8231. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8232. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8233. return (match_prefix_strlen(pw_pattern, path) > 0)
  8234. || (match_prefix_strlen(pattern, path) > 0);
  8235. }
  8236. return 0;
  8237. }
  8238. #if !defined(NO_FILESYSTEMS)
  8239. static int
  8240. scan_directory(struct mg_connection *conn,
  8241. const char *dir,
  8242. void *data,
  8243. int (*cb)(struct de *, void *))
  8244. {
  8245. char path[UTF8_PATH_MAX];
  8246. struct dirent *dp;
  8247. DIR *dirp;
  8248. struct de de;
  8249. int truncated;
  8250. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8251. return 0;
  8252. } else {
  8253. while ((dp = mg_readdir(dirp)) != NULL) {
  8254. /* Do not show current dir and hidden files */
  8255. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8256. || must_hide_file(conn, dp->d_name)) {
  8257. continue;
  8258. }
  8259. mg_snprintf(
  8260. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8261. /* If we don't memset stat structure to zero, mtime will have
  8262. * garbage and strftime() will segfault later on in
  8263. * print_dir_entry(). memset is required only if mg_stat()
  8264. * fails. For more details, see
  8265. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8266. memset(&de.file, 0, sizeof(de.file));
  8267. if (truncated) {
  8268. /* If the path is not complete, skip processing. */
  8269. continue;
  8270. }
  8271. if (!mg_stat(conn, path, &de.file)) {
  8272. mg_cry_internal(conn,
  8273. "%s: mg_stat(%s) failed: %s",
  8274. __func__,
  8275. path,
  8276. strerror(ERRNO));
  8277. }
  8278. de.file_name = dp->d_name;
  8279. if (cb(&de, data)) {
  8280. /* stopped */
  8281. break;
  8282. }
  8283. }
  8284. (void)mg_closedir(dirp);
  8285. }
  8286. return 1;
  8287. }
  8288. #endif /* NO_FILESYSTEMS */
  8289. #if !defined(NO_FILES)
  8290. static int
  8291. remove_directory(struct mg_connection *conn, const char *dir)
  8292. {
  8293. char path[UTF8_PATH_MAX];
  8294. struct dirent *dp;
  8295. DIR *dirp;
  8296. struct de de;
  8297. int truncated;
  8298. int ok = 1;
  8299. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8300. return 0;
  8301. } else {
  8302. while ((dp = mg_readdir(dirp)) != NULL) {
  8303. /* Do not show current dir (but show hidden files as they will
  8304. * also be removed) */
  8305. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8306. continue;
  8307. }
  8308. mg_snprintf(
  8309. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8310. /* If we don't memset stat structure to zero, mtime will have
  8311. * garbage and strftime() will segfault later on in
  8312. * print_dir_entry(). memset is required only if mg_stat()
  8313. * fails. For more details, see
  8314. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8315. memset(&de.file, 0, sizeof(de.file));
  8316. if (truncated) {
  8317. /* Do not delete anything shorter */
  8318. ok = 0;
  8319. continue;
  8320. }
  8321. if (!mg_stat(conn, path, &de.file)) {
  8322. mg_cry_internal(conn,
  8323. "%s: mg_stat(%s) failed: %s",
  8324. __func__,
  8325. path,
  8326. strerror(ERRNO));
  8327. ok = 0;
  8328. }
  8329. if (de.file.is_directory) {
  8330. if (remove_directory(conn, path) == 0) {
  8331. ok = 0;
  8332. }
  8333. } else {
  8334. /* This will fail file is the file is in memory */
  8335. if (mg_remove(conn, path) == 0) {
  8336. ok = 0;
  8337. }
  8338. }
  8339. }
  8340. (void)mg_closedir(dirp);
  8341. IGNORE_UNUSED_RESULT(rmdir(dir));
  8342. }
  8343. return ok;
  8344. }
  8345. #endif
  8346. struct dir_scan_data {
  8347. struct de *entries;
  8348. size_t num_entries;
  8349. size_t arr_size;
  8350. };
  8351. #if !defined(NO_FILESYSTEMS)
  8352. static int
  8353. dir_scan_callback(struct de *de, void *data)
  8354. {
  8355. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8356. struct de *entries = dsd->entries;
  8357. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8358. /* Here "entries" is a temporary pointer and can be replaced,
  8359. * "dsd->entries" is the original pointer */
  8360. entries =
  8361. (struct de *)mg_realloc(entries,
  8362. dsd->arr_size * 2 * sizeof(entries[0]));
  8363. if (entries == NULL) {
  8364. /* stop scan */
  8365. return 1;
  8366. }
  8367. dsd->entries = entries;
  8368. dsd->arr_size *= 2;
  8369. }
  8370. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8371. if (entries[dsd->num_entries].file_name == NULL) {
  8372. /* stop scan */
  8373. return 1;
  8374. }
  8375. entries[dsd->num_entries].file = de->file;
  8376. dsd->num_entries++;
  8377. return 0;
  8378. }
  8379. static void
  8380. handle_directory_request(struct mg_connection *conn, const char *dir)
  8381. {
  8382. size_t i;
  8383. int sort_direction;
  8384. struct dir_scan_data data = {NULL, 0, 128};
  8385. char date[64], *esc, *p;
  8386. const char *title;
  8387. time_t curtime = time(NULL);
  8388. if (!conn) {
  8389. return;
  8390. }
  8391. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8392. mg_send_http_error(conn,
  8393. 500,
  8394. "Error: Cannot open directory\nopendir(%s): %s",
  8395. dir,
  8396. strerror(ERRNO));
  8397. return;
  8398. }
  8399. gmt_time_string(date, sizeof(date), &curtime);
  8400. esc = NULL;
  8401. title = conn->request_info.local_uri;
  8402. if (title[strcspn(title, "&<>")]) {
  8403. /* HTML escaping needed */
  8404. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8405. if (esc) {
  8406. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8407. mg_strlcpy(p, title + i, 2);
  8408. if (*p == '&') {
  8409. strcpy(p, "&amp;");
  8410. } else if (*p == '<') {
  8411. strcpy(p, "&lt;");
  8412. } else if (*p == '>') {
  8413. strcpy(p, "&gt;");
  8414. }
  8415. }
  8416. } else {
  8417. title = "";
  8418. }
  8419. }
  8420. sort_direction = ((conn->request_info.query_string != NULL)
  8421. && (conn->request_info.query_string[0] != '\0')
  8422. && (conn->request_info.query_string[1] == 'd'))
  8423. ? 'a'
  8424. : 'd';
  8425. conn->must_close = 1;
  8426. /* Create 200 OK response */
  8427. mg_response_header_start(conn, 200);
  8428. send_static_cache_header(conn);
  8429. send_additional_header(conn);
  8430. mg_response_header_add(conn,
  8431. "Content-Type",
  8432. "text/html; charset=utf-8",
  8433. -1);
  8434. /* Send all headers */
  8435. mg_response_header_send(conn);
  8436. /* Body */
  8437. mg_printf(conn,
  8438. "<html><head><title>Index of %s</title>"
  8439. "<style>th {text-align: left;}</style></head>"
  8440. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8441. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8442. "<th><a href=\"?d%c\">Modified</a></th>"
  8443. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8444. "<tr><td colspan=\"3\"><hr></td></tr>",
  8445. esc ? esc : title,
  8446. esc ? esc : title,
  8447. sort_direction,
  8448. sort_direction,
  8449. sort_direction);
  8450. mg_free(esc);
  8451. /* Print first entry - link to a parent directory */
  8452. mg_printf(conn,
  8453. "<tr><td><a href=\"%s\">%s</a></td>"
  8454. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8455. "..",
  8456. "Parent directory",
  8457. "-",
  8458. "-");
  8459. /* Sort and print directory entries */
  8460. if (data.entries != NULL) {
  8461. qsort_r(data.entries,
  8462. data.num_entries,
  8463. sizeof(data.entries[0]),
  8464. compare_dir_entries,
  8465. (void *)conn->request_info.query_string);
  8466. for (i = 0; i < data.num_entries; i++) {
  8467. print_dir_entry(conn, &data.entries[i]);
  8468. mg_free(data.entries[i].file_name);
  8469. }
  8470. mg_free(data.entries);
  8471. }
  8472. mg_printf(conn, "%s", "</table></pre></body></html>");
  8473. conn->status_code = 200;
  8474. }
  8475. #endif /* NO_FILESYSTEMS */
  8476. /* Send len bytes from the opened file to the client. */
  8477. static void
  8478. send_file_data(struct mg_connection *conn,
  8479. struct mg_file *filep,
  8480. int64_t offset,
  8481. int64_t len)
  8482. {
  8483. char buf[MG_BUF_LEN];
  8484. int to_read, num_read, num_written;
  8485. int64_t size;
  8486. if (!filep || !conn) {
  8487. return;
  8488. }
  8489. /* Sanity check the offset */
  8490. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8491. : (int64_t)(filep->stat.size);
  8492. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8493. if (len > 0 && filep->access.fp != NULL) {
  8494. /* file stored on disk */
  8495. #if defined(__linux__)
  8496. /* sendfile is only available for Linux */
  8497. if ((conn->ssl == 0) && (conn->throttle == 0)
  8498. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8499. "yes"))) {
  8500. off_t sf_offs = (off_t)offset;
  8501. ssize_t sf_sent;
  8502. int sf_file = fileno(filep->access.fp);
  8503. int loop_cnt = 0;
  8504. do {
  8505. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8506. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8507. size_t sf_tosend =
  8508. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8509. sf_sent =
  8510. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8511. if (sf_sent > 0) {
  8512. len -= sf_sent;
  8513. offset += sf_sent;
  8514. } else if (loop_cnt == 0) {
  8515. /* This file can not be sent using sendfile.
  8516. * This might be the case for pseudo-files in the
  8517. * /sys/ and /proc/ file system.
  8518. * Use the regular user mode copy code instead. */
  8519. break;
  8520. } else if (sf_sent == 0) {
  8521. /* No error, but 0 bytes sent. May be EOF? */
  8522. return;
  8523. }
  8524. loop_cnt++;
  8525. } while ((len > 0) && (sf_sent >= 0));
  8526. if (sf_sent > 0) {
  8527. return; /* OK */
  8528. }
  8529. /* sf_sent<0 means error, thus fall back to the classic way */
  8530. /* This is always the case, if sf_file is not a "normal" file,
  8531. * e.g., for sending data from the output of a CGI process. */
  8532. offset = (int64_t)sf_offs;
  8533. }
  8534. #endif
  8535. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8536. mg_cry_internal(conn,
  8537. "%s: fseeko() failed: %s",
  8538. __func__,
  8539. strerror(ERRNO));
  8540. mg_send_http_error(
  8541. conn,
  8542. 500,
  8543. "%s",
  8544. "Error: Unable to access file at requested position.");
  8545. } else {
  8546. while (len > 0) {
  8547. /* Calculate how much to read from the file in the buffer */
  8548. to_read = sizeof(buf);
  8549. if ((int64_t)to_read > len) {
  8550. to_read = (int)len;
  8551. }
  8552. /* Read from file, exit the loop on error */
  8553. if ((num_read =
  8554. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8555. <= 0) {
  8556. break;
  8557. }
  8558. /* Send read bytes to the client, exit the loop on error */
  8559. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8560. != num_read) {
  8561. break;
  8562. }
  8563. /* Both read and were successful, adjust counters */
  8564. len -= num_written;
  8565. }
  8566. }
  8567. }
  8568. }
  8569. static int
  8570. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8571. {
  8572. return sscanf(header,
  8573. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8574. a,
  8575. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8576. // to an integer value, but function will not report
  8577. // conversion errors; consider using 'strtol' instead
  8578. }
  8579. static void
  8580. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8581. {
  8582. if ((filestat != NULL) && (buf != NULL)) {
  8583. mg_snprintf(NULL,
  8584. NULL, /* All calls to construct_etag use 64 byte buffer */
  8585. buf,
  8586. buf_len,
  8587. "\"%lx.%" INT64_FMT "\"",
  8588. (unsigned long)filestat->last_modified,
  8589. filestat->size);
  8590. }
  8591. }
  8592. static void
  8593. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8594. {
  8595. if (filep != NULL && filep->fp != NULL) {
  8596. #if defined(_WIN32)
  8597. (void)conn; /* Unused. */
  8598. #else
  8599. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8600. mg_cry_internal(conn,
  8601. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8602. __func__,
  8603. strerror(ERRNO));
  8604. }
  8605. #endif
  8606. }
  8607. }
  8608. #if defined(USE_ZLIB)
  8609. #include "mod_zlib.inl"
  8610. #endif
  8611. #if !defined(NO_FILESYSTEMS)
  8612. static void
  8613. handle_static_file_request(struct mg_connection *conn,
  8614. const char *path,
  8615. struct mg_file *filep,
  8616. const char *mime_type,
  8617. const char *additional_headers)
  8618. {
  8619. char lm[64], etag[64];
  8620. char range[128]; /* large enough, so there will be no overflow */
  8621. const char *range_hdr;
  8622. int64_t cl, r1, r2;
  8623. struct vec mime_vec;
  8624. int n, truncated;
  8625. char gz_path[UTF8_PATH_MAX];
  8626. const char *encoding = 0;
  8627. int is_head_request;
  8628. #if defined(USE_ZLIB)
  8629. /* Compression is allowed, unless there is a reason not to use
  8630. * compression. If the file is already compressed, too small or a
  8631. * "range" request was made, on the fly compression is not possible. */
  8632. int allow_on_the_fly_compression = 1;
  8633. #endif
  8634. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8635. return;
  8636. }
  8637. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8638. if (mime_type == NULL) {
  8639. get_mime_type(conn, path, &mime_vec);
  8640. } else {
  8641. mime_vec.ptr = mime_type;
  8642. mime_vec.len = strlen(mime_type);
  8643. }
  8644. if (filep->stat.size > INT64_MAX) {
  8645. mg_send_http_error(conn,
  8646. 500,
  8647. "Error: File size is too large to send\n%" INT64_FMT,
  8648. filep->stat.size);
  8649. return;
  8650. }
  8651. cl = (int64_t)filep->stat.size;
  8652. conn->status_code = 200;
  8653. range[0] = '\0';
  8654. #if defined(USE_ZLIB)
  8655. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8656. * it's important to rewrite the filename after resolving
  8657. * the mime type from it, to preserve the actual file's type */
  8658. if (!conn->accept_gzip) {
  8659. allow_on_the_fly_compression = 0;
  8660. }
  8661. #endif
  8662. /* Check if there is a range header */
  8663. range_hdr = mg_get_header(conn, "Range");
  8664. /* For gzipped files, add *.gz */
  8665. if (filep->stat.is_gzipped) {
  8666. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8667. if (truncated) {
  8668. mg_send_http_error(conn,
  8669. 500,
  8670. "Error: Path of zipped file too long (%s)",
  8671. path);
  8672. return;
  8673. }
  8674. path = gz_path;
  8675. encoding = "gzip";
  8676. #if defined(USE_ZLIB)
  8677. /* File is already compressed. No "on the fly" compression. */
  8678. allow_on_the_fly_compression = 0;
  8679. #endif
  8680. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8681. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8682. struct mg_file_stat file_stat;
  8683. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8684. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8685. && !file_stat.is_directory) {
  8686. file_stat.is_gzipped = 1;
  8687. filep->stat = file_stat;
  8688. cl = (int64_t)filep->stat.size;
  8689. path = gz_path;
  8690. encoding = "gzip";
  8691. #if defined(USE_ZLIB)
  8692. /* File is already compressed. No "on the fly" compression. */
  8693. allow_on_the_fly_compression = 0;
  8694. #endif
  8695. }
  8696. }
  8697. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8698. mg_send_http_error(conn,
  8699. 500,
  8700. "Error: Cannot open file\nfopen(%s): %s",
  8701. path,
  8702. strerror(ERRNO));
  8703. return;
  8704. }
  8705. fclose_on_exec(&filep->access, conn);
  8706. /* If "Range" request was made: parse header, send only selected part
  8707. * of the file. */
  8708. r1 = r2 = 0;
  8709. if ((range_hdr != NULL)
  8710. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8711. && (r2 >= 0)) {
  8712. /* actually, range requests don't play well with a pre-gzipped
  8713. * file (since the range is specified in the uncompressed space) */
  8714. if (filep->stat.is_gzipped) {
  8715. mg_send_http_error(
  8716. conn,
  8717. 416, /* 416 = Range Not Satisfiable */
  8718. "%s",
  8719. "Error: Range requests in gzipped files are not supported");
  8720. (void)mg_fclose(
  8721. &filep->access); /* ignore error on read only file */
  8722. return;
  8723. }
  8724. conn->status_code = 206;
  8725. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8726. mg_snprintf(conn,
  8727. NULL, /* range buffer is big enough */
  8728. range,
  8729. sizeof(range),
  8730. "bytes "
  8731. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8732. r1,
  8733. r1 + cl - 1,
  8734. filep->stat.size);
  8735. #if defined(USE_ZLIB)
  8736. /* Do not compress ranges. */
  8737. allow_on_the_fly_compression = 0;
  8738. #endif
  8739. }
  8740. /* Do not compress small files. Small files do not benefit from file
  8741. * compression, but there is still some overhead. */
  8742. #if defined(USE_ZLIB)
  8743. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8744. /* File is below the size limit. */
  8745. allow_on_the_fly_compression = 0;
  8746. }
  8747. #endif
  8748. /* Prepare Etag, and Last-Modified headers. */
  8749. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8750. construct_etag(etag, sizeof(etag), &filep->stat);
  8751. /* Create 2xx (200, 206) response */
  8752. mg_response_header_start(conn, conn->status_code);
  8753. send_static_cache_header(conn);
  8754. send_additional_header(conn);
  8755. send_cors_header(conn);
  8756. mg_response_header_add(conn,
  8757. "Content-Type",
  8758. mime_vec.ptr,
  8759. (int)mime_vec.len);
  8760. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8761. mg_response_header_add(conn, "Etag", etag, -1);
  8762. #if defined(USE_ZLIB)
  8763. /* On the fly compression allowed */
  8764. if (allow_on_the_fly_compression) {
  8765. /* For on the fly compression, we don't know the content size in
  8766. * advance, so we have to use chunked encoding */
  8767. encoding = "gzip";
  8768. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8769. /* HTTP/2 is always using "chunks" (frames) */
  8770. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8771. }
  8772. } else
  8773. #endif
  8774. {
  8775. /* Without on-the-fly compression, we know the content-length
  8776. * and we can use ranges (with on-the-fly compression we cannot).
  8777. * So we send these response headers only in this case. */
  8778. char len[32];
  8779. int trunc = 0;
  8780. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8781. if (!trunc) {
  8782. mg_response_header_add(conn, "Content-Length", len, -1);
  8783. }
  8784. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8785. }
  8786. if (encoding) {
  8787. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8788. }
  8789. if (range[0] != 0) {
  8790. mg_response_header_add(conn, "Content-Range", range, -1);
  8791. }
  8792. /* The code above does not add any header starting with X- to make
  8793. * sure no one of the additional_headers is included twice */
  8794. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8795. mg_response_header_add_lines(conn, additional_headers);
  8796. }
  8797. /* Send all headers */
  8798. mg_response_header_send(conn);
  8799. if (!is_head_request) {
  8800. #if defined(USE_ZLIB)
  8801. if (allow_on_the_fly_compression) {
  8802. /* Compress and send */
  8803. send_compressed_data(conn, filep);
  8804. } else
  8805. #endif
  8806. {
  8807. /* Send file directly */
  8808. send_file_data(conn, filep, r1, cl);
  8809. }
  8810. }
  8811. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8812. }
  8813. int
  8814. mg_send_file_body(struct mg_connection *conn, const char *path)
  8815. {
  8816. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8817. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8818. return -1;
  8819. }
  8820. fclose_on_exec(&file.access, conn);
  8821. send_file_data(conn, &file, 0, INT64_MAX);
  8822. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8823. return 0; /* >= 0 for OK */
  8824. }
  8825. #endif /* NO_FILESYSTEMS */
  8826. #if !defined(NO_CACHING)
  8827. /* Return True if we should reply 304 Not Modified. */
  8828. static int
  8829. is_not_modified(const struct mg_connection *conn,
  8830. const struct mg_file_stat *filestat)
  8831. {
  8832. char etag[64];
  8833. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8834. const char *inm = mg_get_header(conn, "If-None-Match");
  8835. construct_etag(etag, sizeof(etag), filestat);
  8836. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8837. || ((ims != NULL)
  8838. && (filestat->last_modified <= parse_date_string(ims)));
  8839. }
  8840. static void
  8841. handle_not_modified_static_file_request(struct mg_connection *conn,
  8842. struct mg_file *filep)
  8843. {
  8844. char lm[64], etag[64];
  8845. if ((conn == NULL) || (filep == NULL)) {
  8846. return;
  8847. }
  8848. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8849. construct_etag(etag, sizeof(etag), &filep->stat);
  8850. /* Create 304 "not modified" response */
  8851. mg_response_header_start(conn, 304);
  8852. send_static_cache_header(conn);
  8853. send_additional_header(conn);
  8854. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8855. mg_response_header_add(conn, "Etag", etag, -1);
  8856. /* Send all headers */
  8857. mg_response_header_send(conn);
  8858. }
  8859. #endif
  8860. #if !defined(NO_FILESYSTEMS)
  8861. void
  8862. mg_send_file(struct mg_connection *conn, const char *path)
  8863. {
  8864. mg_send_mime_file2(conn, path, NULL, NULL);
  8865. }
  8866. void
  8867. mg_send_mime_file(struct mg_connection *conn,
  8868. const char *path,
  8869. const char *mime_type)
  8870. {
  8871. mg_send_mime_file2(conn, path, mime_type, NULL);
  8872. }
  8873. void
  8874. mg_send_mime_file2(struct mg_connection *conn,
  8875. const char *path,
  8876. const char *mime_type,
  8877. const char *additional_headers)
  8878. {
  8879. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8880. if (!conn) {
  8881. /* No conn */
  8882. return;
  8883. }
  8884. if (mg_stat(conn, path, &file.stat)) {
  8885. #if !defined(NO_CACHING)
  8886. if (is_not_modified(conn, &file.stat)) {
  8887. /* Send 304 "Not Modified" - this must not send any body data */
  8888. handle_not_modified_static_file_request(conn, &file);
  8889. } else
  8890. #endif /* NO_CACHING */
  8891. if (file.stat.is_directory) {
  8892. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8893. "yes")) {
  8894. handle_directory_request(conn, path);
  8895. } else {
  8896. mg_send_http_error(conn,
  8897. 403,
  8898. "%s",
  8899. "Error: Directory listing denied");
  8900. }
  8901. } else {
  8902. handle_static_file_request(
  8903. conn, path, &file, mime_type, additional_headers);
  8904. }
  8905. } else {
  8906. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8907. }
  8908. }
  8909. /* For a given PUT path, create all intermediate subdirectories.
  8910. * Return 0 if the path itself is a directory.
  8911. * Return 1 if the path leads to a file.
  8912. * Return -1 for if the path is too long.
  8913. * Return -2 if path can not be created.
  8914. */
  8915. static int
  8916. put_dir(struct mg_connection *conn, const char *path)
  8917. {
  8918. char buf[UTF8_PATH_MAX];
  8919. const char *s, *p;
  8920. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8921. size_t len;
  8922. int res = 1;
  8923. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8924. len = (size_t)(p - path);
  8925. if (len >= sizeof(buf)) {
  8926. /* path too long */
  8927. res = -1;
  8928. break;
  8929. }
  8930. memcpy(buf, path, len);
  8931. buf[len] = '\0';
  8932. /* Try to create intermediate directory */
  8933. DEBUG_TRACE("mkdir(%s)", buf);
  8934. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8935. /* path does not exixt and can not be created */
  8936. res = -2;
  8937. break;
  8938. }
  8939. /* Is path itself a directory? */
  8940. if (p[1] == '\0') {
  8941. res = 0;
  8942. }
  8943. }
  8944. return res;
  8945. }
  8946. static void
  8947. remove_bad_file(const struct mg_connection *conn, const char *path)
  8948. {
  8949. int r = mg_remove(conn, path);
  8950. if (r != 0) {
  8951. mg_cry_internal(conn,
  8952. "%s: Cannot remove invalid file %s",
  8953. __func__,
  8954. path);
  8955. }
  8956. }
  8957. long long
  8958. mg_store_body(struct mg_connection *conn, const char *path)
  8959. {
  8960. char buf[MG_BUF_LEN];
  8961. long long len = 0;
  8962. int ret, n;
  8963. struct mg_file fi;
  8964. if (conn->consumed_content != 0) {
  8965. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8966. return -11;
  8967. }
  8968. ret = put_dir(conn, path);
  8969. if (ret < 0) {
  8970. /* -1 for path too long,
  8971. * -2 for path can not be created. */
  8972. return ret;
  8973. }
  8974. if (ret != 1) {
  8975. /* Return 0 means, path itself is a directory. */
  8976. return 0;
  8977. }
  8978. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8979. return -12;
  8980. }
  8981. ret = mg_read(conn, buf, sizeof(buf));
  8982. while (ret > 0) {
  8983. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8984. if (n != ret) {
  8985. (void)mg_fclose(
  8986. &fi.access); /* File is bad and will be removed anyway. */
  8987. remove_bad_file(conn, path);
  8988. return -13;
  8989. }
  8990. len += ret;
  8991. ret = mg_read(conn, buf, sizeof(buf));
  8992. }
  8993. /* File is open for writing. If fclose fails, there was probably an
  8994. * error flushing the buffer to disk, so the file on disk might be
  8995. * broken. Delete it and return an error to the caller. */
  8996. if (mg_fclose(&fi.access) != 0) {
  8997. remove_bad_file(conn, path);
  8998. return -14;
  8999. }
  9000. return len;
  9001. }
  9002. #endif /* NO_FILESYSTEMS */
  9003. /* Parse a buffer:
  9004. * Forward the string pointer till the end of a word, then
  9005. * terminate it and forward till the begin of the next word.
  9006. */
  9007. static int
  9008. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9009. {
  9010. /* Forward until a space is found - use isgraph here */
  9011. /* See http://www.cplusplus.com/reference/cctype/ */
  9012. while (isgraph((unsigned char)**ppw)) {
  9013. (*ppw)++;
  9014. }
  9015. /* Check end of word */
  9016. if (eol) {
  9017. /* must be a end of line */
  9018. if ((**ppw != '\r') && (**ppw != '\n')) {
  9019. return -1;
  9020. }
  9021. } else {
  9022. /* must be a end of a word, but not a line */
  9023. if (**ppw != ' ') {
  9024. return -1;
  9025. }
  9026. }
  9027. /* Terminate and forward to the next word */
  9028. do {
  9029. **ppw = 0;
  9030. (*ppw)++;
  9031. } while (isspace((unsigned char)**ppw));
  9032. /* Check after term */
  9033. if (!eol) {
  9034. /* if it's not the end of line, there must be a next word */
  9035. if (!isgraph((unsigned char)**ppw)) {
  9036. return -1;
  9037. }
  9038. }
  9039. /* ok */
  9040. return 1;
  9041. }
  9042. /* Parse HTTP headers from the given buffer, advance buf pointer
  9043. * to the point where parsing stopped.
  9044. * All parameters must be valid pointers (not NULL).
  9045. * Return <0 on error. */
  9046. static int
  9047. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9048. {
  9049. int i;
  9050. int num_headers = 0;
  9051. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9052. char *dp = *buf;
  9053. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9054. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9055. dp++;
  9056. }
  9057. if (dp == *buf) {
  9058. /* End of headers reached. */
  9059. break;
  9060. }
  9061. /* Drop all spaces after header name before : */
  9062. while (*dp == ' ') {
  9063. *dp = 0;
  9064. dp++;
  9065. }
  9066. if (*dp != ':') {
  9067. /* This is not a valid field. */
  9068. return -1;
  9069. }
  9070. /* End of header key (*dp == ':') */
  9071. /* Truncate here and set the key name */
  9072. *dp = 0;
  9073. hdr[i].name = *buf;
  9074. /* Skip all spaces */
  9075. do {
  9076. dp++;
  9077. } while ((*dp == ' ') || (*dp == '\t'));
  9078. /* The rest of the line is the value */
  9079. hdr[i].value = dp;
  9080. /* Find end of line */
  9081. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9082. dp++;
  9083. };
  9084. /* eliminate \r */
  9085. if (*dp == '\r') {
  9086. *dp = 0;
  9087. dp++;
  9088. if (*dp != '\n') {
  9089. /* This is not a valid line. */
  9090. return -1;
  9091. }
  9092. }
  9093. /* here *dp is either 0 or '\n' */
  9094. /* in any case, we have a new header */
  9095. num_headers = i + 1;
  9096. if (*dp) {
  9097. *dp = 0;
  9098. dp++;
  9099. *buf = dp;
  9100. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9101. /* This is the end of the header */
  9102. break;
  9103. }
  9104. } else {
  9105. *buf = dp;
  9106. break;
  9107. }
  9108. }
  9109. return num_headers;
  9110. }
  9111. struct mg_http_method_info {
  9112. const char *name;
  9113. int request_has_body;
  9114. int response_has_body;
  9115. int is_safe;
  9116. int is_idempotent;
  9117. int is_cacheable;
  9118. };
  9119. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9120. static const struct mg_http_method_info http_methods[] = {
  9121. /* HTTP (RFC 2616) */
  9122. {"GET", 0, 1, 1, 1, 1},
  9123. {"POST", 1, 1, 0, 0, 0},
  9124. {"PUT", 1, 0, 0, 1, 0},
  9125. {"DELETE", 0, 0, 0, 1, 0},
  9126. {"HEAD", 0, 0, 1, 1, 1},
  9127. {"OPTIONS", 0, 0, 1, 1, 0},
  9128. {"CONNECT", 1, 1, 0, 0, 0},
  9129. /* TRACE method (RFC 2616) is not supported for security reasons */
  9130. /* PATCH method (RFC 5789) */
  9131. {"PATCH", 1, 0, 0, 0, 0},
  9132. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9133. /* WEBDAV (RFC 2518) */
  9134. {"PROPFIND", 0, 1, 1, 1, 0},
  9135. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9136. * Some PROPFIND results MAY be cached, with care,
  9137. * as there is no cache validation mechanism for
  9138. * most properties. This method is both safe and
  9139. * idempotent (see Section 9.1 of [RFC2616]). */
  9140. {"MKCOL", 0, 0, 0, 1, 0},
  9141. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9142. * When MKCOL is invoked without a request body,
  9143. * the newly created collection SHOULD have no
  9144. * members. A MKCOL request message may contain
  9145. * a message body. The precise behavior of a MKCOL
  9146. * request when the body is present is undefined,
  9147. * ... ==> We do not support MKCOL with body data.
  9148. * This method is idempotent, but not safe (see
  9149. * Section 9.1 of [RFC2616]). Responses to this
  9150. * method MUST NOT be cached. */
  9151. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9152. {"LOCK", 1, 1, 0, 0, 0},
  9153. {"UNLOCK", 1, 0, 0, 0, 0},
  9154. {"PROPPATCH", 1, 1, 0, 0, 0},
  9155. {"COPY", 1, 0, 0, 0, 0},
  9156. {"MOVE", 1, 1, 0, 0, 0},
  9157. /* Unsupported WEBDAV Methods: */
  9158. /* + 11 methods from RFC 3253 */
  9159. /* ORDERPATCH (RFC 3648) */
  9160. /* ACL (RFC 3744) */
  9161. /* SEARCH (RFC 5323) */
  9162. /* + MicroSoft extensions
  9163. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9164. /* REPORT method (RFC 3253) */
  9165. {"REPORT", 1, 1, 1, 1, 1},
  9166. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9167. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9168. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9169. * to be useful for REST in case a "GET request with body" is
  9170. * required. */
  9171. {NULL, 0, 0, 0, 0, 0}
  9172. /* end of list */
  9173. };
  9174. static const struct mg_http_method_info *
  9175. get_http_method_info(const char *method)
  9176. {
  9177. /* Check if the method is known to the server. The list of all known
  9178. * HTTP methods can be found here at
  9179. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9180. */
  9181. const struct mg_http_method_info *m = http_methods;
  9182. while (m->name) {
  9183. if (!strcmp(m->name, method)) {
  9184. return m;
  9185. }
  9186. m++;
  9187. }
  9188. return NULL;
  9189. }
  9190. static int
  9191. is_valid_http_method(const char *method)
  9192. {
  9193. return (get_http_method_info(method) != NULL);
  9194. }
  9195. /* Parse HTTP request, fill in mg_request_info structure.
  9196. * This function modifies the buffer by NUL-terminating
  9197. * HTTP request components, header names and header values.
  9198. * Parameters:
  9199. * buf (in/out): pointer to the HTTP header to parse and split
  9200. * len (in): length of HTTP header buffer
  9201. * re (out): parsed header as mg_request_info
  9202. * buf and ri must be valid pointers (not NULL), len>0.
  9203. * Returns <0 on error. */
  9204. static int
  9205. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9206. {
  9207. int request_length;
  9208. int init_skip = 0;
  9209. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9210. * remote_port */
  9211. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9212. NULL;
  9213. ri->num_headers = 0;
  9214. /* RFC says that all initial whitespaces should be ignored */
  9215. /* This included all leading \r and \n (isspace) */
  9216. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9217. while ((len > 0) && isspace((unsigned char)*buf)) {
  9218. buf++;
  9219. len--;
  9220. init_skip++;
  9221. }
  9222. if (len == 0) {
  9223. /* Incomplete request */
  9224. return 0;
  9225. }
  9226. /* Control characters are not allowed, including zero */
  9227. if (iscntrl((unsigned char)*buf)) {
  9228. return -1;
  9229. }
  9230. /* Find end of HTTP header */
  9231. request_length = get_http_header_len(buf, len);
  9232. if (request_length <= 0) {
  9233. return request_length;
  9234. }
  9235. buf[request_length - 1] = '\0';
  9236. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9237. return -1;
  9238. }
  9239. /* The first word has to be the HTTP method */
  9240. ri->request_method = buf;
  9241. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9242. return -1;
  9243. }
  9244. /* The second word is the URI */
  9245. ri->request_uri = buf;
  9246. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9247. return -1;
  9248. }
  9249. /* Next would be the HTTP version */
  9250. ri->http_version = buf;
  9251. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9252. return -1;
  9253. }
  9254. /* Check for a valid HTTP version key */
  9255. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9256. /* Invalid request */
  9257. return -1;
  9258. }
  9259. ri->http_version += 5;
  9260. /* Check for a valid http method */
  9261. if (!is_valid_http_method(ri->request_method)) {
  9262. return -1;
  9263. }
  9264. /* Parse all HTTP headers */
  9265. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9266. if (ri->num_headers < 0) {
  9267. /* Error while parsing headers */
  9268. return -1;
  9269. }
  9270. return request_length + init_skip;
  9271. }
  9272. static int
  9273. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9274. {
  9275. int response_length;
  9276. int init_skip = 0;
  9277. char *tmp, *tmp2;
  9278. long l;
  9279. /* Initialize elements. */
  9280. ri->http_version = ri->status_text = NULL;
  9281. ri->num_headers = ri->status_code = 0;
  9282. /* RFC says that all initial whitespaces should be ingored */
  9283. /* This included all leading \r and \n (isspace) */
  9284. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9285. while ((len > 0) && isspace((unsigned char)*buf)) {
  9286. buf++;
  9287. len--;
  9288. init_skip++;
  9289. }
  9290. if (len == 0) {
  9291. /* Incomplete request */
  9292. return 0;
  9293. }
  9294. /* Control characters are not allowed, including zero */
  9295. if (iscntrl((unsigned char)*buf)) {
  9296. return -1;
  9297. }
  9298. /* Find end of HTTP header */
  9299. response_length = get_http_header_len(buf, len);
  9300. if (response_length <= 0) {
  9301. return response_length;
  9302. }
  9303. buf[response_length - 1] = '\0';
  9304. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9305. return -1;
  9306. }
  9307. /* The first word is the HTTP version */
  9308. /* Check for a valid HTTP version key */
  9309. if (strncmp(buf, "HTTP/", 5) != 0) {
  9310. /* Invalid request */
  9311. return -1;
  9312. }
  9313. buf += 5;
  9314. if (!isgraph((unsigned char)buf[0])) {
  9315. /* Invalid request */
  9316. return -1;
  9317. }
  9318. ri->http_version = buf;
  9319. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9320. return -1;
  9321. }
  9322. /* The second word is the status as a number */
  9323. tmp = buf;
  9324. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9325. return -1;
  9326. }
  9327. l = strtol(tmp, &tmp2, 10);
  9328. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9329. /* Everything else but a 3 digit code is invalid */
  9330. return -1;
  9331. }
  9332. ri->status_code = (int)l;
  9333. /* The rest of the line is the status text */
  9334. ri->status_text = buf;
  9335. /* Find end of status text */
  9336. /* isgraph or isspace = isprint */
  9337. while (isprint((unsigned char)*buf)) {
  9338. buf++;
  9339. }
  9340. if ((*buf != '\r') && (*buf != '\n')) {
  9341. return -1;
  9342. }
  9343. /* Terminate string and forward buf to next line */
  9344. do {
  9345. *buf = 0;
  9346. buf++;
  9347. } while (isspace((unsigned char)*buf));
  9348. /* Parse all HTTP headers */
  9349. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9350. if (ri->num_headers < 0) {
  9351. /* Error while parsing headers */
  9352. return -1;
  9353. }
  9354. return response_length + init_skip;
  9355. }
  9356. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9357. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9358. * buffer (which marks the end of HTTP request). Buffer buf may already
  9359. * have some data. The length of the data is stored in nread.
  9360. * Upon every read operation, increase nread by the number of bytes read. */
  9361. static int
  9362. read_message(FILE *fp,
  9363. struct mg_connection *conn,
  9364. char *buf,
  9365. int bufsiz,
  9366. int *nread)
  9367. {
  9368. int request_len, n = 0;
  9369. struct timespec last_action_time;
  9370. double request_timeout;
  9371. if (!conn) {
  9372. return 0;
  9373. }
  9374. memset(&last_action_time, 0, sizeof(last_action_time));
  9375. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9376. /* value of request_timeout is in seconds, config in milliseconds */
  9377. request_timeout =
  9378. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9379. } else {
  9380. request_timeout =
  9381. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9382. / 1000.0;
  9383. }
  9384. if (conn->handled_requests > 0) {
  9385. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9386. request_timeout =
  9387. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9388. / 1000.0;
  9389. }
  9390. }
  9391. request_len = get_http_header_len(buf, *nread);
  9392. while (request_len == 0) {
  9393. /* Full request not yet received */
  9394. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9395. /* Server is to be stopped. */
  9396. return -1;
  9397. }
  9398. if (*nread >= bufsiz) {
  9399. /* Request too long */
  9400. return -2;
  9401. }
  9402. n = pull_inner(
  9403. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9404. if (n == -2) {
  9405. /* Receive error */
  9406. return -1;
  9407. }
  9408. /* update clock after every read request */
  9409. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9410. if (n > 0) {
  9411. *nread += n;
  9412. request_len = get_http_header_len(buf, *nread);
  9413. }
  9414. if ((request_len == 0) && (request_timeout >= 0)) {
  9415. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9416. > request_timeout) {
  9417. /* Timeout */
  9418. return -1;
  9419. }
  9420. }
  9421. }
  9422. return request_len;
  9423. }
  9424. #if !defined(NO_CGI) || !defined(NO_FILES)
  9425. static int
  9426. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9427. {
  9428. const char *expect;
  9429. char buf[MG_BUF_LEN];
  9430. int success = 0;
  9431. if (!conn) {
  9432. return 0;
  9433. }
  9434. expect = mg_get_header(conn, "Expect");
  9435. DEBUG_ASSERT(fp != NULL);
  9436. if (!fp) {
  9437. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9438. return 0;
  9439. }
  9440. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9441. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9442. */
  9443. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9444. } else {
  9445. if (expect != NULL) {
  9446. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9447. conn->status_code = 100;
  9448. } else {
  9449. conn->status_code = 200;
  9450. }
  9451. DEBUG_ASSERT(conn->consumed_content == 0);
  9452. if (conn->consumed_content != 0) {
  9453. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9454. return 0;
  9455. }
  9456. for (;;) {
  9457. int nread = mg_read(conn, buf, sizeof(buf));
  9458. if (nread <= 0) {
  9459. success = (nread == 0);
  9460. break;
  9461. }
  9462. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9463. break;
  9464. }
  9465. }
  9466. /* Each error code path in this function must send an error */
  9467. if (!success) {
  9468. /* NOTE: Maybe some data has already been sent. */
  9469. /* TODO (low): If some data has been sent, a correct error
  9470. * reply can no longer be sent, so just close the connection */
  9471. mg_send_http_error(conn, 500, "%s", "");
  9472. }
  9473. }
  9474. return success;
  9475. }
  9476. #endif
  9477. #if defined(USE_TIMERS)
  9478. #define TIMER_API static
  9479. #include "timer.inl"
  9480. #endif /* USE_TIMERS */
  9481. #if !defined(NO_CGI)
  9482. /* This structure helps to create an environment for the spawned CGI
  9483. * program.
  9484. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9485. * last element must be NULL.
  9486. * However, on Windows there is a requirement that all these
  9487. * VARIABLE=VALUE\0
  9488. * strings must reside in a contiguous buffer. The end of the buffer is
  9489. * marked by two '\0' characters.
  9490. * We satisfy both worlds: we create an envp array (which is vars), all
  9491. * entries are actually pointers inside buf. */
  9492. struct cgi_environment {
  9493. struct mg_connection *conn;
  9494. /* Data block */
  9495. char *buf; /* Environment buffer */
  9496. size_t buflen; /* Space available in buf */
  9497. size_t bufused; /* Space taken in buf */
  9498. /* Index block */
  9499. char **var; /* char **envp */
  9500. size_t varlen; /* Number of variables available in var */
  9501. size_t varused; /* Number of variables stored in var */
  9502. };
  9503. static void addenv(struct cgi_environment *env,
  9504. PRINTF_FORMAT_STRING(const char *fmt),
  9505. ...) PRINTF_ARGS(2, 3);
  9506. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9507. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9508. static void
  9509. addenv(struct cgi_environment *env, const char *fmt, ...)
  9510. {
  9511. size_t i, n, space;
  9512. int truncated = 0;
  9513. char *added;
  9514. va_list ap;
  9515. if ((env->varlen - env->varused) < 2) {
  9516. mg_cry_internal(env->conn,
  9517. "%s: Cannot register CGI variable [%s]",
  9518. __func__,
  9519. fmt);
  9520. return;
  9521. }
  9522. /* Calculate how much space is left in the buffer */
  9523. space = (env->buflen - env->bufused);
  9524. do {
  9525. /* Space for "\0\0" is always needed. */
  9526. if (space <= 2) {
  9527. /* Allocate new buffer */
  9528. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9529. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9530. if (!added) {
  9531. /* Out of memory */
  9532. mg_cry_internal(
  9533. env->conn,
  9534. "%s: Cannot allocate memory for CGI variable [%s]",
  9535. __func__,
  9536. fmt);
  9537. return;
  9538. }
  9539. /* Retarget pointers */
  9540. env->buf = added;
  9541. env->buflen = n;
  9542. for (i = 0, n = 0; i < env->varused; i++) {
  9543. env->var[i] = added + n;
  9544. n += strlen(added + n) + 1;
  9545. }
  9546. space = (env->buflen - env->bufused);
  9547. }
  9548. /* Make a pointer to the free space int the buffer */
  9549. added = env->buf + env->bufused;
  9550. /* Copy VARIABLE=VALUE\0 string into the free space */
  9551. va_start(ap, fmt);
  9552. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9553. va_end(ap);
  9554. /* Do not add truncated strings to the environment */
  9555. if (truncated) {
  9556. /* Reallocate the buffer */
  9557. space = 0;
  9558. }
  9559. } while (truncated);
  9560. /* Calculate number of bytes added to the environment */
  9561. n = strlen(added) + 1;
  9562. env->bufused += n;
  9563. /* Append a pointer to the added string into the envp array */
  9564. env->var[env->varused] = added;
  9565. env->varused++;
  9566. }
  9567. /* Return 0 on success, non-zero if an error occurs. */
  9568. static int
  9569. prepare_cgi_environment(struct mg_connection *conn,
  9570. const char *prog,
  9571. struct cgi_environment *env,
  9572. unsigned char cgi_config_idx)
  9573. {
  9574. const char *s;
  9575. struct vec var_vec;
  9576. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9577. int i, truncated, uri_len;
  9578. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9579. return -1;
  9580. }
  9581. env->conn = conn;
  9582. env->buflen = CGI_ENVIRONMENT_SIZE;
  9583. env->bufused = 0;
  9584. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9585. if (env->buf == NULL) {
  9586. mg_cry_internal(conn,
  9587. "%s: Not enough memory for environmental buffer",
  9588. __func__);
  9589. return -1;
  9590. }
  9591. env->varlen = MAX_CGI_ENVIR_VARS;
  9592. env->varused = 0;
  9593. env->var =
  9594. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9595. if (env->var == NULL) {
  9596. mg_cry_internal(conn,
  9597. "%s: Not enough memory for environmental variables",
  9598. __func__);
  9599. mg_free(env->buf);
  9600. return -1;
  9601. }
  9602. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9603. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9604. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9605. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9606. /* Prepare the environment block */
  9607. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9608. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9609. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9610. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9611. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9612. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9613. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9614. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9615. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9616. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9617. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9618. /* SCRIPT_NAME */
  9619. uri_len = (int)strlen(conn->request_info.local_uri);
  9620. if (conn->path_info == NULL) {
  9621. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9622. /* URI: /path_to_script/script.cgi */
  9623. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9624. } else {
  9625. /* URI: /path_to_script/ ... using index.cgi */
  9626. const char *index_file = strrchr(prog, '/');
  9627. if (index_file) {
  9628. addenv(env,
  9629. "SCRIPT_NAME=%s%s",
  9630. conn->request_info.local_uri,
  9631. index_file + 1);
  9632. }
  9633. }
  9634. } else {
  9635. /* URI: /path_to_script/script.cgi/path_info */
  9636. addenv(env,
  9637. "SCRIPT_NAME=%.*s",
  9638. uri_len - (int)strlen(conn->path_info),
  9639. conn->request_info.local_uri);
  9640. }
  9641. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9642. if (conn->path_info == NULL) {
  9643. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9644. } else {
  9645. addenv(env,
  9646. "PATH_TRANSLATED=%s%s",
  9647. conn->dom_ctx->config[DOCUMENT_ROOT],
  9648. conn->path_info);
  9649. }
  9650. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9651. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9652. addenv(env, "CONTENT_TYPE=%s", s);
  9653. }
  9654. if (conn->request_info.query_string != NULL) {
  9655. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9656. }
  9657. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9658. addenv(env, "CONTENT_LENGTH=%s", s);
  9659. }
  9660. if ((s = getenv("PATH")) != NULL) {
  9661. addenv(env, "PATH=%s", s);
  9662. }
  9663. if (conn->path_info != NULL) {
  9664. addenv(env, "PATH_INFO=%s", conn->path_info);
  9665. }
  9666. if (conn->status_code > 0) {
  9667. /* CGI error handler should show the status code */
  9668. addenv(env, "STATUS=%d", conn->status_code);
  9669. }
  9670. #if defined(_WIN32)
  9671. if ((s = getenv("COMSPEC")) != NULL) {
  9672. addenv(env, "COMSPEC=%s", s);
  9673. }
  9674. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9675. addenv(env, "SYSTEMROOT=%s", s);
  9676. }
  9677. if ((s = getenv("SystemDrive")) != NULL) {
  9678. addenv(env, "SystemDrive=%s", s);
  9679. }
  9680. if ((s = getenv("ProgramFiles")) != NULL) {
  9681. addenv(env, "ProgramFiles=%s", s);
  9682. }
  9683. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9684. addenv(env, "ProgramFiles(x86)=%s", s);
  9685. }
  9686. #else
  9687. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9688. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9689. }
  9690. #endif /* _WIN32 */
  9691. if ((s = getenv("PERLLIB")) != NULL) {
  9692. addenv(env, "PERLLIB=%s", s);
  9693. }
  9694. if (conn->request_info.remote_user != NULL) {
  9695. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9696. addenv(env, "%s", "AUTH_TYPE=Digest");
  9697. }
  9698. /* Add all headers as HTTP_* variables */
  9699. for (i = 0; i < conn->request_info.num_headers; i++) {
  9700. (void)mg_snprintf(conn,
  9701. &truncated,
  9702. http_var_name,
  9703. sizeof(http_var_name),
  9704. "HTTP_%s",
  9705. conn->request_info.http_headers[i].name);
  9706. if (truncated) {
  9707. mg_cry_internal(conn,
  9708. "%s: HTTP header variable too long [%s]",
  9709. __func__,
  9710. conn->request_info.http_headers[i].name);
  9711. continue;
  9712. }
  9713. /* Convert variable name into uppercase, and change - to _ */
  9714. for (p = http_var_name; *p != '\0'; p++) {
  9715. if (*p == '-') {
  9716. *p = '_';
  9717. }
  9718. *p = (char)toupper((unsigned char)*p);
  9719. }
  9720. addenv(env,
  9721. "%s=%s",
  9722. http_var_name,
  9723. conn->request_info.http_headers[i].value);
  9724. }
  9725. /* Add user-specified variables */
  9726. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9727. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9728. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9729. }
  9730. env->var[env->varused] = NULL;
  9731. env->buf[env->bufused] = '\0';
  9732. return 0;
  9733. }
  9734. /* Data for CGI process control: PID and number of references */
  9735. struct process_control_data {
  9736. pid_t pid;
  9737. ptrdiff_t references;
  9738. };
  9739. static int
  9740. abort_cgi_process(void *data)
  9741. {
  9742. /* Waitpid checks for child status and won't work for a pid that does
  9743. * not identify a child of the current process. Thus, if the pid is
  9744. * reused, we will not affect a different process. */
  9745. struct process_control_data *proc = (struct process_control_data *)data;
  9746. int status = 0;
  9747. ptrdiff_t refs;
  9748. pid_t ret_pid;
  9749. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9750. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9751. /* Stop child process */
  9752. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9753. kill(proc->pid, SIGABRT);
  9754. /* Wait until process is terminated (don't leave zombies) */
  9755. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9756. ;
  9757. } else {
  9758. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9759. }
  9760. /* Dec reference counter */
  9761. refs = mg_atomic_dec(&proc->references);
  9762. if (refs == 0) {
  9763. /* no more references - free data */
  9764. mg_free(data);
  9765. }
  9766. return 0;
  9767. }
  9768. /* Local (static) function assumes all arguments are valid. */
  9769. static void
  9770. handle_cgi_request(struct mg_connection *conn,
  9771. const char *prog,
  9772. unsigned char cgi_config_idx)
  9773. {
  9774. char *buf;
  9775. size_t buflen;
  9776. int headers_len, data_len, i, truncated;
  9777. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9778. const char *status, *status_text, *connection_state;
  9779. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9780. struct mg_request_info ri;
  9781. struct cgi_environment blk;
  9782. FILE *in = NULL, *out = NULL, *err = NULL;
  9783. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9784. pid_t pid = (pid_t)-1;
  9785. struct process_control_data *proc = NULL;
  9786. #if defined(USE_TIMERS)
  9787. double cgi_timeout;
  9788. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9789. /* Get timeout in seconds */
  9790. cgi_timeout =
  9791. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9792. } else {
  9793. cgi_timeout =
  9794. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9795. }
  9796. #endif
  9797. buf = NULL;
  9798. buflen = conn->phys_ctx->max_request_size;
  9799. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9800. if (i != 0) {
  9801. blk.buf = NULL;
  9802. blk.var = NULL;
  9803. goto done;
  9804. }
  9805. /* CGI must be executed in its own directory. 'dir' must point to the
  9806. * directory containing executable program, 'p' must point to the
  9807. * executable program name relative to 'dir'. */
  9808. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9809. if (truncated) {
  9810. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9811. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9812. goto done;
  9813. }
  9814. if ((p = strrchr(dir, '/')) != NULL) {
  9815. *p++ = '\0';
  9816. } else {
  9817. dir[0] = '.';
  9818. dir[1] = '\0';
  9819. p = (char *)prog;
  9820. }
  9821. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9822. status = strerror(ERRNO);
  9823. mg_cry_internal(
  9824. conn,
  9825. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9826. prog,
  9827. status);
  9828. mg_send_http_error(conn,
  9829. 500,
  9830. "Error: Cannot create CGI pipe: %s",
  9831. status);
  9832. goto done;
  9833. }
  9834. proc = (struct process_control_data *)
  9835. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9836. if (proc == NULL) {
  9837. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9838. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9839. goto done;
  9840. }
  9841. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9842. pid = spawn_process(
  9843. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9844. if (pid == (pid_t)-1) {
  9845. status = strerror(ERRNO);
  9846. mg_cry_internal(
  9847. conn,
  9848. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9849. prog,
  9850. status);
  9851. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9852. mg_free(proc);
  9853. proc = NULL;
  9854. goto done;
  9855. }
  9856. /* Store data in shared process_control_data */
  9857. proc->pid = pid;
  9858. proc->references = 1;
  9859. #if defined(USE_TIMERS)
  9860. if (cgi_timeout > 0.0) {
  9861. proc->references = 2;
  9862. // Start a timer for CGI
  9863. timer_add(conn->phys_ctx,
  9864. cgi_timeout /* in seconds */,
  9865. 0.0,
  9866. 1,
  9867. abort_cgi_process,
  9868. (void *)proc,
  9869. NULL);
  9870. }
  9871. #endif
  9872. /* Parent closes only one side of the pipes.
  9873. * If we don't mark them as closed, close() attempt before
  9874. * return from this function throws an exception on Windows.
  9875. * Windows does not like when closed descriptor is closed again. */
  9876. (void)close(fdin[0]);
  9877. (void)close(fdout[1]);
  9878. (void)close(fderr[1]);
  9879. fdin[0] = fdout[1] = fderr[1] = -1;
  9880. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9881. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9882. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9883. status = strerror(ERRNO);
  9884. mg_cry_internal(conn,
  9885. "Error: CGI program \"%s\": Can not open fd: %s",
  9886. prog,
  9887. status);
  9888. mg_send_http_error(conn,
  9889. 500,
  9890. "Error: CGI can not open fd\nfdopen: %s",
  9891. status);
  9892. goto done;
  9893. }
  9894. setbuf(in, NULL);
  9895. setbuf(out, NULL);
  9896. setbuf(err, NULL);
  9897. fout.access.fp = out;
  9898. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9899. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9900. conn->content_len);
  9901. /* This is a POST/PUT request, or another request with body data. */
  9902. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9903. /* Error sending the body data */
  9904. mg_cry_internal(
  9905. conn,
  9906. "Error: CGI program \"%s\": Forward body data failed",
  9907. prog);
  9908. goto done;
  9909. }
  9910. }
  9911. /* Close so child gets an EOF. */
  9912. fclose(in);
  9913. in = NULL;
  9914. fdin[1] = -1;
  9915. /* Now read CGI reply into a buffer. We need to set correct
  9916. * status code, thus we need to see all HTTP headers first.
  9917. * Do not send anything back to client, until we buffer in all
  9918. * HTTP headers. */
  9919. data_len = 0;
  9920. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9921. if (buf == NULL) {
  9922. mg_send_http_error(conn,
  9923. 500,
  9924. "Error: Not enough memory for CGI buffer (%u bytes)",
  9925. (unsigned int)buflen);
  9926. mg_cry_internal(
  9927. conn,
  9928. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9929. "bytes)",
  9930. prog,
  9931. (unsigned int)buflen);
  9932. goto done;
  9933. }
  9934. DEBUG_TRACE("CGI: %s", "wait for response");
  9935. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9936. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9937. if (headers_len <= 0) {
  9938. /* Could not parse the CGI response. Check if some error message on
  9939. * stderr. */
  9940. i = pull_all(err, conn, buf, (int)buflen);
  9941. if (i > 0) {
  9942. /* CGI program explicitly sent an error */
  9943. /* Write the error message to the internal log */
  9944. mg_cry_internal(conn,
  9945. "Error: CGI program \"%s\" sent error "
  9946. "message: [%.*s]",
  9947. prog,
  9948. i,
  9949. buf);
  9950. /* Don't send the error message back to the client */
  9951. mg_send_http_error(conn,
  9952. 500,
  9953. "Error: CGI program \"%s\" failed.",
  9954. prog);
  9955. } else {
  9956. /* CGI program did not explicitly send an error, but a broken
  9957. * respon header */
  9958. mg_cry_internal(conn,
  9959. "Error: CGI program sent malformed or too big "
  9960. "(>%u bytes) HTTP headers: [%.*s]",
  9961. (unsigned)buflen,
  9962. data_len,
  9963. buf);
  9964. mg_send_http_error(conn,
  9965. 500,
  9966. "Error: CGI program sent malformed or too big "
  9967. "(>%u bytes) HTTP headers: [%.*s]",
  9968. (unsigned)buflen,
  9969. data_len,
  9970. buf);
  9971. }
  9972. /* in both cases, abort processing CGI */
  9973. goto done;
  9974. }
  9975. pbuf = buf;
  9976. buf[headers_len - 1] = '\0';
  9977. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9978. /* Make up and send the status line */
  9979. status_text = "OK";
  9980. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9981. != NULL) {
  9982. conn->status_code = atoi(status);
  9983. status_text = status;
  9984. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9985. status_text++;
  9986. }
  9987. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9988. != NULL) {
  9989. conn->status_code = 307;
  9990. } else {
  9991. conn->status_code = 200;
  9992. }
  9993. connection_state =
  9994. get_header(ri.http_headers, ri.num_headers, "Connection");
  9995. if (!header_has_option(connection_state, "keep-alive")) {
  9996. conn->must_close = 1;
  9997. }
  9998. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9999. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10000. /* Send headers */
  10001. for (i = 0; i < ri.num_headers; i++) {
  10002. DEBUG_TRACE("CGI header: %s: %s",
  10003. ri.http_headers[i].name,
  10004. ri.http_headers[i].value);
  10005. mg_printf(conn,
  10006. "%s: %s\r\n",
  10007. ri.http_headers[i].name,
  10008. ri.http_headers[i].value);
  10009. }
  10010. mg_write(conn, "\r\n", 2);
  10011. /* Send chunk of data that may have been read after the headers */
  10012. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10013. /* Read the rest of CGI output and send to the client */
  10014. DEBUG_TRACE("CGI: %s", "forward all data");
  10015. send_file_data(conn, &fout, 0, INT64_MAX);
  10016. DEBUG_TRACE("CGI: %s", "all data sent");
  10017. done:
  10018. mg_free(blk.var);
  10019. mg_free(blk.buf);
  10020. if (pid != (pid_t)-1) {
  10021. abort_cgi_process((void *)proc);
  10022. }
  10023. if (fdin[0] != -1) {
  10024. close(fdin[0]);
  10025. }
  10026. if (fdout[1] != -1) {
  10027. close(fdout[1]);
  10028. }
  10029. if (fderr[1] != -1) {
  10030. close(fderr[1]);
  10031. }
  10032. if (in != NULL) {
  10033. fclose(in);
  10034. } else if (fdin[1] != -1) {
  10035. close(fdin[1]);
  10036. }
  10037. if (out != NULL) {
  10038. fclose(out);
  10039. } else if (fdout[0] != -1) {
  10040. close(fdout[0]);
  10041. }
  10042. if (err != NULL) {
  10043. fclose(err);
  10044. } else if (fderr[0] != -1) {
  10045. close(fderr[0]);
  10046. }
  10047. mg_free(buf);
  10048. }
  10049. #endif /* !NO_CGI */
  10050. #if !defined(NO_FILES)
  10051. static void
  10052. dav_mkcol(struct mg_connection *conn, const char *path)
  10053. {
  10054. int rc, body_len;
  10055. struct de de;
  10056. if (conn == NULL) {
  10057. return;
  10058. }
  10059. /* TODO (mid): Check the mg_send_http_error situations in this function
  10060. */
  10061. memset(&de.file, 0, sizeof(de.file));
  10062. if (!mg_stat(conn, path, &de.file)) {
  10063. mg_cry_internal(conn,
  10064. "%s: mg_stat(%s) failed: %s",
  10065. __func__,
  10066. path,
  10067. strerror(ERRNO));
  10068. }
  10069. if (de.file.last_modified) {
  10070. /* TODO (mid): This check does not seem to make any sense ! */
  10071. /* TODO (mid): Add a webdav unit test first, before changing
  10072. * anything here. */
  10073. mg_send_http_error(
  10074. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10075. return;
  10076. }
  10077. body_len = conn->data_len - conn->request_len;
  10078. if (body_len > 0) {
  10079. mg_send_http_error(
  10080. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10081. return;
  10082. }
  10083. rc = mg_mkdir(conn, path, 0755);
  10084. if (rc == 0) {
  10085. /* Create 201 "Created" response */
  10086. mg_response_header_start(conn, 201);
  10087. send_static_cache_header(conn);
  10088. send_additional_header(conn);
  10089. mg_response_header_add(conn, "Content-Length", "0", -1);
  10090. /* Send all headers - there is no body */
  10091. mg_response_header_send(conn);
  10092. } else {
  10093. int http_status = 500;
  10094. switch (errno) {
  10095. case EEXIST:
  10096. http_status = 405;
  10097. break;
  10098. case EACCES:
  10099. http_status = 403;
  10100. break;
  10101. case ENOENT:
  10102. http_status = 409;
  10103. break;
  10104. }
  10105. mg_send_http_error(conn,
  10106. http_status,
  10107. "Error processing %s: %s",
  10108. path,
  10109. strerror(ERRNO));
  10110. }
  10111. }
  10112. /* Forward decrlaration */
  10113. static int get_uri_type(const char *uri);
  10114. static const char *
  10115. get_rel_url_at_current_server(const char *uri,
  10116. const struct mg_connection *conn);
  10117. static void
  10118. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10119. {
  10120. const char *overwrite_hdr;
  10121. const char *destination_hdr;
  10122. const char *root;
  10123. int rc, dest_uri_type;
  10124. int http_status = 400;
  10125. int do_overwrite = 0;
  10126. int destination_ok = 0;
  10127. char dest_path[UTF8_PATH_MAX];
  10128. struct mg_file_stat ignored;
  10129. if (conn == NULL) {
  10130. return;
  10131. }
  10132. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10133. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10134. destination_hdr = mg_get_header(conn, "Destination");
  10135. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10136. do_overwrite = 1;
  10137. }
  10138. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10139. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10140. return;
  10141. }
  10142. if (root != NULL) {
  10143. char *local_dest = NULL;
  10144. dest_uri_type = get_uri_type(destination_hdr);
  10145. if (dest_uri_type == 2) {
  10146. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10147. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10148. const char *h =
  10149. get_rel_url_at_current_server(destination_hdr, conn);
  10150. if (h) {
  10151. local_dest = mg_strdup_ctx(h, conn->phys_ctx);
  10152. }
  10153. }
  10154. if (local_dest != NULL) {
  10155. remove_dot_segments(local_dest);
  10156. if (local_dest[0] == '/') {
  10157. int trunc_check = 0;
  10158. mg_snprintf(conn,
  10159. &trunc_check,
  10160. dest_path,
  10161. sizeof(dest_path),
  10162. "%s/%s",
  10163. root,
  10164. local_dest);
  10165. if (trunc_check == 0) {
  10166. destination_ok = 1;
  10167. }
  10168. }
  10169. mg_free(local_dest);
  10170. }
  10171. }
  10172. if (!destination_ok) {
  10173. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10174. return;
  10175. }
  10176. /* Check now if this file exists */
  10177. if (mg_stat(conn, dest_path, &ignored)) {
  10178. /* File exists */
  10179. if (do_overwrite) {
  10180. /* Overwrite allowed: delete the file first */
  10181. remove(dest_path);
  10182. } else {
  10183. /* No overwrite: return error */
  10184. mg_send_http_error(conn,
  10185. 412,
  10186. "Destination already exists: %s",
  10187. dest_path);
  10188. return;
  10189. }
  10190. }
  10191. /* Copy / Move / Rename operation. */
  10192. #if defined(_WIN32)
  10193. {
  10194. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10195. wchar_t wSource[UTF16_PATH_MAX];
  10196. wchar_t wDest[UTF16_PATH_MAX];
  10197. BOOL ok;
  10198. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10199. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10200. if (do_copy) {
  10201. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10202. } else {
  10203. ok = MoveFileExW(wSource,
  10204. wDest,
  10205. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10206. }
  10207. if (ok) {
  10208. rc = 0;
  10209. } else {
  10210. DWORD lastErr = GetLastError();
  10211. if (lastErr == ERROR_ALREADY_EXISTS) {
  10212. mg_send_http_error(conn,
  10213. 412,
  10214. "Destination already exists: %s",
  10215. dest_path);
  10216. return;
  10217. }
  10218. rc = -1;
  10219. http_status = 400;
  10220. }
  10221. }
  10222. #else
  10223. {
  10224. /* Linux uses already UTF-8, we don't need to convert file names. */
  10225. if (do_copy) {
  10226. /* TODO: COPY for Linux. */
  10227. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10228. return;
  10229. }
  10230. rc = rename(path, dest_path);
  10231. if (rc) {
  10232. switch (errno) {
  10233. case EEXIST:
  10234. http_status = 412;
  10235. break;
  10236. case EACCES:
  10237. http_status = 403;
  10238. break;
  10239. case ENOENT:
  10240. http_status = 409;
  10241. break;
  10242. }
  10243. }
  10244. }
  10245. #endif
  10246. if (rc == 0) {
  10247. /* Create 204 "No Content" response */
  10248. mg_response_header_start(conn, 204);
  10249. mg_response_header_add(conn, "Content-Length", "0", -1);
  10250. /* Send all headers - there is no body */
  10251. mg_response_header_send(conn);
  10252. } else {
  10253. mg_send_http_error(conn, http_status, "Operation failed");
  10254. }
  10255. }
  10256. static void
  10257. put_file(struct mg_connection *conn, const char *path)
  10258. {
  10259. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10260. const char *range;
  10261. int64_t r1, r2;
  10262. int rc;
  10263. if (conn == NULL) {
  10264. return;
  10265. }
  10266. if (mg_stat(conn, path, &file.stat)) {
  10267. /* File already exists */
  10268. conn->status_code = 200;
  10269. if (file.stat.is_directory) {
  10270. /* This is an already existing directory,
  10271. * so there is nothing to do for the server. */
  10272. rc = 0;
  10273. } else {
  10274. /* File exists and is not a directory. */
  10275. /* Can it be replaced? */
  10276. /* Check if the server may write this file */
  10277. if (access(path, W_OK) == 0) {
  10278. /* Access granted */
  10279. rc = 1;
  10280. } else {
  10281. mg_send_http_error(
  10282. conn,
  10283. 403,
  10284. "Error: Put not possible\nReplacing %s is not allowed",
  10285. path);
  10286. return;
  10287. }
  10288. }
  10289. } else {
  10290. /* File should be created */
  10291. conn->status_code = 201;
  10292. rc = put_dir(conn, path);
  10293. }
  10294. if (rc == 0) {
  10295. /* put_dir returns 0 if path is a directory */
  10296. /* Create response */
  10297. mg_response_header_start(conn, conn->status_code);
  10298. send_no_cache_header(conn);
  10299. send_additional_header(conn);
  10300. mg_response_header_add(conn, "Content-Length", "0", -1);
  10301. /* Send all headers - there is no body */
  10302. mg_response_header_send(conn);
  10303. /* Request to create a directory has been fulfilled successfully.
  10304. * No need to put a file. */
  10305. return;
  10306. }
  10307. if (rc == -1) {
  10308. /* put_dir returns -1 if the path is too long */
  10309. mg_send_http_error(conn,
  10310. 414,
  10311. "Error: Path too long\nput_dir(%s): %s",
  10312. path,
  10313. strerror(ERRNO));
  10314. return;
  10315. }
  10316. if (rc == -2) {
  10317. /* put_dir returns -2 if the directory can not be created */
  10318. mg_send_http_error(conn,
  10319. 500,
  10320. "Error: Can not create directory\nput_dir(%s): %s",
  10321. path,
  10322. strerror(ERRNO));
  10323. return;
  10324. }
  10325. /* A file should be created or overwritten. */
  10326. /* Currently CivetWeb does not nead read+write access. */
  10327. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10328. || file.access.fp == NULL) {
  10329. (void)mg_fclose(&file.access);
  10330. mg_send_http_error(conn,
  10331. 500,
  10332. "Error: Can not create file\nfopen(%s): %s",
  10333. path,
  10334. strerror(ERRNO));
  10335. return;
  10336. }
  10337. fclose_on_exec(&file.access, conn);
  10338. range = mg_get_header(conn, "Content-Range");
  10339. r1 = r2 = 0;
  10340. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10341. conn->status_code = 206; /* Partial content */
  10342. fseeko(file.access.fp, r1, SEEK_SET);
  10343. }
  10344. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10345. /* forward_body_data failed.
  10346. * The error code has already been sent to the client,
  10347. * and conn->status_code is already set. */
  10348. (void)mg_fclose(&file.access);
  10349. return;
  10350. }
  10351. if (mg_fclose(&file.access) != 0) {
  10352. /* fclose failed. This might have different reasons, but a likely
  10353. * one is "no space on disk", http 507. */
  10354. conn->status_code = 507;
  10355. }
  10356. /* Create response (status_code has been set before) */
  10357. mg_response_header_start(conn, conn->status_code);
  10358. send_no_cache_header(conn);
  10359. send_additional_header(conn);
  10360. mg_response_header_add(conn, "Content-Length", "0", -1);
  10361. /* Send all headers - there is no body */
  10362. mg_response_header_send(conn);
  10363. }
  10364. static void
  10365. delete_file(struct mg_connection *conn, const char *path)
  10366. {
  10367. struct de de;
  10368. memset(&de.file, 0, sizeof(de.file));
  10369. if (!mg_stat(conn, path, &de.file)) {
  10370. /* mg_stat returns 0 if the file does not exist */
  10371. mg_send_http_error(conn,
  10372. 404,
  10373. "Error: Cannot delete file\nFile %s not found",
  10374. path);
  10375. return;
  10376. }
  10377. if (de.file.is_directory) {
  10378. if (remove_directory(conn, path)) {
  10379. /* Delete is successful: Return 204 without content. */
  10380. mg_send_http_error(conn, 204, "%s", "");
  10381. } else {
  10382. /* Delete is not successful: Return 500 (Server error). */
  10383. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10384. }
  10385. return;
  10386. }
  10387. /* This is an existing file (not a directory).
  10388. * Check if write permission is granted. */
  10389. if (access(path, W_OK) != 0) {
  10390. /* File is read only */
  10391. mg_send_http_error(
  10392. conn,
  10393. 403,
  10394. "Error: Delete not possible\nDeleting %s is not allowed",
  10395. path);
  10396. return;
  10397. }
  10398. /* Try to delete it. */
  10399. if (mg_remove(conn, path) == 0) {
  10400. /* Delete was successful: Return 204 without content. */
  10401. mg_response_header_start(conn, 204);
  10402. send_no_cache_header(conn);
  10403. send_additional_header(conn);
  10404. mg_response_header_add(conn, "Content-Length", "0", -1);
  10405. mg_response_header_send(conn);
  10406. } else {
  10407. /* Delete not successful (file locked). */
  10408. mg_send_http_error(conn,
  10409. 423,
  10410. "Error: Cannot delete file\nremove(%s): %s",
  10411. path,
  10412. strerror(ERRNO));
  10413. }
  10414. }
  10415. #endif /* !NO_FILES */
  10416. #if !defined(NO_FILESYSTEMS)
  10417. static void
  10418. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10419. static void
  10420. do_ssi_include(struct mg_connection *conn,
  10421. const char *ssi,
  10422. char *tag,
  10423. int include_level)
  10424. {
  10425. char file_name[MG_BUF_LEN], path[512], *p;
  10426. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10427. size_t len;
  10428. int truncated = 0;
  10429. if (conn == NULL) {
  10430. return;
  10431. }
  10432. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10433. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10434. * always < MG_BUF_LEN. */
  10435. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10436. /* File name is relative to the webserver root */
  10437. file_name[511] = 0;
  10438. (void)mg_snprintf(conn,
  10439. &truncated,
  10440. path,
  10441. sizeof(path),
  10442. "%s/%s",
  10443. conn->dom_ctx->config[DOCUMENT_ROOT],
  10444. file_name);
  10445. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10446. /* File name is relative to the webserver working directory
  10447. * or it is absolute system path */
  10448. file_name[511] = 0;
  10449. (void)
  10450. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10451. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10452. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10453. /* File name is relative to the currect document */
  10454. file_name[511] = 0;
  10455. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10456. if (!truncated) {
  10457. if ((p = strrchr(path, '/')) != NULL) {
  10458. p[1] = '\0';
  10459. }
  10460. len = strlen(path);
  10461. (void)mg_snprintf(conn,
  10462. &truncated,
  10463. path + len,
  10464. sizeof(path) - len,
  10465. "%s",
  10466. file_name);
  10467. }
  10468. } else {
  10469. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10470. return;
  10471. }
  10472. if (truncated) {
  10473. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10474. return;
  10475. }
  10476. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10477. mg_cry_internal(conn,
  10478. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10479. tag,
  10480. path,
  10481. strerror(ERRNO));
  10482. } else {
  10483. fclose_on_exec(&file.access, conn);
  10484. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10485. > 0) {
  10486. send_ssi_file(conn, path, &file, include_level + 1);
  10487. } else {
  10488. send_file_data(conn, &file, 0, INT64_MAX);
  10489. }
  10490. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10491. }
  10492. }
  10493. #if !defined(NO_POPEN)
  10494. static void
  10495. do_ssi_exec(struct mg_connection *conn, char *tag)
  10496. {
  10497. char cmd[1024] = "";
  10498. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10499. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10500. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10501. } else {
  10502. cmd[1023] = 0;
  10503. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10504. mg_cry_internal(conn,
  10505. "Cannot SSI #exec: [%s]: %s",
  10506. cmd,
  10507. strerror(ERRNO));
  10508. } else {
  10509. send_file_data(conn, &file, 0, INT64_MAX);
  10510. pclose(file.access.fp);
  10511. }
  10512. }
  10513. }
  10514. #endif /* !NO_POPEN */
  10515. static int
  10516. mg_fgetc(struct mg_file *filep)
  10517. {
  10518. if (filep == NULL) {
  10519. return EOF;
  10520. }
  10521. if (filep->access.fp != NULL) {
  10522. return fgetc(filep->access.fp);
  10523. } else {
  10524. return EOF;
  10525. }
  10526. }
  10527. static void
  10528. send_ssi_file(struct mg_connection *conn,
  10529. const char *path,
  10530. struct mg_file *filep,
  10531. int include_level)
  10532. {
  10533. char buf[MG_BUF_LEN];
  10534. int ch, len, in_tag, in_ssi_tag;
  10535. if (include_level > 10) {
  10536. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10537. return;
  10538. }
  10539. in_tag = in_ssi_tag = len = 0;
  10540. /* Read file, byte by byte, and look for SSI include tags */
  10541. while ((ch = mg_fgetc(filep)) != EOF) {
  10542. if (in_tag) {
  10543. /* We are in a tag, either SSI tag or html tag */
  10544. if (ch == '>') {
  10545. /* Tag is closing */
  10546. buf[len++] = '>';
  10547. if (in_ssi_tag) {
  10548. /* Handle SSI tag */
  10549. buf[len] = 0;
  10550. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10551. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10552. #if !defined(NO_POPEN)
  10553. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10554. do_ssi_exec(conn, buf + 9);
  10555. #endif /* !NO_POPEN */
  10556. } else {
  10557. mg_cry_internal(conn,
  10558. "%s: unknown SSI "
  10559. "command: \"%s\"",
  10560. path,
  10561. buf);
  10562. }
  10563. len = 0;
  10564. in_ssi_tag = in_tag = 0;
  10565. } else {
  10566. /* Not an SSI tag */
  10567. /* Flush buffer */
  10568. (void)mg_write(conn, buf, (size_t)len);
  10569. len = 0;
  10570. in_tag = 0;
  10571. }
  10572. } else {
  10573. /* Tag is still open */
  10574. buf[len++] = (char)(ch & 0xff);
  10575. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10576. /* All SSI tags start with <!--# */
  10577. in_ssi_tag = 1;
  10578. }
  10579. if ((len + 2) > (int)sizeof(buf)) {
  10580. /* Tag to long for buffer */
  10581. mg_cry_internal(conn, "%s: tag is too large", path);
  10582. return;
  10583. }
  10584. }
  10585. } else {
  10586. /* We are not in a tag yet. */
  10587. if (ch == '<') {
  10588. /* Tag is opening */
  10589. in_tag = 1;
  10590. if (len > 0) {
  10591. /* Flush current buffer.
  10592. * Buffer is filled with "len" bytes. */
  10593. (void)mg_write(conn, buf, (size_t)len);
  10594. }
  10595. /* Store the < */
  10596. len = 1;
  10597. buf[0] = '<';
  10598. } else {
  10599. /* No Tag */
  10600. /* Add data to buffer */
  10601. buf[len++] = (char)(ch & 0xff);
  10602. /* Flush if buffer is full */
  10603. if (len == (int)sizeof(buf)) {
  10604. mg_write(conn, buf, (size_t)len);
  10605. len = 0;
  10606. }
  10607. }
  10608. }
  10609. }
  10610. /* Send the rest of buffered data */
  10611. if (len > 0) {
  10612. mg_write(conn, buf, (size_t)len);
  10613. }
  10614. }
  10615. static void
  10616. handle_ssi_file_request(struct mg_connection *conn,
  10617. const char *path,
  10618. struct mg_file *filep)
  10619. {
  10620. char date[64];
  10621. time_t curtime = time(NULL);
  10622. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10623. return;
  10624. }
  10625. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10626. /* File exists (precondition for calling this function),
  10627. * but can not be opened by the server. */
  10628. mg_send_http_error(conn,
  10629. 500,
  10630. "Error: Cannot read file\nfopen(%s): %s",
  10631. path,
  10632. strerror(ERRNO));
  10633. } else {
  10634. /* Set "must_close" for HTTP/1.x, since we do not know the
  10635. * content length */
  10636. conn->must_close = 1;
  10637. gmt_time_string(date, sizeof(date), &curtime);
  10638. fclose_on_exec(&filep->access, conn);
  10639. /* 200 OK response */
  10640. mg_response_header_start(conn, 200);
  10641. send_no_cache_header(conn);
  10642. send_additional_header(conn);
  10643. send_cors_header(conn);
  10644. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10645. mg_response_header_send(conn);
  10646. /* Header sent, now send body */
  10647. send_ssi_file(conn, path, filep, 0);
  10648. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10649. }
  10650. }
  10651. #endif /* NO_FILESYSTEMS */
  10652. #if !defined(NO_FILES)
  10653. static void
  10654. send_options(struct mg_connection *conn)
  10655. {
  10656. int i;
  10657. char methods[256] = {0};
  10658. if (!conn) {
  10659. return;
  10660. }
  10661. /* We do not set a "Cache-Control" header here, but leave the default.
  10662. * Since browsers do not send an OPTIONS request, we can not test the
  10663. * effect anyway. */
  10664. mg_response_header_start(conn, 200);
  10665. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10666. for (i = 0; http_methods[i].name != NULL; i++) {
  10667. if (i > 0) {
  10668. strcat(methods, ", ");
  10669. strcat(methods, http_methods[i].name);
  10670. } else {
  10671. strcpy(methods, http_methods[i].name);
  10672. }
  10673. }
  10674. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10675. /* Use the same as before */
  10676. mg_response_header_add(conn, "Allow", methods, -1);
  10677. mg_response_header_add(conn, "DAV", "1", -1);
  10678. } else {
  10679. /* TODO: Check this later for HTTP/2 */
  10680. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10681. }
  10682. send_additional_header(conn);
  10683. mg_response_header_send(conn);
  10684. }
  10685. /* Writes PROPFIND properties for a collection element */
  10686. static int
  10687. print_props(struct mg_connection *conn,
  10688. const char *uri,
  10689. const char *name,
  10690. struct mg_file_stat *filep)
  10691. {
  10692. size_t href_size, i, j;
  10693. int len;
  10694. char *href, mtime[64];
  10695. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10696. return 0;
  10697. }
  10698. /* Estimate worst case size for encoding */
  10699. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10700. href = (char *)mg_malloc(href_size);
  10701. if (href == NULL) {
  10702. return 0;
  10703. }
  10704. len = mg_url_encode(uri, href, href_size);
  10705. if (len >= 0) {
  10706. /* Append an extra string */
  10707. mg_url_encode(name, href + len, href_size - (size_t)len);
  10708. }
  10709. /* Directory separator should be preserved. */
  10710. for (i = j = 0; href[i]; j++) {
  10711. if (!strncmp(href + i, "%2f", 3)) {
  10712. href[j] = '/';
  10713. i += 3;
  10714. } else {
  10715. href[j] = href[i++];
  10716. }
  10717. }
  10718. href[j] = '\0';
  10719. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10720. mg_printf(conn,
  10721. "<d:response>"
  10722. "<d:href>%s</d:href>"
  10723. "<d:propstat>"
  10724. "<d:prop>"
  10725. "<d:resourcetype>%s</d:resourcetype>"
  10726. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10727. "<d:getlastmodified>%s</d:getlastmodified>"
  10728. "</d:prop>"
  10729. "<d:status>HTTP/1.1 200 OK</d:status>"
  10730. "</d:propstat>"
  10731. "</d:response>\n",
  10732. href,
  10733. filep->is_directory ? "<d:collection/>" : "",
  10734. filep->size,
  10735. mtime);
  10736. mg_free(href);
  10737. return 1;
  10738. }
  10739. static int
  10740. print_dav_dir_entry(struct de *de, void *data)
  10741. {
  10742. struct mg_connection *conn = (struct mg_connection *)data;
  10743. if (!de || !conn
  10744. || !print_props(
  10745. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10746. /* stop scan */
  10747. return 1;
  10748. }
  10749. return 0;
  10750. }
  10751. static void
  10752. handle_propfind(struct mg_connection *conn,
  10753. const char *path,
  10754. struct mg_file_stat *filep)
  10755. {
  10756. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10757. const char *depth = mg_get_header(conn, "Depth");
  10758. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10759. int i;
  10760. if (!conn || !path || !filep || !conn->dom_ctx) {
  10761. return;
  10762. }
  10763. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10764. /* return 207 "Multi-Status" */
  10765. conn->must_close = 1;
  10766. mg_response_header_start(conn, 207);
  10767. send_static_cache_header(conn);
  10768. send_additional_header(conn);
  10769. mg_response_header_add(conn,
  10770. "Content-Type",
  10771. "application/xml; charset=utf-8",
  10772. -1);
  10773. mg_response_header_send(conn);
  10774. /* Content */
  10775. mg_printf(conn,
  10776. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10777. "<d:multistatus xmlns:d='DAV:'>\n");
  10778. /* Print properties for the requested resource itself */
  10779. print_props(conn, conn->request_info.local_uri, "", filep);
  10780. /* If it is a directory, print directory entries too if Depth is not 0
  10781. */
  10782. if (filep->is_directory
  10783. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10784. "yes")
  10785. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10786. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10787. }
  10788. /* add lock discovery data */
  10789. if (!filep->is_directory) {
  10790. /* Lock information*/
  10791. mg_printf(conn,
  10792. "<d:response>"
  10793. "<d:href>%s</d:href>"
  10794. "<d:propstat>"
  10795. "<d:prop>"
  10796. "<d:lockdiscovery>\n",
  10797. link_buf);
  10798. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10799. if (!strcmp(dav_lock[i].path, link_buf)) {
  10800. mg_printf(conn,
  10801. "<d:activelock>"
  10802. "<d:locktype><d:write/></d:locktype>"
  10803. "<d:lockscope><d:exclusive/></d:lockscope>"
  10804. "<d:depth>0</d:depth>"
  10805. "<d:owner>%s</d:owner>"
  10806. "<d:timeout>Second-%u</d:timeout>"
  10807. "<d:locktoken>"
  10808. "<d:href>%s</d:href>"
  10809. "</d:locktoken>"
  10810. "</d:activelock>\n",
  10811. dav_lock[i].user,
  10812. (unsigned)LOCK_DURATION_S,
  10813. dav_lock[i].token);
  10814. }
  10815. }
  10816. mg_printf(conn,
  10817. "</d:lockdiscovery>"
  10818. "</d:prop>"
  10819. "<d:status>HTTP/1.1 200 OK</d:status>"
  10820. "</d:propstat>"
  10821. "</d:response>\n");
  10822. }
  10823. mg_printf(conn, "%s\n", "</d:multistatus>");
  10824. }
  10825. static void
  10826. dav_lock_file(struct mg_connection *conn, const char *path)
  10827. {
  10828. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10829. uint64_t new_locktime;
  10830. int lock_index = -1;
  10831. int i;
  10832. uint64_t LOCK_DURATION_NS =
  10833. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  10834. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10835. if (!conn || !path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10836. return;
  10837. }
  10838. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10839. /* const char *refresh = mg_get_header(conn, "If"); */
  10840. /* Link refresh should have an "If" header:
  10841. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  10842. * But it seems Windows Explorer does not send them.
  10843. */
  10844. mg_lock_context(conn->phys_ctx);
  10845. new_locktime = mg_get_current_time_ns();
  10846. /* Find a slot for a lock */
  10847. while (lock_index < 0) {
  10848. /* find existing lock */
  10849. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10850. if (!strcmp(dav_lock[i].path, link_buf)) {
  10851. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  10852. /* locked by the same user */
  10853. dav_lock[i].locktime = new_locktime;
  10854. lock_index = i;
  10855. break;
  10856. } else {
  10857. /* already locked by someone else */
  10858. if (new_locktime
  10859. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  10860. /* Lock expired */
  10861. dav_lock[i].path[0] = 0;
  10862. } else {
  10863. /* Lock still valid */
  10864. mg_unlock_context(conn->phys_ctx);
  10865. mg_send_http_error(conn, 423, "%s", "Already locked");
  10866. return;
  10867. }
  10868. }
  10869. }
  10870. }
  10871. /* create new lock token */
  10872. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  10873. if (dav_lock[i].path[0] == 0) {
  10874. char s[32];
  10875. dav_lock[i].locktime = mg_get_current_time_ns();
  10876. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  10877. mg_md5(dav_lock[i].token,
  10878. link_buf,
  10879. "\x01",
  10880. s,
  10881. "\x01",
  10882. conn->request_info.remote_user,
  10883. NULL);
  10884. strncpy(dav_lock[i].path,
  10885. link_buf,
  10886. sizeof(dav_lock[i].path) - 1);
  10887. strncpy(dav_lock[i].user,
  10888. conn->request_info.remote_user,
  10889. sizeof(dav_lock[i].user) - 1);
  10890. lock_index = i;
  10891. break;
  10892. }
  10893. }
  10894. if (lock_index < 0) {
  10895. /* too many locks. Find oldest lock */
  10896. uint64_t oldest_locktime = dav_lock[0].locktime;
  10897. lock_index = 0;
  10898. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  10899. if (dav_lock[i].locktime < oldest_locktime) {
  10900. oldest_locktime = dav_lock[i].locktime;
  10901. lock_index = i;
  10902. }
  10903. }
  10904. /* invalidate oldest lock */
  10905. dav_lock[lock_index].path[0] = 0;
  10906. }
  10907. }
  10908. mg_unlock_context(conn->phys_ctx);
  10909. /* return 200 "OK" */
  10910. conn->must_close = 1;
  10911. mg_response_header_start(conn, 200);
  10912. send_static_cache_header(conn);
  10913. send_additional_header(conn);
  10914. mg_response_header_add(conn,
  10915. "Content-Type",
  10916. "application/xml; charset=utf-8",
  10917. -1);
  10918. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  10919. mg_response_header_send(conn);
  10920. /* Content */
  10921. mg_printf(conn,
  10922. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10923. "<d:prop xmlns:d=\"DAV:\">\n"
  10924. " <d:lockdiscovery>\n"
  10925. " <d:activelock>\n"
  10926. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  10927. " <d:locktype><d:write/></d:locktype>\n"
  10928. " <d:owner>\n"
  10929. " <d:href>%s</d:href>\n"
  10930. " </d:owner>\n"
  10931. " <d:timeout>Second-%u</d:timeout>\n"
  10932. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  10933. " <d:lockroot>\n"
  10934. " <d:href>%s</d:href>\n"
  10935. " </d:lockroot>\n"
  10936. " </d:activelock>\n"
  10937. " </d:lockdiscovery>\n"
  10938. " </d:prop>\n",
  10939. dav_lock[lock_index].user,
  10940. (LOCK_DURATION_S),
  10941. dav_lock[lock_index].token,
  10942. dav_lock[lock_index].path);
  10943. }
  10944. static void
  10945. dav_unlock_file(struct mg_connection *conn, const char *path)
  10946. {
  10947. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10948. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  10949. int lock_index;
  10950. if (!conn || !path || !conn->dom_ctx || !conn->request_info.remote_user) {
  10951. return;
  10952. }
  10953. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10954. mg_lock_context(conn->phys_ctx);
  10955. /* find existing lock */
  10956. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  10957. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  10958. /* Success: return 204 "No Content" */
  10959. mg_unlock_context(conn->phys_ctx);
  10960. conn->must_close = 1;
  10961. mg_response_header_start(conn, 204);
  10962. mg_response_header_send(conn);
  10963. return;
  10964. }
  10965. }
  10966. mg_unlock_context(conn->phys_ctx);
  10967. /* Error: Cannot unlock a resource that is not locked */
  10968. mg_send_http_error(conn, 423, "%s", "Lock not found");
  10969. }
  10970. static void
  10971. dav_proppatch(struct mg_connection *conn, const char *path)
  10972. {
  10973. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  10974. if (!conn || !path || !conn->dom_ctx) {
  10975. return;
  10976. }
  10977. /* return 207 "Multi-Status" */
  10978. conn->must_close = 1;
  10979. mg_response_header_start(conn, 207);
  10980. send_static_cache_header(conn);
  10981. send_additional_header(conn);
  10982. mg_response_header_add(conn,
  10983. "Content-Type",
  10984. "application/xml; charset=utf-8",
  10985. -1);
  10986. mg_response_header_send(conn);
  10987. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  10988. /* Content */
  10989. mg_printf(conn,
  10990. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10991. "<d:multistatus xmlns:d='DAV:'>\n"
  10992. "<d:response>\n<d:href>%s</d:href>\n",
  10993. link_buf);
  10994. mg_printf(conn,
  10995. "<d:propstat><d:status>HTTP/1.1 403 "
  10996. "Forbidden</d:status></d:propstat>\n");
  10997. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  10998. }
  10999. #endif
  11000. void
  11001. mg_lock_connection(struct mg_connection *conn)
  11002. {
  11003. if (conn) {
  11004. (void)pthread_mutex_lock(&conn->mutex);
  11005. }
  11006. }
  11007. void
  11008. mg_unlock_connection(struct mg_connection *conn)
  11009. {
  11010. if (conn) {
  11011. (void)pthread_mutex_unlock(&conn->mutex);
  11012. }
  11013. }
  11014. void
  11015. mg_lock_context(struct mg_context *ctx)
  11016. {
  11017. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11018. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11019. }
  11020. }
  11021. void
  11022. mg_unlock_context(struct mg_context *ctx)
  11023. {
  11024. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11025. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11026. }
  11027. }
  11028. #if defined(USE_LUA)
  11029. #include "mod_lua.inl"
  11030. #endif /* USE_LUA */
  11031. #if defined(USE_DUKTAPE)
  11032. #include "mod_duktape.inl"
  11033. #endif /* USE_DUKTAPE */
  11034. #if defined(USE_WEBSOCKET)
  11035. #if !defined(NO_SSL_DL)
  11036. #define SHA_API static
  11037. #include "sha1.inl"
  11038. #endif
  11039. static int
  11040. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11041. {
  11042. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11043. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11044. size_t dst_len = sizeof(b64_sha);
  11045. SHA_CTX sha_ctx;
  11046. int truncated;
  11047. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11048. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11049. if (truncated) {
  11050. conn->must_close = 1;
  11051. return 0;
  11052. }
  11053. DEBUG_TRACE("%s", "Send websocket handshake");
  11054. SHA1_Init(&sha_ctx);
  11055. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11056. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11057. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11058. mg_printf(conn,
  11059. "HTTP/1.1 101 Switching Protocols\r\n"
  11060. "Upgrade: websocket\r\n"
  11061. "Connection: Upgrade\r\n"
  11062. "Sec-WebSocket-Accept: %s\r\n",
  11063. b64_sha);
  11064. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11065. // Send negotiated compression extension parameters
  11066. websocket_deflate_response(conn);
  11067. #endif
  11068. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11069. mg_printf(conn,
  11070. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11071. conn->request_info.acceptedWebSocketSubprotocol);
  11072. } else {
  11073. mg_printf(conn, "%s", "\r\n");
  11074. }
  11075. return 1;
  11076. }
  11077. #if !defined(MG_MAX_UNANSWERED_PING)
  11078. /* Configuration of the maximum number of websocket PINGs that might
  11079. * stay unanswered before the connection is considered broken.
  11080. * Note: The name of this define may still change (until it is
  11081. * defined as a compile parameter in a documentation).
  11082. */
  11083. #define MG_MAX_UNANSWERED_PING (5)
  11084. #endif
  11085. static void
  11086. read_websocket(struct mg_connection *conn,
  11087. mg_websocket_data_handler ws_data_handler,
  11088. void *callback_data)
  11089. {
  11090. /* Pointer to the beginning of the portion of the incoming websocket
  11091. * message queue.
  11092. * The original websocket upgrade request is never removed, so the queue
  11093. * begins after it. */
  11094. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11095. int n, error, exit_by_callback;
  11096. int ret;
  11097. /* body_len is the length of the entire queue in bytes
  11098. * len is the length of the current message
  11099. * data_len is the length of the current message's data payload
  11100. * header_len is the length of the current message's header */
  11101. size_t i, len, mask_len = 0, header_len, body_len;
  11102. uint64_t data_len = 0;
  11103. /* "The masking key is a 32-bit value chosen at random by the client."
  11104. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11105. */
  11106. unsigned char mask[4];
  11107. /* data points to the place where the message is stored when passed to
  11108. * the websocket_data callback. This is either mem on the stack, or a
  11109. * dynamically allocated buffer if it is too large. */
  11110. unsigned char mem[4096];
  11111. unsigned char mop; /* mask flag and opcode */
  11112. /* Variables used for connection monitoring */
  11113. double timeout = -1.0;
  11114. int enable_ping_pong = 0;
  11115. int ping_count = 0;
  11116. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11117. enable_ping_pong =
  11118. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11119. "yes");
  11120. }
  11121. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11122. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11123. }
  11124. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11125. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11126. }
  11127. if (timeout <= 0.0) {
  11128. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11129. }
  11130. /* Enter data processing loop */
  11131. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11132. conn->request_info.remote_addr,
  11133. conn->request_info.remote_port);
  11134. conn->in_websocket_handling = 1;
  11135. mg_set_thread_name("wsock");
  11136. /* Loop continuously, reading messages from the socket, invoking the
  11137. * callback, and waiting repeatedly until an error occurs. */
  11138. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11139. && (!conn->must_close)) {
  11140. header_len = 0;
  11141. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11142. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11143. len = buf[1] & 127;
  11144. mask_len = (buf[1] & 128) ? 4 : 0;
  11145. if ((len < 126) && (body_len >= mask_len)) {
  11146. /* inline 7-bit length field */
  11147. data_len = len;
  11148. header_len = 2 + mask_len;
  11149. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11150. /* 16-bit length field */
  11151. header_len = 4 + mask_len;
  11152. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11153. } else if (body_len >= (10 + mask_len)) {
  11154. /* 64-bit length field */
  11155. uint32_t l1, l2;
  11156. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11157. memcpy(&l2, &buf[6], 4);
  11158. header_len = 10 + mask_len;
  11159. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11160. if (data_len > (uint64_t)0x7FFF0000ul) {
  11161. /* no can do */
  11162. mg_cry_internal(
  11163. conn,
  11164. "%s",
  11165. "websocket out of memory; closing connection");
  11166. break;
  11167. }
  11168. }
  11169. }
  11170. if ((header_len > 0) && (body_len >= header_len)) {
  11171. /* Allocate space to hold websocket payload */
  11172. unsigned char *data = mem;
  11173. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11174. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11175. conn->phys_ctx);
  11176. if (data == NULL) {
  11177. /* Allocation failed, exit the loop and then close the
  11178. * connection */
  11179. mg_cry_internal(
  11180. conn,
  11181. "%s",
  11182. "websocket out of memory; closing connection");
  11183. break;
  11184. }
  11185. }
  11186. /* Copy the mask before we shift the queue and destroy it */
  11187. if (mask_len > 0) {
  11188. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11189. } else {
  11190. memset(mask, 0, sizeof(mask));
  11191. }
  11192. /* Read frame payload from the first message in the queue into
  11193. * data and advance the queue by moving the memory in place. */
  11194. DEBUG_ASSERT(body_len >= header_len);
  11195. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11196. mop = buf[0]; /* current mask and opcode */
  11197. /* Overflow case */
  11198. len = body_len - header_len;
  11199. memcpy(data, buf + header_len, len);
  11200. error = 0;
  11201. while ((uint64_t)len < data_len) {
  11202. n = pull_inner(NULL,
  11203. conn,
  11204. (char *)(data + len),
  11205. (int)(data_len - len),
  11206. timeout);
  11207. if (n <= -2) {
  11208. error = 1;
  11209. break;
  11210. } else if (n > 0) {
  11211. len += (size_t)n;
  11212. } else {
  11213. /* Timeout: should retry */
  11214. /* TODO: retry condition */
  11215. }
  11216. }
  11217. if (error) {
  11218. mg_cry_internal(
  11219. conn,
  11220. "%s",
  11221. "Websocket pull failed; closing connection");
  11222. if (data != mem) {
  11223. mg_free(data);
  11224. }
  11225. break;
  11226. }
  11227. conn->data_len = conn->request_len;
  11228. } else {
  11229. mop = buf[0]; /* current mask and opcode, overwritten by
  11230. * memmove() */
  11231. /* Length of the message being read at the front of the
  11232. * queue. Cast to 31 bit is OK, since we limited
  11233. * data_len before. */
  11234. len = (size_t)data_len + header_len;
  11235. /* Copy the data payload into the data pointer for the
  11236. * callback. Cast to 31 bit is OK, since we
  11237. * limited data_len */
  11238. memcpy(data, buf + header_len, (size_t)data_len);
  11239. /* Move the queue forward len bytes */
  11240. memmove(buf, buf + len, body_len - len);
  11241. /* Mark the queue as advanced */
  11242. conn->data_len -= (int)len;
  11243. }
  11244. /* Apply mask if necessary */
  11245. if (mask_len > 0) {
  11246. for (i = 0; i < (size_t)data_len; i++) {
  11247. data[i] ^= mask[i & 3];
  11248. }
  11249. }
  11250. exit_by_callback = 0;
  11251. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11252. /* filter PONG messages */
  11253. DEBUG_TRACE("PONG from %s:%u",
  11254. conn->request_info.remote_addr,
  11255. conn->request_info.remote_port);
  11256. /* No unanwered PINGs left */
  11257. ping_count = 0;
  11258. } else if (enable_ping_pong
  11259. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11260. /* reply PING messages */
  11261. DEBUG_TRACE("Reply PING from %s:%u",
  11262. conn->request_info.remote_addr,
  11263. conn->request_info.remote_port);
  11264. ret = mg_websocket_write(conn,
  11265. MG_WEBSOCKET_OPCODE_PONG,
  11266. (char *)data,
  11267. (size_t)data_len);
  11268. if (ret <= 0) {
  11269. /* Error: send failed */
  11270. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11271. break;
  11272. }
  11273. } else {
  11274. /* Exit the loop if callback signals to exit (server side),
  11275. * or "connection close" opcode received (client side). */
  11276. if (ws_data_handler != NULL) {
  11277. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11278. if (mop & 0x40) {
  11279. /* Inflate the data received if bit RSV1 is set. */
  11280. if (!conn->websocket_deflate_initialized) {
  11281. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11282. exit_by_callback = 1;
  11283. }
  11284. if (!exit_by_callback) {
  11285. size_t inflate_buf_size_old = 0;
  11286. size_t inflate_buf_size =
  11287. data_len
  11288. * 4; // Initial guess of the inflated message
  11289. // size. We double the memory when needed.
  11290. Bytef *inflated = NULL;
  11291. Bytef *new_mem = NULL;
  11292. conn->websocket_inflate_state.avail_in =
  11293. (uInt)(data_len + 4);
  11294. conn->websocket_inflate_state.next_in = data;
  11295. // Add trailing 0x00 0x00 0xff 0xff bytes
  11296. data[data_len] = '\x00';
  11297. data[data_len + 1] = '\x00';
  11298. data[data_len + 2] = '\xff';
  11299. data[data_len + 3] = '\xff';
  11300. do {
  11301. if (inflate_buf_size_old == 0) {
  11302. new_mem =
  11303. (Bytef *)mg_calloc(inflate_buf_size,
  11304. sizeof(Bytef));
  11305. } else {
  11306. inflate_buf_size *= 2;
  11307. new_mem =
  11308. (Bytef *)mg_realloc(inflated,
  11309. inflate_buf_size);
  11310. }
  11311. if (new_mem == NULL) {
  11312. mg_cry_internal(
  11313. conn,
  11314. "Out of memory: Cannot allocate "
  11315. "inflate buffer of %lu bytes",
  11316. (unsigned long)inflate_buf_size);
  11317. exit_by_callback = 1;
  11318. break;
  11319. }
  11320. inflated = new_mem;
  11321. conn->websocket_inflate_state.avail_out =
  11322. (uInt)(inflate_buf_size
  11323. - inflate_buf_size_old);
  11324. conn->websocket_inflate_state.next_out =
  11325. inflated + inflate_buf_size_old;
  11326. ret = inflate(&conn->websocket_inflate_state,
  11327. Z_SYNC_FLUSH);
  11328. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11329. || ret == Z_MEM_ERROR) {
  11330. mg_cry_internal(
  11331. conn,
  11332. "ZLIB inflate error: %i %s",
  11333. ret,
  11334. (conn->websocket_inflate_state.msg
  11335. ? conn->websocket_inflate_state.msg
  11336. : "<no error message>"));
  11337. exit_by_callback = 1;
  11338. break;
  11339. }
  11340. inflate_buf_size_old = inflate_buf_size;
  11341. } while (conn->websocket_inflate_state.avail_out
  11342. == 0);
  11343. inflate_buf_size -=
  11344. conn->websocket_inflate_state.avail_out;
  11345. if (!ws_data_handler(conn,
  11346. mop,
  11347. (char *)inflated,
  11348. inflate_buf_size,
  11349. callback_data)) {
  11350. exit_by_callback = 1;
  11351. }
  11352. mg_free(inflated);
  11353. }
  11354. } else
  11355. #endif
  11356. if (!ws_data_handler(conn,
  11357. mop,
  11358. (char *)data,
  11359. (size_t)data_len,
  11360. callback_data)) {
  11361. exit_by_callback = 1;
  11362. }
  11363. }
  11364. }
  11365. /* It a buffer has been allocated, free it again */
  11366. if (data != mem) {
  11367. mg_free(data);
  11368. }
  11369. if (exit_by_callback) {
  11370. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11371. conn->request_info.remote_addr,
  11372. conn->request_info.remote_port);
  11373. break;
  11374. }
  11375. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11376. /* Opcode == 8, connection close */
  11377. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11378. conn->request_info.remote_addr,
  11379. conn->request_info.remote_port);
  11380. break;
  11381. }
  11382. /* Not breaking the loop, process next websocket frame. */
  11383. } else {
  11384. /* Read from the socket into the next available location in the
  11385. * message queue. */
  11386. n = pull_inner(NULL,
  11387. conn,
  11388. conn->buf + conn->data_len,
  11389. conn->buf_size - conn->data_len,
  11390. timeout);
  11391. if (n <= -2) {
  11392. /* Error, no bytes read */
  11393. DEBUG_TRACE("PULL from %s:%u failed",
  11394. conn->request_info.remote_addr,
  11395. conn->request_info.remote_port);
  11396. break;
  11397. }
  11398. if (n > 0) {
  11399. conn->data_len += n;
  11400. /* Reset open PING count */
  11401. ping_count = 0;
  11402. } else {
  11403. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11404. && (!conn->must_close)) {
  11405. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11406. /* Stop sending PING */
  11407. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11408. "- closing connection",
  11409. ping_count,
  11410. conn->request_info.remote_addr,
  11411. conn->request_info.remote_port);
  11412. break;
  11413. }
  11414. if (enable_ping_pong) {
  11415. /* Send Websocket PING message */
  11416. DEBUG_TRACE("PING to %s:%u",
  11417. conn->request_info.remote_addr,
  11418. conn->request_info.remote_port);
  11419. ret = mg_websocket_write(conn,
  11420. MG_WEBSOCKET_OPCODE_PING,
  11421. NULL,
  11422. 0);
  11423. if (ret <= 0) {
  11424. /* Error: send failed */
  11425. DEBUG_TRACE("Send PING failed (%i)", ret);
  11426. break;
  11427. }
  11428. ping_count++;
  11429. }
  11430. }
  11431. /* Timeout: should retry */
  11432. /* TODO: get timeout def */
  11433. }
  11434. }
  11435. }
  11436. /* Leave data processing loop */
  11437. mg_set_thread_name("worker");
  11438. conn->in_websocket_handling = 0;
  11439. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11440. conn->request_info.remote_addr,
  11441. conn->request_info.remote_port);
  11442. }
  11443. static int
  11444. mg_websocket_write_exec(struct mg_connection *conn,
  11445. int opcode,
  11446. const char *data,
  11447. size_t dataLen,
  11448. uint32_t masking_key)
  11449. {
  11450. unsigned char header[14];
  11451. size_t headerLen;
  11452. int retval;
  11453. #if defined(GCC_DIAGNOSTIC)
  11454. /* Disable spurious conversion warning for GCC */
  11455. #pragma GCC diagnostic push
  11456. #pragma GCC diagnostic ignored "-Wconversion"
  11457. #endif
  11458. /* Note that POSIX/Winsock's send() is threadsafe
  11459. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11460. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11461. * push(), although that is only a problem if the packet is large or
  11462. * outgoing buffer is full). */
  11463. /* TODO: Check if this lock should be moved to user land.
  11464. * Currently the server sets this lock for websockets, but
  11465. * not for any other connection. It must be set for every
  11466. * conn read/written by more than one thread, no matter if
  11467. * it is a websocket or regular connection. */
  11468. (void)mg_lock_connection(conn);
  11469. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11470. size_t deflated_size = 0;
  11471. Bytef *deflated = 0;
  11472. // Deflate websocket messages over 100kb
  11473. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11474. if (use_deflate) {
  11475. if (!conn->websocket_deflate_initialized) {
  11476. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11477. return 0;
  11478. }
  11479. // Deflating the message
  11480. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11481. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11482. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11483. deflated_size = (Bytef *)compressBound((uLong)dataLen);
  11484. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11485. if (deflated == NULL) {
  11486. mg_cry_internal(
  11487. conn,
  11488. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11489. (unsigned long)deflated_size);
  11490. mg_unlock_connection(conn);
  11491. return -1;
  11492. }
  11493. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11494. conn->websocket_deflate_state.next_out = deflated;
  11495. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11496. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11497. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11498. } else
  11499. #endif
  11500. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11501. #if defined(GCC_DIAGNOSTIC)
  11502. #pragma GCC diagnostic pop
  11503. #endif
  11504. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11505. if (dataLen < 126) {
  11506. /* inline 7-bit length field */
  11507. header[1] = (unsigned char)dataLen;
  11508. headerLen = 2;
  11509. } else if (dataLen <= 0xFFFF) {
  11510. /* 16-bit length field */
  11511. uint16_t len = htons((uint16_t)dataLen);
  11512. header[1] = 126;
  11513. memcpy(header + 2, &len, 2);
  11514. headerLen = 4;
  11515. } else {
  11516. /* 64-bit length field */
  11517. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11518. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11519. header[1] = 127;
  11520. memcpy(header + 2, &len1, 4);
  11521. memcpy(header + 6, &len2, 4);
  11522. headerLen = 10;
  11523. }
  11524. if (masking_key) {
  11525. /* add mask */
  11526. header[1] |= 0x80;
  11527. memcpy(header + headerLen, &masking_key, 4);
  11528. headerLen += 4;
  11529. }
  11530. retval = mg_write(conn, header, headerLen);
  11531. if (retval != (int)headerLen) {
  11532. /* Did not send complete header */
  11533. retval = -1;
  11534. } else {
  11535. if (dataLen > 0) {
  11536. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11537. if (use_deflate) {
  11538. retval = mg_write(conn, deflated, dataLen);
  11539. mg_free(deflated);
  11540. } else
  11541. #endif
  11542. retval = mg_write(conn, data, dataLen);
  11543. }
  11544. /* if dataLen == 0, the header length (2) is returned */
  11545. }
  11546. /* TODO: Remove this unlock as well, when lock is removed. */
  11547. mg_unlock_connection(conn);
  11548. return retval;
  11549. }
  11550. int
  11551. mg_websocket_write(struct mg_connection *conn,
  11552. int opcode,
  11553. const char *data,
  11554. size_t dataLen)
  11555. {
  11556. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11557. }
  11558. static void
  11559. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11560. {
  11561. size_t i = 0;
  11562. i = 0;
  11563. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11564. /* Convert in 32 bit words, if data is 4 byte aligned */
  11565. while (i < (in_len - 3)) {
  11566. *(uint32_t *)(void *)(out + i) =
  11567. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11568. i += 4;
  11569. }
  11570. }
  11571. if (i != in_len) {
  11572. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11573. while (i < in_len) {
  11574. *(uint8_t *)(void *)(out + i) =
  11575. *(uint8_t *)(void *)(in + i)
  11576. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11577. i++;
  11578. }
  11579. }
  11580. }
  11581. int
  11582. mg_websocket_client_write(struct mg_connection *conn,
  11583. int opcode,
  11584. const char *data,
  11585. size_t dataLen)
  11586. {
  11587. int retval = -1;
  11588. char *masked_data =
  11589. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11590. uint32_t masking_key = 0;
  11591. if (masked_data == NULL) {
  11592. /* Return -1 in an error case */
  11593. mg_cry_internal(conn,
  11594. "%s",
  11595. "Cannot allocate buffer for masked websocket response: "
  11596. "Out of memory");
  11597. return -1;
  11598. }
  11599. do {
  11600. /* Get a masking key - but not 0 */
  11601. masking_key = (uint32_t)get_random();
  11602. } while (masking_key == 0);
  11603. mask_data(data, dataLen, masking_key, masked_data);
  11604. retval = mg_websocket_write_exec(
  11605. conn, opcode, masked_data, dataLen, masking_key);
  11606. mg_free(masked_data);
  11607. return retval;
  11608. }
  11609. static void
  11610. handle_websocket_request(struct mg_connection *conn,
  11611. const char *path,
  11612. int is_callback_resource,
  11613. struct mg_websocket_subprotocols *subprotocols,
  11614. mg_websocket_connect_handler ws_connect_handler,
  11615. mg_websocket_ready_handler ws_ready_handler,
  11616. mg_websocket_data_handler ws_data_handler,
  11617. mg_websocket_close_handler ws_close_handler,
  11618. void *cbData)
  11619. {
  11620. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11621. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11622. ptrdiff_t lua_websock = 0;
  11623. #if !defined(USE_LUA)
  11624. (void)path;
  11625. #endif
  11626. /* Step 1: Check websocket protocol version. */
  11627. /* Step 1.1: Check Sec-WebSocket-Key. */
  11628. if (!websock_key) {
  11629. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11630. * requires a Sec-WebSocket-Key header.
  11631. */
  11632. /* It could be the hixie draft version
  11633. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11634. */
  11635. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11636. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11637. char key3[8];
  11638. if ((key1 != NULL) && (key2 != NULL)) {
  11639. /* This version uses 8 byte body data in a GET request */
  11640. conn->content_len = 8;
  11641. if (8 == mg_read(conn, key3, 8)) {
  11642. /* This is the hixie version */
  11643. mg_send_http_error(conn,
  11644. 426,
  11645. "%s",
  11646. "Protocol upgrade to RFC 6455 required");
  11647. return;
  11648. }
  11649. }
  11650. /* This is an unknown version */
  11651. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11652. return;
  11653. }
  11654. /* Step 1.2: Check websocket protocol version. */
  11655. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11656. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11657. /* Reject wrong versions */
  11658. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11659. return;
  11660. }
  11661. /* Step 1.3: Could check for "Host", but we do not really nead this
  11662. * value for anything, so just ignore it. */
  11663. /* Step 2: If a callback is responsible, call it. */
  11664. if (is_callback_resource) {
  11665. /* Step 2.1 check and select subprotocol */
  11666. const char *protocols[64]; // max 64 headers
  11667. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11668. "Sec-WebSocket-Protocol",
  11669. protocols,
  11670. 64);
  11671. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11672. int headerNo, idx;
  11673. size_t len;
  11674. const char *sep, *curSubProtocol,
  11675. *acceptedWebSocketSubprotocol = NULL;
  11676. /* look for matching subprotocol */
  11677. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11678. /* There might be multiple headers ... */
  11679. const char *protocol = protocols[headerNo];
  11680. curSubProtocol = protocol;
  11681. /* ... and in every header there might be a , separated list */
  11682. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11683. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11684. curSubProtocol++;
  11685. sep = strchr(curSubProtocol, ',');
  11686. if (sep) {
  11687. len = (size_t)(sep - curSubProtocol);
  11688. } else {
  11689. len = strlen(curSubProtocol);
  11690. }
  11691. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11692. // COMPARE: curSubProtocol ==
  11693. // subprotocols->subprotocols[idx]
  11694. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11695. && (strncmp(curSubProtocol,
  11696. subprotocols->subprotocols[idx],
  11697. len)
  11698. == 0)) {
  11699. acceptedWebSocketSubprotocol =
  11700. subprotocols->subprotocols[idx];
  11701. break;
  11702. }
  11703. }
  11704. curSubProtocol += len;
  11705. }
  11706. }
  11707. conn->request_info.acceptedWebSocketSubprotocol =
  11708. acceptedWebSocketSubprotocol;
  11709. }
  11710. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11711. websocket_deflate_negotiate(conn);
  11712. #endif
  11713. if ((ws_connect_handler != NULL)
  11714. && (ws_connect_handler(conn, cbData) != 0)) {
  11715. /* C callback has returned non-zero, do not proceed with
  11716. * handshake.
  11717. */
  11718. /* Note that C callbacks are no longer called when Lua is
  11719. * responsible, so C can no longer filter callbacks for Lua. */
  11720. return;
  11721. }
  11722. }
  11723. #if defined(USE_LUA)
  11724. /* Step 3: No callback. Check if Lua is responsible. */
  11725. else {
  11726. /* Step 3.1: Check if Lua is responsible. */
  11727. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11728. lua_websock = match_prefix_strlen(
  11729. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11730. }
  11731. if (lua_websock) {
  11732. /* Step 3.2: Lua is responsible: call it. */
  11733. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11734. if (!conn->lua_websocket_state) {
  11735. /* Lua rejected the new client */
  11736. return;
  11737. }
  11738. }
  11739. }
  11740. #endif
  11741. /* Step 4: Check if there is a responsible websocket handler. */
  11742. if (!is_callback_resource && !lua_websock) {
  11743. /* There is no callback, and Lua is not responsible either. */
  11744. /* Reply with a 404 Not Found. We are still at a standard
  11745. * HTTP request here, before the websocket handshake, so
  11746. * we can still send standard HTTP error replies. */
  11747. mg_send_http_error(conn, 404, "%s", "Not found");
  11748. return;
  11749. }
  11750. /* Step 5: The websocket connection has been accepted */
  11751. if (!send_websocket_handshake(conn, websock_key)) {
  11752. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11753. return;
  11754. }
  11755. /* Step 6: Call the ready handler */
  11756. if (is_callback_resource) {
  11757. if (ws_ready_handler != NULL) {
  11758. ws_ready_handler(conn, cbData);
  11759. }
  11760. #if defined(USE_LUA)
  11761. } else if (lua_websock) {
  11762. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11763. /* the ready handler returned false */
  11764. return;
  11765. }
  11766. #endif
  11767. }
  11768. /* Step 7: Enter the read loop */
  11769. if (is_callback_resource) {
  11770. read_websocket(conn, ws_data_handler, cbData);
  11771. #if defined(USE_LUA)
  11772. } else if (lua_websock) {
  11773. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11774. #endif
  11775. }
  11776. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11777. /* Step 8: Close the deflate & inflate buffers */
  11778. if (conn->websocket_deflate_initialized) {
  11779. deflateEnd(&conn->websocket_deflate_state);
  11780. inflateEnd(&conn->websocket_inflate_state);
  11781. }
  11782. #endif
  11783. /* Step 9: Call the close handler */
  11784. if (ws_close_handler) {
  11785. ws_close_handler(conn, cbData);
  11786. }
  11787. }
  11788. #endif /* !USE_WEBSOCKET */
  11789. /* Is upgrade request:
  11790. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11791. * 1 = upgrade to websocket
  11792. * 2 = upgrade to HTTP/2
  11793. * -1 = upgrade to unknown protocol
  11794. */
  11795. static int
  11796. should_switch_to_protocol(const struct mg_connection *conn)
  11797. {
  11798. const char *upgrade, *connection;
  11799. /* A websocket protocoll has the following HTTP headers:
  11800. *
  11801. * Connection: Upgrade
  11802. * Upgrade: Websocket
  11803. */
  11804. connection = mg_get_header(conn, "Connection");
  11805. if (connection == NULL) {
  11806. return PROTOCOL_TYPE_HTTP1;
  11807. }
  11808. if (!mg_strcasestr(connection, "upgrade")) {
  11809. return PROTOCOL_TYPE_HTTP1;
  11810. }
  11811. upgrade = mg_get_header(conn, "Upgrade");
  11812. if (upgrade == NULL) {
  11813. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11814. return -1;
  11815. }
  11816. /* Upgrade to ... */
  11817. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11818. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11819. * "Sec-WebSocket-Version" are also required.
  11820. * Don't check them here, since even an unsupported websocket protocol
  11821. * request still IS a websocket request (in contrast to a standard HTTP
  11822. * request). It will fail later in handle_websocket_request.
  11823. */
  11824. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11825. }
  11826. if (0 != mg_strcasestr(upgrade, "h2")) {
  11827. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11828. }
  11829. /* Upgrade to another protocol */
  11830. return -1;
  11831. }
  11832. static int
  11833. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11834. {
  11835. int n;
  11836. unsigned int a, b, c, d, slash;
  11837. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  11838. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  11839. // integer value, but function will not report conversion
  11840. // errors; consider using 'strtol' instead
  11841. slash = 32;
  11842. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  11843. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  11844. // an integer value, but function will not report conversion
  11845. // errors; consider using 'strtol' instead
  11846. n = 0;
  11847. }
  11848. }
  11849. if ((n > 0) && ((size_t)n == vec->len)) {
  11850. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11851. /* IPv4 format */
  11852. if (sa->sa.sa_family == AF_INET) {
  11853. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  11854. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11855. | ((uint32_t)c << 8) | (uint32_t)d;
  11856. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11857. return (ip & mask) == net;
  11858. }
  11859. return 0;
  11860. }
  11861. }
  11862. #if defined(USE_IPV6)
  11863. else {
  11864. char ad[50];
  11865. const char *p;
  11866. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11867. slash = 128;
  11868. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11869. n = 0;
  11870. }
  11871. }
  11872. if ((n <= 0) && no_strict) {
  11873. /* no square brackets? */
  11874. p = strchr(vec->ptr, '/');
  11875. if (p && (p < (vec->ptr + vec->len))) {
  11876. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11877. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11878. n += (int)(p - vec->ptr);
  11879. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11880. } else {
  11881. n = 0;
  11882. }
  11883. } else if (vec->len < sizeof(ad)) {
  11884. n = (int)vec->len;
  11885. slash = 128;
  11886. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11887. }
  11888. }
  11889. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11890. p = ad;
  11891. c = 0;
  11892. /* zone indexes are unsupported, at least two colons are needed */
  11893. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11894. if (*(p++) == ':') {
  11895. c++;
  11896. }
  11897. }
  11898. if ((*p == '\0') && (c >= 2)) {
  11899. struct sockaddr_in6 sin6;
  11900. unsigned int i;
  11901. /* for strict validation, an actual IPv6 argument is needed */
  11902. if (sa->sa.sa_family != AF_INET6) {
  11903. return 0;
  11904. }
  11905. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11906. /* IPv6 format */
  11907. for (i = 0; i < 16; i++) {
  11908. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11909. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11910. uint8_t mask = 0;
  11911. if (8 * i + 8 < slash) {
  11912. mask = 0xFFu;
  11913. } else if (8 * i < slash) {
  11914. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11915. }
  11916. if ((ip & mask) != net) {
  11917. return 0;
  11918. }
  11919. }
  11920. return 1;
  11921. }
  11922. }
  11923. }
  11924. }
  11925. #else
  11926. (void)no_strict;
  11927. #endif
  11928. /* malformed */
  11929. return -1;
  11930. }
  11931. static int
  11932. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11933. {
  11934. int throttle = 0;
  11935. struct vec vec, val;
  11936. char mult;
  11937. double v;
  11938. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11939. mult = ',';
  11940. if ((val.ptr == NULL)
  11941. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  11942. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  11943. // to an integer value, but function will not report
  11944. // conversion errors; consider using 'strtol' instead
  11945. || (v < 0)
  11946. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11947. && (mult != ','))) {
  11948. continue;
  11949. }
  11950. v *= (lowercase(&mult) == 'k')
  11951. ? 1024
  11952. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11953. if (vec.len == 1 && vec.ptr[0] == '*') {
  11954. throttle = (int)v;
  11955. } else {
  11956. int matched = parse_match_net(&vec, rsa, 0);
  11957. if (matched >= 0) {
  11958. /* a valid IP subnet */
  11959. if (matched) {
  11960. throttle = (int)v;
  11961. }
  11962. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11963. throttle = (int)v;
  11964. }
  11965. }
  11966. }
  11967. return throttle;
  11968. }
  11969. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11970. #include "handle_form.inl"
  11971. static int
  11972. get_first_ssl_listener_index(const struct mg_context *ctx)
  11973. {
  11974. unsigned int i;
  11975. int idx = -1;
  11976. if (ctx) {
  11977. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11978. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11979. }
  11980. }
  11981. return idx;
  11982. }
  11983. /* Return host (without port) */
  11984. static void
  11985. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11986. {
  11987. const char *host_header =
  11988. get_header(ri->http_headers, ri->num_headers, "Host");
  11989. host->ptr = NULL;
  11990. host->len = 0;
  11991. if (host_header != NULL) {
  11992. const char *pos;
  11993. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11994. * is found. */
  11995. if (*host_header == '[') {
  11996. pos = strchr(host_header, ']');
  11997. if (!pos) {
  11998. /* Malformed hostname starts with '[', but no ']' found */
  11999. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12000. return;
  12001. }
  12002. /* terminate after ']' */
  12003. host->ptr = host_header;
  12004. host->len = (size_t)(pos + 1 - host_header);
  12005. } else {
  12006. /* Otherwise, a ':' separates hostname and port number */
  12007. pos = strchr(host_header, ':');
  12008. if (pos != NULL) {
  12009. host->len = (size_t)(pos - host_header);
  12010. } else {
  12011. host->len = strlen(host_header);
  12012. }
  12013. host->ptr = host_header;
  12014. }
  12015. }
  12016. }
  12017. static int
  12018. switch_domain_context(struct mg_connection *conn)
  12019. {
  12020. struct vec host;
  12021. get_host_from_request_info(&host, &conn->request_info);
  12022. if (host.ptr) {
  12023. if (conn->ssl) {
  12024. /* This is a HTTPS connection, maybe we have a hostname
  12025. * from SNI (set in ssl_servername_callback). */
  12026. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12027. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12028. /* We are not using the default domain */
  12029. if ((strlen(sslhost) != host.len)
  12030. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12031. /* Mismatch between SNI domain and HTTP domain */
  12032. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12033. sslhost,
  12034. (int)host.len,
  12035. host.ptr);
  12036. return 0;
  12037. }
  12038. }
  12039. } else {
  12040. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12041. while (dom) {
  12042. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12043. size_t domNameLen = strlen(domName);
  12044. if ((domNameLen == host.len)
  12045. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12046. /* Found matching domain */
  12047. DEBUG_TRACE("HTTP domain %s found",
  12048. dom->config[AUTHENTICATION_DOMAIN]);
  12049. /* TODO: Check if this is a HTTP or HTTPS domain */
  12050. conn->dom_ctx = dom;
  12051. break;
  12052. }
  12053. mg_lock_context(conn->phys_ctx);
  12054. dom = dom->next;
  12055. mg_unlock_context(conn->phys_ctx);
  12056. }
  12057. }
  12058. DEBUG_TRACE("HTTP%s Host: %.*s",
  12059. conn->ssl ? "S" : "",
  12060. (int)host.len,
  12061. host.ptr);
  12062. } else {
  12063. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12064. return 1;
  12065. }
  12066. return 1;
  12067. }
  12068. static void
  12069. redirect_to_https_port(struct mg_connection *conn, int port)
  12070. {
  12071. char target_url[MG_BUF_LEN];
  12072. int truncated = 0;
  12073. const char *expect_proto =
  12074. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12075. /* Use "308 Permanent Redirect" */
  12076. int redirect_code = 308;
  12077. /* In any case, close the current connection */
  12078. conn->must_close = 1;
  12079. /* Send host, port, uri and (if it exists) ?query_string */
  12080. if (mg_construct_local_link(
  12081. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12082. < 0) {
  12083. truncated = 1;
  12084. } else if (conn->request_info.query_string != NULL) {
  12085. size_t slen1 = strlen(target_url);
  12086. size_t slen2 = strlen(conn->request_info.query_string);
  12087. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12088. target_url[slen1] = '?';
  12089. memcpy(target_url + slen1 + 1,
  12090. conn->request_info.query_string,
  12091. slen2);
  12092. target_url[slen1 + slen2 + 1] = 0;
  12093. } else {
  12094. truncated = 1;
  12095. }
  12096. }
  12097. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12098. * is used as buffer size) */
  12099. if (truncated) {
  12100. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12101. return;
  12102. }
  12103. /* Use redirect helper function */
  12104. mg_send_http_redirect(conn, target_url, redirect_code);
  12105. }
  12106. static void
  12107. mg_set_handler_type(struct mg_context *phys_ctx,
  12108. struct mg_domain_context *dom_ctx,
  12109. const char *uri,
  12110. int handler_type,
  12111. int is_delete_request,
  12112. mg_request_handler handler,
  12113. struct mg_websocket_subprotocols *subprotocols,
  12114. mg_websocket_connect_handler connect_handler,
  12115. mg_websocket_ready_handler ready_handler,
  12116. mg_websocket_data_handler data_handler,
  12117. mg_websocket_close_handler close_handler,
  12118. mg_authorization_handler auth_handler,
  12119. void *cbdata)
  12120. {
  12121. struct mg_handler_info *tmp_rh, **lastref;
  12122. size_t urilen = strlen(uri);
  12123. if (handler_type == WEBSOCKET_HANDLER) {
  12124. DEBUG_ASSERT(handler == NULL);
  12125. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12126. || ready_handler != NULL || data_handler != NULL
  12127. || close_handler != NULL);
  12128. DEBUG_ASSERT(auth_handler == NULL);
  12129. if (handler != NULL) {
  12130. return;
  12131. }
  12132. if (!is_delete_request && (connect_handler == NULL)
  12133. && (ready_handler == NULL) && (data_handler == NULL)
  12134. && (close_handler == NULL)) {
  12135. return;
  12136. }
  12137. if (auth_handler != NULL) {
  12138. return;
  12139. }
  12140. } else if (handler_type == REQUEST_HANDLER) {
  12141. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12142. && data_handler == NULL && close_handler == NULL);
  12143. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12144. DEBUG_ASSERT(auth_handler == NULL);
  12145. if ((connect_handler != NULL) || (ready_handler != NULL)
  12146. || (data_handler != NULL) || (close_handler != NULL)) {
  12147. return;
  12148. }
  12149. if (!is_delete_request && (handler == NULL)) {
  12150. return;
  12151. }
  12152. if (auth_handler != NULL) {
  12153. return;
  12154. }
  12155. } else if (handler_type == AUTH_HANDLER) {
  12156. DEBUG_ASSERT(handler == NULL);
  12157. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12158. && data_handler == NULL && close_handler == NULL);
  12159. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12160. if (handler != NULL) {
  12161. return;
  12162. }
  12163. if ((connect_handler != NULL) || (ready_handler != NULL)
  12164. || (data_handler != NULL) || (close_handler != NULL)) {
  12165. return;
  12166. }
  12167. if (!is_delete_request && (auth_handler == NULL)) {
  12168. return;
  12169. }
  12170. } else {
  12171. /* Unknown handler type. */
  12172. return;
  12173. }
  12174. if (!phys_ctx || !dom_ctx) {
  12175. /* no context available */
  12176. return;
  12177. }
  12178. mg_lock_context(phys_ctx);
  12179. /* first try to find an existing handler */
  12180. do {
  12181. lastref = &(dom_ctx->handlers);
  12182. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12183. tmp_rh = tmp_rh->next) {
  12184. if (tmp_rh->handler_type == handler_type
  12185. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12186. if (!is_delete_request) {
  12187. /* update existing handler */
  12188. if (handler_type == REQUEST_HANDLER) {
  12189. /* Wait for end of use before updating */
  12190. if (tmp_rh->refcount) {
  12191. mg_unlock_context(phys_ctx);
  12192. mg_sleep(1);
  12193. mg_lock_context(phys_ctx);
  12194. /* tmp_rh might have been freed, search again. */
  12195. break;
  12196. }
  12197. /* Ok, the handler is no more use -> Update it */
  12198. tmp_rh->handler = handler;
  12199. } else if (handler_type == WEBSOCKET_HANDLER) {
  12200. tmp_rh->subprotocols = subprotocols;
  12201. tmp_rh->connect_handler = connect_handler;
  12202. tmp_rh->ready_handler = ready_handler;
  12203. tmp_rh->data_handler = data_handler;
  12204. tmp_rh->close_handler = close_handler;
  12205. } else { /* AUTH_HANDLER */
  12206. tmp_rh->auth_handler = auth_handler;
  12207. }
  12208. tmp_rh->cbdata = cbdata;
  12209. } else {
  12210. /* remove existing handler */
  12211. if (handler_type == REQUEST_HANDLER) {
  12212. /* Wait for end of use before removing */
  12213. if (tmp_rh->refcount) {
  12214. tmp_rh->removing = 1;
  12215. mg_unlock_context(phys_ctx);
  12216. mg_sleep(1);
  12217. mg_lock_context(phys_ctx);
  12218. /* tmp_rh might have been freed, search again. */
  12219. break;
  12220. }
  12221. /* Ok, the handler is no more used */
  12222. }
  12223. *lastref = tmp_rh->next;
  12224. mg_free(tmp_rh->uri);
  12225. mg_free(tmp_rh);
  12226. }
  12227. mg_unlock_context(phys_ctx);
  12228. return;
  12229. }
  12230. lastref = &(tmp_rh->next);
  12231. }
  12232. } while (tmp_rh != NULL);
  12233. if (is_delete_request) {
  12234. /* no handler to set, this was a remove request to a non-existing
  12235. * handler */
  12236. mg_unlock_context(phys_ctx);
  12237. return;
  12238. }
  12239. tmp_rh =
  12240. (struct mg_handler_info *)mg_calloc_ctx(1,
  12241. sizeof(struct mg_handler_info),
  12242. phys_ctx);
  12243. if (tmp_rh == NULL) {
  12244. mg_unlock_context(phys_ctx);
  12245. mg_cry_ctx_internal(phys_ctx,
  12246. "%s",
  12247. "Cannot create new request handler struct, OOM");
  12248. return;
  12249. }
  12250. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12251. if (!tmp_rh->uri) {
  12252. mg_unlock_context(phys_ctx);
  12253. mg_free(tmp_rh);
  12254. mg_cry_ctx_internal(phys_ctx,
  12255. "%s",
  12256. "Cannot create new request handler struct, OOM");
  12257. return;
  12258. }
  12259. tmp_rh->uri_len = urilen;
  12260. if (handler_type == REQUEST_HANDLER) {
  12261. tmp_rh->refcount = 0;
  12262. tmp_rh->removing = 0;
  12263. tmp_rh->handler = handler;
  12264. } else if (handler_type == WEBSOCKET_HANDLER) {
  12265. tmp_rh->subprotocols = subprotocols;
  12266. tmp_rh->connect_handler = connect_handler;
  12267. tmp_rh->ready_handler = ready_handler;
  12268. tmp_rh->data_handler = data_handler;
  12269. tmp_rh->close_handler = close_handler;
  12270. } else { /* AUTH_HANDLER */
  12271. tmp_rh->auth_handler = auth_handler;
  12272. }
  12273. tmp_rh->cbdata = cbdata;
  12274. tmp_rh->handler_type = handler_type;
  12275. tmp_rh->next = NULL;
  12276. *lastref = tmp_rh;
  12277. mg_unlock_context(phys_ctx);
  12278. }
  12279. void
  12280. mg_set_request_handler(struct mg_context *ctx,
  12281. const char *uri,
  12282. mg_request_handler handler,
  12283. void *cbdata)
  12284. {
  12285. mg_set_handler_type(ctx,
  12286. &(ctx->dd),
  12287. uri,
  12288. REQUEST_HANDLER,
  12289. handler == NULL,
  12290. handler,
  12291. NULL,
  12292. NULL,
  12293. NULL,
  12294. NULL,
  12295. NULL,
  12296. NULL,
  12297. cbdata);
  12298. }
  12299. void
  12300. mg_set_websocket_handler(struct mg_context *ctx,
  12301. const char *uri,
  12302. mg_websocket_connect_handler connect_handler,
  12303. mg_websocket_ready_handler ready_handler,
  12304. mg_websocket_data_handler data_handler,
  12305. mg_websocket_close_handler close_handler,
  12306. void *cbdata)
  12307. {
  12308. mg_set_websocket_handler_with_subprotocols(ctx,
  12309. uri,
  12310. NULL,
  12311. connect_handler,
  12312. ready_handler,
  12313. data_handler,
  12314. close_handler,
  12315. cbdata);
  12316. }
  12317. void
  12318. mg_set_websocket_handler_with_subprotocols(
  12319. struct mg_context *ctx,
  12320. const char *uri,
  12321. struct mg_websocket_subprotocols *subprotocols,
  12322. mg_websocket_connect_handler connect_handler,
  12323. mg_websocket_ready_handler ready_handler,
  12324. mg_websocket_data_handler data_handler,
  12325. mg_websocket_close_handler close_handler,
  12326. void *cbdata)
  12327. {
  12328. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12329. && (data_handler == NULL)
  12330. && (close_handler == NULL);
  12331. mg_set_handler_type(ctx,
  12332. &(ctx->dd),
  12333. uri,
  12334. WEBSOCKET_HANDLER,
  12335. is_delete_request,
  12336. NULL,
  12337. subprotocols,
  12338. connect_handler,
  12339. ready_handler,
  12340. data_handler,
  12341. close_handler,
  12342. NULL,
  12343. cbdata);
  12344. }
  12345. void
  12346. mg_set_auth_handler(struct mg_context *ctx,
  12347. const char *uri,
  12348. mg_authorization_handler handler,
  12349. void *cbdata)
  12350. {
  12351. mg_set_handler_type(ctx,
  12352. &(ctx->dd),
  12353. uri,
  12354. AUTH_HANDLER,
  12355. handler == NULL,
  12356. NULL,
  12357. NULL,
  12358. NULL,
  12359. NULL,
  12360. NULL,
  12361. NULL,
  12362. handler,
  12363. cbdata);
  12364. }
  12365. static int
  12366. get_request_handler(struct mg_connection *conn,
  12367. int handler_type,
  12368. mg_request_handler *handler,
  12369. struct mg_websocket_subprotocols **subprotocols,
  12370. mg_websocket_connect_handler *connect_handler,
  12371. mg_websocket_ready_handler *ready_handler,
  12372. mg_websocket_data_handler *data_handler,
  12373. mg_websocket_close_handler *close_handler,
  12374. mg_authorization_handler *auth_handler,
  12375. void **cbdata,
  12376. struct mg_handler_info **handler_info)
  12377. {
  12378. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12379. if (request_info) {
  12380. const char *uri = request_info->local_uri;
  12381. size_t urilen = strlen(uri);
  12382. struct mg_handler_info *tmp_rh;
  12383. int step, matched;
  12384. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12385. return 0;
  12386. }
  12387. mg_lock_context(conn->phys_ctx);
  12388. for (step = 0; step < 3; step++) {
  12389. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12390. tmp_rh = tmp_rh->next) {
  12391. if (tmp_rh->handler_type != handler_type) {
  12392. continue;
  12393. }
  12394. if (step == 0) {
  12395. /* first try for an exact match */
  12396. matched = (tmp_rh->uri_len == urilen)
  12397. && (strcmp(tmp_rh->uri, uri) == 0);
  12398. } else if (step == 1) {
  12399. /* next try for a partial match, we will accept
  12400. uri/something */
  12401. matched =
  12402. (tmp_rh->uri_len < urilen)
  12403. && (uri[tmp_rh->uri_len] == '/')
  12404. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12405. } else {
  12406. /* finally try for pattern match */
  12407. matched =
  12408. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12409. }
  12410. if (matched) {
  12411. if (handler_type == WEBSOCKET_HANDLER) {
  12412. *subprotocols = tmp_rh->subprotocols;
  12413. *connect_handler = tmp_rh->connect_handler;
  12414. *ready_handler = tmp_rh->ready_handler;
  12415. *data_handler = tmp_rh->data_handler;
  12416. *close_handler = tmp_rh->close_handler;
  12417. } else if (handler_type == REQUEST_HANDLER) {
  12418. if (tmp_rh->removing) {
  12419. /* Treat as none found */
  12420. step = 2;
  12421. break;
  12422. }
  12423. *handler = tmp_rh->handler;
  12424. /* Acquire handler and give it back */
  12425. tmp_rh->refcount++;
  12426. *handler_info = tmp_rh;
  12427. } else { /* AUTH_HANDLER */
  12428. *auth_handler = tmp_rh->auth_handler;
  12429. }
  12430. *cbdata = tmp_rh->cbdata;
  12431. mg_unlock_context(conn->phys_ctx);
  12432. return 1;
  12433. }
  12434. }
  12435. }
  12436. mg_unlock_context(conn->phys_ctx);
  12437. }
  12438. return 0; /* none found */
  12439. }
  12440. /* Check if the script file is in a path, allowed for script files.
  12441. * This can be used if uploading files is possible not only for the server
  12442. * admin, and the upload mechanism does not check the file extension.
  12443. */
  12444. static int
  12445. is_in_script_path(const struct mg_connection *conn, const char *path)
  12446. {
  12447. /* TODO (Feature): Add config value for allowed script path.
  12448. * Default: All allowed. */
  12449. (void)conn;
  12450. (void)path;
  12451. return 1;
  12452. }
  12453. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12454. static int
  12455. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12456. int bits,
  12457. char *data,
  12458. size_t len,
  12459. void *cbdata)
  12460. {
  12461. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12462. if (pcallbacks->websocket_data) {
  12463. return pcallbacks->websocket_data(conn, bits, data, len);
  12464. }
  12465. /* No handler set - assume "OK" */
  12466. return 1;
  12467. }
  12468. static void
  12469. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12470. void *cbdata)
  12471. {
  12472. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12473. if (pcallbacks->connection_close) {
  12474. pcallbacks->connection_close(conn);
  12475. }
  12476. }
  12477. #endif
  12478. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12479. */
  12480. static void
  12481. release_handler_ref(struct mg_connection *conn,
  12482. struct mg_handler_info *handler_info)
  12483. {
  12484. if (handler_info != NULL) {
  12485. /* Use context lock for ref counter */
  12486. mg_lock_context(conn->phys_ctx);
  12487. handler_info->refcount--;
  12488. mg_unlock_context(conn->phys_ctx);
  12489. }
  12490. }
  12491. /* This is the heart of the Civetweb's logic.
  12492. * This function is called when the request is read, parsed and validated,
  12493. * and Civetweb must decide what action to take: serve a file, or
  12494. * a directory, or call embedded function, etcetera. */
  12495. static void
  12496. handle_request(struct mg_connection *conn)
  12497. {
  12498. struct mg_request_info *ri = &conn->request_info;
  12499. char path[UTF8_PATH_MAX];
  12500. int uri_len, ssl_index;
  12501. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12502. is_put_or_delete_request = 0, is_callback_resource = 0,
  12503. is_template_text_file = 0, is_webdav_request = 0;
  12504. int i;
  12505. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12506. mg_request_handler callback_handler = NULL;
  12507. struct mg_handler_info *handler_info = NULL;
  12508. struct mg_websocket_subprotocols *subprotocols;
  12509. mg_websocket_connect_handler ws_connect_handler = NULL;
  12510. mg_websocket_ready_handler ws_ready_handler = NULL;
  12511. mg_websocket_data_handler ws_data_handler = NULL;
  12512. mg_websocket_close_handler ws_close_handler = NULL;
  12513. void *callback_data = NULL;
  12514. mg_authorization_handler auth_handler = NULL;
  12515. void *auth_callback_data = NULL;
  12516. int handler_type;
  12517. time_t curtime = time(NULL);
  12518. char date[64];
  12519. char *tmp;
  12520. path[0] = 0;
  12521. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12522. conn->request_state = 0;
  12523. /* 1. get the request url */
  12524. /* 1.1. split into url and query string */
  12525. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12526. != NULL) {
  12527. *((char *)conn->request_info.query_string++) = '\0';
  12528. }
  12529. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12530. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12531. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12532. if (ssl_index >= 0) {
  12533. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12534. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12535. redirect_to_https_port(conn, port);
  12536. } else {
  12537. /* A http to https forward port has been specified,
  12538. * but no https port to forward to. */
  12539. mg_send_http_error(conn,
  12540. 503,
  12541. "%s",
  12542. "Error: SSL forward not configured properly");
  12543. mg_cry_internal(conn,
  12544. "%s",
  12545. "Can not redirect to SSL, no SSL port available");
  12546. }
  12547. return;
  12548. }
  12549. uri_len = (int)strlen(ri->local_uri);
  12550. /* 1.3. decode url (if config says so) */
  12551. if (should_decode_url(conn)) {
  12552. mg_url_decode(
  12553. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12554. }
  12555. /* URL decode the query-string only if explicity set in the configuration */
  12556. if (conn->request_info.query_string) {
  12557. if (should_decode_query_string(conn)) {
  12558. url_decode_in_place((char *)conn->request_info.query_string);
  12559. }
  12560. }
  12561. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12562. * possible. The fact that we cleaned the URI is stored in that the
  12563. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12564. * ri->local_uri_raw still points to memory allocated in
  12565. * worker_thread_run(). ri->local_uri is private to the request so we
  12566. * don't have to use preallocated memory here. */
  12567. tmp = mg_strdup(ri->local_uri_raw);
  12568. if (!tmp) {
  12569. /* Out of memory. We cannot do anything reasonable here. */
  12570. return;
  12571. }
  12572. remove_dot_segments(tmp);
  12573. ri->local_uri = tmp;
  12574. /* step 1. completed, the url is known now */
  12575. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12576. /*
  12577. char req_str[1024];
  12578. sprintf(req_str, "REQUEST: %s %s\n", ri->request_method, ri->local_uri);
  12579. OutputDebugStringA(req_str);
  12580. */
  12581. /* 2. if this ip has limited speed, set it for this connection */
  12582. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12583. &conn->client.rsa,
  12584. ri->local_uri);
  12585. /* 3. call a "handle everything" callback, if registered */
  12586. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12587. /* Note that since V1.7 the "begin_request" function is called
  12588. * before an authorization check. If an authorization check is
  12589. * required, use a request_handler instead. */
  12590. i = conn->phys_ctx->callbacks.begin_request(conn);
  12591. if (i > 0) {
  12592. /* callback already processed the request. Store the
  12593. return value as a status code for the access log. */
  12594. conn->status_code = i;
  12595. if (!conn->must_close) {
  12596. discard_unread_request_data(conn);
  12597. }
  12598. return;
  12599. } else if (i == 0) {
  12600. /* civetweb should process the request */
  12601. } else {
  12602. /* unspecified - may change with the next version */
  12603. return;
  12604. }
  12605. }
  12606. /* request not yet handled by a handler or redirect, so the request
  12607. * is processed here */
  12608. /* 4. Check for CORS preflight requests and handle them (if configured).
  12609. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12610. */
  12611. if (!strcmp(ri->request_method, "OPTIONS")) {
  12612. /* Send a response to CORS preflights only if
  12613. * access_control_allow_methods is not NULL and not an empty string.
  12614. * In this case, scripts can still handle CORS. */
  12615. const char *cors_meth_cfg =
  12616. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12617. const char *cors_orig_cfg =
  12618. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12619. const char *cors_origin =
  12620. get_header(ri->http_headers, ri->num_headers, "Origin");
  12621. const char *cors_acrm = get_header(ri->http_headers,
  12622. ri->num_headers,
  12623. "Access-Control-Request-Method");
  12624. /* Todo: check if cors_origin is in cors_orig_cfg.
  12625. * Or, let the client check this. */
  12626. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12627. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12628. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12629. /* This is a valid CORS preflight, and the server is configured
  12630. * to handle it automatically. */
  12631. const char *cors_acrh =
  12632. get_header(ri->http_headers,
  12633. ri->num_headers,
  12634. "Access-Control-Request-Headers");
  12635. gmt_time_string(date, sizeof(date), &curtime);
  12636. mg_printf(conn,
  12637. "HTTP/1.1 200 OK\r\n"
  12638. "Date: %s\r\n"
  12639. "Access-Control-Allow-Origin: %s\r\n"
  12640. "Access-Control-Allow-Methods: %s\r\n"
  12641. "Content-Length: 0\r\n"
  12642. "Connection: %s\r\n",
  12643. date,
  12644. cors_orig_cfg,
  12645. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12646. suggest_connection_header(conn));
  12647. if (cors_acrh != NULL) {
  12648. /* CORS request is asking for additional headers */
  12649. const char *cors_hdr_cfg =
  12650. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12651. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12652. /* Allow only if access_control_allow_headers is
  12653. * not NULL and not an empty string. If this
  12654. * configuration is set to *, allow everything.
  12655. * Otherwise this configuration must be a list
  12656. * of allowed HTTP header names. */
  12657. mg_printf(conn,
  12658. "Access-Control-Allow-Headers: %s\r\n",
  12659. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12660. : cors_hdr_cfg));
  12661. }
  12662. }
  12663. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12664. mg_printf(conn, "\r\n");
  12665. return;
  12666. }
  12667. }
  12668. /* 5. interpret the url to find out how the request must be handled
  12669. */
  12670. /* 5.1. first test, if the request targets the regular http(s)://
  12671. * protocol namespace or the websocket ws(s):// protocol namespace.
  12672. */
  12673. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12674. #if defined(USE_WEBSOCKET)
  12675. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12676. #else
  12677. handler_type = REQUEST_HANDLER;
  12678. #endif /* defined(USE_WEBSOCKET) */
  12679. if (is_websocket_request) {
  12680. HTTP1_only;
  12681. }
  12682. /* 5.2. check if the request will be handled by a callback */
  12683. if (get_request_handler(conn,
  12684. handler_type,
  12685. &callback_handler,
  12686. &subprotocols,
  12687. &ws_connect_handler,
  12688. &ws_ready_handler,
  12689. &ws_data_handler,
  12690. &ws_close_handler,
  12691. NULL,
  12692. &callback_data,
  12693. &handler_info)) {
  12694. /* 5.2.1. A callback will handle this request. All requests
  12695. * handled by a callback have to be considered as requests
  12696. * to a script resource. */
  12697. is_callback_resource = 1;
  12698. is_script_resource = 1;
  12699. is_put_or_delete_request = is_put_or_delete_method(conn);
  12700. /* Never handle a C callback according to File WebDav rules,
  12701. * even if it is a webdav method */
  12702. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  12703. } else {
  12704. no_callback_resource:
  12705. /* 5.2.2. No callback is responsible for this request. The URI
  12706. * addresses a file based resource (static content or Lua/cgi
  12707. * scripts in the file system). */
  12708. is_callback_resource = 0;
  12709. interpret_uri(conn,
  12710. path,
  12711. sizeof(path),
  12712. &file.stat,
  12713. &is_found,
  12714. &is_script_resource,
  12715. &is_websocket_request,
  12716. &is_put_or_delete_request,
  12717. &is_webdav_request,
  12718. &is_template_text_file);
  12719. }
  12720. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  12721. if (is_webdav_request) {
  12722. /* TODO: Do we need a config option? */
  12723. int webdav_not_allowed = 0;
  12724. if (webdav_not_allowed) {
  12725. mg_send_http_error(conn,
  12726. 405,
  12727. "%s method not allowed",
  12728. conn->request_info.request_method);
  12729. return;
  12730. }
  12731. }
  12732. /* 6. authorization check */
  12733. /* 6.1. a custom authorization handler is installed */
  12734. if (get_request_handler(conn,
  12735. AUTH_HANDLER,
  12736. NULL,
  12737. NULL,
  12738. NULL,
  12739. NULL,
  12740. NULL,
  12741. NULL,
  12742. &auth_handler,
  12743. &auth_callback_data,
  12744. NULL)) {
  12745. if (!auth_handler(conn, auth_callback_data)) {
  12746. /* Callback handler will not be used anymore. Release it */
  12747. release_handler_ref(conn, handler_info);
  12748. return;
  12749. }
  12750. } else if (is_put_or_delete_request && !is_script_resource
  12751. && !is_callback_resource) {
  12752. HTTP1_only;
  12753. /* 6.2. this request is a PUT/DELETE to a real file */
  12754. /* 6.2.1. thus, the server must have real files */
  12755. #if defined(NO_FILES)
  12756. if (1) {
  12757. #else
  12758. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12759. #endif
  12760. /* This code path will not be called for request handlers */
  12761. DEBUG_ASSERT(handler_info == NULL);
  12762. /* This server does not have any real files, thus the
  12763. * PUT/DELETE methods are not valid. */
  12764. mg_send_http_error(conn,
  12765. 405,
  12766. "%s method not allowed",
  12767. conn->request_info.request_method);
  12768. return;
  12769. }
  12770. #if !defined(NO_FILES)
  12771. /* 6.2.2. Check if put authorization for static files is
  12772. * available.
  12773. */
  12774. if (!is_authorized_for_put(conn)) {
  12775. send_authorization_request(conn, NULL);
  12776. return;
  12777. }
  12778. #endif
  12779. } else {
  12780. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12781. * or it is a PUT or DELETE request to a resource that does not
  12782. * correspond to a file. Check authorization. */
  12783. if (!check_authorization(conn, path)) {
  12784. send_authorization_request(conn, NULL);
  12785. /* Callback handler will not be used anymore. Release it */
  12786. release_handler_ref(conn, handler_info);
  12787. return;
  12788. }
  12789. }
  12790. /* request is authorized or does not need authorization */
  12791. /* 7. check if there are request handlers for this uri */
  12792. if (is_callback_resource) {
  12793. HTTP1_only;
  12794. if (!is_websocket_request) {
  12795. i = callback_handler(conn, callback_data);
  12796. /* Callback handler will not be used anymore. Release it */
  12797. release_handler_ref(conn, handler_info);
  12798. if (i > 0) {
  12799. /* Do nothing, callback has served the request. Store
  12800. * then return value as status code for the log and discard
  12801. * all data from the client not used by the callback. */
  12802. conn->status_code = i;
  12803. if (!conn->must_close) {
  12804. discard_unread_request_data(conn);
  12805. }
  12806. } else {
  12807. /* The handler did NOT handle the request. */
  12808. /* Some proper reactions would be:
  12809. * a) close the connections without sending anything
  12810. * b) send a 404 not found
  12811. * c) try if there is a file matching the URI
  12812. * It would be possible to do a, b or c in the callback
  12813. * implementation, and return 1 - we cannot do anything
  12814. * here, that is not possible in the callback.
  12815. *
  12816. * TODO: What would be the best reaction here?
  12817. * (Note: The reaction may change, if there is a better
  12818. * idea.)
  12819. */
  12820. /* For the moment, use option c: We look for a proper file,
  12821. * but since a file request is not always a script resource,
  12822. * the authorization check might be different. */
  12823. callback_handler = NULL;
  12824. /* Here we are at a dead end:
  12825. * According to URI matching, a callback should be
  12826. * responsible for handling the request,
  12827. * we called it, but the callback declared itself
  12828. * not responsible.
  12829. * We use a goto here, to get out of this dead end,
  12830. * and continue with the default handling.
  12831. * A goto here is simpler and better to understand
  12832. * than some curious loop. */
  12833. goto no_callback_resource;
  12834. }
  12835. } else {
  12836. #if defined(USE_WEBSOCKET)
  12837. handle_websocket_request(conn,
  12838. path,
  12839. is_callback_resource,
  12840. subprotocols,
  12841. ws_connect_handler,
  12842. ws_ready_handler,
  12843. ws_data_handler,
  12844. ws_close_handler,
  12845. callback_data);
  12846. #endif
  12847. }
  12848. return;
  12849. }
  12850. /* 8. handle websocket requests */
  12851. #if defined(USE_WEBSOCKET)
  12852. if (is_websocket_request) {
  12853. HTTP1_only;
  12854. if (is_script_resource) {
  12855. if (is_in_script_path(conn, path)) {
  12856. /* Websocket Lua script */
  12857. handle_websocket_request(conn,
  12858. path,
  12859. 0 /* Lua Script */,
  12860. NULL,
  12861. NULL,
  12862. NULL,
  12863. NULL,
  12864. NULL,
  12865. conn->phys_ctx->user_data);
  12866. } else {
  12867. /* Script was in an illegal path */
  12868. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12869. }
  12870. } else {
  12871. mg_send_http_error(conn, 404, "%s", "Not found");
  12872. }
  12873. return;
  12874. } else
  12875. #endif
  12876. #if defined(NO_FILES)
  12877. /* 9a. In case the server uses only callbacks, this uri is
  12878. * unknown.
  12879. * Then, all request handling ends here. */
  12880. mg_send_http_error(conn, 404, "%s", "Not Found");
  12881. #else
  12882. /* 9b. This request is either for a static file or resource handled
  12883. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12884. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12885. mg_send_http_error(conn, 404, "%s", "Not Found");
  12886. return;
  12887. }
  12888. /* 10. Request is handled by a script */
  12889. if (is_script_resource) {
  12890. HTTP1_only;
  12891. handle_file_based_request(conn, path, &file);
  12892. return;
  12893. }
  12894. /* 11. Handle put/delete/mkcol requests */
  12895. if (is_put_or_delete_request) {
  12896. HTTP1_only;
  12897. /* 11.1. PUT method */
  12898. if (!strcmp(ri->request_method, "PUT")) {
  12899. put_file(conn, path);
  12900. return;
  12901. }
  12902. /* 11.2. DELETE method */
  12903. if (!strcmp(ri->request_method, "DELETE")) {
  12904. delete_file(conn, path);
  12905. return;
  12906. }
  12907. /* 11.3. MKCOL method */
  12908. if (!strcmp(ri->request_method, "MKCOL")) {
  12909. dav_mkcol(conn, path);
  12910. return;
  12911. }
  12912. /* 11.4. MOVE method */
  12913. if (!strcmp(ri->request_method, "MOVE")) {
  12914. dav_move_file(conn, path, 0);
  12915. return;
  12916. }
  12917. if (!strcmp(ri->request_method, "COPY")) {
  12918. dav_move_file(conn, path, 1);
  12919. return;
  12920. }
  12921. /* 11.5. LOCK method */
  12922. if (!strcmp(ri->request_method, "LOCK")) {
  12923. dav_lock_file(conn, path);
  12924. return;
  12925. }
  12926. /* 11.6. UNLOCK method */
  12927. if (!strcmp(ri->request_method, "UNLOCK")) {
  12928. dav_unlock_file(conn, path);
  12929. return;
  12930. }
  12931. /* 11.7. PROPPATCH method */
  12932. if (!strcmp(ri->request_method, "PROPPATCH")) {
  12933. dav_proppatch(conn, path);
  12934. return;
  12935. }
  12936. /* 11.8. Other methods, e.g.: PATCH
  12937. * This method is not supported for static resources,
  12938. * only for scripts (Lua, CGI) and callbacks. */
  12939. mg_send_http_error(conn,
  12940. 405,
  12941. "%s method not allowed",
  12942. conn->request_info.request_method);
  12943. return;
  12944. }
  12945. /* 11. File does not exist, or it was configured that it should be
  12946. * hidden */
  12947. if (!is_found || (must_hide_file(conn, path))) {
  12948. mg_send_http_error(conn, 404, "%s", "Not found");
  12949. return;
  12950. }
  12951. /* 12. Directory uris should end with a slash */
  12952. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  12953. && (ri->local_uri[uri_len - 1] != '/')) {
  12954. size_t len = strlen(ri->request_uri);
  12955. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12956. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12957. if (!new_path) {
  12958. mg_send_http_error(conn, 500, "out or memory");
  12959. } else {
  12960. memcpy(new_path, ri->request_uri, len);
  12961. new_path[len] = '/';
  12962. new_path[len + 1] = 0;
  12963. if (ri->query_string) {
  12964. new_path[len + 1] = '?';
  12965. /* Copy query string including terminating zero */
  12966. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12967. }
  12968. mg_send_http_redirect(conn, new_path, 301);
  12969. mg_free(new_path);
  12970. }
  12971. return;
  12972. }
  12973. /* 13. Handle other methods than GET/HEAD */
  12974. /* 13.1. Handle PROPFIND */
  12975. if (!strcmp(ri->request_method, "PROPFIND")) {
  12976. handle_propfind(conn, path, &file.stat);
  12977. return;
  12978. }
  12979. /* 13.2. Handle OPTIONS for files */
  12980. if (!strcmp(ri->request_method, "OPTIONS")) {
  12981. /* This standard handler is only used for real files.
  12982. * Scripts should support the OPTIONS method themselves, to allow a
  12983. * maximum flexibility.
  12984. * Lua and CGI scripts may fully support CORS this way (including
  12985. * preflights). */
  12986. send_options(conn);
  12987. return;
  12988. }
  12989. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12990. if ((0 != strcmp(ri->request_method, "GET"))
  12991. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12992. mg_send_http_error(conn,
  12993. 405,
  12994. "%s method not allowed",
  12995. conn->request_info.request_method);
  12996. return;
  12997. }
  12998. /* 14. directories */
  12999. if (file.stat.is_directory) {
  13000. /* Substitute files have already been handled above. */
  13001. /* Here we can either generate and send a directory listing,
  13002. * or send an "access denied" error. */
  13003. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13004. "yes")) {
  13005. handle_directory_request(conn, path);
  13006. } else {
  13007. mg_send_http_error(conn,
  13008. 403,
  13009. "%s",
  13010. "Error: Directory listing denied");
  13011. }
  13012. return;
  13013. }
  13014. /* 15. Files with search/replace patterns: LSP and SSI */
  13015. if (is_template_text_file) {
  13016. HTTP1_only;
  13017. handle_file_based_request(conn, path, &file);
  13018. return;
  13019. }
  13020. /* 16. Static file - maybe cached */
  13021. #if !defined(NO_CACHING)
  13022. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13023. /* Send 304 "Not Modified" - this must not send any body data */
  13024. handle_not_modified_static_file_request(conn, &file);
  13025. return;
  13026. }
  13027. #endif /* !NO_CACHING */
  13028. /* 17. Static file - not cached */
  13029. handle_static_file_request(conn, path, &file, NULL, NULL);
  13030. #endif /* !defined(NO_FILES) */
  13031. }
  13032. #if !defined(NO_FILESYSTEMS)
  13033. static void
  13034. handle_file_based_request(struct mg_connection *conn,
  13035. const char *path,
  13036. struct mg_file *file)
  13037. {
  13038. #if !defined(NO_CGI)
  13039. unsigned char cgi_config_idx, inc, max;
  13040. #endif
  13041. if (!conn || !conn->dom_ctx) {
  13042. return;
  13043. }
  13044. #if defined(USE_LUA)
  13045. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13046. path)
  13047. > 0) {
  13048. if (is_in_script_path(conn, path)) {
  13049. /* Lua server page: an SSI like page containing mostly plain
  13050. * html code plus some tags with server generated contents. */
  13051. handle_lsp_request(conn, path, file, NULL);
  13052. } else {
  13053. /* Script was in an illegal path */
  13054. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13055. }
  13056. return;
  13057. }
  13058. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13059. > 0) {
  13060. if (is_in_script_path(conn, path)) {
  13061. /* Lua in-server module script: a CGI like script used to
  13062. * generate the entire reply. */
  13063. mg_exec_lua_script(conn, path, NULL);
  13064. } else {
  13065. /* Script was in an illegal path */
  13066. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13067. }
  13068. return;
  13069. }
  13070. #endif
  13071. #if defined(USE_DUKTAPE)
  13072. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13073. path)
  13074. > 0) {
  13075. if (is_in_script_path(conn, path)) {
  13076. /* Call duktape to generate the page */
  13077. mg_exec_duktape_script(conn, path);
  13078. } else {
  13079. /* Script was in an illegal path */
  13080. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13081. }
  13082. return;
  13083. }
  13084. #endif
  13085. #if !defined(NO_CGI)
  13086. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13087. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13088. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13089. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13090. if (match_prefix_strlen(
  13091. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13092. path)
  13093. > 0) {
  13094. if (is_in_script_path(conn, path)) {
  13095. /* CGI scripts may support all HTTP methods */
  13096. handle_cgi_request(conn, path, 0);
  13097. } else {
  13098. /* Script was in an illegal path */
  13099. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13100. }
  13101. return;
  13102. }
  13103. }
  13104. }
  13105. #endif /* !NO_CGI */
  13106. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13107. if (is_in_script_path(conn, path)) {
  13108. handle_ssi_file_request(conn, path, file);
  13109. } else {
  13110. /* Script was in an illegal path */
  13111. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13112. }
  13113. return;
  13114. }
  13115. #if !defined(NO_CACHING)
  13116. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13117. /* Send 304 "Not Modified" - this must not send any body data */
  13118. handle_not_modified_static_file_request(conn, file);
  13119. return;
  13120. }
  13121. #endif /* !NO_CACHING */
  13122. handle_static_file_request(conn, path, file, NULL, NULL);
  13123. }
  13124. #endif /* NO_FILESYSTEMS */
  13125. static void
  13126. close_all_listening_sockets(struct mg_context *ctx)
  13127. {
  13128. unsigned int i;
  13129. if (!ctx) {
  13130. return;
  13131. }
  13132. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13133. closesocket(ctx->listening_sockets[i].sock);
  13134. #if defined(USE_X_DOM_SOCKET)
  13135. /* For unix domain sockets, the socket name represents a file that has
  13136. * to be deleted. */
  13137. /* See
  13138. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13139. */
  13140. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13141. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13142. IGNORE_UNUSED_RESULT(
  13143. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13144. }
  13145. #endif
  13146. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13147. }
  13148. mg_free(ctx->listening_sockets);
  13149. ctx->listening_sockets = NULL;
  13150. mg_free(ctx->listening_socket_fds);
  13151. ctx->listening_socket_fds = NULL;
  13152. }
  13153. /* Valid listening port specification is: [ip_address:]port[s]
  13154. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13155. * Examples for IPv6: [::]:80, [::1]:80,
  13156. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13157. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13158. * In order to bind to both, IPv4 and IPv6, you can either add
  13159. * both ports using 8080,[::]:8080, or the short form +8080.
  13160. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13161. * one only accepting IPv4 the other only IPv6. +8080 creates
  13162. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13163. * environment, they might work differently, or might not work
  13164. * at all - it must be tested what options work best in the
  13165. * relevant network environment.
  13166. */
  13167. static int
  13168. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13169. {
  13170. unsigned int a, b, c, d;
  13171. unsigned port;
  13172. unsigned long portUL;
  13173. int ch, len;
  13174. const char *cb;
  13175. char *endptr;
  13176. #if defined(USE_IPV6)
  13177. char buf[100] = {0};
  13178. #endif
  13179. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13180. * Also, all-zeroes in the socket address means binding to all addresses
  13181. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13182. memset(so, 0, sizeof(*so));
  13183. so->lsa.sin.sin_family = AF_INET;
  13184. *ip_version = 0;
  13185. /* Initialize len as invalid. */
  13186. port = 0;
  13187. len = 0;
  13188. /* Test for different ways to format this string */
  13189. if (sscanf(vec->ptr,
  13190. "%u.%u.%u.%u:%u%n",
  13191. &a,
  13192. &b,
  13193. &c,
  13194. &d,
  13195. &port,
  13196. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13197. // to an integer value, but function will not report
  13198. // conversion errors; consider using 'strtol' instead
  13199. == 5) {
  13200. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13201. so->lsa.sin.sin_addr.s_addr =
  13202. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13203. so->lsa.sin.sin_port = htons((uint16_t)port);
  13204. *ip_version = 4;
  13205. #if defined(USE_IPV6)
  13206. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13207. && ((size_t)len <= vec->len)
  13208. && mg_inet_pton(
  13209. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13210. /* IPv6 address, examples: see above */
  13211. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13212. */
  13213. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13214. *ip_version = 6;
  13215. #endif
  13216. } else if ((vec->ptr[0] == '+')
  13217. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13218. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13219. // string to an integer value, but function will not
  13220. // report conversion errors; consider using 'strtol'
  13221. // instead
  13222. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13223. /* Add 1 to len for the + character we skipped before */
  13224. len++;
  13225. #if defined(USE_IPV6)
  13226. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13227. so->lsa.sin6.sin6_family = AF_INET6;
  13228. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13229. *ip_version = 4 + 6;
  13230. #else
  13231. /* Bind to IPv4 only, since IPv6 is not built in. */
  13232. so->lsa.sin.sin_port = htons((uint16_t)port);
  13233. *ip_version = 4;
  13234. #endif
  13235. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13236. && (vec->ptr != endptr)) {
  13237. len = (int)(endptr - vec->ptr);
  13238. port = (uint16_t)portUL;
  13239. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13240. so->lsa.sin.sin_port = htons((uint16_t)port);
  13241. *ip_version = 4;
  13242. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13243. /* String could be a hostname. This check algotithm
  13244. * will only work for RFC 952 compliant hostnames,
  13245. * starting with a letter, containing only letters,
  13246. * digits and hyphen ('-'). Newer specs may allow
  13247. * more, but this is not guaranteed here, since it
  13248. * may interfere with rules for port option lists. */
  13249. /* According to RFC 1035, hostnames are restricted to 255 characters
  13250. * in total (63 between two dots). */
  13251. char hostname[256];
  13252. size_t hostnlen = (size_t)(cb - vec->ptr);
  13253. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13254. /* This would be invalid in any case */
  13255. *ip_version = 0;
  13256. return 0;
  13257. }
  13258. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13259. if (mg_inet_pton(
  13260. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13261. if (sscanf(cb + 1, "%u%n", &port, &len)
  13262. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13263. // string to an integer value, but function will not
  13264. // report conversion errors; consider using 'strtol'
  13265. // instead
  13266. *ip_version = 4;
  13267. so->lsa.sin.sin_port = htons((uint16_t)port);
  13268. len += (int)(hostnlen + 1);
  13269. } else {
  13270. len = 0;
  13271. }
  13272. #if defined(USE_IPV6)
  13273. } else if (mg_inet_pton(AF_INET6,
  13274. hostname,
  13275. &so->lsa.sin6,
  13276. sizeof(so->lsa.sin6),
  13277. 1)) {
  13278. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13279. *ip_version = 6;
  13280. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13281. len += (int)(hostnlen + 1);
  13282. } else {
  13283. len = 0;
  13284. }
  13285. #endif
  13286. } else {
  13287. len = 0;
  13288. }
  13289. #if defined(USE_X_DOM_SOCKET)
  13290. } else if (vec->ptr[0] == 'x') {
  13291. /* unix (linux) domain socket */
  13292. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13293. len = vec->len;
  13294. so->lsa.sun.sun_family = AF_UNIX;
  13295. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13296. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13297. port = 0;
  13298. *ip_version = 99;
  13299. } else {
  13300. /* String too long */
  13301. len = 0;
  13302. }
  13303. #endif
  13304. } else {
  13305. /* Parsing failure. */
  13306. len = 0;
  13307. }
  13308. /* sscanf and the option splitting code ensure the following condition
  13309. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  13310. if ((len > 0) && is_valid_port(port)
  13311. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  13312. /* Next character after the port number */
  13313. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  13314. so->is_ssl = (ch == 's');
  13315. so->ssl_redir = (ch == 'r');
  13316. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  13317. return 1;
  13318. }
  13319. }
  13320. /* Reset ip_version to 0 if there is an error */
  13321. *ip_version = 0;
  13322. return 0;
  13323. }
  13324. /* Is there any SSL port in use? */
  13325. static int
  13326. is_ssl_port_used(const char *ports)
  13327. {
  13328. if (ports) {
  13329. /* There are several different allowed syntax variants:
  13330. * - "80" for a single port using every network interface
  13331. * - "localhost:80" for a single port using only localhost
  13332. * - "80,localhost:8080" for two ports, one bound to localhost
  13333. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13334. * to IPv4 localhost, one to IPv6 localhost
  13335. * - "+80" use port 80 for IPv4 and IPv6
  13336. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13337. * for both: IPv4 and IPv4
  13338. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13339. * additionally port 8080 bound to localhost connections
  13340. *
  13341. * If we just look for 's' anywhere in the string, "localhost:80"
  13342. * will be detected as SSL (false positive).
  13343. * Looking for 's' after a digit may cause false positives in
  13344. * "my24service:8080".
  13345. * Looking from 's' backward if there are only ':' and numbers
  13346. * before will not work for "24service:8080" (non SSL, port 8080)
  13347. * or "24s" (SSL, port 24).
  13348. *
  13349. * Remark: Initially hostnames were not allowed to start with a
  13350. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13351. * Section 2.1).
  13352. *
  13353. * To get this correct, the entire string must be parsed as a whole,
  13354. * reading it as a list element for element and parsing with an
  13355. * algorithm equivalent to parse_port_string.
  13356. *
  13357. * In fact, we use local interface names here, not arbitrary
  13358. * hostnames, so in most cases the only name will be "localhost".
  13359. *
  13360. * So, for now, we use this simple algorithm, that may still return
  13361. * a false positive in bizarre cases.
  13362. */
  13363. int i;
  13364. int portslen = (int)strlen(ports);
  13365. char prevIsNumber = 0;
  13366. for (i = 0; i < portslen; i++) {
  13367. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  13368. return 1;
  13369. }
  13370. if (ports[i] >= '0' && ports[i] <= '9') {
  13371. prevIsNumber = 1;
  13372. } else {
  13373. prevIsNumber = 0;
  13374. }
  13375. }
  13376. }
  13377. return 0;
  13378. }
  13379. static int
  13380. set_ports_option(struct mg_context *phys_ctx)
  13381. {
  13382. const char *list;
  13383. int on = 1;
  13384. #if defined(USE_IPV6)
  13385. int off = 0;
  13386. #endif
  13387. struct vec vec;
  13388. struct socket so, *ptr;
  13389. struct mg_pollfd *pfd;
  13390. union usa usa;
  13391. socklen_t len;
  13392. int ip_version;
  13393. int portsTotal = 0;
  13394. int portsOk = 0;
  13395. const char *opt_txt;
  13396. long opt_listen_backlog;
  13397. if (!phys_ctx) {
  13398. return 0;
  13399. }
  13400. memset(&so, 0, sizeof(so));
  13401. memset(&usa, 0, sizeof(usa));
  13402. len = sizeof(usa);
  13403. list = phys_ctx->dd.config[LISTENING_PORTS];
  13404. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13405. portsTotal++;
  13406. if (!parse_port_string(&vec, &so, &ip_version)) {
  13407. mg_cry_ctx_internal(
  13408. phys_ctx,
  13409. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13410. (int)vec.len,
  13411. vec.ptr,
  13412. portsTotal,
  13413. "[IP_ADDRESS:]PORT[s|r]");
  13414. continue;
  13415. }
  13416. #if !defined(NO_SSL)
  13417. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13418. mg_cry_ctx_internal(phys_ctx,
  13419. "Cannot add SSL socket (entry %i)",
  13420. portsTotal);
  13421. continue;
  13422. }
  13423. #endif
  13424. /* Create socket. */
  13425. /* For a list of protocol numbers (e.g., TCP==6) see:
  13426. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13427. */
  13428. if ((so.sock =
  13429. socket(so.lsa.sa.sa_family,
  13430. SOCK_STREAM,
  13431. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13432. == INVALID_SOCKET) {
  13433. mg_cry_ctx_internal(phys_ctx,
  13434. "cannot create socket (entry %i)",
  13435. portsTotal);
  13436. continue;
  13437. }
  13438. #if defined(_WIN32)
  13439. /* Windows SO_REUSEADDR lets many procs binds to a
  13440. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13441. * if someone already has the socket -- DTL */
  13442. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13443. * Windows might need a few seconds before
  13444. * the same port can be used again in the
  13445. * same process, so a short Sleep may be
  13446. * required between mg_stop and mg_start.
  13447. */
  13448. if (setsockopt(so.sock,
  13449. SOL_SOCKET,
  13450. SO_EXCLUSIVEADDRUSE,
  13451. (SOCK_OPT_TYPE)&on,
  13452. sizeof(on))
  13453. != 0) {
  13454. /* Set reuse option, but don't abort on errors. */
  13455. mg_cry_ctx_internal(
  13456. phys_ctx,
  13457. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13458. portsTotal);
  13459. }
  13460. #else
  13461. if (setsockopt(so.sock,
  13462. SOL_SOCKET,
  13463. SO_REUSEADDR,
  13464. (SOCK_OPT_TYPE)&on,
  13465. sizeof(on))
  13466. != 0) {
  13467. /* Set reuse option, but don't abort on errors. */
  13468. mg_cry_ctx_internal(
  13469. phys_ctx,
  13470. "cannot set socket option SO_REUSEADDR (entry %i)",
  13471. portsTotal);
  13472. }
  13473. #endif
  13474. #if defined(USE_X_DOM_SOCKET)
  13475. if (ip_version == 99) {
  13476. /* Unix domain socket */
  13477. } else
  13478. #endif
  13479. if (ip_version > 4) {
  13480. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13481. #if defined(USE_IPV6)
  13482. if (ip_version > 6) {
  13483. if (so.lsa.sa.sa_family == AF_INET6
  13484. && setsockopt(so.sock,
  13485. IPPROTO_IPV6,
  13486. IPV6_V6ONLY,
  13487. (void *)&off,
  13488. sizeof(off))
  13489. != 0) {
  13490. /* Set IPv6 only option, but don't abort on errors. */
  13491. mg_cry_ctx_internal(phys_ctx,
  13492. "cannot set socket option "
  13493. "IPV6_V6ONLY=off (entry %i)",
  13494. portsTotal);
  13495. }
  13496. } else {
  13497. if (so.lsa.sa.sa_family == AF_INET6
  13498. && setsockopt(so.sock,
  13499. IPPROTO_IPV6,
  13500. IPV6_V6ONLY,
  13501. (void *)&on,
  13502. sizeof(on))
  13503. != 0) {
  13504. /* Set IPv6 only option, but don't abort on errors. */
  13505. mg_cry_ctx_internal(phys_ctx,
  13506. "cannot set socket option "
  13507. "IPV6_V6ONLY=on (entry %i)",
  13508. portsTotal);
  13509. }
  13510. }
  13511. #else
  13512. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13513. closesocket(so.sock);
  13514. so.sock = INVALID_SOCKET;
  13515. continue;
  13516. #endif
  13517. }
  13518. if (so.lsa.sa.sa_family == AF_INET) {
  13519. len = sizeof(so.lsa.sin);
  13520. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13521. mg_cry_ctx_internal(phys_ctx,
  13522. "cannot bind to %.*s: %d (%s)",
  13523. (int)vec.len,
  13524. vec.ptr,
  13525. (int)ERRNO,
  13526. strerror(errno));
  13527. closesocket(so.sock);
  13528. so.sock = INVALID_SOCKET;
  13529. continue;
  13530. }
  13531. }
  13532. #if defined(USE_IPV6)
  13533. else if (so.lsa.sa.sa_family == AF_INET6) {
  13534. len = sizeof(so.lsa.sin6);
  13535. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13536. mg_cry_ctx_internal(phys_ctx,
  13537. "cannot bind to IPv6 %.*s: %d (%s)",
  13538. (int)vec.len,
  13539. vec.ptr,
  13540. (int)ERRNO,
  13541. strerror(errno));
  13542. closesocket(so.sock);
  13543. so.sock = INVALID_SOCKET;
  13544. continue;
  13545. }
  13546. }
  13547. #endif
  13548. #if defined(USE_X_DOM_SOCKET)
  13549. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13550. len = sizeof(so.lsa.sun);
  13551. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13552. mg_cry_ctx_internal(phys_ctx,
  13553. "cannot bind to unix socket %s: %d (%s)",
  13554. so.lsa.sun.sun_path,
  13555. (int)ERRNO,
  13556. strerror(errno));
  13557. closesocket(so.sock);
  13558. so.sock = INVALID_SOCKET;
  13559. continue;
  13560. }
  13561. }
  13562. #endif
  13563. else {
  13564. mg_cry_ctx_internal(
  13565. phys_ctx,
  13566. "cannot bind: address family not supported (entry %i)",
  13567. portsTotal);
  13568. closesocket(so.sock);
  13569. so.sock = INVALID_SOCKET;
  13570. continue;
  13571. }
  13572. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  13573. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  13574. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  13575. mg_cry_ctx_internal(phys_ctx,
  13576. "%s value \"%s\" is invalid",
  13577. config_options[LISTEN_BACKLOG_SIZE].name,
  13578. opt_txt);
  13579. closesocket(so.sock);
  13580. so.sock = INVALID_SOCKET;
  13581. continue;
  13582. }
  13583. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13584. mg_cry_ctx_internal(phys_ctx,
  13585. "cannot listen to %.*s: %d (%s)",
  13586. (int)vec.len,
  13587. vec.ptr,
  13588. (int)ERRNO,
  13589. strerror(errno));
  13590. closesocket(so.sock);
  13591. so.sock = INVALID_SOCKET;
  13592. continue;
  13593. }
  13594. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13595. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13596. int err = (int)ERRNO;
  13597. mg_cry_ctx_internal(phys_ctx,
  13598. "call to getsockname failed %.*s: %d (%s)",
  13599. (int)vec.len,
  13600. vec.ptr,
  13601. err,
  13602. strerror(errno));
  13603. closesocket(so.sock);
  13604. so.sock = INVALID_SOCKET;
  13605. continue;
  13606. }
  13607. /* Update lsa port in case of random free ports */
  13608. #if defined(USE_IPV6)
  13609. if (so.lsa.sa.sa_family == AF_INET6) {
  13610. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13611. } else
  13612. #endif
  13613. {
  13614. so.lsa.sin.sin_port = usa.sin.sin_port;
  13615. }
  13616. if ((ptr = (struct socket *)
  13617. mg_realloc_ctx(phys_ctx->listening_sockets,
  13618. (phys_ctx->num_listening_sockets + 1)
  13619. * sizeof(phys_ctx->listening_sockets[0]),
  13620. phys_ctx))
  13621. == NULL) {
  13622. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13623. closesocket(so.sock);
  13624. so.sock = INVALID_SOCKET;
  13625. continue;
  13626. }
  13627. if ((pfd = (struct mg_pollfd *)
  13628. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13629. (phys_ctx->num_listening_sockets + 1)
  13630. * sizeof(phys_ctx->listening_socket_fds[0]),
  13631. phys_ctx))
  13632. == NULL) {
  13633. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13634. closesocket(so.sock);
  13635. so.sock = INVALID_SOCKET;
  13636. mg_free(ptr);
  13637. continue;
  13638. }
  13639. set_close_on_exec(so.sock, NULL, phys_ctx);
  13640. phys_ctx->listening_sockets = ptr;
  13641. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13642. phys_ctx->listening_socket_fds = pfd;
  13643. phys_ctx->num_listening_sockets++;
  13644. portsOk++;
  13645. }
  13646. if (portsOk != portsTotal) {
  13647. close_all_listening_sockets(phys_ctx);
  13648. portsOk = 0;
  13649. }
  13650. return portsOk;
  13651. }
  13652. static const char *
  13653. header_val(const struct mg_connection *conn, const char *header)
  13654. {
  13655. const char *header_value;
  13656. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13657. return "-";
  13658. } else {
  13659. return header_value;
  13660. }
  13661. }
  13662. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13663. #include "external_log_access.inl"
  13664. #elif !defined(NO_FILESYSTEMS)
  13665. static void
  13666. log_access(const struct mg_connection *conn)
  13667. {
  13668. const struct mg_request_info *ri;
  13669. struct mg_file fi;
  13670. char date[64], src_addr[IP_ADDR_STR_LEN];
  13671. struct tm *tm;
  13672. const char *referer;
  13673. const char *user_agent;
  13674. char log_buf[4096];
  13675. if (!conn || !conn->dom_ctx) {
  13676. return;
  13677. }
  13678. /* Set log message to "empty" */
  13679. log_buf[0] = 0;
  13680. #if defined(USE_LUA)
  13681. if (conn->phys_ctx->lua_bg_log_available) {
  13682. int ret;
  13683. struct mg_context *ctx = conn->phys_ctx;
  13684. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13685. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13686. /* call "log()" in Lua */
  13687. lua_getglobal(lstate, "log");
  13688. prepare_lua_request_info_inner(conn, lstate);
  13689. push_lua_response_log_data(conn, lstate);
  13690. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13691. if (ret == 0) {
  13692. int t = lua_type(lstate, -1);
  13693. if (t == LUA_TBOOLEAN) {
  13694. if (lua_toboolean(lstate, -1) == 0) {
  13695. /* log() returned false: do not log */
  13696. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13697. return;
  13698. }
  13699. /* log returned true: continue logging */
  13700. } else if (t == LUA_TSTRING) {
  13701. size_t len;
  13702. const char *txt = lua_tolstring(lstate, -1, &len);
  13703. if ((len == 0) || (*txt == 0)) {
  13704. /* log() returned empty string: do not log */
  13705. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13706. return;
  13707. }
  13708. /* Copy test from Lua into log_buf */
  13709. if (len >= sizeof(log_buf)) {
  13710. len = sizeof(log_buf) - 1;
  13711. }
  13712. memcpy(log_buf, txt, len);
  13713. log_buf[len] = 0;
  13714. }
  13715. } else {
  13716. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13717. }
  13718. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13719. }
  13720. #endif
  13721. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13722. if (mg_fopen(conn,
  13723. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13724. MG_FOPEN_MODE_APPEND,
  13725. &fi)
  13726. == 0) {
  13727. fi.access.fp = NULL;
  13728. }
  13729. } else {
  13730. fi.access.fp = NULL;
  13731. }
  13732. /* Log is written to a file and/or a callback. If both are not set,
  13733. * executing the rest of the function is pointless. */
  13734. if ((fi.access.fp == NULL)
  13735. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13736. return;
  13737. }
  13738. /* If we did not get a log message from Lua, create it here. */
  13739. if (!log_buf[0]) {
  13740. tm = localtime(&conn->conn_birth_time);
  13741. if (tm != NULL) {
  13742. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13743. } else {
  13744. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13745. date[sizeof(date) - 1] = '\0';
  13746. }
  13747. ri = &conn->request_info;
  13748. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13749. referer = header_val(conn, "Referer");
  13750. user_agent = header_val(conn, "User-Agent");
  13751. mg_snprintf(conn,
  13752. NULL, /* Ignore truncation in access log */
  13753. log_buf,
  13754. sizeof(log_buf),
  13755. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13756. " %s %s",
  13757. src_addr,
  13758. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13759. date,
  13760. ri->request_method ? ri->request_method : "-",
  13761. ri->request_uri ? ri->request_uri : "-",
  13762. ri->query_string ? "?" : "",
  13763. ri->query_string ? ri->query_string : "",
  13764. ri->http_version,
  13765. conn->status_code,
  13766. conn->num_bytes_sent,
  13767. referer,
  13768. user_agent);
  13769. }
  13770. /* Here we have a log message in log_buf. Call the callback */
  13771. if (conn->phys_ctx->callbacks.log_access) {
  13772. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13773. /* do not log if callack returns non-zero */
  13774. if (fi.access.fp) {
  13775. mg_fclose(&fi.access);
  13776. }
  13777. return;
  13778. }
  13779. }
  13780. /* Store in file */
  13781. if (fi.access.fp) {
  13782. int ok = 1;
  13783. flockfile(fi.access.fp);
  13784. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13785. ok = 0;
  13786. }
  13787. if (fflush(fi.access.fp) != 0) {
  13788. ok = 0;
  13789. }
  13790. funlockfile(fi.access.fp);
  13791. if (mg_fclose(&fi.access) != 0) {
  13792. ok = 0;
  13793. }
  13794. if (!ok) {
  13795. mg_cry_internal(conn,
  13796. "Error writing log file %s",
  13797. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13798. }
  13799. }
  13800. }
  13801. #else
  13802. #error "Either enable filesystems or provide a custom log_access implementation"
  13803. #endif /* Externally provided function */
  13804. /* Verify given socket address against the ACL.
  13805. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13806. */
  13807. static int
  13808. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13809. {
  13810. int allowed, flag, matched;
  13811. struct vec vec;
  13812. if (phys_ctx) {
  13813. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13814. /* If any ACL is set, deny by default */
  13815. allowed = (list == NULL) ? '+' : '-';
  13816. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13817. flag = vec.ptr[0];
  13818. matched = -1;
  13819. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13820. vec.ptr++;
  13821. vec.len--;
  13822. matched = parse_match_net(&vec, sa, 1);
  13823. }
  13824. if (matched < 0) {
  13825. mg_cry_ctx_internal(phys_ctx,
  13826. "%s: subnet must be [+|-]IP-addr[/x]",
  13827. __func__);
  13828. return -1;
  13829. }
  13830. if (matched) {
  13831. allowed = flag;
  13832. }
  13833. }
  13834. return allowed == '+';
  13835. }
  13836. return -1;
  13837. }
  13838. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13839. static int
  13840. set_uid_option(struct mg_context *phys_ctx)
  13841. {
  13842. int success = 0;
  13843. if (phys_ctx) {
  13844. /* We are currently running as curr_uid. */
  13845. const uid_t curr_uid = getuid();
  13846. /* If set, we want to run as run_as_user. */
  13847. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13848. const struct passwd *to_pw = NULL;
  13849. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13850. /* run_as_user does not exist on the system. We can't proceed
  13851. * further. */
  13852. mg_cry_ctx_internal(phys_ctx,
  13853. "%s: unknown user [%s]",
  13854. __func__,
  13855. run_as_user);
  13856. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13857. /* There was either no request to change user, or we're already
  13858. * running as run_as_user. Nothing else to do.
  13859. */
  13860. success = 1;
  13861. } else {
  13862. /* Valid change request. */
  13863. if (setgid(to_pw->pw_gid) == -1) {
  13864. mg_cry_ctx_internal(phys_ctx,
  13865. "%s: setgid(%s): %s",
  13866. __func__,
  13867. run_as_user,
  13868. strerror(errno));
  13869. } else if (setgroups(0, NULL) == -1) {
  13870. mg_cry_ctx_internal(phys_ctx,
  13871. "%s: setgroups(): %s",
  13872. __func__,
  13873. strerror(errno));
  13874. } else if (setuid(to_pw->pw_uid) == -1) {
  13875. mg_cry_ctx_internal(phys_ctx,
  13876. "%s: setuid(%s): %s",
  13877. __func__,
  13878. run_as_user,
  13879. strerror(errno));
  13880. } else {
  13881. success = 1;
  13882. }
  13883. }
  13884. }
  13885. return success;
  13886. }
  13887. #endif /* !_WIN32 */
  13888. static void
  13889. tls_dtor(void *key)
  13890. {
  13891. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13892. /* key == pthread_getspecific(sTlsKey); */
  13893. if (tls) {
  13894. if (tls->is_master == 2) {
  13895. tls->is_master = -3; /* Mark memory as dead */
  13896. mg_free(tls);
  13897. }
  13898. }
  13899. pthread_setspecific(sTlsKey, NULL);
  13900. }
  13901. #if defined(USE_MBEDTLS)
  13902. /* Check if SSL is required.
  13903. * If so, set up ctx->ssl_ctx pointer. */
  13904. static int
  13905. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13906. {
  13907. if (!phys_ctx) {
  13908. return 0;
  13909. }
  13910. if (!dom_ctx) {
  13911. dom_ctx = &(phys_ctx->dd);
  13912. }
  13913. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13914. /* No SSL port is set. No need to setup SSL. */
  13915. return 1;
  13916. }
  13917. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13918. if (dom_ctx->ssl_ctx == NULL) {
  13919. fprintf(stderr, "ssl_ctx malloc failed\n");
  13920. return 0;
  13921. }
  13922. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13923. == 0
  13924. ? 1
  13925. : 0;
  13926. }
  13927. #elif !defined(NO_SSL)
  13928. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13929. struct mg_domain_context *dom_ctx,
  13930. const char *pem,
  13931. const char *chain);
  13932. static const char *ssl_error(void);
  13933. static int
  13934. refresh_trust(struct mg_connection *conn)
  13935. {
  13936. struct stat cert_buf;
  13937. int64_t t = 0;
  13938. const char *pem;
  13939. const char *chain;
  13940. int should_verify_peer;
  13941. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13942. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13943. * refresh_trust still can not work. */
  13944. return 0;
  13945. }
  13946. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13947. if (chain == NULL) {
  13948. /* pem is not NULL here */
  13949. chain = pem;
  13950. }
  13951. if (*chain == 0) {
  13952. chain = NULL;
  13953. }
  13954. if (stat(pem, &cert_buf) != -1) {
  13955. t = (int64_t)cert_buf.st_mtime;
  13956. }
  13957. mg_lock_context(conn->phys_ctx);
  13958. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13959. conn->dom_ctx->ssl_cert_last_mtime = t;
  13960. should_verify_peer = 0;
  13961. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13962. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13963. == 0) {
  13964. should_verify_peer = 1;
  13965. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13966. "optional")
  13967. == 0) {
  13968. should_verify_peer = 1;
  13969. }
  13970. }
  13971. if (should_verify_peer) {
  13972. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13973. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13974. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13975. ca_file,
  13976. ca_path)
  13977. != 1) {
  13978. mg_unlock_context(conn->phys_ctx);
  13979. mg_cry_ctx_internal(
  13980. conn->phys_ctx,
  13981. "SSL_CTX_load_verify_locations error: %s "
  13982. "ssl_verify_peer requires setting "
  13983. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13984. "present in "
  13985. "the .conf file?",
  13986. ssl_error());
  13987. return 0;
  13988. }
  13989. }
  13990. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13991. mg_unlock_context(conn->phys_ctx);
  13992. return 0;
  13993. }
  13994. }
  13995. mg_unlock_context(conn->phys_ctx);
  13996. return 1;
  13997. }
  13998. #if defined(OPENSSL_API_1_1)
  13999. #else
  14000. static pthread_mutex_t *ssl_mutexes;
  14001. #endif /* OPENSSL_API_1_1 */
  14002. static int
  14003. sslize(struct mg_connection *conn,
  14004. int (*func)(SSL *),
  14005. const struct mg_client_options *client_options)
  14006. {
  14007. int ret, err;
  14008. int short_trust;
  14009. unsigned timeout = 1024;
  14010. unsigned i;
  14011. if (!conn) {
  14012. return 0;
  14013. }
  14014. short_trust =
  14015. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14016. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14017. if (short_trust) {
  14018. int trust_ret = refresh_trust(conn);
  14019. if (!trust_ret) {
  14020. return trust_ret;
  14021. }
  14022. }
  14023. mg_lock_context(conn->phys_ctx);
  14024. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14025. mg_unlock_context(conn->phys_ctx);
  14026. if (conn->ssl == NULL) {
  14027. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14028. OPENSSL_REMOVE_THREAD_STATE();
  14029. return 0;
  14030. }
  14031. SSL_set_app_data(conn->ssl, (char *)conn);
  14032. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14033. if (ret != 1) {
  14034. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14035. SSL_free(conn->ssl);
  14036. conn->ssl = NULL;
  14037. OPENSSL_REMOVE_THREAD_STATE();
  14038. return 0;
  14039. }
  14040. if (client_options) {
  14041. if (client_options->host_name) {
  14042. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14043. }
  14044. }
  14045. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14046. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14047. /* NOTE: The loop below acts as a back-off, so we can end
  14048. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14049. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14050. if (to >= 0) {
  14051. timeout = (unsigned)to;
  14052. }
  14053. }
  14054. /* SSL functions may fail and require to be called again:
  14055. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14056. * Here "func" could be SSL_connect or SSL_accept. */
  14057. for (i = 0; i <= timeout; i += 50) {
  14058. ERR_clear_error();
  14059. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14060. ret = func(conn->ssl);
  14061. if (ret != 1) {
  14062. err = SSL_get_error(conn->ssl, ret);
  14063. if ((err == SSL_ERROR_WANT_CONNECT)
  14064. || (err == SSL_ERROR_WANT_ACCEPT)
  14065. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14066. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14067. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14068. /* Don't wait if the server is going to be stopped. */
  14069. break;
  14070. }
  14071. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14072. /* Simply retry the function call. */
  14073. mg_sleep(50);
  14074. } else {
  14075. /* Need to retry the function call "later".
  14076. * See https://linux.die.net/man/3/ssl_get_error
  14077. * This is typical for non-blocking sockets. */
  14078. struct mg_pollfd pfd;
  14079. int pollres;
  14080. pfd.fd = conn->client.sock;
  14081. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  14082. || (err == SSL_ERROR_WANT_WRITE))
  14083. ? POLLOUT
  14084. : POLLIN;
  14085. pollres =
  14086. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  14087. if (pollres < 0) {
  14088. /* Break if error occured (-1)
  14089. * or server shutdown (-2) */
  14090. break;
  14091. }
  14092. }
  14093. } else if (err == SSL_ERROR_SYSCALL) {
  14094. /* This is an IO error. Look at errno. */
  14095. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14096. break;
  14097. } else {
  14098. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14099. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14100. break;
  14101. }
  14102. } else {
  14103. /* success */
  14104. break;
  14105. }
  14106. }
  14107. ERR_clear_error();
  14108. if (ret != 1) {
  14109. SSL_free(conn->ssl);
  14110. conn->ssl = NULL;
  14111. OPENSSL_REMOVE_THREAD_STATE();
  14112. return 0;
  14113. }
  14114. return 1;
  14115. }
  14116. /* Return OpenSSL error message (from CRYPTO lib) */
  14117. static const char *
  14118. ssl_error(void)
  14119. {
  14120. unsigned long err;
  14121. err = ERR_get_error();
  14122. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14123. }
  14124. static int
  14125. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14126. {
  14127. int i;
  14128. const char hexdigit[] = "0123456789abcdef";
  14129. if ((memlen <= 0) || (buflen <= 0)) {
  14130. return 0;
  14131. }
  14132. if (buflen < (3 * memlen)) {
  14133. return 0;
  14134. }
  14135. for (i = 0; i < memlen; i++) {
  14136. if (i > 0) {
  14137. buf[3 * i - 1] = ' ';
  14138. }
  14139. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14140. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14141. }
  14142. buf[3 * memlen - 1] = 0;
  14143. return 1;
  14144. }
  14145. static int
  14146. ssl_get_client_cert_info(const struct mg_connection *conn,
  14147. struct mg_client_cert *client_cert)
  14148. {
  14149. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14150. if (cert) {
  14151. char str_buf[1024];
  14152. unsigned char buf[256];
  14153. char *str_serial = NULL;
  14154. unsigned int ulen;
  14155. int ilen;
  14156. unsigned char *tmp_buf;
  14157. unsigned char *tmp_p;
  14158. /* Handle to algorithm used for fingerprint */
  14159. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14160. /* Get Subject and issuer */
  14161. X509_NAME *subj = X509_get_subject_name(cert);
  14162. X509_NAME *iss = X509_get_issuer_name(cert);
  14163. /* Get serial number */
  14164. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14165. /* Translate serial number to a hex string */
  14166. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14167. if (serial_bn) {
  14168. str_serial = BN_bn2hex(serial_bn);
  14169. BN_free(serial_bn);
  14170. }
  14171. client_cert->serial =
  14172. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14173. /* Translate subject and issuer to a string */
  14174. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14175. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14176. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14177. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14178. /* Calculate SHA1 fingerprint and store as a hex string */
  14179. ulen = 0;
  14180. /* ASN1_digest is deprecated. Do the calculation manually,
  14181. * using EVP_Digest. */
  14182. ilen = i2d_X509(cert, NULL);
  14183. tmp_buf = (ilen > 0)
  14184. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14185. conn->phys_ctx)
  14186. : NULL;
  14187. if (tmp_buf) {
  14188. tmp_p = tmp_buf;
  14189. (void)i2d_X509(cert, &tmp_p);
  14190. if (!EVP_Digest(
  14191. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14192. ulen = 0;
  14193. }
  14194. mg_free(tmp_buf);
  14195. }
  14196. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14197. *str_buf = 0;
  14198. }
  14199. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14200. client_cert->peer_cert = (void *)cert;
  14201. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14202. * see https://linux.die.net/man/3/bn_bn2hex */
  14203. OPENSSL_free(str_serial);
  14204. return 1;
  14205. }
  14206. return 0;
  14207. }
  14208. #if defined(OPENSSL_API_1_1)
  14209. #else
  14210. static void
  14211. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14212. {
  14213. (void)line;
  14214. (void)file;
  14215. if (mode & 1) {
  14216. /* 1 is CRYPTO_LOCK */
  14217. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14218. } else {
  14219. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14220. }
  14221. }
  14222. #endif /* OPENSSL_API_1_1 */
  14223. #if !defined(NO_SSL_DL)
  14224. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14225. static void *
  14226. load_tls_dll(char *ebuf,
  14227. size_t ebuf_len,
  14228. const char *dll_name,
  14229. struct ssl_func *sw,
  14230. int *feature_missing)
  14231. {
  14232. union {
  14233. void *p;
  14234. void (*fp)(void);
  14235. } u;
  14236. void *dll_handle;
  14237. struct ssl_func *fp;
  14238. int ok;
  14239. int truncated = 0;
  14240. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14241. mg_snprintf(NULL,
  14242. NULL, /* No truncation check for ebuf */
  14243. ebuf,
  14244. ebuf_len,
  14245. "%s: cannot load %s",
  14246. __func__,
  14247. dll_name);
  14248. return NULL;
  14249. }
  14250. ok = 1;
  14251. for (fp = sw; fp->name != NULL; fp++) {
  14252. #if defined(_WIN32)
  14253. /* GetProcAddress() returns pointer to function */
  14254. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14255. #else
  14256. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14257. * pointers to function pointers. We need to use a union to make a
  14258. * cast. */
  14259. u.p = dlsym(dll_handle, fp->name);
  14260. #endif /* _WIN32 */
  14261. /* Set pointer (might be NULL) */
  14262. fp->ptr = u.fp;
  14263. if (u.fp == NULL) {
  14264. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14265. if (feature_missing) {
  14266. feature_missing[fp->required]++;
  14267. }
  14268. if (fp->required == TLS_Mandatory) {
  14269. /* Mandatory function is missing */
  14270. if (ok) {
  14271. /* This is the first missing function.
  14272. * Create a new error message. */
  14273. mg_snprintf(NULL,
  14274. &truncated,
  14275. ebuf,
  14276. ebuf_len,
  14277. "%s: %s: cannot find %s",
  14278. __func__,
  14279. dll_name,
  14280. fp->name);
  14281. ok = 0;
  14282. } else {
  14283. /* This is yet anothermissing function.
  14284. * Append existing error message. */
  14285. size_t cur_len = strlen(ebuf);
  14286. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14287. mg_snprintf(NULL,
  14288. &truncated,
  14289. ebuf + cur_len,
  14290. ebuf_len - cur_len - 3,
  14291. ", %s",
  14292. fp->name);
  14293. if (truncated) {
  14294. /* If truncated, add "..." */
  14295. strcat(ebuf, "...");
  14296. }
  14297. }
  14298. }
  14299. }
  14300. }
  14301. }
  14302. if (!ok) {
  14303. (void)dlclose(dll_handle);
  14304. return NULL;
  14305. }
  14306. return dll_handle;
  14307. }
  14308. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14309. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14310. #endif /* NO_SSL_DL */
  14311. #if defined(SSL_ALREADY_INITIALIZED)
  14312. static volatile ptrdiff_t cryptolib_users =
  14313. 1; /* Reference counter for crypto library. */
  14314. #else
  14315. static volatile ptrdiff_t cryptolib_users =
  14316. 0; /* Reference counter for crypto library. */
  14317. #endif
  14318. static int
  14319. initialize_openssl(char *ebuf, size_t ebuf_len)
  14320. {
  14321. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14322. int i, num_locks;
  14323. size_t size;
  14324. #endif
  14325. if (ebuf_len > 0) {
  14326. ebuf[0] = 0;
  14327. }
  14328. #if !defined(NO_SSL_DL)
  14329. if (!cryptolib_dll_handle) {
  14330. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14331. cryptolib_dll_handle = load_tls_dll(
  14332. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14333. if (!cryptolib_dll_handle) {
  14334. mg_snprintf(NULL,
  14335. NULL, /* No truncation check for ebuf */
  14336. ebuf,
  14337. ebuf_len,
  14338. "%s: error loading library %s",
  14339. __func__,
  14340. CRYPTO_LIB);
  14341. DEBUG_TRACE("%s", ebuf);
  14342. return 0;
  14343. }
  14344. }
  14345. #endif /* NO_SSL_DL */
  14346. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14347. return 1;
  14348. }
  14349. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14350. /* Initialize locking callbacks, needed for thread safety.
  14351. * http://www.openssl.org/support/faq.html#PROG1
  14352. */
  14353. num_locks = CRYPTO_num_locks();
  14354. if (num_locks < 0) {
  14355. num_locks = 0;
  14356. }
  14357. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14358. /* allocate mutex array, if required */
  14359. if (num_locks == 0) {
  14360. /* No mutex array required */
  14361. ssl_mutexes = NULL;
  14362. } else {
  14363. /* Mutex array required - allocate it */
  14364. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14365. /* Check OOM */
  14366. if (ssl_mutexes == NULL) {
  14367. mg_snprintf(NULL,
  14368. NULL, /* No truncation check for ebuf */
  14369. ebuf,
  14370. ebuf_len,
  14371. "%s: cannot allocate mutexes: %s",
  14372. __func__,
  14373. ssl_error());
  14374. DEBUG_TRACE("%s", ebuf);
  14375. return 0;
  14376. }
  14377. /* initialize mutex array */
  14378. for (i = 0; i < num_locks; i++) {
  14379. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14380. mg_snprintf(NULL,
  14381. NULL, /* No truncation check for ebuf */
  14382. ebuf,
  14383. ebuf_len,
  14384. "%s: error initializing mutex %i of %i",
  14385. __func__,
  14386. i,
  14387. num_locks);
  14388. DEBUG_TRACE("%s", ebuf);
  14389. mg_free(ssl_mutexes);
  14390. return 0;
  14391. }
  14392. }
  14393. }
  14394. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14395. CRYPTO_set_id_callback(&mg_current_thread_id);
  14396. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14397. #if !defined(NO_SSL_DL)
  14398. if (!ssllib_dll_handle) {
  14399. ssllib_dll_handle =
  14400. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14401. if (!ssllib_dll_handle) {
  14402. #if !defined(OPENSSL_API_1_1)
  14403. mg_free(ssl_mutexes);
  14404. #endif
  14405. DEBUG_TRACE("%s", ebuf);
  14406. return 0;
  14407. }
  14408. }
  14409. #endif /* NO_SSL_DL */
  14410. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14411. && !defined(NO_SSL_DL)
  14412. /* Initialize SSL library */
  14413. OPENSSL_init_ssl(0, NULL);
  14414. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14415. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14416. NULL);
  14417. #else
  14418. /* Initialize SSL library */
  14419. SSL_library_init();
  14420. SSL_load_error_strings();
  14421. #endif
  14422. return 1;
  14423. }
  14424. static int
  14425. ssl_use_pem_file(struct mg_context *phys_ctx,
  14426. struct mg_domain_context *dom_ctx,
  14427. const char *pem,
  14428. const char *chain)
  14429. {
  14430. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14431. mg_cry_ctx_internal(phys_ctx,
  14432. "%s: cannot open certificate file %s: %s",
  14433. __func__,
  14434. pem,
  14435. ssl_error());
  14436. return 0;
  14437. }
  14438. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14439. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14440. mg_cry_ctx_internal(phys_ctx,
  14441. "%s: cannot open private key file %s: %s",
  14442. __func__,
  14443. pem,
  14444. ssl_error());
  14445. return 0;
  14446. }
  14447. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14448. mg_cry_ctx_internal(phys_ctx,
  14449. "%s: certificate and private key do not match: %s",
  14450. __func__,
  14451. pem);
  14452. return 0;
  14453. }
  14454. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14455. * chain files that contain private keys and certificates in
  14456. * SSL_CTX_use_certificate_chain_file.
  14457. * The CivetWeb-Server used pem-Files that contained both information.
  14458. * In order to make wolfSSL work, it is split in two files.
  14459. * One file that contains key and certificate used by the server and
  14460. * an optional chain file for the ssl stack.
  14461. */
  14462. if (chain) {
  14463. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14464. mg_cry_ctx_internal(phys_ctx,
  14465. "%s: cannot use certificate chain file %s: %s",
  14466. __func__,
  14467. chain,
  14468. ssl_error());
  14469. return 0;
  14470. }
  14471. }
  14472. return 1;
  14473. }
  14474. #if defined(OPENSSL_API_1_1)
  14475. static unsigned long
  14476. ssl_get_protocol(int version_id)
  14477. {
  14478. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14479. if (version_id > 0)
  14480. ret |= SSL_OP_NO_SSLv2;
  14481. if (version_id > 1)
  14482. ret |= SSL_OP_NO_SSLv3;
  14483. if (version_id > 2)
  14484. ret |= SSL_OP_NO_TLSv1;
  14485. if (version_id > 3)
  14486. ret |= SSL_OP_NO_TLSv1_1;
  14487. if (version_id > 4)
  14488. ret |= SSL_OP_NO_TLSv1_2;
  14489. #if defined(SSL_OP_NO_TLSv1_3)
  14490. if (version_id > 5)
  14491. ret |= SSL_OP_NO_TLSv1_3;
  14492. #endif
  14493. return ret;
  14494. }
  14495. #else
  14496. static long
  14497. ssl_get_protocol(int version_id)
  14498. {
  14499. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14500. if (version_id > 0)
  14501. ret |= SSL_OP_NO_SSLv2;
  14502. if (version_id > 1)
  14503. ret |= SSL_OP_NO_SSLv3;
  14504. if (version_id > 2)
  14505. ret |= SSL_OP_NO_TLSv1;
  14506. if (version_id > 3)
  14507. ret |= SSL_OP_NO_TLSv1_1;
  14508. if (version_id > 4)
  14509. ret |= SSL_OP_NO_TLSv1_2;
  14510. #if defined(SSL_OP_NO_TLSv1_3)
  14511. if (version_id > 5)
  14512. ret |= SSL_OP_NO_TLSv1_3;
  14513. #endif
  14514. return (long)ret;
  14515. }
  14516. #endif /* OPENSSL_API_1_1 */
  14517. /* SSL callback documentation:
  14518. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14519. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14520. * https://linux.die.net/man/3/ssl_set_info_callback */
  14521. /* Note: There is no "const" for the first argument in the documentation
  14522. * examples, however some (maybe most, but not all) headers of OpenSSL
  14523. * versions / OpenSSL compatibility layers have it. Having a different
  14524. * definition will cause a warning in C and an error in C++. Use "const SSL
  14525. * *", while automatical conversion from "SSL *" works for all compilers,
  14526. * but not other way around */
  14527. static void
  14528. ssl_info_callback(const SSL *ssl, int what, int ret)
  14529. {
  14530. (void)ret;
  14531. if (what & SSL_CB_HANDSHAKE_START) {
  14532. SSL_get_app_data(ssl);
  14533. }
  14534. if (what & SSL_CB_HANDSHAKE_DONE) {
  14535. /* TODO: check for openSSL 1.1 */
  14536. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14537. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14538. }
  14539. }
  14540. static int
  14541. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14542. {
  14543. #if defined(GCC_DIAGNOSTIC)
  14544. #pragma GCC diagnostic push
  14545. #pragma GCC diagnostic ignored "-Wcast-align"
  14546. #endif /* defined(GCC_DIAGNOSTIC) */
  14547. /* We used an aligned pointer in SSL_set_app_data */
  14548. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14549. #if defined(GCC_DIAGNOSTIC)
  14550. #pragma GCC diagnostic pop
  14551. #endif /* defined(GCC_DIAGNOSTIC) */
  14552. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14553. (void)ad;
  14554. (void)arg;
  14555. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14556. DEBUG_ASSERT(0);
  14557. return SSL_TLSEXT_ERR_NOACK;
  14558. }
  14559. conn->dom_ctx = &(conn->phys_ctx->dd);
  14560. /* Old clients (Win XP) will not support SNI. Then, there
  14561. * is no server name available in the request - we can
  14562. * only work with the default certificate.
  14563. * Multiple HTTPS hosts on one IP+port are only possible
  14564. * with a certificate containing all alternative names.
  14565. */
  14566. if ((servername == NULL) || (*servername == 0)) {
  14567. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  14568. mg_lock_context(conn->phys_ctx);
  14569. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14570. mg_unlock_context(conn->phys_ctx);
  14571. return SSL_TLSEXT_ERR_NOACK;
  14572. }
  14573. DEBUG_TRACE("TLS connection to host %s", servername);
  14574. while (conn->dom_ctx) {
  14575. if (!mg_strcasecmp(servername,
  14576. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  14577. /* Found matching domain */
  14578. DEBUG_TRACE("TLS domain %s found",
  14579. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  14580. break;
  14581. }
  14582. mg_lock_context(conn->phys_ctx);
  14583. conn->dom_ctx = conn->dom_ctx->next;
  14584. mg_unlock_context(conn->phys_ctx);
  14585. }
  14586. if (conn->dom_ctx == NULL) {
  14587. /* Default domain */
  14588. DEBUG_TRACE("TLS default domain %s used",
  14589. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14590. conn->dom_ctx = &(conn->phys_ctx->dd);
  14591. }
  14592. mg_lock_context(conn->phys_ctx);
  14593. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14594. mg_unlock_context(conn->phys_ctx);
  14595. return SSL_TLSEXT_ERR_OK;
  14596. }
  14597. #if defined(USE_ALPN)
  14598. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14599. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14600. alpn_proto_list + 3 + 8,
  14601. NULL};
  14602. #if defined(USE_HTTP2)
  14603. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14604. alpn_proto_list + 3,
  14605. alpn_proto_list + 3 + 8,
  14606. NULL};
  14607. #endif
  14608. static int
  14609. alpn_select_cb(SSL *ssl,
  14610. const unsigned char **out,
  14611. unsigned char *outlen,
  14612. const unsigned char *in,
  14613. unsigned int inlen,
  14614. void *arg)
  14615. {
  14616. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14617. unsigned int i, j, enable_http2 = 0;
  14618. const char **alpn_proto_order = alpn_proto_order_http1;
  14619. struct mg_workerTLS *tls =
  14620. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14621. (void)ssl;
  14622. if (tls == NULL) {
  14623. /* Need to store protocol in Thread Local Storage */
  14624. /* If there is no Thread Local Storage, don't use ALPN */
  14625. return SSL_TLSEXT_ERR_NOACK;
  14626. }
  14627. #if defined(USE_HTTP2)
  14628. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14629. if (enable_http2) {
  14630. alpn_proto_order = alpn_proto_order_http2;
  14631. }
  14632. #endif
  14633. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14634. /* check all accepted protocols in this order */
  14635. const char *alpn_proto = alpn_proto_order[j];
  14636. /* search input for matching protocol */
  14637. for (i = 0; i < inlen; i++) {
  14638. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14639. *out = in + i + 1;
  14640. *outlen = in[i];
  14641. tls->alpn_proto = alpn_proto;
  14642. return SSL_TLSEXT_ERR_OK;
  14643. }
  14644. }
  14645. }
  14646. /* Nothing found */
  14647. return SSL_TLSEXT_ERR_NOACK;
  14648. }
  14649. static int
  14650. next_protos_advertised_cb(SSL *ssl,
  14651. const unsigned char **data,
  14652. unsigned int *len,
  14653. void *arg)
  14654. {
  14655. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14656. *data = (const unsigned char *)alpn_proto_list;
  14657. *len = (unsigned int)strlen((const char *)data);
  14658. (void)ssl;
  14659. (void)dom_ctx;
  14660. return SSL_TLSEXT_ERR_OK;
  14661. }
  14662. static int
  14663. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14664. {
  14665. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14666. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14667. (const unsigned char *)alpn_proto_list,
  14668. alpn_len);
  14669. if (ret != 0) {
  14670. mg_cry_ctx_internal(phys_ctx,
  14671. "SSL_CTX_set_alpn_protos error: %s",
  14672. ssl_error());
  14673. }
  14674. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14675. alpn_select_cb,
  14676. (void *)dom_ctx);
  14677. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14678. next_protos_advertised_cb,
  14679. (void *)dom_ctx);
  14680. return ret;
  14681. }
  14682. #endif
  14683. /* Setup SSL CTX as required by CivetWeb */
  14684. static int
  14685. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14686. struct mg_domain_context *dom_ctx,
  14687. const char *pem,
  14688. const char *chain)
  14689. {
  14690. int callback_ret;
  14691. int should_verify_peer;
  14692. int peer_certificate_optional;
  14693. const char *ca_path;
  14694. const char *ca_file;
  14695. int use_default_verify_paths;
  14696. int verify_depth;
  14697. struct timespec now_mt;
  14698. md5_byte_t ssl_context_id[16];
  14699. md5_state_t md5state;
  14700. int protocol_ver;
  14701. int ssl_cache_timeout;
  14702. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14703. && !defined(NO_SSL_DL)
  14704. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14705. mg_cry_ctx_internal(phys_ctx,
  14706. "SSL_CTX_new (server) error: %s",
  14707. ssl_error());
  14708. return 0;
  14709. }
  14710. #else
  14711. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14712. mg_cry_ctx_internal(phys_ctx,
  14713. "SSL_CTX_new (server) error: %s",
  14714. ssl_error());
  14715. return 0;
  14716. }
  14717. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14718. #if defined(SSL_OP_NO_TLSv1_3)
  14719. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14720. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14721. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14722. | SSL_OP_NO_TLSv1_3);
  14723. #else
  14724. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14725. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14726. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14727. #endif
  14728. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14729. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14730. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14731. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14732. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14733. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14734. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14735. #if defined(SSL_OP_NO_RENEGOTIATION)
  14736. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14737. #endif
  14738. #if !defined(NO_SSL_DL)
  14739. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14740. #endif /* NO_SSL_DL */
  14741. /* In SSL documentation examples callback defined without const
  14742. * specifier 'void (*)(SSL *, int, int)' See:
  14743. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14744. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14745. * But in the source code const SSL is used:
  14746. * 'void (*)(const SSL *, int, int)' See:
  14747. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14748. * Problem about wrong documentation described, but not resolved:
  14749. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14750. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14751. * But when compiled with modern C++ compiler, correct const should be
  14752. * provided
  14753. */
  14754. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14755. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14756. ssl_servername_callback);
  14757. /* If a callback has been specified, call it. */
  14758. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14759. ? 0
  14760. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14761. phys_ctx->user_data));
  14762. /* If callback returns 0, civetweb sets up the SSL certificate.
  14763. * If it returns 1, civetweb assumes the calback already did this.
  14764. * If it returns -1, initializing ssl fails. */
  14765. if (callback_ret < 0) {
  14766. mg_cry_ctx_internal(phys_ctx,
  14767. "SSL callback returned error: %i",
  14768. callback_ret);
  14769. return 0;
  14770. }
  14771. if (callback_ret > 0) {
  14772. /* Callback did everything. */
  14773. return 1;
  14774. }
  14775. /* If a domain callback has been specified, call it. */
  14776. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14777. ? 0
  14778. : (phys_ctx->callbacks.init_ssl_domain(
  14779. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14780. dom_ctx->ssl_ctx,
  14781. phys_ctx->user_data));
  14782. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14783. * If it returns 1, civetweb assumes the calback already did this.
  14784. * If it returns -1, initializing ssl fails. */
  14785. if (callback_ret < 0) {
  14786. mg_cry_ctx_internal(phys_ctx,
  14787. "Domain SSL callback returned error: %i",
  14788. callback_ret);
  14789. return 0;
  14790. }
  14791. if (callback_ret > 0) {
  14792. /* Domain callback did everything. */
  14793. return 1;
  14794. }
  14795. /* Use some combination of start time, domain and port as a SSL
  14796. * context ID. This should be unique on the current machine. */
  14797. md5_init(&md5state);
  14798. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14799. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14800. md5_append(&md5state,
  14801. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14802. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14803. md5_append(&md5state,
  14804. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14805. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14806. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14807. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14808. md5_finish(&md5state, ssl_context_id);
  14809. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14810. (unsigned char *)ssl_context_id,
  14811. sizeof(ssl_context_id));
  14812. if (pem != NULL) {
  14813. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14814. return 0;
  14815. }
  14816. }
  14817. /* Should we support client certificates? */
  14818. /* Default is "no". */
  14819. should_verify_peer = 0;
  14820. peer_certificate_optional = 0;
  14821. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14822. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14823. /* Yes, they are mandatory */
  14824. should_verify_peer = 1;
  14825. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14826. "optional")
  14827. == 0) {
  14828. /* Yes, they are optional */
  14829. should_verify_peer = 1;
  14830. peer_certificate_optional = 1;
  14831. }
  14832. }
  14833. use_default_verify_paths =
  14834. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14835. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14836. == 0);
  14837. if (should_verify_peer) {
  14838. ca_path = dom_ctx->config[SSL_CA_PATH];
  14839. ca_file = dom_ctx->config[SSL_CA_FILE];
  14840. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14841. != 1) {
  14842. mg_cry_ctx_internal(phys_ctx,
  14843. "SSL_CTX_load_verify_locations error: %s "
  14844. "ssl_verify_peer requires setting "
  14845. "either ssl_ca_path or ssl_ca_file. "
  14846. "Is any of them present in the "
  14847. ".conf file?",
  14848. ssl_error());
  14849. return 0;
  14850. }
  14851. if (peer_certificate_optional) {
  14852. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14853. } else {
  14854. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14855. SSL_VERIFY_PEER
  14856. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14857. NULL);
  14858. }
  14859. if (use_default_verify_paths
  14860. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14861. mg_cry_ctx_internal(phys_ctx,
  14862. "SSL_CTX_set_default_verify_paths error: %s",
  14863. ssl_error());
  14864. return 0;
  14865. }
  14866. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14867. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14868. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14869. }
  14870. }
  14871. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14872. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14873. dom_ctx->config[SSL_CIPHER_LIST])
  14874. != 1) {
  14875. mg_cry_ctx_internal(phys_ctx,
  14876. "SSL_CTX_set_cipher_list error: %s",
  14877. ssl_error());
  14878. }
  14879. }
  14880. /* SSL session caching */
  14881. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14882. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14883. : 0);
  14884. if (ssl_cache_timeout > 0) {
  14885. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14886. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14887. * default */
  14888. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14889. }
  14890. #if defined(USE_ALPN)
  14891. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14892. #if !defined(NO_SSL_DL)
  14893. if (!tls_feature_missing[TLS_ALPN])
  14894. #endif
  14895. {
  14896. init_alpn(phys_ctx, dom_ctx);
  14897. }
  14898. #endif
  14899. return 1;
  14900. }
  14901. /* Check if SSL is required.
  14902. * If so, dynamically load SSL library
  14903. * and set up ctx->ssl_ctx pointer. */
  14904. static int
  14905. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14906. {
  14907. void *ssl_ctx = 0;
  14908. int callback_ret;
  14909. const char *pem;
  14910. const char *chain;
  14911. char ebuf[128];
  14912. if (!phys_ctx) {
  14913. return 0;
  14914. }
  14915. if (!dom_ctx) {
  14916. dom_ctx = &(phys_ctx->dd);
  14917. }
  14918. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14919. /* No SSL port is set. No need to setup SSL. */
  14920. return 1;
  14921. }
  14922. /* Check for external SSL_CTX */
  14923. callback_ret =
  14924. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14925. ? 0
  14926. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14927. phys_ctx->user_data));
  14928. if (callback_ret < 0) {
  14929. /* Callback exists and returns <0: Initializing failed. */
  14930. mg_cry_ctx_internal(phys_ctx,
  14931. "external_ssl_ctx callback returned error: %i",
  14932. callback_ret);
  14933. return 0;
  14934. } else if (callback_ret > 0) {
  14935. /* Callback exists and returns >0: Initializing complete,
  14936. * civetweb should not modify the SSL context. */
  14937. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14938. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14939. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14940. return 0;
  14941. }
  14942. return 1;
  14943. }
  14944. /* If the callback does not exist or return 0, civetweb must initialize
  14945. * the SSL context. Handle "domain" callback next. */
  14946. /* Check for external domain SSL_CTX callback. */
  14947. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14948. ? 0
  14949. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14950. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14951. &ssl_ctx,
  14952. phys_ctx->user_data));
  14953. if (callback_ret < 0) {
  14954. /* Callback < 0: Error. Abort init. */
  14955. mg_cry_ctx_internal(
  14956. phys_ctx,
  14957. "external_ssl_ctx_domain callback returned error: %i",
  14958. callback_ret);
  14959. return 0;
  14960. } else if (callback_ret > 0) {
  14961. /* Callback > 0: Consider init done. */
  14962. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14963. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14964. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14965. return 0;
  14966. }
  14967. return 1;
  14968. }
  14969. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14970. * 0, CivetWeb should continue initializing SSL */
  14971. /* If PEM file is not specified and the init_ssl callbacks
  14972. * are not specified, setup will fail. */
  14973. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14974. && (phys_ctx->callbacks.init_ssl == NULL)
  14975. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14976. /* No certificate and no init_ssl callbacks:
  14977. * Essential data to set up TLS is missing.
  14978. */
  14979. mg_cry_ctx_internal(phys_ctx,
  14980. "Initializing SSL failed: -%s is not set",
  14981. config_options[SSL_CERTIFICATE].name);
  14982. return 0;
  14983. }
  14984. /* If a certificate chain is configured, use it. */
  14985. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14986. if (chain == NULL) {
  14987. /* Default: certificate chain in PEM file */
  14988. chain = pem;
  14989. }
  14990. if ((chain != NULL) && (*chain == 0)) {
  14991. /* If the chain is an empty string, don't use it. */
  14992. chain = NULL;
  14993. }
  14994. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14995. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14996. return 0;
  14997. }
  14998. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14999. }
  15000. static void
  15001. uninitialize_openssl(void)
  15002. {
  15003. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15004. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15005. /* Shutdown according to
  15006. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15007. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15008. */
  15009. CONF_modules_unload(1);
  15010. #else
  15011. int i;
  15012. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15013. /* Shutdown according to
  15014. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15015. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15016. */
  15017. CRYPTO_set_locking_callback(NULL);
  15018. CRYPTO_set_id_callback(NULL);
  15019. ENGINE_cleanup();
  15020. CONF_modules_unload(1);
  15021. ERR_free_strings();
  15022. EVP_cleanup();
  15023. CRYPTO_cleanup_all_ex_data();
  15024. OPENSSL_REMOVE_THREAD_STATE();
  15025. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15026. pthread_mutex_destroy(&ssl_mutexes[i]);
  15027. }
  15028. mg_free(ssl_mutexes);
  15029. ssl_mutexes = NULL;
  15030. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15031. }
  15032. }
  15033. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15034. #if !defined(NO_FILESYSTEMS)
  15035. static int
  15036. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15037. {
  15038. if (phys_ctx) {
  15039. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15040. const char *path;
  15041. struct mg_connection fc;
  15042. if (!dom_ctx) {
  15043. dom_ctx = &(phys_ctx->dd);
  15044. }
  15045. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15046. if ((path != NULL)
  15047. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15048. mg_cry_ctx_internal(phys_ctx,
  15049. "Cannot open %s: %s",
  15050. path,
  15051. strerror(ERRNO));
  15052. return 0;
  15053. }
  15054. return 1;
  15055. }
  15056. return 0;
  15057. }
  15058. #endif /* NO_FILESYSTEMS */
  15059. static int
  15060. set_acl_option(struct mg_context *phys_ctx)
  15061. {
  15062. union usa sa;
  15063. memset(&sa, 0, sizeof(sa));
  15064. #if defined(USE_IPV6)
  15065. sa.sin6.sin6_family = AF_INET6;
  15066. #else
  15067. sa.sin.sin_family = AF_INET;
  15068. #endif
  15069. return check_acl(phys_ctx, &sa) != -1;
  15070. }
  15071. static void
  15072. reset_per_request_attributes(struct mg_connection *conn)
  15073. {
  15074. if (!conn) {
  15075. return;
  15076. }
  15077. conn->num_bytes_sent = conn->consumed_content = 0;
  15078. conn->path_info = NULL;
  15079. conn->status_code = -1;
  15080. conn->content_len = -1;
  15081. conn->is_chunked = 0;
  15082. conn->must_close = 0;
  15083. conn->request_len = 0;
  15084. conn->request_state = 0;
  15085. conn->throttle = 0;
  15086. conn->accept_gzip = 0;
  15087. conn->response_info.content_length = conn->request_info.content_length = -1;
  15088. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15089. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15090. conn->response_info.status_text = NULL;
  15091. conn->response_info.status_code = 0;
  15092. conn->request_info.remote_user = NULL;
  15093. conn->request_info.request_method = NULL;
  15094. conn->request_info.request_uri = NULL;
  15095. /* Free cleaned local URI (if any) */
  15096. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15097. mg_free((void *)conn->request_info.local_uri);
  15098. conn->request_info.local_uri = NULL;
  15099. }
  15100. conn->request_info.local_uri = NULL;
  15101. #if defined(USE_SERVER_STATS)
  15102. conn->processing_time = 0;
  15103. #endif
  15104. }
  15105. static int
  15106. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15107. {
  15108. if ((so->lsa.sa.sa_family == AF_INET)
  15109. || (so->lsa.sa.sa_family == AF_INET6)) {
  15110. /* Only for TCP sockets */
  15111. if (setsockopt(so->sock,
  15112. IPPROTO_TCP,
  15113. TCP_NODELAY,
  15114. (SOCK_OPT_TYPE)&nodelay_on,
  15115. sizeof(nodelay_on))
  15116. != 0) {
  15117. /* Error */
  15118. return 1;
  15119. }
  15120. }
  15121. /* OK */
  15122. return 0;
  15123. }
  15124. #if !defined(__ZEPHYR__)
  15125. static void
  15126. close_socket_gracefully(struct mg_connection *conn)
  15127. {
  15128. #if defined(_WIN32)
  15129. char buf[MG_BUF_LEN];
  15130. int n;
  15131. #endif
  15132. struct linger linger;
  15133. int error_code = 0;
  15134. int linger_timeout = -2;
  15135. socklen_t opt_len = sizeof(error_code);
  15136. if (!conn) {
  15137. return;
  15138. }
  15139. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15140. * "Note that enabling a nonzero timeout on a nonblocking socket
  15141. * is not recommended.", so set it to blocking now */
  15142. set_blocking_mode(conn->client.sock);
  15143. /* Send FIN to the client */
  15144. shutdown(conn->client.sock, SHUTDOWN_WR);
  15145. #if defined(_WIN32)
  15146. /* Read and discard pending incoming data. If we do not do that and
  15147. * close
  15148. * the socket, the data in the send buffer may be discarded. This
  15149. * behaviour is seen on Windows, when client keeps sending data
  15150. * when server decides to close the connection; then when client
  15151. * does recv() it gets no data back. */
  15152. do {
  15153. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15154. } while (n > 0);
  15155. #endif
  15156. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15157. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15158. }
  15159. /* Set linger option according to configuration */
  15160. if (linger_timeout >= 0) {
  15161. /* Set linger option to avoid socket hanging out after close. This
  15162. * prevent ephemeral port exhaust problem under high QPS. */
  15163. linger.l_onoff = 1;
  15164. #if defined(_MSC_VER)
  15165. #pragma warning(push)
  15166. #pragma warning(disable : 4244)
  15167. #endif
  15168. #if defined(GCC_DIAGNOSTIC)
  15169. #pragma GCC diagnostic push
  15170. #pragma GCC diagnostic ignored "-Wconversion"
  15171. #endif
  15172. /* Data type of linger structure elements may differ,
  15173. * so we don't know what cast we need here.
  15174. * Disable type conversion warnings. */
  15175. linger.l_linger = (linger_timeout + 999) / 1000;
  15176. #if defined(GCC_DIAGNOSTIC)
  15177. #pragma GCC diagnostic pop
  15178. #endif
  15179. #if defined(_MSC_VER)
  15180. #pragma warning(pop)
  15181. #endif
  15182. } else {
  15183. linger.l_onoff = 0;
  15184. linger.l_linger = 0;
  15185. }
  15186. if (linger_timeout < -1) {
  15187. /* Default: don't configure any linger */
  15188. } else if (getsockopt(conn->client.sock,
  15189. SOL_SOCKET,
  15190. SO_ERROR,
  15191. #if defined(_WIN32) /* WinSock uses different data type here */
  15192. (char *)&error_code,
  15193. #else
  15194. &error_code,
  15195. #endif
  15196. &opt_len)
  15197. != 0) {
  15198. /* Cannot determine if socket is already closed. This should
  15199. * not occur and never did in a test. Log an error message
  15200. * and continue. */
  15201. mg_cry_internal(conn,
  15202. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15203. __func__,
  15204. strerror(ERRNO));
  15205. #if defined(_WIN32)
  15206. } else if (error_code == WSAECONNRESET) {
  15207. #else
  15208. } else if (error_code == ECONNRESET) {
  15209. #endif
  15210. /* Socket already closed by client/peer, close socket without linger
  15211. */
  15212. } else {
  15213. /* Set linger timeout */
  15214. if (setsockopt(conn->client.sock,
  15215. SOL_SOCKET,
  15216. SO_LINGER,
  15217. (char *)&linger,
  15218. sizeof(linger))
  15219. != 0) {
  15220. mg_cry_internal(
  15221. conn,
  15222. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15223. __func__,
  15224. linger.l_onoff,
  15225. linger.l_linger,
  15226. strerror(ERRNO));
  15227. }
  15228. }
  15229. /* Now we know that our FIN is ACK-ed, safe to close */
  15230. closesocket(conn->client.sock);
  15231. conn->client.sock = INVALID_SOCKET;
  15232. }
  15233. #endif
  15234. static void
  15235. close_connection(struct mg_connection *conn)
  15236. {
  15237. #if defined(USE_SERVER_STATS)
  15238. conn->conn_state = 6; /* to close */
  15239. #endif
  15240. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15241. if (conn->lua_websocket_state) {
  15242. lua_websocket_close(conn, conn->lua_websocket_state);
  15243. conn->lua_websocket_state = NULL;
  15244. }
  15245. #endif
  15246. mg_lock_connection(conn);
  15247. /* Set close flag, so keep-alive loops will stop */
  15248. conn->must_close = 1;
  15249. /* call the connection_close callback if assigned */
  15250. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15251. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15252. conn->phys_ctx->callbacks.connection_close(conn);
  15253. }
  15254. }
  15255. /* Reset user data, after close callback is called.
  15256. * Do not reuse it. If the user needs a destructor,
  15257. * it must be done in the connection_close callback. */
  15258. mg_set_user_connection_data(conn, NULL);
  15259. #if defined(USE_SERVER_STATS)
  15260. conn->conn_state = 7; /* closing */
  15261. #endif
  15262. #if defined(USE_MBEDTLS)
  15263. if (conn->ssl != NULL) {
  15264. mbed_ssl_close(conn->ssl);
  15265. conn->ssl = NULL;
  15266. }
  15267. #elif !defined(NO_SSL)
  15268. if (conn->ssl != NULL) {
  15269. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15270. */
  15271. SSL_shutdown(conn->ssl);
  15272. SSL_free(conn->ssl);
  15273. OPENSSL_REMOVE_THREAD_STATE();
  15274. conn->ssl = NULL;
  15275. }
  15276. #endif
  15277. if (conn->client.sock != INVALID_SOCKET) {
  15278. #if defined(__ZEPHYR__)
  15279. closesocket(conn->client.sock);
  15280. #else
  15281. close_socket_gracefully(conn);
  15282. #endif
  15283. conn->client.sock = INVALID_SOCKET;
  15284. }
  15285. /* call the connection_closed callback if assigned */
  15286. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15287. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15288. conn->phys_ctx->callbacks.connection_closed(conn);
  15289. }
  15290. }
  15291. mg_unlock_connection(conn);
  15292. #if defined(USE_SERVER_STATS)
  15293. conn->conn_state = 8; /* closed */
  15294. #endif
  15295. }
  15296. void
  15297. mg_close_connection(struct mg_connection *conn)
  15298. {
  15299. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15300. return;
  15301. }
  15302. #if defined(USE_WEBSOCKET)
  15303. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15304. if (conn->in_websocket_handling) {
  15305. /* Set close flag, so the server thread can exit. */
  15306. conn->must_close = 1;
  15307. return;
  15308. }
  15309. }
  15310. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15311. unsigned int i;
  15312. /* client context: loops must end */
  15313. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15314. conn->must_close = 1;
  15315. /* We need to get the client thread out of the select/recv call
  15316. * here. */
  15317. /* Since we use a sleep quantum of some seconds to check for recv
  15318. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15319. /* join worker thread */
  15320. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  15321. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15322. }
  15323. }
  15324. #endif /* defined(USE_WEBSOCKET) */
  15325. close_connection(conn);
  15326. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15327. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15328. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15329. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15330. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15331. }
  15332. #endif
  15333. #if defined(USE_WEBSOCKET)
  15334. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15335. mg_free(conn->phys_ctx->worker_threadids);
  15336. (void)pthread_mutex_destroy(&conn->mutex);
  15337. mg_free(conn);
  15338. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15339. (void)pthread_mutex_destroy(&conn->mutex);
  15340. mg_free(conn);
  15341. }
  15342. #else
  15343. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15344. (void)pthread_mutex_destroy(&conn->mutex);
  15345. mg_free(conn);
  15346. }
  15347. #endif /* defined(USE_WEBSOCKET) */
  15348. }
  15349. static struct mg_connection *
  15350. mg_connect_client_impl(const struct mg_client_options *client_options,
  15351. int use_ssl,
  15352. char *ebuf,
  15353. size_t ebuf_len)
  15354. {
  15355. struct mg_connection *conn = NULL;
  15356. SOCKET sock;
  15357. union usa sa;
  15358. struct sockaddr *psa;
  15359. socklen_t len;
  15360. unsigned max_req_size =
  15361. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15362. /* Size of structures, aligned to 8 bytes */
  15363. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15364. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15365. conn =
  15366. (struct mg_connection *)mg_calloc(1,
  15367. conn_size + ctx_size + max_req_size);
  15368. if (conn == NULL) {
  15369. mg_snprintf(NULL,
  15370. NULL, /* No truncation check for ebuf */
  15371. ebuf,
  15372. ebuf_len,
  15373. "calloc(): %s",
  15374. strerror(ERRNO));
  15375. return NULL;
  15376. }
  15377. #if defined(GCC_DIAGNOSTIC)
  15378. #pragma GCC diagnostic push
  15379. #pragma GCC diagnostic ignored "-Wcast-align"
  15380. #endif /* defined(GCC_DIAGNOSTIC) */
  15381. /* conn_size is aligned to 8 bytes */
  15382. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15383. #if defined(GCC_DIAGNOSTIC)
  15384. #pragma GCC diagnostic pop
  15385. #endif /* defined(GCC_DIAGNOSTIC) */
  15386. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15387. conn->buf_size = (int)max_req_size;
  15388. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15389. conn->dom_ctx = &(conn->phys_ctx->dd);
  15390. if (!connect_socket(conn->phys_ctx,
  15391. client_options->host,
  15392. client_options->port,
  15393. use_ssl,
  15394. ebuf,
  15395. ebuf_len,
  15396. &sock,
  15397. &sa)) {
  15398. /* ebuf is set by connect_socket,
  15399. * free all memory and return NULL; */
  15400. mg_free(conn);
  15401. return NULL;
  15402. }
  15403. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15404. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15405. && !defined(NO_SSL_DL)
  15406. if (use_ssl
  15407. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15408. == NULL) {
  15409. mg_snprintf(NULL,
  15410. NULL, /* No truncation check for ebuf */
  15411. ebuf,
  15412. ebuf_len,
  15413. "SSL_CTX_new error: %s",
  15414. ssl_error());
  15415. closesocket(sock);
  15416. mg_free(conn);
  15417. return NULL;
  15418. }
  15419. #else
  15420. if (use_ssl
  15421. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15422. == NULL) {
  15423. mg_snprintf(NULL,
  15424. NULL, /* No truncation check for ebuf */
  15425. ebuf,
  15426. ebuf_len,
  15427. "SSL_CTX_new error: %s",
  15428. ssl_error());
  15429. closesocket(sock);
  15430. mg_free(conn);
  15431. return NULL;
  15432. }
  15433. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15434. #endif /* NO_SSL */
  15435. #if defined(USE_IPV6)
  15436. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15437. : sizeof(conn->client.rsa.sin6);
  15438. psa = (sa.sa.sa_family == AF_INET)
  15439. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15440. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15441. #else
  15442. len = sizeof(conn->client.rsa.sin);
  15443. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15444. #endif
  15445. conn->client.sock = sock;
  15446. conn->client.lsa = sa;
  15447. if (getsockname(sock, psa, &len) != 0) {
  15448. mg_cry_internal(conn,
  15449. "%s: getsockname() failed: %s",
  15450. __func__,
  15451. strerror(ERRNO));
  15452. }
  15453. conn->client.is_ssl = use_ssl ? 1 : 0;
  15454. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15455. mg_snprintf(NULL,
  15456. NULL, /* No truncation check for ebuf */
  15457. ebuf,
  15458. ebuf_len,
  15459. "Can not create mutex");
  15460. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15461. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15462. #endif
  15463. closesocket(sock);
  15464. mg_free(conn);
  15465. return NULL;
  15466. }
  15467. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15468. if (use_ssl) {
  15469. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15470. * SSL_CTX_set_verify call is needed to switch off server
  15471. * certificate checking, which is off by default in OpenSSL and
  15472. * on in yaSSL. */
  15473. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15474. * SSL_VERIFY_PEER, verify_ssl_server); */
  15475. if (client_options->client_cert) {
  15476. if (!ssl_use_pem_file(conn->phys_ctx,
  15477. conn->dom_ctx,
  15478. client_options->client_cert,
  15479. NULL)) {
  15480. mg_snprintf(NULL,
  15481. NULL, /* No truncation check for ebuf */
  15482. ebuf,
  15483. ebuf_len,
  15484. "Can not use SSL client certificate");
  15485. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15486. closesocket(sock);
  15487. mg_free(conn);
  15488. return NULL;
  15489. }
  15490. }
  15491. if (client_options->server_cert) {
  15492. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15493. client_options->server_cert,
  15494. NULL)
  15495. != 1) {
  15496. mg_cry_internal(conn,
  15497. "SSL_CTX_load_verify_locations error: %s ",
  15498. ssl_error());
  15499. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15500. closesocket(sock);
  15501. mg_free(conn);
  15502. return NULL;
  15503. }
  15504. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15505. } else {
  15506. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15507. }
  15508. if (!sslize(conn, SSL_connect, client_options)) {
  15509. mg_snprintf(NULL,
  15510. NULL, /* No truncation check for ebuf */
  15511. ebuf,
  15512. ebuf_len,
  15513. "SSL connection error");
  15514. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15515. closesocket(sock);
  15516. mg_free(conn);
  15517. return NULL;
  15518. }
  15519. }
  15520. #endif
  15521. return conn;
  15522. }
  15523. CIVETWEB_API struct mg_connection *
  15524. mg_connect_client_secure(const struct mg_client_options *client_options,
  15525. char *error_buffer,
  15526. size_t error_buffer_size)
  15527. {
  15528. return mg_connect_client_impl(client_options,
  15529. 1,
  15530. error_buffer,
  15531. error_buffer_size);
  15532. }
  15533. struct mg_connection *
  15534. mg_connect_client(const char *host,
  15535. int port,
  15536. int use_ssl,
  15537. char *error_buffer,
  15538. size_t error_buffer_size)
  15539. {
  15540. struct mg_client_options opts;
  15541. memset(&opts, 0, sizeof(opts));
  15542. opts.host = host;
  15543. opts.port = port;
  15544. if (use_ssl) {
  15545. opts.host_name = host;
  15546. }
  15547. return mg_connect_client_impl(&opts,
  15548. use_ssl,
  15549. error_buffer,
  15550. error_buffer_size);
  15551. }
  15552. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15553. struct mg_connection *
  15554. mg_connect_client2(const char *host,
  15555. const char *protocol,
  15556. int port,
  15557. const char *path,
  15558. struct mg_init_data *init,
  15559. struct mg_error_data *error)
  15560. {
  15561. (void)path;
  15562. (void)init;
  15563. int is_ssl, is_ws;
  15564. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  15565. if (error != NULL) {
  15566. error->code = 0;
  15567. if (error->text_buffer_size > 0) {
  15568. *error->text = 0;
  15569. }
  15570. }
  15571. if ((host == NULL) || (protocol == NULL)) {
  15572. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15573. mg_snprintf(NULL,
  15574. NULL, /* No truncation check for error buffers */
  15575. error->text,
  15576. error->text_buffer_size,
  15577. "%s",
  15578. "Invalid parameters");
  15579. }
  15580. return NULL;
  15581. }
  15582. /* check all known protocolls */
  15583. if (!mg_strcasecmp(protocol, "http")) {
  15584. is_ssl = 0;
  15585. is_ws = 0;
  15586. } else if (!mg_strcasecmp(protocol, "https")) {
  15587. is_ssl = 1;
  15588. is_ws = 0;
  15589. #if defined(USE_WEBSOCKET)
  15590. } else if (!mg_strcasecmp(protocol, "ws")) {
  15591. is_ssl = 0;
  15592. is_ws = 1;
  15593. } else if (!mg_strcasecmp(protocol, "wss")) {
  15594. is_ssl = 1;
  15595. is_ws = 1;
  15596. #endif
  15597. } else {
  15598. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15599. mg_snprintf(NULL,
  15600. NULL, /* No truncation check for error buffers */
  15601. error->text,
  15602. error->text_buffer_size,
  15603. "Protocol %s not supported",
  15604. protocol);
  15605. }
  15606. return NULL;
  15607. }
  15608. /* TODO: The current implementation here just calls the old
  15609. * implementations, without using any new options. This is just a first
  15610. * step to test the new interfaces. */
  15611. #if defined(USE_WEBSOCKET)
  15612. if (is_ws) {
  15613. /* TODO: implement all options */
  15614. return mg_connect_websocket_client(
  15615. host,
  15616. port,
  15617. is_ssl,
  15618. ((error != NULL) ? error->text : NULL),
  15619. ((error != NULL) ? error->text_buffer_size : 0),
  15620. (path ? path : ""),
  15621. NULL /* TODO: origin */,
  15622. experimental_websocket_client_data_wrapper,
  15623. experimental_websocket_client_close_wrapper,
  15624. (void *)init->callbacks);
  15625. }
  15626. #else
  15627. (void)is_ws;
  15628. #endif
  15629. /* TODO: all additional options */
  15630. struct mg_client_options opts;
  15631. memset(&opts, 0, sizeof(opts));
  15632. opts.host = host;
  15633. opts.port = port;
  15634. return mg_connect_client_impl(&opts,
  15635. is_ssl,
  15636. ((error != NULL) ? error->text : NULL),
  15637. ((error != NULL) ? error->text_buffer_size
  15638. : 0));
  15639. }
  15640. #endif
  15641. static const struct {
  15642. const char *proto;
  15643. size_t proto_len;
  15644. unsigned default_port;
  15645. } abs_uri_protocols[] = {{"http://", 7, 80},
  15646. {"https://", 8, 443},
  15647. {"ws://", 5, 80},
  15648. {"wss://", 6, 443},
  15649. {NULL, 0, 0}};
  15650. /* Check if the uri is valid.
  15651. * return 0 for invalid uri,
  15652. * return 1 for *,
  15653. * return 2 for relative uri,
  15654. * return 3 for absolute uri without port,
  15655. * return 4 for absolute uri with port */
  15656. static int
  15657. get_uri_type(const char *uri)
  15658. {
  15659. int i;
  15660. const char *hostend, *portbegin;
  15661. char *portend;
  15662. unsigned long port;
  15663. /* According to the HTTP standard
  15664. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15665. * URI can be an asterisk (*) or should start with slash (relative uri),
  15666. * or it should start with the protocol (absolute uri). */
  15667. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15668. /* asterisk */
  15669. return 1;
  15670. }
  15671. /* Valid URIs according to RFC 3986
  15672. * (https://www.ietf.org/rfc/rfc3986.txt)
  15673. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15674. * and unreserved characters A-Z a-z 0-9 and -._~
  15675. * and % encoded symbols.
  15676. */
  15677. for (i = 0; uri[i] != 0; i++) {
  15678. if (uri[i] < 33) {
  15679. /* control characters and spaces are invalid */
  15680. return 0;
  15681. }
  15682. /* Allow everything else here (See #894) */
  15683. }
  15684. /* A relative uri starts with a / character */
  15685. if (uri[0] == '/') {
  15686. /* relative uri */
  15687. return 2;
  15688. }
  15689. /* It could be an absolute uri: */
  15690. /* This function only checks if the uri is valid, not if it is
  15691. * addressing the current server. So civetweb can also be used
  15692. * as a proxy server. */
  15693. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15694. if (mg_strncasecmp(uri,
  15695. abs_uri_protocols[i].proto,
  15696. abs_uri_protocols[i].proto_len)
  15697. == 0) {
  15698. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15699. if (!hostend) {
  15700. return 0;
  15701. }
  15702. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15703. if (!portbegin) {
  15704. return 3;
  15705. }
  15706. port = strtoul(portbegin + 1, &portend, 10);
  15707. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15708. return 0;
  15709. }
  15710. return 4;
  15711. }
  15712. }
  15713. return 0;
  15714. }
  15715. /* Return NULL or the relative uri at the current server */
  15716. static const char *
  15717. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15718. {
  15719. const char *server_domain;
  15720. size_t server_domain_len;
  15721. size_t request_domain_len = 0;
  15722. unsigned long port = 0;
  15723. int i, auth_domain_check_enabled;
  15724. const char *hostbegin = NULL;
  15725. const char *hostend = NULL;
  15726. const char *portbegin;
  15727. char *portend;
  15728. auth_domain_check_enabled =
  15729. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15730. /* DNS is case insensitive, so use case insensitive string compare here
  15731. */
  15732. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15733. if (mg_strncasecmp(uri,
  15734. abs_uri_protocols[i].proto,
  15735. abs_uri_protocols[i].proto_len)
  15736. == 0) {
  15737. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15738. hostend = strchr(hostbegin, '/');
  15739. if (!hostend) {
  15740. return 0;
  15741. }
  15742. portbegin = strchr(hostbegin, ':');
  15743. if ((!portbegin) || (portbegin > hostend)) {
  15744. port = abs_uri_protocols[i].default_port;
  15745. request_domain_len = (size_t)(hostend - hostbegin);
  15746. } else {
  15747. port = strtoul(portbegin + 1, &portend, 10);
  15748. if ((portend != hostend) || (port <= 0)
  15749. || !is_valid_port(port)) {
  15750. return 0;
  15751. }
  15752. request_domain_len = (size_t)(portbegin - hostbegin);
  15753. }
  15754. /* protocol found, port set */
  15755. break;
  15756. }
  15757. }
  15758. if (!port) {
  15759. /* port remains 0 if the protocol is not found */
  15760. return 0;
  15761. }
  15762. /* Check if the request is directed to a different server. */
  15763. /* First check if the port is the same. */
  15764. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15765. /* Request is directed to a different port */
  15766. return 0;
  15767. }
  15768. /* Finally check if the server corresponds to the authentication
  15769. * domain of the server (the server domain).
  15770. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15771. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15772. * but do not allow substrings (like
  15773. * http://notmydomain.com/path/file.ext
  15774. * or http://mydomain.com.fake/path/file.ext).
  15775. */
  15776. if (auth_domain_check_enabled) {
  15777. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15778. server_domain_len = strlen(server_domain);
  15779. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15780. return 0;
  15781. }
  15782. if ((request_domain_len == server_domain_len)
  15783. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15784. /* Request is directed to this server - full name match. */
  15785. } else {
  15786. if (request_domain_len < (server_domain_len + 2)) {
  15787. /* Request is directed to another server: The server name
  15788. * is longer than the request name.
  15789. * Drop this case here to avoid overflows in the
  15790. * following checks. */
  15791. return 0;
  15792. }
  15793. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15794. /* Request is directed to another server: It could be a
  15795. * substring
  15796. * like notmyserver.com */
  15797. return 0;
  15798. }
  15799. if (0
  15800. != memcmp(server_domain,
  15801. hostbegin + request_domain_len - server_domain_len,
  15802. server_domain_len)) {
  15803. /* Request is directed to another server:
  15804. * The server name is different. */
  15805. return 0;
  15806. }
  15807. }
  15808. }
  15809. return hostend;
  15810. }
  15811. static int
  15812. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15813. {
  15814. if (ebuf_len > 0) {
  15815. ebuf[0] = '\0';
  15816. }
  15817. *err = 0;
  15818. reset_per_request_attributes(conn);
  15819. if (!conn) {
  15820. mg_snprintf(conn,
  15821. NULL, /* No truncation check for ebuf */
  15822. ebuf,
  15823. ebuf_len,
  15824. "%s",
  15825. "Internal error");
  15826. *err = 500;
  15827. return 0;
  15828. }
  15829. /* Set the time the request was received. This value should be used for
  15830. * timeouts. */
  15831. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15832. conn->request_len =
  15833. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15834. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15835. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15836. mg_snprintf(conn,
  15837. NULL, /* No truncation check for ebuf */
  15838. ebuf,
  15839. ebuf_len,
  15840. "%s",
  15841. "Invalid message size");
  15842. *err = 500;
  15843. return 0;
  15844. }
  15845. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15846. mg_snprintf(conn,
  15847. NULL, /* No truncation check for ebuf */
  15848. ebuf,
  15849. ebuf_len,
  15850. "%s",
  15851. "Message too large");
  15852. *err = 413;
  15853. return 0;
  15854. }
  15855. if (conn->request_len <= 0) {
  15856. if (conn->data_len > 0) {
  15857. mg_snprintf(conn,
  15858. NULL, /* No truncation check for ebuf */
  15859. ebuf,
  15860. ebuf_len,
  15861. "%s",
  15862. "Malformed message");
  15863. *err = 400;
  15864. } else {
  15865. /* Server did not recv anything -> just close the connection */
  15866. conn->must_close = 1;
  15867. mg_snprintf(conn,
  15868. NULL, /* No truncation check for ebuf */
  15869. ebuf,
  15870. ebuf_len,
  15871. "%s",
  15872. "No data received");
  15873. *err = 0;
  15874. }
  15875. return 0;
  15876. }
  15877. return 1;
  15878. }
  15879. static int
  15880. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15881. {
  15882. const char *cl;
  15883. conn->connection_type =
  15884. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15885. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15886. return 0;
  15887. }
  15888. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15889. <= 0) {
  15890. mg_snprintf(conn,
  15891. NULL, /* No truncation check for ebuf */
  15892. ebuf,
  15893. ebuf_len,
  15894. "%s",
  15895. "Bad request");
  15896. *err = 400;
  15897. return 0;
  15898. }
  15899. /* Message is a valid request */
  15900. if (!switch_domain_context(conn)) {
  15901. mg_snprintf(conn,
  15902. NULL, /* No truncation check for ebuf */
  15903. ebuf,
  15904. ebuf_len,
  15905. "%s",
  15906. "Bad request: Host mismatch");
  15907. *err = 400;
  15908. return 0;
  15909. }
  15910. #if USE_ZLIB
  15911. if (((cl = get_header(conn->request_info.http_headers,
  15912. conn->request_info.num_headers,
  15913. "Accept-Encoding"))
  15914. != NULL)
  15915. && strstr(cl, "gzip")) {
  15916. conn->accept_gzip = 1;
  15917. }
  15918. #endif
  15919. if (((cl = get_header(conn->request_info.http_headers,
  15920. conn->request_info.num_headers,
  15921. "Transfer-Encoding"))
  15922. != NULL)
  15923. && mg_strcasecmp(cl, "identity")) {
  15924. if (mg_strcasecmp(cl, "chunked")) {
  15925. mg_snprintf(conn,
  15926. NULL, /* No truncation check for ebuf */
  15927. ebuf,
  15928. ebuf_len,
  15929. "%s",
  15930. "Bad request");
  15931. *err = 400;
  15932. return 0;
  15933. }
  15934. conn->is_chunked = 1;
  15935. conn->content_len = 0; /* not yet read */
  15936. } else if ((cl = get_header(conn->request_info.http_headers,
  15937. conn->request_info.num_headers,
  15938. "Content-Length"))
  15939. != NULL) {
  15940. /* Request has content length set */
  15941. char *endptr = NULL;
  15942. conn->content_len = strtoll(cl, &endptr, 10);
  15943. if ((endptr == cl) || (conn->content_len < 0)) {
  15944. mg_snprintf(conn,
  15945. NULL, /* No truncation check for ebuf */
  15946. ebuf,
  15947. ebuf_len,
  15948. "%s",
  15949. "Bad request");
  15950. *err = 411;
  15951. return 0;
  15952. }
  15953. /* Publish the content length back to the request info. */
  15954. conn->request_info.content_length = conn->content_len;
  15955. } else {
  15956. /* There is no exception, see RFC7230. */
  15957. conn->content_len = 0;
  15958. }
  15959. return 1;
  15960. }
  15961. /* conn is assumed to be valid in this internal function */
  15962. static int
  15963. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15964. {
  15965. const char *cl;
  15966. conn->connection_type =
  15967. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15968. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15969. return 0;
  15970. }
  15971. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15972. <= 0) {
  15973. mg_snprintf(conn,
  15974. NULL, /* No truncation check for ebuf */
  15975. ebuf,
  15976. ebuf_len,
  15977. "%s",
  15978. "Bad response");
  15979. *err = 400;
  15980. return 0;
  15981. }
  15982. /* Message is a valid response */
  15983. if (((cl = get_header(conn->response_info.http_headers,
  15984. conn->response_info.num_headers,
  15985. "Transfer-Encoding"))
  15986. != NULL)
  15987. && mg_strcasecmp(cl, "identity")) {
  15988. if (mg_strcasecmp(cl, "chunked")) {
  15989. mg_snprintf(conn,
  15990. NULL, /* No truncation check for ebuf */
  15991. ebuf,
  15992. ebuf_len,
  15993. "%s",
  15994. "Bad request");
  15995. *err = 400;
  15996. return 0;
  15997. }
  15998. conn->is_chunked = 1;
  15999. conn->content_len = 0; /* not yet read */
  16000. } else if ((cl = get_header(conn->response_info.http_headers,
  16001. conn->response_info.num_headers,
  16002. "Content-Length"))
  16003. != NULL) {
  16004. char *endptr = NULL;
  16005. conn->content_len = strtoll(cl, &endptr, 10);
  16006. if ((endptr == cl) || (conn->content_len < 0)) {
  16007. mg_snprintf(conn,
  16008. NULL, /* No truncation check for ebuf */
  16009. ebuf,
  16010. ebuf_len,
  16011. "%s",
  16012. "Bad request");
  16013. *err = 411;
  16014. return 0;
  16015. }
  16016. /* Publish the content length back to the response info. */
  16017. conn->response_info.content_length = conn->content_len;
  16018. /* TODO: check if it is still used in response_info */
  16019. conn->request_info.content_length = conn->content_len;
  16020. /* TODO: we should also consider HEAD method */
  16021. if (conn->response_info.status_code == 304) {
  16022. conn->content_len = 0;
  16023. }
  16024. } else {
  16025. /* TODO: we should also consider HEAD method */
  16026. if (((conn->response_info.status_code >= 100)
  16027. && (conn->response_info.status_code <= 199))
  16028. || (conn->response_info.status_code == 204)
  16029. || (conn->response_info.status_code == 304)) {
  16030. conn->content_len = 0;
  16031. } else {
  16032. conn->content_len = -1; /* unknown content length */
  16033. }
  16034. }
  16035. return 1;
  16036. }
  16037. int
  16038. mg_get_response(struct mg_connection *conn,
  16039. char *ebuf,
  16040. size_t ebuf_len,
  16041. int timeout)
  16042. {
  16043. int err, ret;
  16044. char txt[32]; /* will not overflow */
  16045. char *save_timeout;
  16046. char *new_timeout;
  16047. if (ebuf_len > 0) {
  16048. ebuf[0] = '\0';
  16049. }
  16050. if (!conn) {
  16051. mg_snprintf(conn,
  16052. NULL, /* No truncation check for ebuf */
  16053. ebuf,
  16054. ebuf_len,
  16055. "%s",
  16056. "Parameter error");
  16057. return -1;
  16058. }
  16059. /* Reset the previous responses */
  16060. conn->data_len = 0;
  16061. /* Implementation of API function for HTTP clients */
  16062. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16063. if (timeout >= 0) {
  16064. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16065. new_timeout = txt;
  16066. } else {
  16067. new_timeout = NULL;
  16068. }
  16069. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16070. ret = get_response(conn, ebuf, ebuf_len, &err);
  16071. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16072. /* TODO: here, the URI is the http response code */
  16073. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16074. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16075. /* TODO (mid): Define proper return values - maybe return length?
  16076. * For the first test use <0 for error and >0 for OK */
  16077. return (ret == 0) ? -1 : +1;
  16078. }
  16079. struct mg_connection *
  16080. mg_download(const char *host,
  16081. int port,
  16082. int use_ssl,
  16083. char *ebuf,
  16084. size_t ebuf_len,
  16085. const char *fmt,
  16086. ...)
  16087. {
  16088. struct mg_connection *conn;
  16089. va_list ap;
  16090. int i;
  16091. int reqerr;
  16092. if (ebuf_len > 0) {
  16093. ebuf[0] = '\0';
  16094. }
  16095. va_start(ap, fmt);
  16096. /* open a connection */
  16097. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16098. if (conn != NULL) {
  16099. i = mg_vprintf(conn, fmt, ap);
  16100. if (i <= 0) {
  16101. mg_snprintf(conn,
  16102. NULL, /* No truncation check for ebuf */
  16103. ebuf,
  16104. ebuf_len,
  16105. "%s",
  16106. "Error sending request");
  16107. } else {
  16108. /* make sure the buffer is clear */
  16109. conn->data_len = 0;
  16110. get_response(conn, ebuf, ebuf_len, &reqerr);
  16111. /* TODO: here, the URI is the http response code */
  16112. conn->request_info.local_uri = conn->request_info.request_uri;
  16113. }
  16114. }
  16115. /* if an error occurred, close the connection */
  16116. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16117. mg_close_connection(conn);
  16118. conn = NULL;
  16119. }
  16120. va_end(ap);
  16121. return conn;
  16122. }
  16123. struct websocket_client_thread_data {
  16124. struct mg_connection *conn;
  16125. mg_websocket_data_handler data_handler;
  16126. mg_websocket_close_handler close_handler;
  16127. void *callback_data;
  16128. };
  16129. #if defined(USE_WEBSOCKET)
  16130. #if defined(_WIN32)
  16131. static unsigned __stdcall websocket_client_thread(void *data)
  16132. #else
  16133. static void *
  16134. websocket_client_thread(void *data)
  16135. #endif
  16136. {
  16137. struct websocket_client_thread_data *cdata =
  16138. (struct websocket_client_thread_data *)data;
  16139. void *user_thread_ptr = NULL;
  16140. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16141. struct sigaction sa;
  16142. /* Ignore SIGPIPE */
  16143. memset(&sa, 0, sizeof(sa));
  16144. sa.sa_handler = SIG_IGN;
  16145. sigaction(SIGPIPE, &sa, NULL);
  16146. #endif
  16147. mg_set_thread_name("ws-clnt");
  16148. if (cdata->conn->phys_ctx) {
  16149. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16150. /* 3 indicates a websocket client thread */
  16151. /* TODO: check if conn->phys_ctx can be set */
  16152. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16153. cdata->conn->phys_ctx, 3);
  16154. }
  16155. }
  16156. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16157. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16158. if (cdata->close_handler != NULL) {
  16159. cdata->close_handler(cdata->conn, cdata->callback_data);
  16160. }
  16161. /* The websocket_client context has only this thread. If it runs out,
  16162. set the stop_flag to 2 (= "stopped"). */
  16163. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16164. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16165. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16166. 3,
  16167. user_thread_ptr);
  16168. }
  16169. mg_free((void *)cdata);
  16170. #if defined(_WIN32)
  16171. return 0;
  16172. #else
  16173. return NULL;
  16174. #endif
  16175. }
  16176. #endif
  16177. static struct mg_connection *
  16178. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16179. int use_ssl,
  16180. char *error_buffer,
  16181. size_t error_buffer_size,
  16182. const char *path,
  16183. const char *origin,
  16184. const char *extensions,
  16185. mg_websocket_data_handler data_func,
  16186. mg_websocket_close_handler close_func,
  16187. void *user_data)
  16188. {
  16189. struct mg_connection *conn = NULL;
  16190. #if defined(USE_WEBSOCKET)
  16191. struct websocket_client_thread_data *thread_data;
  16192. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16193. const char *host = client_options->host;
  16194. int i;
  16195. #if defined(__clang__)
  16196. #pragma clang diagnostic push
  16197. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16198. #endif
  16199. /* Establish the client connection and request upgrade */
  16200. conn = mg_connect_client_impl(client_options,
  16201. use_ssl,
  16202. error_buffer,
  16203. error_buffer_size);
  16204. /* Connection object will be null if something goes wrong */
  16205. if (conn == NULL) {
  16206. /* error_buffer should be already filled ... */
  16207. if (!error_buffer[0]) {
  16208. /* ... if not add an error message */
  16209. mg_snprintf(conn,
  16210. NULL, /* No truncation check for ebuf */
  16211. error_buffer,
  16212. error_buffer_size,
  16213. "Unexpected error");
  16214. }
  16215. return NULL;
  16216. }
  16217. if (origin != NULL) {
  16218. if (extensions != NULL) {
  16219. i = mg_printf(conn,
  16220. "GET %s HTTP/1.1\r\n"
  16221. "Host: %s\r\n"
  16222. "Upgrade: websocket\r\n"
  16223. "Connection: Upgrade\r\n"
  16224. "Sec-WebSocket-Key: %s\r\n"
  16225. "Sec-WebSocket-Version: 13\r\n"
  16226. "Sec-WebSocket-Extensions: %s\r\n"
  16227. "Origin: %s\r\n"
  16228. "\r\n",
  16229. path,
  16230. host,
  16231. magic,
  16232. extensions,
  16233. origin);
  16234. } else {
  16235. i = mg_printf(conn,
  16236. "GET %s HTTP/1.1\r\n"
  16237. "Host: %s\r\n"
  16238. "Upgrade: websocket\r\n"
  16239. "Connection: Upgrade\r\n"
  16240. "Sec-WebSocket-Key: %s\r\n"
  16241. "Sec-WebSocket-Version: 13\r\n"
  16242. "Origin: %s\r\n"
  16243. "\r\n",
  16244. path,
  16245. host,
  16246. magic,
  16247. origin);
  16248. }
  16249. } else {
  16250. if (extensions != NULL) {
  16251. i = mg_printf(conn,
  16252. "GET %s HTTP/1.1\r\n"
  16253. "Host: %s\r\n"
  16254. "Upgrade: websocket\r\n"
  16255. "Connection: Upgrade\r\n"
  16256. "Sec-WebSocket-Key: %s\r\n"
  16257. "Sec-WebSocket-Version: 13\r\n"
  16258. "Sec-WebSocket-Extensions: %s\r\n"
  16259. "\r\n",
  16260. path,
  16261. host,
  16262. magic,
  16263. extensions);
  16264. } else {
  16265. i = mg_printf(conn,
  16266. "GET %s HTTP/1.1\r\n"
  16267. "Host: %s\r\n"
  16268. "Upgrade: websocket\r\n"
  16269. "Connection: Upgrade\r\n"
  16270. "Sec-WebSocket-Key: %s\r\n"
  16271. "Sec-WebSocket-Version: 13\r\n"
  16272. "\r\n",
  16273. path,
  16274. host,
  16275. magic);
  16276. }
  16277. }
  16278. if (i <= 0) {
  16279. mg_snprintf(conn,
  16280. NULL, /* No truncation check for ebuf */
  16281. error_buffer,
  16282. error_buffer_size,
  16283. "%s",
  16284. "Error sending request");
  16285. mg_close_connection(conn);
  16286. return NULL;
  16287. }
  16288. conn->data_len = 0;
  16289. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16290. mg_close_connection(conn);
  16291. return NULL;
  16292. }
  16293. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16294. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16295. #if defined(__clang__)
  16296. #pragma clang diagnostic pop
  16297. #endif
  16298. if (conn->response_info.status_code != 101) {
  16299. /* We sent an "upgrade" request. For a correct websocket
  16300. * protocol handshake, we expect a "101 Continue" response.
  16301. * Otherwise it is a protocol violation. Maybe the HTTP
  16302. * Server does not know websockets. */
  16303. if (!*error_buffer) {
  16304. /* set an error, if not yet set */
  16305. mg_snprintf(conn,
  16306. NULL, /* No truncation check for ebuf */
  16307. error_buffer,
  16308. error_buffer_size,
  16309. "Unexpected server reply");
  16310. }
  16311. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16312. mg_close_connection(conn);
  16313. return NULL;
  16314. }
  16315. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16316. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16317. if (!thread_data) {
  16318. DEBUG_TRACE("%s\r\n", "Out of memory");
  16319. mg_close_connection(conn);
  16320. return NULL;
  16321. }
  16322. thread_data->conn = conn;
  16323. thread_data->data_handler = data_func;
  16324. thread_data->close_handler = close_func;
  16325. thread_data->callback_data = user_data;
  16326. conn->phys_ctx->worker_threadids =
  16327. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16328. if (!conn->phys_ctx->worker_threadids) {
  16329. DEBUG_TRACE("%s\r\n", "Out of memory");
  16330. mg_free(thread_data);
  16331. mg_close_connection(conn);
  16332. return NULL;
  16333. }
  16334. /* Now upgrade to ws/wss client context */
  16335. conn->phys_ctx->user_data = user_data;
  16336. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16337. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  16338. /* Start a thread to read the websocket client connection
  16339. * This thread will automatically stop when mg_disconnect is
  16340. * called on the client connection */
  16341. if (mg_start_thread_with_id(websocket_client_thread,
  16342. thread_data,
  16343. conn->phys_ctx->worker_threadids)
  16344. != 0) {
  16345. conn->phys_ctx->cfg_worker_threads = 0;
  16346. mg_free(thread_data);
  16347. mg_close_connection(conn);
  16348. conn = NULL;
  16349. DEBUG_TRACE("%s",
  16350. "Websocket client connect thread could not be started\r\n");
  16351. }
  16352. #else
  16353. /* Appease "unused parameter" warnings */
  16354. (void)client_options;
  16355. (void)use_ssl;
  16356. (void)error_buffer;
  16357. (void)error_buffer_size;
  16358. (void)path;
  16359. (void)origin;
  16360. (void)extensions;
  16361. (void)user_data;
  16362. (void)data_func;
  16363. (void)close_func;
  16364. #endif
  16365. return conn;
  16366. }
  16367. struct mg_connection *
  16368. mg_connect_websocket_client(const char *host,
  16369. int port,
  16370. int use_ssl,
  16371. char *error_buffer,
  16372. size_t error_buffer_size,
  16373. const char *path,
  16374. const char *origin,
  16375. mg_websocket_data_handler data_func,
  16376. mg_websocket_close_handler close_func,
  16377. void *user_data)
  16378. {
  16379. struct mg_client_options client_options;
  16380. memset(&client_options, 0, sizeof(client_options));
  16381. client_options.host = host;
  16382. client_options.port = port;
  16383. return mg_connect_websocket_client_impl(&client_options,
  16384. use_ssl,
  16385. error_buffer,
  16386. error_buffer_size,
  16387. path,
  16388. origin,
  16389. NULL,
  16390. data_func,
  16391. close_func,
  16392. user_data);
  16393. }
  16394. struct mg_connection *
  16395. mg_connect_websocket_client_secure(
  16396. const struct mg_client_options *client_options,
  16397. char *error_buffer,
  16398. size_t error_buffer_size,
  16399. const char *path,
  16400. const char *origin,
  16401. mg_websocket_data_handler data_func,
  16402. mg_websocket_close_handler close_func,
  16403. void *user_data)
  16404. {
  16405. if (!client_options) {
  16406. return NULL;
  16407. }
  16408. return mg_connect_websocket_client_impl(client_options,
  16409. 1,
  16410. error_buffer,
  16411. error_buffer_size,
  16412. path,
  16413. origin,
  16414. NULL,
  16415. data_func,
  16416. close_func,
  16417. user_data);
  16418. }
  16419. struct mg_connection *
  16420. mg_connect_websocket_client_extensions(const char *host,
  16421. int port,
  16422. int use_ssl,
  16423. char *error_buffer,
  16424. size_t error_buffer_size,
  16425. const char *path,
  16426. const char *origin,
  16427. const char *extensions,
  16428. mg_websocket_data_handler data_func,
  16429. mg_websocket_close_handler close_func,
  16430. void *user_data)
  16431. {
  16432. struct mg_client_options client_options;
  16433. memset(&client_options, 0, sizeof(client_options));
  16434. client_options.host = host;
  16435. client_options.port = port;
  16436. return mg_connect_websocket_client_impl(&client_options,
  16437. use_ssl,
  16438. error_buffer,
  16439. error_buffer_size,
  16440. path,
  16441. origin,
  16442. extensions,
  16443. data_func,
  16444. close_func,
  16445. user_data);
  16446. }
  16447. struct mg_connection *
  16448. mg_connect_websocket_client_secure_extensions(
  16449. const struct mg_client_options *client_options,
  16450. char *error_buffer,
  16451. size_t error_buffer_size,
  16452. const char *path,
  16453. const char *origin,
  16454. const char *extensions,
  16455. mg_websocket_data_handler data_func,
  16456. mg_websocket_close_handler close_func,
  16457. void *user_data)
  16458. {
  16459. if (!client_options) {
  16460. return NULL;
  16461. }
  16462. return mg_connect_websocket_client_impl(client_options,
  16463. 1,
  16464. error_buffer,
  16465. error_buffer_size,
  16466. path,
  16467. origin,
  16468. extensions,
  16469. data_func,
  16470. close_func,
  16471. user_data);
  16472. }
  16473. /* Prepare connection data structure */
  16474. static void
  16475. init_connection(struct mg_connection *conn)
  16476. {
  16477. /* Is keep alive allowed by the server */
  16478. int keep_alive_enabled =
  16479. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16480. if (!keep_alive_enabled) {
  16481. conn->must_close = 1;
  16482. }
  16483. /* Important: on new connection, reset the receiving buffer. Credit
  16484. * goes to crule42. */
  16485. conn->data_len = 0;
  16486. conn->handled_requests = 0;
  16487. conn->connection_type = CONNECTION_TYPE_INVALID;
  16488. mg_set_user_connection_data(conn, NULL);
  16489. #if defined(USE_SERVER_STATS)
  16490. conn->conn_state = 2; /* init */
  16491. #endif
  16492. /* call the init_connection callback if assigned */
  16493. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16494. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16495. void *conn_data = NULL;
  16496. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16497. mg_set_user_connection_data(conn, conn_data);
  16498. }
  16499. }
  16500. }
  16501. /* Process a connection - may handle multiple requests
  16502. * using the same connection.
  16503. * Must be called with a valid connection (conn and
  16504. * conn->phys_ctx must be valid).
  16505. */
  16506. static void
  16507. process_new_connection(struct mg_connection *conn)
  16508. {
  16509. struct mg_request_info *ri = &conn->request_info;
  16510. int keep_alive, discard_len;
  16511. char ebuf[100];
  16512. const char *hostend;
  16513. int reqerr, uri_type;
  16514. #if defined(USE_SERVER_STATS)
  16515. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  16516. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  16517. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  16518. #endif
  16519. DEBUG_TRACE("Start processing connection from %s",
  16520. conn->request_info.remote_addr);
  16521. /* Loop over multiple requests sent using the same connection
  16522. * (while "keep alive"). */
  16523. do {
  16524. DEBUG_TRACE("calling get_request (%i times for this connection)",
  16525. conn->handled_requests + 1);
  16526. #if defined(USE_SERVER_STATS)
  16527. conn->conn_state = 3; /* ready */
  16528. #endif
  16529. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  16530. /* The request sent by the client could not be understood by
  16531. * the server, or it was incomplete or a timeout. Send an
  16532. * error message and close the connection. */
  16533. if (reqerr > 0) {
  16534. DEBUG_ASSERT(ebuf[0] != '\0');
  16535. mg_send_http_error(conn, reqerr, "%s", ebuf);
  16536. }
  16537. } else if (strcmp(ri->http_version, "1.0")
  16538. && strcmp(ri->http_version, "1.1")) {
  16539. /* HTTP/2 is not allowed here */
  16540. mg_snprintf(conn,
  16541. NULL, /* No truncation check for ebuf */
  16542. ebuf,
  16543. sizeof(ebuf),
  16544. "Bad HTTP version: [%s]",
  16545. ri->http_version);
  16546. mg_send_http_error(conn, 505, "%s", ebuf);
  16547. }
  16548. if (ebuf[0] == '\0') {
  16549. uri_type = get_uri_type(conn->request_info.request_uri);
  16550. switch (uri_type) {
  16551. case 1:
  16552. /* Asterisk */
  16553. conn->request_info.local_uri_raw = 0;
  16554. /* TODO: Deal with '*'. */
  16555. break;
  16556. case 2:
  16557. /* relative uri */
  16558. conn->request_info.local_uri_raw =
  16559. conn->request_info.request_uri;
  16560. break;
  16561. case 3:
  16562. case 4:
  16563. /* absolute uri (with/without port) */
  16564. hostend = get_rel_url_at_current_server(
  16565. conn->request_info.request_uri, conn);
  16566. if (hostend) {
  16567. conn->request_info.local_uri_raw = hostend;
  16568. } else {
  16569. conn->request_info.local_uri_raw = NULL;
  16570. }
  16571. break;
  16572. default:
  16573. mg_snprintf(conn,
  16574. NULL, /* No truncation check for ebuf */
  16575. ebuf,
  16576. sizeof(ebuf),
  16577. "Invalid URI");
  16578. mg_send_http_error(conn, 400, "%s", ebuf);
  16579. conn->request_info.local_uri_raw = NULL;
  16580. break;
  16581. }
  16582. conn->request_info.local_uri =
  16583. (char *)conn->request_info.local_uri_raw;
  16584. }
  16585. if (ebuf[0] != '\0') {
  16586. conn->protocol_type = -1;
  16587. } else {
  16588. /* HTTP/1 allows protocol upgrade */
  16589. conn->protocol_type = should_switch_to_protocol(conn);
  16590. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16591. /* This will occur, if a HTTP/1.1 request should be upgraded
  16592. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16593. * Since most (all?) major browsers only support HTTP/2 using
  16594. * ALPN, this is hard to test and very low priority.
  16595. * Deactivate it (at least for now).
  16596. */
  16597. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16598. }
  16599. }
  16600. DEBUG_TRACE("http: %s, error: %s",
  16601. (ri->http_version ? ri->http_version : "none"),
  16602. (ebuf[0] ? ebuf : "none"));
  16603. if (ebuf[0] == '\0') {
  16604. if (conn->request_info.local_uri) {
  16605. /* handle request to local server */
  16606. handle_request_stat_log(conn);
  16607. } else {
  16608. /* TODO: handle non-local request (PROXY) */
  16609. conn->must_close = 1;
  16610. }
  16611. } else {
  16612. conn->must_close = 1;
  16613. }
  16614. /* Response complete. Free header buffer */
  16615. free_buffered_response_header_list(conn);
  16616. if (ri->remote_user != NULL) {
  16617. mg_free((void *)ri->remote_user);
  16618. /* Important! When having connections with and without auth
  16619. * would cause double free and then crash */
  16620. ri->remote_user = NULL;
  16621. }
  16622. /* NOTE(lsm): order is important here. should_keep_alive() call
  16623. * is using parsed request, which will be invalid after
  16624. * memmove's below.
  16625. * Therefore, memorize should_keep_alive() result now for later
  16626. * use in loop exit condition. */
  16627. /* Enable it only if this request is completely discardable. */
  16628. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16629. && should_keep_alive(conn) && (conn->content_len >= 0)
  16630. && (conn->request_len > 0)
  16631. && ((conn->is_chunked == 4)
  16632. || (!conn->is_chunked
  16633. && ((conn->consumed_content == conn->content_len)
  16634. || ((conn->request_len + conn->content_len)
  16635. <= conn->data_len))))
  16636. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16637. if (keep_alive) {
  16638. /* Discard all buffered data for this request */
  16639. discard_len =
  16640. ((conn->request_len + conn->content_len) < conn->data_len)
  16641. ? (int)(conn->request_len + conn->content_len)
  16642. : conn->data_len;
  16643. conn->data_len -= discard_len;
  16644. if (conn->data_len > 0) {
  16645. DEBUG_TRACE("discard_len = %d", discard_len);
  16646. memmove(conn->buf,
  16647. conn->buf + discard_len,
  16648. (size_t)conn->data_len);
  16649. }
  16650. }
  16651. DEBUG_ASSERT(conn->data_len >= 0);
  16652. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16653. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16654. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16655. (long int)conn->data_len,
  16656. (long int)conn->buf_size);
  16657. break;
  16658. }
  16659. conn->handled_requests++;
  16660. } while (keep_alive);
  16661. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16662. conn->request_info.remote_addr,
  16663. difftime(time(NULL), conn->conn_birth_time));
  16664. close_connection(conn);
  16665. #if defined(USE_SERVER_STATS)
  16666. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16667. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16668. #endif
  16669. }
  16670. #if defined(ALTERNATIVE_QUEUE)
  16671. static void
  16672. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16673. {
  16674. unsigned int i;
  16675. while (!ctx->stop_flag) {
  16676. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16677. /* find a free worker slot and signal it */
  16678. if (ctx->client_socks[i].in_use == 2) {
  16679. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16680. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16681. ctx->client_socks[i] = *sp;
  16682. ctx->client_socks[i].in_use = 1;
  16683. /* socket has been moved to the consumer */
  16684. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16685. (void)event_signal(ctx->client_wait_events[i]);
  16686. return;
  16687. }
  16688. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16689. }
  16690. }
  16691. /* queue is full */
  16692. mg_sleep(1);
  16693. }
  16694. /* must consume */
  16695. set_blocking_mode(sp->sock);
  16696. closesocket(sp->sock);
  16697. }
  16698. static int
  16699. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16700. {
  16701. DEBUG_TRACE("%s", "going idle");
  16702. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16703. ctx->client_socks[thread_index].in_use = 2;
  16704. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16705. event_wait(ctx->client_wait_events[thread_index]);
  16706. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16707. *sp = ctx->client_socks[thread_index];
  16708. if (ctx->stop_flag) {
  16709. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16710. if (sp->in_use == 1) {
  16711. /* must consume */
  16712. set_blocking_mode(sp->sock);
  16713. closesocket(sp->sock);
  16714. }
  16715. return 0;
  16716. }
  16717. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16718. if (sp->in_use == 1) {
  16719. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16720. return 1;
  16721. }
  16722. /* must not reach here */
  16723. DEBUG_ASSERT(0);
  16724. return 0;
  16725. }
  16726. #else /* ALTERNATIVE_QUEUE */
  16727. /* Worker threads take accepted socket from the queue */
  16728. static int
  16729. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16730. {
  16731. (void)thread_index;
  16732. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16733. DEBUG_TRACE("%s", "going idle");
  16734. /* If the queue is empty, wait. We're idle at this point. */
  16735. while ((ctx->sq_head == ctx->sq_tail)
  16736. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16737. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16738. }
  16739. /* If we're stopping, sq_head may be equal to sq_tail. */
  16740. if (ctx->sq_head > ctx->sq_tail) {
  16741. /* Copy socket from the queue and increment tail */
  16742. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16743. ctx->sq_tail++;
  16744. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16745. /* Wrap pointers if needed */
  16746. while (ctx->sq_tail > ctx->sq_size) {
  16747. ctx->sq_tail -= ctx->sq_size;
  16748. ctx->sq_head -= ctx->sq_size;
  16749. }
  16750. }
  16751. (void)pthread_cond_signal(&ctx->sq_empty);
  16752. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16753. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16754. }
  16755. /* Master thread adds accepted socket to a queue */
  16756. static void
  16757. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16758. {
  16759. int queue_filled;
  16760. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16761. queue_filled = ctx->sq_head - ctx->sq_tail;
  16762. /* If the queue is full, wait */
  16763. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16764. && (queue_filled >= ctx->sq_size)) {
  16765. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16766. #if defined(USE_SERVER_STATS)
  16767. if (queue_filled > ctx->sq_max_fill) {
  16768. ctx->sq_max_fill = queue_filled;
  16769. }
  16770. #endif
  16771. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16772. ctx->sq_blocked = 0; /* Not blocked now */
  16773. queue_filled = ctx->sq_head - ctx->sq_tail;
  16774. }
  16775. if (queue_filled < ctx->sq_size) {
  16776. /* Copy socket to the queue and increment head */
  16777. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16778. ctx->sq_head++;
  16779. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16780. }
  16781. queue_filled = ctx->sq_head - ctx->sq_tail;
  16782. #if defined(USE_SERVER_STATS)
  16783. if (queue_filled > ctx->sq_max_fill) {
  16784. ctx->sq_max_fill = queue_filled;
  16785. }
  16786. #endif
  16787. (void)pthread_cond_signal(&ctx->sq_full);
  16788. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16789. }
  16790. #endif /* ALTERNATIVE_QUEUE */
  16791. static void
  16792. worker_thread_run(struct mg_connection *conn)
  16793. {
  16794. struct mg_context *ctx = conn->phys_ctx;
  16795. int thread_index;
  16796. struct mg_workerTLS tls;
  16797. mg_set_thread_name("worker");
  16798. tls.is_master = 0;
  16799. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16800. #if defined(_WIN32)
  16801. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16802. #endif
  16803. /* Initialize thread local storage before calling any callback */
  16804. pthread_setspecific(sTlsKey, &tls);
  16805. /* Check if there is a user callback */
  16806. if (ctx->callbacks.init_thread) {
  16807. /* call init_thread for a worker thread (type 1), and store the
  16808. * return value */
  16809. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16810. } else {
  16811. /* No callback: set user pointer to NULL */
  16812. tls.user_ptr = NULL;
  16813. }
  16814. /* Connection structure has been pre-allocated */
  16815. thread_index = (int)(conn - ctx->worker_connections);
  16816. if ((thread_index < 0)
  16817. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16818. mg_cry_ctx_internal(ctx,
  16819. "Internal error: Invalid worker index %i",
  16820. thread_index);
  16821. return;
  16822. }
  16823. /* Request buffers are not pre-allocated. They are private to the
  16824. * request and do not contain any state information that might be
  16825. * of interest to anyone observing a server status. */
  16826. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16827. if (conn->buf == NULL) {
  16828. mg_cry_ctx_internal(
  16829. ctx,
  16830. "Out of memory: Cannot allocate buffer for worker %i",
  16831. thread_index);
  16832. return;
  16833. }
  16834. conn->buf_size = (int)ctx->max_request_size;
  16835. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16836. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16837. conn->request_info.user_data = ctx->user_data;
  16838. /* Allocate a mutex for this connection to allow communication both
  16839. * within the request handler and from elsewhere in the application
  16840. */
  16841. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16842. mg_free(conn->buf);
  16843. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16844. return;
  16845. }
  16846. #if defined(USE_SERVER_STATS)
  16847. conn->conn_state = 1; /* not consumed */
  16848. #endif
  16849. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16850. * signal sq_empty condvar to wake up the master waiting in
  16851. * produce_socket() */
  16852. while (consume_socket(ctx, &conn->client, thread_index)) {
  16853. /* New connections must start with new protocol negotiation */
  16854. tls.alpn_proto = NULL;
  16855. #if defined(USE_SERVER_STATS)
  16856. conn->conn_close_time = 0;
  16857. #endif
  16858. conn->conn_birth_time = time(NULL);
  16859. /* Fill in IP, port info early so even if SSL setup below fails,
  16860. * error handler would have the corresponding info.
  16861. * Thanks to Johannes Winkelmann for the patch.
  16862. */
  16863. conn->request_info.remote_port =
  16864. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16865. conn->request_info.server_port =
  16866. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16867. sockaddr_to_string(conn->request_info.remote_addr,
  16868. sizeof(conn->request_info.remote_addr),
  16869. &conn->client.rsa);
  16870. DEBUG_TRACE("Incomming %sconnection from %s",
  16871. (conn->client.is_ssl ? "SSL " : ""),
  16872. conn->request_info.remote_addr);
  16873. conn->request_info.is_ssl = conn->client.is_ssl;
  16874. if (conn->client.is_ssl) {
  16875. #if defined(USE_MBEDTLS)
  16876. /* HTTPS connection */
  16877. if (mbed_ssl_accept(&(conn->ssl),
  16878. conn->dom_ctx->ssl_ctx,
  16879. (int *)&(conn->client.sock),
  16880. conn->phys_ctx)
  16881. == 0) {
  16882. /* conn->dom_ctx is set in get_request */
  16883. /* process HTTPS connection */
  16884. init_connection(conn);
  16885. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16886. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16887. process_new_connection(conn);
  16888. } else {
  16889. /* make sure the connection is cleaned up on SSL failure */
  16890. close_connection(conn);
  16891. }
  16892. #elif !defined(NO_SSL)
  16893. /* HTTPS connection */
  16894. if (sslize(conn, SSL_accept, NULL)) {
  16895. /* conn->dom_ctx is set in get_request */
  16896. /* Get SSL client certificate information (if set) */
  16897. struct mg_client_cert client_cert;
  16898. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16899. conn->request_info.client_cert = &client_cert;
  16900. }
  16901. /* process HTTPS connection */
  16902. #if defined(USE_HTTP2)
  16903. if ((tls.alpn_proto != NULL)
  16904. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16905. /* process HTTPS/2 connection */
  16906. init_connection(conn);
  16907. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16908. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16909. conn->content_len =
  16910. -1; /* content length is not predefined */
  16911. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16912. process_new_http2_connection(conn);
  16913. } else
  16914. #endif
  16915. {
  16916. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16917. init_connection(conn);
  16918. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16919. /* Start with HTTP, WS will be an "upgrade" request later */
  16920. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16921. process_new_connection(conn);
  16922. }
  16923. /* Free client certificate info */
  16924. if (conn->request_info.client_cert) {
  16925. mg_free((void *)(conn->request_info.client_cert->subject));
  16926. mg_free((void *)(conn->request_info.client_cert->issuer));
  16927. mg_free((void *)(conn->request_info.client_cert->serial));
  16928. mg_free((void *)(conn->request_info.client_cert->finger));
  16929. /* Free certificate memory */
  16930. X509_free(
  16931. (X509 *)conn->request_info.client_cert->peer_cert);
  16932. conn->request_info.client_cert->peer_cert = 0;
  16933. conn->request_info.client_cert->subject = 0;
  16934. conn->request_info.client_cert->issuer = 0;
  16935. conn->request_info.client_cert->serial = 0;
  16936. conn->request_info.client_cert->finger = 0;
  16937. conn->request_info.client_cert = 0;
  16938. }
  16939. } else {
  16940. /* make sure the connection is cleaned up on SSL failure */
  16941. close_connection(conn);
  16942. }
  16943. #endif
  16944. } else {
  16945. /* process HTTP connection */
  16946. init_connection(conn);
  16947. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16948. /* Start with HTTP, WS will be an "upgrade" request later */
  16949. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16950. process_new_connection(conn);
  16951. }
  16952. DEBUG_TRACE("%s", "Connection closed");
  16953. #if defined(USE_SERVER_STATS)
  16954. conn->conn_close_time = time(NULL);
  16955. #endif
  16956. }
  16957. /* Call exit thread user callback */
  16958. if (ctx->callbacks.exit_thread) {
  16959. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16960. }
  16961. /* delete thread local storage objects */
  16962. pthread_setspecific(sTlsKey, NULL);
  16963. #if defined(_WIN32)
  16964. CloseHandle(tls.pthread_cond_helper_mutex);
  16965. #endif
  16966. pthread_mutex_destroy(&conn->mutex);
  16967. /* Free the request buffer. */
  16968. conn->buf_size = 0;
  16969. mg_free(conn->buf);
  16970. conn->buf = NULL;
  16971. /* Free cleaned URI (if any) */
  16972. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16973. mg_free((void *)conn->request_info.local_uri);
  16974. conn->request_info.local_uri = NULL;
  16975. }
  16976. #if defined(USE_SERVER_STATS)
  16977. conn->conn_state = 9; /* done */
  16978. #endif
  16979. DEBUG_TRACE("%s", "exiting");
  16980. }
  16981. /* Threads have different return types on Windows and Unix. */
  16982. #if defined(_WIN32)
  16983. static unsigned __stdcall worker_thread(void *thread_func_param)
  16984. {
  16985. worker_thread_run((struct mg_connection *)thread_func_param);
  16986. return 0;
  16987. }
  16988. #else
  16989. static void *
  16990. worker_thread(void *thread_func_param)
  16991. {
  16992. #if !defined(__ZEPHYR__)
  16993. struct sigaction sa;
  16994. /* Ignore SIGPIPE */
  16995. memset(&sa, 0, sizeof(sa));
  16996. sa.sa_handler = SIG_IGN;
  16997. sigaction(SIGPIPE, &sa, NULL);
  16998. #endif
  16999. worker_thread_run((struct mg_connection *)thread_func_param);
  17000. return NULL;
  17001. }
  17002. #endif /* _WIN32 */
  17003. /* This is an internal function, thus all arguments are expected to be
  17004. * valid - a NULL check is not required. */
  17005. static void
  17006. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17007. {
  17008. struct socket so;
  17009. char src_addr[IP_ADDR_STR_LEN];
  17010. socklen_t len = sizeof(so.rsa);
  17011. #if !defined(__ZEPHYR__)
  17012. int on = 1;
  17013. #endif
  17014. memset(&so, 0, sizeof(so));
  17015. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17016. == INVALID_SOCKET) {
  17017. } else if (check_acl(ctx, &so.rsa) != 1) {
  17018. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17019. mg_cry_ctx_internal(ctx,
  17020. "%s: %s is not allowed to connect",
  17021. __func__,
  17022. src_addr);
  17023. closesocket(so.sock);
  17024. } else {
  17025. /* Put so socket structure into the queue */
  17026. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17027. set_close_on_exec(so.sock, NULL, ctx);
  17028. so.is_ssl = listener->is_ssl;
  17029. so.ssl_redir = listener->ssl_redir;
  17030. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17031. mg_cry_ctx_internal(ctx,
  17032. "%s: getsockname() failed: %s",
  17033. __func__,
  17034. strerror(ERRNO));
  17035. }
  17036. #if !defined(__ZEPHYR__)
  17037. if ((so.lsa.sa.sa_family == AF_INET)
  17038. || (so.lsa.sa.sa_family == AF_INET6)) {
  17039. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17040. * This is needed because if HTTP-level keep-alive
  17041. * is enabled, and client resets the connection, server won't get
  17042. * TCP FIN or RST and will keep the connection open forever. With
  17043. * TCP keep-alive, next keep-alive handshake will figure out that
  17044. * the client is down and will close the server end.
  17045. * Thanks to Igor Klopov who suggested the patch. */
  17046. if (setsockopt(so.sock,
  17047. SOL_SOCKET,
  17048. SO_KEEPALIVE,
  17049. (SOCK_OPT_TYPE)&on,
  17050. sizeof(on))
  17051. != 0) {
  17052. mg_cry_ctx_internal(
  17053. ctx,
  17054. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17055. __func__,
  17056. strerror(ERRNO));
  17057. }
  17058. }
  17059. #endif
  17060. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17061. * to effectively fill up the underlying IP packet payload and
  17062. * reduce the overhead of sending lots of small buffers. However
  17063. * this hurts the server's throughput (ie. operations per second)
  17064. * when HTTP 1.1 persistent connections are used and the responses
  17065. * are relatively small (eg. less than 1400 bytes).
  17066. */
  17067. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17068. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17069. if (set_tcp_nodelay(&so, 1) != 0) {
  17070. mg_cry_ctx_internal(
  17071. ctx,
  17072. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17073. __func__,
  17074. strerror(ERRNO));
  17075. }
  17076. }
  17077. /* The "non blocking" property should already be
  17078. * inherited from the parent socket. Set it for
  17079. * non-compliant socket implementations. */
  17080. set_non_blocking_mode(so.sock);
  17081. so.in_use = 0;
  17082. produce_socket(ctx, &so);
  17083. }
  17084. }
  17085. static void
  17086. master_thread_run(struct mg_context *ctx)
  17087. {
  17088. struct mg_workerTLS tls;
  17089. struct mg_pollfd *pfd;
  17090. unsigned int i;
  17091. unsigned int workerthreadcount;
  17092. if (!ctx) {
  17093. return;
  17094. }
  17095. mg_set_thread_name("master");
  17096. /* Increase priority of the master thread */
  17097. #if defined(_WIN32)
  17098. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17099. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17100. int min_prio = sched_get_priority_min(SCHED_RR);
  17101. int max_prio = sched_get_priority_max(SCHED_RR);
  17102. if ((min_prio >= 0) && (max_prio >= 0)
  17103. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17104. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17105. struct sched_param sched_param = {0};
  17106. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17107. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17108. }
  17109. #endif
  17110. /* Initialize thread local storage */
  17111. #if defined(_WIN32)
  17112. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17113. #endif
  17114. tls.is_master = 1;
  17115. pthread_setspecific(sTlsKey, &tls);
  17116. if (ctx->callbacks.init_thread) {
  17117. /* Callback for the master thread (type 0) */
  17118. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17119. } else {
  17120. tls.user_ptr = NULL;
  17121. }
  17122. /* Lua background script "start" event */
  17123. #if defined(USE_LUA)
  17124. if (ctx->lua_background_state) {
  17125. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17126. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17127. /* call "start()" in Lua */
  17128. lua_getglobal(lstate, "start");
  17129. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17130. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17131. if (ret != 0) {
  17132. struct mg_connection fc;
  17133. lua_cry(fake_connection(&fc, ctx),
  17134. ret,
  17135. lstate,
  17136. "lua_background_script",
  17137. "start");
  17138. }
  17139. } else {
  17140. lua_pop(lstate, 1);
  17141. }
  17142. /* determine if there is a "log()" function in Lua background script */
  17143. lua_getglobal(lstate, "log");
  17144. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17145. ctx->lua_bg_log_available = 1;
  17146. }
  17147. lua_pop(lstate, 1);
  17148. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17149. }
  17150. #endif
  17151. /* Server starts *now* */
  17152. ctx->start_time = time(NULL);
  17153. /* Server accept loop */
  17154. pfd = ctx->listening_socket_fds;
  17155. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17156. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17157. pfd[i].fd = ctx->listening_sockets[i].sock;
  17158. pfd[i].events = POLLIN;
  17159. }
  17160. if (mg_poll(pfd,
  17161. ctx->num_listening_sockets,
  17162. SOCKET_TIMEOUT_QUANTUM,
  17163. &(ctx->stop_flag))
  17164. > 0) {
  17165. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17166. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17167. * successful poll, and POLLIN is defined as
  17168. * (POLLRDNORM | POLLRDBAND)
  17169. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17170. * pfd[i].revents == POLLIN. */
  17171. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17172. && (pfd[i].revents & POLLIN)) {
  17173. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17174. }
  17175. }
  17176. }
  17177. }
  17178. /* Here stop_flag is 1 - Initiate shutdown. */
  17179. DEBUG_TRACE("%s", "stopping workers");
  17180. /* Stop signal received: somebody called mg_stop. Quit. */
  17181. close_all_listening_sockets(ctx);
  17182. /* Wakeup workers that are waiting for connections to handle. */
  17183. #if defined(ALTERNATIVE_QUEUE)
  17184. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17185. event_signal(ctx->client_wait_events[i]);
  17186. }
  17187. #else
  17188. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17189. pthread_cond_broadcast(&ctx->sq_full);
  17190. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17191. #endif
  17192. /* Join all worker threads to avoid leaking threads. */
  17193. workerthreadcount = ctx->cfg_worker_threads;
  17194. for (i = 0; i < workerthreadcount; i++) {
  17195. if (ctx->worker_threadids[i] != 0) {
  17196. mg_join_thread(ctx->worker_threadids[i]);
  17197. }
  17198. }
  17199. #if defined(USE_LUA)
  17200. /* Free Lua state of lua background task */
  17201. if (ctx->lua_background_state) {
  17202. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17203. ctx->lua_bg_log_available = 0;
  17204. /* call "stop()" in Lua */
  17205. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17206. lua_getglobal(lstate, "stop");
  17207. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17208. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17209. if (ret != 0) {
  17210. struct mg_connection fc;
  17211. lua_cry(fake_connection(&fc, ctx),
  17212. ret,
  17213. lstate,
  17214. "lua_background_script",
  17215. "stop");
  17216. }
  17217. }
  17218. lua_close(lstate);
  17219. ctx->lua_background_state = 0;
  17220. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17221. }
  17222. #endif
  17223. DEBUG_TRACE("%s", "exiting");
  17224. /* call exit thread callback */
  17225. if (ctx->callbacks.exit_thread) {
  17226. /* Callback for the master thread (type 0) */
  17227. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17228. }
  17229. #if defined(_WIN32)
  17230. CloseHandle(tls.pthread_cond_helper_mutex);
  17231. #endif
  17232. pthread_setspecific(sTlsKey, NULL);
  17233. /* Signal mg_stop() that we're done.
  17234. * WARNING: This must be the very last thing this
  17235. * thread does, as ctx becomes invalid after this line. */
  17236. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17237. }
  17238. /* Threads have different return types on Windows and Unix. */
  17239. #if defined(_WIN32)
  17240. static unsigned __stdcall master_thread(void *thread_func_param)
  17241. {
  17242. master_thread_run((struct mg_context *)thread_func_param);
  17243. return 0;
  17244. }
  17245. #else
  17246. static void *
  17247. master_thread(void *thread_func_param)
  17248. {
  17249. #if !defined(__ZEPHYR__)
  17250. struct sigaction sa;
  17251. /* Ignore SIGPIPE */
  17252. memset(&sa, 0, sizeof(sa));
  17253. sa.sa_handler = SIG_IGN;
  17254. sigaction(SIGPIPE, &sa, NULL);
  17255. #endif
  17256. master_thread_run((struct mg_context *)thread_func_param);
  17257. return NULL;
  17258. }
  17259. #endif /* _WIN32 */
  17260. static void
  17261. free_context(struct mg_context *ctx)
  17262. {
  17263. int i;
  17264. struct mg_handler_info *tmp_rh;
  17265. if (ctx == NULL) {
  17266. return;
  17267. }
  17268. /* Call user callback */
  17269. if (ctx->callbacks.exit_context) {
  17270. ctx->callbacks.exit_context(ctx);
  17271. }
  17272. /* All threads exited, no sync is needed. Destroy thread mutex and
  17273. * condvars
  17274. */
  17275. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17276. #if defined(ALTERNATIVE_QUEUE)
  17277. mg_free(ctx->client_socks);
  17278. if (ctx->client_wait_events != NULL) {
  17279. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17280. event_destroy(ctx->client_wait_events[i]);
  17281. }
  17282. mg_free(ctx->client_wait_events);
  17283. }
  17284. #else
  17285. (void)pthread_cond_destroy(&ctx->sq_empty);
  17286. (void)pthread_cond_destroy(&ctx->sq_full);
  17287. mg_free(ctx->squeue);
  17288. #endif
  17289. /* Destroy other context global data structures mutex */
  17290. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17291. #if defined(USE_LUA)
  17292. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17293. #endif
  17294. /* Deallocate config parameters */
  17295. for (i = 0; i < NUM_OPTIONS; i++) {
  17296. if (ctx->dd.config[i] != NULL) {
  17297. #if defined(_MSC_VER)
  17298. #pragma warning(suppress : 6001)
  17299. #endif
  17300. mg_free(ctx->dd.config[i]);
  17301. }
  17302. }
  17303. /* Deallocate request handlers */
  17304. while (ctx->dd.handlers) {
  17305. tmp_rh = ctx->dd.handlers;
  17306. ctx->dd.handlers = tmp_rh->next;
  17307. mg_free(tmp_rh->uri);
  17308. mg_free(tmp_rh);
  17309. }
  17310. #if defined(USE_MBEDTLS)
  17311. if (ctx->dd.ssl_ctx != NULL) {
  17312. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17313. mg_free(ctx->dd.ssl_ctx);
  17314. ctx->dd.ssl_ctx = NULL;
  17315. }
  17316. #elif !defined(NO_SSL)
  17317. /* Deallocate SSL context */
  17318. if (ctx->dd.ssl_ctx != NULL) {
  17319. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17320. int callback_ret =
  17321. (ctx->callbacks.external_ssl_ctx == NULL)
  17322. ? 0
  17323. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17324. if (callback_ret == 0) {
  17325. SSL_CTX_free(ctx->dd.ssl_ctx);
  17326. }
  17327. /* else: ignore error and ommit SSL_CTX_free in case
  17328. * callback_ret is 1 */
  17329. }
  17330. #endif /* !NO_SSL */
  17331. /* Deallocate worker thread ID array */
  17332. mg_free(ctx->worker_threadids);
  17333. /* Deallocate worker thread ID array */
  17334. mg_free(ctx->worker_connections);
  17335. /* deallocate system name string */
  17336. mg_free(ctx->systemName);
  17337. /* Deallocate context itself */
  17338. mg_free(ctx);
  17339. }
  17340. void
  17341. mg_stop(struct mg_context *ctx)
  17342. {
  17343. pthread_t mt;
  17344. if (!ctx) {
  17345. return;
  17346. }
  17347. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17348. * two threads is not allowed. */
  17349. mt = ctx->masterthreadid;
  17350. if (mt == 0) {
  17351. return;
  17352. }
  17353. ctx->masterthreadid = 0;
  17354. /* Set stop flag, so all threads know they have to exit. */
  17355. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17356. /* Join timer thread */
  17357. #if defined(USE_TIMERS)
  17358. timers_exit(ctx);
  17359. #endif
  17360. /* Wait until everything has stopped. */
  17361. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17362. (void)mg_sleep(10);
  17363. }
  17364. /* Wait to stop master thread */
  17365. mg_join_thread(mt);
  17366. /* Close remaining Lua states */
  17367. #if defined(USE_LUA)
  17368. lua_ctx_exit(ctx);
  17369. #endif
  17370. /* Free memory */
  17371. free_context(ctx);
  17372. }
  17373. static void
  17374. get_system_name(char **sysName)
  17375. {
  17376. #if defined(_WIN32)
  17377. char name[128];
  17378. DWORD dwVersion = 0;
  17379. DWORD dwMajorVersion = 0;
  17380. DWORD dwMinorVersion = 0;
  17381. DWORD dwBuild = 0;
  17382. BOOL wowRet, isWoW = FALSE;
  17383. #if defined(_MSC_VER)
  17384. #pragma warning(push)
  17385. /* GetVersion was declared deprecated */
  17386. #pragma warning(disable : 4996)
  17387. #endif
  17388. dwVersion = GetVersion();
  17389. #if defined(_MSC_VER)
  17390. #pragma warning(pop)
  17391. #endif
  17392. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17393. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17394. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17395. (void)dwBuild;
  17396. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17397. sprintf(name,
  17398. "Windows %u.%u%s",
  17399. (unsigned)dwMajorVersion,
  17400. (unsigned)dwMinorVersion,
  17401. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17402. *sysName = mg_strdup(name);
  17403. #elif defined(__ZEPHYR__)
  17404. *sysName = mg_strdup("Zephyr OS");
  17405. #else
  17406. struct utsname name;
  17407. memset(&name, 0, sizeof(name));
  17408. uname(&name);
  17409. *sysName = mg_strdup(name.sysname);
  17410. #endif
  17411. }
  17412. static void
  17413. legacy_init(const char **options)
  17414. {
  17415. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17416. if (options) {
  17417. const char **run_options = options;
  17418. const char *optname = config_options[LISTENING_PORTS].name;
  17419. /* Try to find the "listening_ports" option */
  17420. while (*run_options) {
  17421. if (!strcmp(*run_options, optname)) {
  17422. ports_option = run_options[1];
  17423. }
  17424. run_options += 2;
  17425. }
  17426. }
  17427. if (is_ssl_port_used(ports_option)) {
  17428. /* Initialize with SSL support */
  17429. mg_init_library(MG_FEATURES_TLS);
  17430. } else {
  17431. /* Initialize without SSL support */
  17432. mg_init_library(MG_FEATURES_DEFAULT);
  17433. }
  17434. }
  17435. struct mg_context *
  17436. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  17437. {
  17438. struct mg_context *ctx;
  17439. const char *name, *value, *default_value;
  17440. int idx, ok, workerthreadcount;
  17441. unsigned int i;
  17442. int itmp;
  17443. void (*exit_callback)(const struct mg_context *ctx) = 0;
  17444. const char **options =
  17445. ((init != NULL) ? (init->configuration_options) : (NULL));
  17446. struct mg_workerTLS tls;
  17447. if (error != NULL) {
  17448. error->code = 0;
  17449. if (error->text_buffer_size > 0) {
  17450. *error->text = 0;
  17451. }
  17452. }
  17453. if (mg_init_library_called == 0) {
  17454. /* Legacy INIT, if mg_start is called without mg_init_library.
  17455. * Note: This will cause a memory leak when unloading the library.
  17456. */
  17457. legacy_init(options);
  17458. }
  17459. if (mg_init_library_called == 0) {
  17460. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17461. mg_snprintf(NULL,
  17462. NULL, /* No truncation check for error buffers */
  17463. error->text,
  17464. error->text_buffer_size,
  17465. "%s",
  17466. "Library uninitialized");
  17467. }
  17468. return NULL;
  17469. }
  17470. /* Allocate context and initialize reasonable general case defaults. */
  17471. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  17472. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17473. mg_snprintf(NULL,
  17474. NULL, /* No truncation check for error buffers */
  17475. error->text,
  17476. error->text_buffer_size,
  17477. "%s",
  17478. "Out of memory");
  17479. }
  17480. return NULL;
  17481. }
  17482. /* Random number generator will initialize at the first call */
  17483. ctx->dd.auth_nonce_mask =
  17484. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  17485. /* Save started thread index to reuse in other external API calls
  17486. * For the sake of thread synchronization all non-civetweb threads
  17487. * can be considered as single external thread */
  17488. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17489. tls.is_master = -1; /* Thread calling mg_start */
  17490. tls.thread_idx = ctx->starter_thread_idx;
  17491. #if defined(_WIN32)
  17492. tls.pthread_cond_helper_mutex = NULL;
  17493. #endif
  17494. pthread_setspecific(sTlsKey, &tls);
  17495. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  17496. #if !defined(ALTERNATIVE_QUEUE)
  17497. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  17498. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  17499. ctx->sq_blocked = 0;
  17500. #endif
  17501. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  17502. #if defined(USE_LUA)
  17503. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  17504. #endif
  17505. if (!ok) {
  17506. const char *err_msg =
  17507. "Cannot initialize thread synchronization objects";
  17508. /* Fatal error - abort start. However, this situation should never
  17509. * occur in practice. */
  17510. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17511. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17512. mg_snprintf(NULL,
  17513. NULL, /* No truncation check for error buffers */
  17514. error->text,
  17515. error->text_buffer_size,
  17516. "%s",
  17517. err_msg);
  17518. }
  17519. mg_free(ctx);
  17520. pthread_setspecific(sTlsKey, NULL);
  17521. return NULL;
  17522. }
  17523. if ((init != NULL) && (init->callbacks != NULL)) {
  17524. /* Set all callbacks except exit_context. */
  17525. ctx->callbacks = *init->callbacks;
  17526. exit_callback = init->callbacks->exit_context;
  17527. /* The exit callback is activated once the context is successfully
  17528. * created. It should not be called, if an incomplete context object
  17529. * is deleted during a failed initialization. */
  17530. ctx->callbacks.exit_context = 0;
  17531. }
  17532. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  17533. ctx->dd.handlers = NULL;
  17534. ctx->dd.next = NULL;
  17535. #if defined(USE_LUA)
  17536. lua_ctx_init(ctx);
  17537. #endif
  17538. /* Store options */
  17539. while (options && (name = *options++) != NULL) {
  17540. if ((idx = get_option_index(name)) == -1) {
  17541. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17542. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17543. mg_snprintf(NULL,
  17544. NULL, /* No truncation check for error buffers */
  17545. error->text,
  17546. error->text_buffer_size,
  17547. "Invalid configuration option: %s",
  17548. name);
  17549. }
  17550. free_context(ctx);
  17551. pthread_setspecific(sTlsKey, NULL);
  17552. return NULL;
  17553. } else if ((value = *options++) == NULL) {
  17554. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17555. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17556. mg_snprintf(NULL,
  17557. NULL, /* No truncation check for error buffers */
  17558. error->text,
  17559. error->text_buffer_size,
  17560. "Invalid configuration option value: %s",
  17561. name);
  17562. }
  17563. free_context(ctx);
  17564. pthread_setspecific(sTlsKey, NULL);
  17565. return NULL;
  17566. }
  17567. if (ctx->dd.config[idx] != NULL) {
  17568. /* A duplicate configuration option is not an error - the last
  17569. * option value will be used. */
  17570. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17571. mg_free(ctx->dd.config[idx]);
  17572. }
  17573. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17574. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17575. }
  17576. /* Set default value if needed */
  17577. for (i = 0; config_options[i].name != NULL; i++) {
  17578. default_value = config_options[i].default_value;
  17579. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17580. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17581. }
  17582. }
  17583. /* Request size option */
  17584. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17585. if (itmp < 1024) {
  17586. mg_cry_ctx_internal(ctx,
  17587. "%s too small",
  17588. config_options[MAX_REQUEST_SIZE].name);
  17589. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17590. mg_snprintf(NULL,
  17591. NULL, /* No truncation check for error buffers */
  17592. error->text,
  17593. error->text_buffer_size,
  17594. "Invalid configuration option value: %s",
  17595. config_options[MAX_REQUEST_SIZE].name);
  17596. }
  17597. free_context(ctx);
  17598. pthread_setspecific(sTlsKey, NULL);
  17599. return NULL;
  17600. }
  17601. ctx->max_request_size = (unsigned)itmp;
  17602. /* Queue length */
  17603. #if !defined(ALTERNATIVE_QUEUE)
  17604. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17605. if (itmp < 1) {
  17606. mg_cry_ctx_internal(ctx,
  17607. "%s too small",
  17608. config_options[CONNECTION_QUEUE_SIZE].name);
  17609. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17610. mg_snprintf(NULL,
  17611. NULL, /* No truncation check for error buffers */
  17612. error->text,
  17613. error->text_buffer_size,
  17614. "Invalid configuration option value: %s",
  17615. config_options[CONNECTION_QUEUE_SIZE].name);
  17616. }
  17617. free_context(ctx);
  17618. pthread_setspecific(sTlsKey, NULL);
  17619. return NULL;
  17620. }
  17621. ctx->squeue =
  17622. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17623. if (ctx->squeue == NULL) {
  17624. mg_cry_ctx_internal(ctx,
  17625. "Out of memory: Cannot allocate %s",
  17626. config_options[CONNECTION_QUEUE_SIZE].name);
  17627. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17628. mg_snprintf(NULL,
  17629. NULL, /* No truncation check for error buffers */
  17630. error->text,
  17631. error->text_buffer_size,
  17632. "Out of memory: Cannot allocate %s",
  17633. config_options[CONNECTION_QUEUE_SIZE].name);
  17634. }
  17635. free_context(ctx);
  17636. pthread_setspecific(sTlsKey, NULL);
  17637. return NULL;
  17638. }
  17639. ctx->sq_size = itmp;
  17640. #endif
  17641. /* Worker thread count option */
  17642. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17643. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17644. if (workerthreadcount <= 0) {
  17645. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17646. } else {
  17647. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17648. }
  17649. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17650. mg_snprintf(NULL,
  17651. NULL, /* No truncation check for error buffers */
  17652. error->text,
  17653. error->text_buffer_size,
  17654. "Invalid configuration option value: %s",
  17655. config_options[NUM_THREADS].name);
  17656. }
  17657. free_context(ctx);
  17658. pthread_setspecific(sTlsKey, NULL);
  17659. return NULL;
  17660. }
  17661. /* Document root */
  17662. #if defined(NO_FILES)
  17663. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17664. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17665. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17666. mg_snprintf(NULL,
  17667. NULL, /* No truncation check for error buffers */
  17668. error->text,
  17669. error->text_buffer_size,
  17670. "Invalid configuration option value: %s",
  17671. config_options[DOCUMENT_ROOT].name);
  17672. }
  17673. free_context(ctx);
  17674. pthread_setspecific(sTlsKey, NULL);
  17675. return NULL;
  17676. }
  17677. #endif
  17678. get_system_name(&ctx->systemName);
  17679. #if defined(USE_LUA)
  17680. /* If a Lua background script has been configured, start it. */
  17681. ctx->lua_bg_log_available = 0;
  17682. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17683. char ebuf[256];
  17684. struct vec opt_vec;
  17685. struct vec eq_vec;
  17686. const char *sparams;
  17687. memset(ebuf, 0, sizeof(ebuf));
  17688. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17689. /* Create a Lua state, load all standard libraries and the mg table */
  17690. lua_State *state = mg_lua_context_script_prepare(
  17691. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17692. if (!state) {
  17693. mg_cry_ctx_internal(ctx,
  17694. "lua_background_script load error: %s",
  17695. ebuf);
  17696. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17697. mg_snprintf(NULL,
  17698. NULL, /* No truncation check for error buffers */
  17699. error->text,
  17700. error->text_buffer_size,
  17701. "Error in script %s: %s",
  17702. config_options[LUA_BACKGROUND_SCRIPT].name,
  17703. ebuf);
  17704. }
  17705. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17706. free_context(ctx);
  17707. pthread_setspecific(sTlsKey, NULL);
  17708. return NULL;
  17709. }
  17710. /* Add a table with parameters into mg.params */
  17711. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17712. if (sparams && sparams[0]) {
  17713. lua_getglobal(state, "mg");
  17714. lua_pushstring(state, "params");
  17715. lua_newtable(state);
  17716. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17717. != NULL) {
  17718. reg_llstring(
  17719. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17720. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17721. break;
  17722. }
  17723. lua_rawset(state, -3);
  17724. lua_pop(state, 1);
  17725. }
  17726. /* Call script */
  17727. state = mg_lua_context_script_run(state,
  17728. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17729. ctx,
  17730. ebuf,
  17731. sizeof(ebuf));
  17732. if (!state) {
  17733. mg_cry_ctx_internal(ctx,
  17734. "lua_background_script start error: %s",
  17735. ebuf);
  17736. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17737. mg_snprintf(NULL,
  17738. NULL, /* No truncation check for error buffers */
  17739. error->text,
  17740. error->text_buffer_size,
  17741. "Error in script %s: %s",
  17742. config_options[DOCUMENT_ROOT].name,
  17743. ebuf);
  17744. }
  17745. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17746. free_context(ctx);
  17747. pthread_setspecific(sTlsKey, NULL);
  17748. return NULL;
  17749. }
  17750. /* state remains valid */
  17751. ctx->lua_background_state = (void *)state;
  17752. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17753. } else {
  17754. ctx->lua_background_state = 0;
  17755. }
  17756. #endif
  17757. /* Step by step initialization of ctx - depending on build options */
  17758. #if !defined(NO_FILESYSTEMS)
  17759. if (!set_gpass_option(ctx, NULL)) {
  17760. const char *err_msg = "Invalid global password file";
  17761. /* Fatal error - abort start. */
  17762. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17763. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17764. mg_snprintf(NULL,
  17765. NULL, /* No truncation check for error buffers */
  17766. error->text,
  17767. error->text_buffer_size,
  17768. "%s",
  17769. err_msg);
  17770. }
  17771. free_context(ctx);
  17772. pthread_setspecific(sTlsKey, NULL);
  17773. return NULL;
  17774. }
  17775. #endif
  17776. #if defined(USE_MBEDTLS)
  17777. if (!mg_sslctx_init(ctx, NULL)) {
  17778. const char *err_msg = "Error initializing SSL context";
  17779. /* Fatal error - abort start. */
  17780. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17781. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17782. mg_snprintf(NULL,
  17783. NULL, /* No truncation check for error buffers */
  17784. error->text,
  17785. error->text_buffer_size,
  17786. "%s",
  17787. err_msg);
  17788. }
  17789. free_context(ctx);
  17790. pthread_setspecific(sTlsKey, NULL);
  17791. return NULL;
  17792. }
  17793. #elif !defined(NO_SSL)
  17794. if (!init_ssl_ctx(ctx, NULL)) {
  17795. const char *err_msg = "Error initializing SSL context";
  17796. /* Fatal error - abort start. */
  17797. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17798. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17799. mg_snprintf(NULL,
  17800. NULL, /* No truncation check for error buffers */
  17801. error->text,
  17802. error->text_buffer_size,
  17803. "%s",
  17804. err_msg);
  17805. }
  17806. free_context(ctx);
  17807. pthread_setspecific(sTlsKey, NULL);
  17808. return NULL;
  17809. }
  17810. #endif
  17811. if (!set_ports_option(ctx)) {
  17812. const char *err_msg = "Failed to setup server ports";
  17813. /* Fatal error - abort start. */
  17814. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17815. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17816. mg_snprintf(NULL,
  17817. NULL, /* No truncation check for error buffers */
  17818. error->text,
  17819. error->text_buffer_size,
  17820. "%s",
  17821. err_msg);
  17822. }
  17823. free_context(ctx);
  17824. pthread_setspecific(sTlsKey, NULL);
  17825. return NULL;
  17826. }
  17827. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17828. if (!set_uid_option(ctx)) {
  17829. const char *err_msg = "Failed to run as configured user";
  17830. /* Fatal error - abort start. */
  17831. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17832. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17833. mg_snprintf(NULL,
  17834. NULL, /* No truncation check for error buffers */
  17835. error->text,
  17836. error->text_buffer_size,
  17837. "%s",
  17838. err_msg);
  17839. }
  17840. free_context(ctx);
  17841. pthread_setspecific(sTlsKey, NULL);
  17842. return NULL;
  17843. }
  17844. #endif
  17845. if (!set_acl_option(ctx)) {
  17846. const char *err_msg = "Failed to setup access control list";
  17847. /* Fatal error - abort start. */
  17848. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17849. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17850. mg_snprintf(NULL,
  17851. NULL, /* No truncation check for error buffers */
  17852. error->text,
  17853. error->text_buffer_size,
  17854. "%s",
  17855. err_msg);
  17856. }
  17857. free_context(ctx);
  17858. pthread_setspecific(sTlsKey, NULL);
  17859. return NULL;
  17860. }
  17861. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17862. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17863. sizeof(pthread_t),
  17864. ctx);
  17865. if (ctx->worker_threadids == NULL) {
  17866. const char *err_msg = "Not enough memory for worker thread ID array";
  17867. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17868. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17869. mg_snprintf(NULL,
  17870. NULL, /* No truncation check for error buffers */
  17871. error->text,
  17872. error->text_buffer_size,
  17873. "%s",
  17874. err_msg);
  17875. }
  17876. free_context(ctx);
  17877. pthread_setspecific(sTlsKey, NULL);
  17878. return NULL;
  17879. }
  17880. ctx->worker_connections =
  17881. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17882. sizeof(struct mg_connection),
  17883. ctx);
  17884. if (ctx->worker_connections == NULL) {
  17885. const char *err_msg =
  17886. "Not enough memory for worker thread connection array";
  17887. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17888. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17889. mg_snprintf(NULL,
  17890. NULL, /* No truncation check for error buffers */
  17891. error->text,
  17892. error->text_buffer_size,
  17893. "%s",
  17894. err_msg);
  17895. }
  17896. free_context(ctx);
  17897. pthread_setspecific(sTlsKey, NULL);
  17898. return NULL;
  17899. }
  17900. #if defined(ALTERNATIVE_QUEUE)
  17901. ctx->client_wait_events =
  17902. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17903. sizeof(ctx->client_wait_events[0]),
  17904. ctx);
  17905. if (ctx->client_wait_events == NULL) {
  17906. const char *err_msg = "Not enough memory for worker event array";
  17907. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17908. mg_free(ctx->worker_threadids);
  17909. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17910. mg_snprintf(NULL,
  17911. NULL, /* No truncation check for error buffers */
  17912. error->text,
  17913. error->text_buffer_size,
  17914. "%s",
  17915. err_msg);
  17916. }
  17917. free_context(ctx);
  17918. pthread_setspecific(sTlsKey, NULL);
  17919. return NULL;
  17920. }
  17921. ctx->client_socks =
  17922. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17923. sizeof(ctx->client_socks[0]),
  17924. ctx);
  17925. if (ctx->client_socks == NULL) {
  17926. const char *err_msg = "Not enough memory for worker socket array";
  17927. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17928. mg_free(ctx->client_wait_events);
  17929. mg_free(ctx->worker_threadids);
  17930. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17931. mg_snprintf(NULL,
  17932. NULL, /* No truncation check for error buffers */
  17933. error->text,
  17934. error->text_buffer_size,
  17935. "%s",
  17936. err_msg);
  17937. }
  17938. free_context(ctx);
  17939. pthread_setspecific(sTlsKey, NULL);
  17940. return NULL;
  17941. }
  17942. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17943. ctx->client_wait_events[i] = event_create();
  17944. if (ctx->client_wait_events[i] == 0) {
  17945. const char *err_msg = "Error creating worker event %i";
  17946. mg_cry_ctx_internal(ctx, err_msg, i);
  17947. while (i > 0) {
  17948. i--;
  17949. event_destroy(ctx->client_wait_events[i]);
  17950. }
  17951. mg_free(ctx->client_socks);
  17952. mg_free(ctx->client_wait_events);
  17953. mg_free(ctx->worker_threadids);
  17954. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17955. mg_snprintf(NULL,
  17956. NULL, /* No truncation check for error buffers */
  17957. error->text,
  17958. error->text_buffer_size,
  17959. err_msg,
  17960. i);
  17961. }
  17962. free_context(ctx);
  17963. pthread_setspecific(sTlsKey, NULL);
  17964. return NULL;
  17965. }
  17966. }
  17967. #endif
  17968. #if defined(USE_TIMERS)
  17969. if (timers_init(ctx) != 0) {
  17970. const char *err_msg = "Error creating timers";
  17971. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17972. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17973. mg_snprintf(NULL,
  17974. NULL, /* No truncation check for error buffers */
  17975. error->text,
  17976. error->text_buffer_size,
  17977. "%s",
  17978. err_msg);
  17979. }
  17980. free_context(ctx);
  17981. pthread_setspecific(sTlsKey, NULL);
  17982. return NULL;
  17983. }
  17984. #endif
  17985. /* Context has been created - init user libraries */
  17986. if (ctx->callbacks.init_context) {
  17987. ctx->callbacks.init_context(ctx);
  17988. }
  17989. /* From now, the context is successfully created.
  17990. * When it is destroyed, the exit callback should be called. */
  17991. ctx->callbacks.exit_context = exit_callback;
  17992. ctx->context_type = CONTEXT_SERVER; /* server context */
  17993. /* Start worker threads */
  17994. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17995. /* worker_thread sets up the other fields */
  17996. ctx->worker_connections[i].phys_ctx = ctx;
  17997. if (mg_start_thread_with_id(worker_thread,
  17998. &ctx->worker_connections[i],
  17999. &ctx->worker_threadids[i])
  18000. != 0) {
  18001. long error_no = (long)ERRNO;
  18002. /* thread was not created */
  18003. if (i > 0) {
  18004. /* If the second, third, ... thread cannot be created, set a
  18005. * warning, but keep running. */
  18006. mg_cry_ctx_internal(ctx,
  18007. "Cannot start worker thread %i: error %ld",
  18008. i + 1,
  18009. error_no);
  18010. /* If the server initialization should stop here, all
  18011. * threads that have already been created must be stopped
  18012. * first, before any free_context(ctx) call.
  18013. */
  18014. } else {
  18015. /* If the first worker thread cannot be created, stop
  18016. * initialization and free the entire server context. */
  18017. mg_cry_ctx_internal(ctx,
  18018. "Cannot create threads: error %ld",
  18019. error_no);
  18020. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18021. mg_snprintf(
  18022. NULL,
  18023. NULL, /* No truncation check for error buffers */
  18024. error->text,
  18025. error->text_buffer_size,
  18026. "Cannot create first worker thread: error %ld",
  18027. error_no);
  18028. }
  18029. free_context(ctx);
  18030. pthread_setspecific(sTlsKey, NULL);
  18031. return NULL;
  18032. }
  18033. break;
  18034. }
  18035. }
  18036. /* Start master (listening) thread */
  18037. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18038. pthread_setspecific(sTlsKey, NULL);
  18039. return ctx;
  18040. }
  18041. struct mg_context *
  18042. mg_start(const struct mg_callbacks *callbacks,
  18043. void *user_data,
  18044. const char **options)
  18045. {
  18046. struct mg_init_data init = {0};
  18047. init.callbacks = callbacks;
  18048. init.user_data = user_data;
  18049. init.configuration_options = options;
  18050. return mg_start2(&init, NULL);
  18051. }
  18052. /* Add an additional domain to an already running web server. */
  18053. int
  18054. mg_start_domain2(struct mg_context *ctx,
  18055. const char **options,
  18056. struct mg_error_data *error)
  18057. {
  18058. const char *name;
  18059. const char *value;
  18060. const char *default_value;
  18061. struct mg_domain_context *new_dom;
  18062. struct mg_domain_context *dom;
  18063. int idx, i;
  18064. if (error != NULL) {
  18065. error->code = 0;
  18066. if (error->text_buffer_size > 0) {
  18067. *error->text = 0;
  18068. }
  18069. }
  18070. if ((ctx == NULL) || (options == NULL)) {
  18071. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18072. mg_snprintf(NULL,
  18073. NULL, /* No truncation check for error buffers */
  18074. error->text,
  18075. error->text_buffer_size,
  18076. "%s",
  18077. "Invalid parameters");
  18078. }
  18079. return -1;
  18080. }
  18081. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18082. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18083. mg_snprintf(NULL,
  18084. NULL, /* No truncation check for error buffers */
  18085. error->text,
  18086. error->text_buffer_size,
  18087. "%s",
  18088. "Server already stopped");
  18089. }
  18090. return -1;
  18091. }
  18092. new_dom = (struct mg_domain_context *)
  18093. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18094. if (!new_dom) {
  18095. /* Out of memory */
  18096. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18097. mg_snprintf(NULL,
  18098. NULL, /* No truncation check for error buffers */
  18099. error->text,
  18100. error->text_buffer_size,
  18101. "%s",
  18102. "Out or memory");
  18103. }
  18104. return -6;
  18105. }
  18106. /* Store options - TODO: unite duplicate code */
  18107. while (options && (name = *options++) != NULL) {
  18108. if ((idx = get_option_index(name)) == -1) {
  18109. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18110. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18111. mg_snprintf(NULL,
  18112. NULL, /* No truncation check for error buffers */
  18113. error->text,
  18114. error->text_buffer_size,
  18115. "Invalid option: %s",
  18116. name);
  18117. }
  18118. mg_free(new_dom);
  18119. return -2;
  18120. } else if ((value = *options++) == NULL) {
  18121. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18122. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18123. mg_snprintf(NULL,
  18124. NULL, /* No truncation check for error buffers */
  18125. error->text,
  18126. error->text_buffer_size,
  18127. "Invalid option value: %s",
  18128. name);
  18129. }
  18130. mg_free(new_dom);
  18131. return -2;
  18132. }
  18133. if (new_dom->config[idx] != NULL) {
  18134. /* Duplicate option: Later values overwrite earlier ones. */
  18135. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18136. mg_free(new_dom->config[idx]);
  18137. }
  18138. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18139. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18140. }
  18141. /* Authentication domain is mandatory */
  18142. /* TODO: Maybe use a new option hostname? */
  18143. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18144. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18145. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18146. mg_snprintf(NULL,
  18147. NULL, /* No truncation check for error buffers */
  18148. error->text,
  18149. error->text_buffer_size,
  18150. "Mandatory option %s missing",
  18151. config_options[AUTHENTICATION_DOMAIN].name);
  18152. }
  18153. mg_free(new_dom);
  18154. return -4;
  18155. }
  18156. /* Set default value if needed. Take the config value from
  18157. * ctx as a default value. */
  18158. for (i = 0; config_options[i].name != NULL; i++) {
  18159. default_value = ctx->dd.config[i];
  18160. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18161. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18162. }
  18163. }
  18164. new_dom->handlers = NULL;
  18165. new_dom->next = NULL;
  18166. new_dom->nonce_count = 0;
  18167. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18168. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18169. new_dom->shared_lua_websockets = NULL;
  18170. #endif
  18171. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18172. if (!init_ssl_ctx(ctx, new_dom)) {
  18173. /* Init SSL failed */
  18174. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18175. mg_snprintf(NULL,
  18176. NULL, /* No truncation check for error buffers */
  18177. error->text,
  18178. error->text_buffer_size,
  18179. "%s",
  18180. "Initializing SSL context failed");
  18181. }
  18182. mg_free(new_dom);
  18183. return -3;
  18184. }
  18185. #endif
  18186. /* Add element to linked list. */
  18187. mg_lock_context(ctx);
  18188. idx = 0;
  18189. dom = &(ctx->dd);
  18190. for (;;) {
  18191. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18192. dom->config[AUTHENTICATION_DOMAIN])) {
  18193. /* Domain collision */
  18194. mg_cry_ctx_internal(ctx,
  18195. "domain %s already in use",
  18196. new_dom->config[AUTHENTICATION_DOMAIN]);
  18197. if ((error != NULL) && (error->text_buffer_size > 0)) {
  18198. mg_snprintf(NULL,
  18199. NULL, /* No truncation check for error buffers */
  18200. error->text,
  18201. error->text_buffer_size,
  18202. "Domain %s specified by %s is already in use",
  18203. new_dom->config[AUTHENTICATION_DOMAIN],
  18204. config_options[AUTHENTICATION_DOMAIN].name);
  18205. }
  18206. mg_free(new_dom);
  18207. mg_unlock_context(ctx);
  18208. return -5;
  18209. }
  18210. /* Count number of domains */
  18211. idx++;
  18212. if (dom->next == NULL) {
  18213. dom->next = new_dom;
  18214. break;
  18215. }
  18216. dom = dom->next;
  18217. }
  18218. mg_unlock_context(ctx);
  18219. /* Return domain number */
  18220. return idx;
  18221. }
  18222. int
  18223. mg_start_domain(struct mg_context *ctx, const char **options)
  18224. {
  18225. return mg_start_domain2(ctx, options, NULL);
  18226. }
  18227. /* Feature check API function */
  18228. unsigned
  18229. mg_check_feature(unsigned feature)
  18230. {
  18231. static const unsigned feature_set = 0
  18232. /* Set bits for available features according to API documentation.
  18233. * This bit mask is created at compile time, according to the active
  18234. * preprocessor defines. It is a single const value at runtime. */
  18235. #if !defined(NO_FILES)
  18236. | MG_FEATURES_FILES
  18237. #endif
  18238. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18239. | MG_FEATURES_SSL
  18240. #endif
  18241. #if !defined(NO_CGI)
  18242. | MG_FEATURES_CGI
  18243. #endif
  18244. #if defined(USE_IPV6)
  18245. | MG_FEATURES_IPV6
  18246. #endif
  18247. #if defined(USE_WEBSOCKET)
  18248. | MG_FEATURES_WEBSOCKET
  18249. #endif
  18250. #if defined(USE_LUA)
  18251. | MG_FEATURES_LUA
  18252. #endif
  18253. #if defined(USE_DUKTAPE)
  18254. | MG_FEATURES_SSJS
  18255. #endif
  18256. #if !defined(NO_CACHING)
  18257. | MG_FEATURES_CACHE
  18258. #endif
  18259. #if defined(USE_SERVER_STATS)
  18260. | MG_FEATURES_STATS
  18261. #endif
  18262. #if defined(USE_ZLIB)
  18263. | MG_FEATURES_COMPRESSION
  18264. #endif
  18265. #if defined(USE_HTTP2)
  18266. | MG_FEATURES_HTTP2
  18267. #endif
  18268. #if defined(USE_X_DOM_SOCKET)
  18269. | MG_FEATURES_X_DOMAIN_SOCKET
  18270. #endif
  18271. /* Set some extra bits not defined in the API documentation.
  18272. * These bits may change without further notice. */
  18273. #if defined(MG_LEGACY_INTERFACE)
  18274. | 0x80000000u
  18275. #endif
  18276. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18277. | 0x40000000u
  18278. #endif
  18279. #if !defined(NO_RESPONSE_BUFFERING)
  18280. | 0x20000000u
  18281. #endif
  18282. #if defined(MEMORY_DEBUGGING)
  18283. | 0x10000000u
  18284. #endif
  18285. ;
  18286. return (feature & feature_set);
  18287. }
  18288. static size_t
  18289. mg_str_append(char **dst, char *end, const char *src)
  18290. {
  18291. size_t len = strlen(src);
  18292. if (*dst != end) {
  18293. /* Append src if enough space, or close dst. */
  18294. if ((size_t)(end - *dst) > len) {
  18295. strcpy(*dst, src);
  18296. *dst += len;
  18297. } else {
  18298. *dst = end;
  18299. }
  18300. }
  18301. return len;
  18302. }
  18303. /* Get system information. It can be printed or stored by the caller.
  18304. * Return the size of available information. */
  18305. int
  18306. mg_get_system_info(char *buffer, int buflen)
  18307. {
  18308. char *end, *append_eoobj = NULL, block[256];
  18309. size_t system_info_length = 0;
  18310. #if defined(_WIN32)
  18311. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18312. #else
  18313. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18314. #endif
  18315. if ((buffer == NULL) || (buflen < 1)) {
  18316. buflen = 0;
  18317. end = buffer;
  18318. } else {
  18319. *buffer = 0;
  18320. end = buffer + buflen;
  18321. }
  18322. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18323. /* has enough space to append eoobj */
  18324. append_eoobj = buffer;
  18325. if (end) {
  18326. end -= sizeof(eoobj) - 1;
  18327. }
  18328. }
  18329. system_info_length += mg_str_append(&buffer, end, "{");
  18330. /* Server version */
  18331. {
  18332. const char *version = mg_version();
  18333. mg_snprintf(NULL,
  18334. NULL,
  18335. block,
  18336. sizeof(block),
  18337. "%s\"version\" : \"%s\"",
  18338. eol,
  18339. version);
  18340. system_info_length += mg_str_append(&buffer, end, block);
  18341. }
  18342. /* System info */
  18343. {
  18344. #if defined(_WIN32)
  18345. DWORD dwVersion = 0;
  18346. DWORD dwMajorVersion = 0;
  18347. DWORD dwMinorVersion = 0;
  18348. SYSTEM_INFO si;
  18349. GetSystemInfo(&si);
  18350. #if defined(_MSC_VER)
  18351. #pragma warning(push)
  18352. /* GetVersion was declared deprecated */
  18353. #pragma warning(disable : 4996)
  18354. #endif
  18355. dwVersion = GetVersion();
  18356. #if defined(_MSC_VER)
  18357. #pragma warning(pop)
  18358. #endif
  18359. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  18360. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  18361. mg_snprintf(NULL,
  18362. NULL,
  18363. block,
  18364. sizeof(block),
  18365. ",%s\"os\" : \"Windows %u.%u\"",
  18366. eol,
  18367. (unsigned)dwMajorVersion,
  18368. (unsigned)dwMinorVersion);
  18369. system_info_length += mg_str_append(&buffer, end, block);
  18370. mg_snprintf(NULL,
  18371. NULL,
  18372. block,
  18373. sizeof(block),
  18374. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  18375. eol,
  18376. (unsigned)si.wProcessorArchitecture,
  18377. (unsigned)si.dwNumberOfProcessors,
  18378. (unsigned)si.dwActiveProcessorMask);
  18379. system_info_length += mg_str_append(&buffer, end, block);
  18380. #elif defined(__ZEPHYR__)
  18381. mg_snprintf(NULL,
  18382. NULL,
  18383. block,
  18384. sizeof(block),
  18385. ",%s\"os\" : \"%s %s\"",
  18386. eol,
  18387. "Zephyr OS",
  18388. ZEPHYR_VERSION);
  18389. system_info_length += mg_str_append(&buffer, end, block);
  18390. #else
  18391. struct utsname name;
  18392. memset(&name, 0, sizeof(name));
  18393. uname(&name);
  18394. mg_snprintf(NULL,
  18395. NULL,
  18396. block,
  18397. sizeof(block),
  18398. ",%s\"os\" : \"%s %s (%s) - %s\"",
  18399. eol,
  18400. name.sysname,
  18401. name.version,
  18402. name.release,
  18403. name.machine);
  18404. system_info_length += mg_str_append(&buffer, end, block);
  18405. #endif
  18406. }
  18407. /* Features */
  18408. {
  18409. mg_snprintf(NULL,
  18410. NULL,
  18411. block,
  18412. sizeof(block),
  18413. ",%s\"features\" : %lu"
  18414. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  18415. eol,
  18416. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  18417. eol,
  18418. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  18419. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  18420. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  18421. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  18422. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  18423. : "",
  18424. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  18425. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  18426. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  18427. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  18428. system_info_length += mg_str_append(&buffer, end, block);
  18429. #if defined(USE_LUA)
  18430. mg_snprintf(NULL,
  18431. NULL,
  18432. block,
  18433. sizeof(block),
  18434. ",%s\"lua_version\" : \"%u (%s)\"",
  18435. eol,
  18436. (unsigned)LUA_VERSION_NUM,
  18437. LUA_RELEASE);
  18438. system_info_length += mg_str_append(&buffer, end, block);
  18439. #endif
  18440. #if defined(USE_DUKTAPE)
  18441. mg_snprintf(NULL,
  18442. NULL,
  18443. block,
  18444. sizeof(block),
  18445. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  18446. eol,
  18447. (unsigned)DUK_VERSION / 10000,
  18448. ((unsigned)DUK_VERSION / 100) % 100,
  18449. (unsigned)DUK_VERSION % 100);
  18450. system_info_length += mg_str_append(&buffer, end, block);
  18451. #endif
  18452. }
  18453. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  18454. {
  18455. #if defined(BUILD_DATE)
  18456. const char *bd = BUILD_DATE;
  18457. #else
  18458. #if defined(GCC_DIAGNOSTIC)
  18459. #if GCC_VERSION >= 40900
  18460. #pragma GCC diagnostic push
  18461. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  18462. * does not work in some versions. If "BUILD_DATE" is defined to some
  18463. * string, it is used instead of __DATE__. */
  18464. #pragma GCC diagnostic ignored "-Wdate-time"
  18465. #endif
  18466. #endif
  18467. const char *bd = __DATE__;
  18468. #if defined(GCC_DIAGNOSTIC)
  18469. #if GCC_VERSION >= 40900
  18470. #pragma GCC diagnostic pop
  18471. #endif
  18472. #endif
  18473. #endif
  18474. mg_snprintf(
  18475. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  18476. system_info_length += mg_str_append(&buffer, end, block);
  18477. }
  18478. /* Compiler information */
  18479. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  18480. {
  18481. #if defined(_MSC_VER)
  18482. mg_snprintf(NULL,
  18483. NULL,
  18484. block,
  18485. sizeof(block),
  18486. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  18487. eol,
  18488. (unsigned)_MSC_VER,
  18489. (unsigned)_MSC_FULL_VER);
  18490. system_info_length += mg_str_append(&buffer, end, block);
  18491. #elif defined(__MINGW64__)
  18492. mg_snprintf(NULL,
  18493. NULL,
  18494. block,
  18495. sizeof(block),
  18496. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  18497. eol,
  18498. (unsigned)__MINGW64_VERSION_MAJOR,
  18499. (unsigned)__MINGW64_VERSION_MINOR);
  18500. system_info_length += mg_str_append(&buffer, end, block);
  18501. mg_snprintf(NULL,
  18502. NULL,
  18503. block,
  18504. sizeof(block),
  18505. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18506. eol,
  18507. (unsigned)__MINGW32_MAJOR_VERSION,
  18508. (unsigned)__MINGW32_MINOR_VERSION);
  18509. system_info_length += mg_str_append(&buffer, end, block);
  18510. #elif defined(__MINGW32__)
  18511. mg_snprintf(NULL,
  18512. NULL,
  18513. block,
  18514. sizeof(block),
  18515. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  18516. eol,
  18517. (unsigned)__MINGW32_MAJOR_VERSION,
  18518. (unsigned)__MINGW32_MINOR_VERSION);
  18519. system_info_length += mg_str_append(&buffer, end, block);
  18520. #elif defined(__clang__)
  18521. mg_snprintf(NULL,
  18522. NULL,
  18523. block,
  18524. sizeof(block),
  18525. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  18526. eol,
  18527. __clang_major__,
  18528. __clang_minor__,
  18529. __clang_patchlevel__,
  18530. __clang_version__);
  18531. system_info_length += mg_str_append(&buffer, end, block);
  18532. #elif defined(__GNUC__)
  18533. mg_snprintf(NULL,
  18534. NULL,
  18535. block,
  18536. sizeof(block),
  18537. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  18538. eol,
  18539. (unsigned)__GNUC__,
  18540. (unsigned)__GNUC_MINOR__,
  18541. (unsigned)__GNUC_PATCHLEVEL__);
  18542. system_info_length += mg_str_append(&buffer, end, block);
  18543. #elif defined(__INTEL_COMPILER)
  18544. mg_snprintf(NULL,
  18545. NULL,
  18546. block,
  18547. sizeof(block),
  18548. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  18549. eol,
  18550. (unsigned)__INTEL_COMPILER);
  18551. system_info_length += mg_str_append(&buffer, end, block);
  18552. #elif defined(__BORLANDC__)
  18553. mg_snprintf(NULL,
  18554. NULL,
  18555. block,
  18556. sizeof(block),
  18557. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  18558. eol,
  18559. (unsigned)__BORLANDC__);
  18560. system_info_length += mg_str_append(&buffer, end, block);
  18561. #elif defined(__SUNPRO_C)
  18562. mg_snprintf(NULL,
  18563. NULL,
  18564. block,
  18565. sizeof(block),
  18566. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  18567. eol,
  18568. (unsigned)__SUNPRO_C);
  18569. system_info_length += mg_str_append(&buffer, end, block);
  18570. #else
  18571. mg_snprintf(NULL,
  18572. NULL,
  18573. block,
  18574. sizeof(block),
  18575. ",%s\"compiler\" : \"other\"",
  18576. eol);
  18577. system_info_length += mg_str_append(&buffer, end, block);
  18578. #endif
  18579. }
  18580. /* Determine 32/64 bit data mode.
  18581. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18582. {
  18583. mg_snprintf(NULL,
  18584. NULL,
  18585. block,
  18586. sizeof(block),
  18587. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18588. "char:%u/%u, "
  18589. "ptr:%u, size:%u, time:%u\"",
  18590. eol,
  18591. (unsigned)sizeof(short),
  18592. (unsigned)sizeof(int),
  18593. (unsigned)sizeof(long),
  18594. (unsigned)sizeof(long long),
  18595. (unsigned)sizeof(float),
  18596. (unsigned)sizeof(double),
  18597. (unsigned)sizeof(long double),
  18598. (unsigned)sizeof(char),
  18599. (unsigned)sizeof(wchar_t),
  18600. (unsigned)sizeof(void *),
  18601. (unsigned)sizeof(size_t),
  18602. (unsigned)sizeof(time_t));
  18603. system_info_length += mg_str_append(&buffer, end, block);
  18604. }
  18605. /* Terminate string */
  18606. if (append_eoobj) {
  18607. strcat(append_eoobj, eoobj);
  18608. }
  18609. system_info_length += sizeof(eoobj) - 1;
  18610. return (int)system_info_length;
  18611. }
  18612. /* Get context information. It can be printed or stored by the caller.
  18613. * Return the size of available information. */
  18614. int
  18615. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18616. {
  18617. #if defined(USE_SERVER_STATS)
  18618. char *end, *append_eoobj = NULL, block[256];
  18619. size_t context_info_length = 0;
  18620. #if defined(_WIN32)
  18621. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18622. #else
  18623. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18624. #endif
  18625. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18626. if ((buffer == NULL) || (buflen < 1)) {
  18627. buflen = 0;
  18628. end = buffer;
  18629. } else {
  18630. *buffer = 0;
  18631. end = buffer + buflen;
  18632. }
  18633. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18634. /* has enough space to append eoobj */
  18635. append_eoobj = buffer;
  18636. end -= sizeof(eoobj) - 1;
  18637. }
  18638. context_info_length += mg_str_append(&buffer, end, "{");
  18639. if (ms) { /* <-- should be always true */
  18640. /* Memory information */
  18641. int blockCount = (int)ms->blockCount;
  18642. int64_t totalMemUsed = ms->totalMemUsed;
  18643. int64_t maxMemUsed = ms->maxMemUsed;
  18644. if (totalMemUsed > maxMemUsed) {
  18645. maxMemUsed = totalMemUsed;
  18646. }
  18647. mg_snprintf(NULL,
  18648. NULL,
  18649. block,
  18650. sizeof(block),
  18651. "%s\"memory\" : {%s"
  18652. "\"blocks\" : %i,%s"
  18653. "\"used\" : %" INT64_FMT ",%s"
  18654. "\"maxUsed\" : %" INT64_FMT "%s"
  18655. "}",
  18656. eol,
  18657. eol,
  18658. blockCount,
  18659. eol,
  18660. totalMemUsed,
  18661. eol,
  18662. maxMemUsed,
  18663. eol);
  18664. context_info_length += mg_str_append(&buffer, end, block);
  18665. }
  18666. if (ctx) {
  18667. /* Declare all variables at begin of the block, to comply
  18668. * with old C standards. */
  18669. char start_time_str[64] = {0};
  18670. char now_str[64] = {0};
  18671. time_t start_time = ctx->start_time;
  18672. time_t now = time(NULL);
  18673. int64_t total_data_read, total_data_written;
  18674. int active_connections = (int)ctx->active_connections;
  18675. int max_active_connections = (int)ctx->max_active_connections;
  18676. int total_connections = (int)ctx->total_connections;
  18677. if (active_connections > max_active_connections) {
  18678. max_active_connections = active_connections;
  18679. }
  18680. if (active_connections > total_connections) {
  18681. total_connections = active_connections;
  18682. }
  18683. /* Connections information */
  18684. mg_snprintf(NULL,
  18685. NULL,
  18686. block,
  18687. sizeof(block),
  18688. ",%s\"connections\" : {%s"
  18689. "\"active\" : %i,%s"
  18690. "\"maxActive\" : %i,%s"
  18691. "\"total\" : %i%s"
  18692. "}",
  18693. eol,
  18694. eol,
  18695. active_connections,
  18696. eol,
  18697. max_active_connections,
  18698. eol,
  18699. total_connections,
  18700. eol);
  18701. context_info_length += mg_str_append(&buffer, end, block);
  18702. /* Queue information */
  18703. #if !defined(ALTERNATIVE_QUEUE)
  18704. mg_snprintf(NULL,
  18705. NULL,
  18706. block,
  18707. sizeof(block),
  18708. ",%s\"queue\" : {%s"
  18709. "\"length\" : %i,%s"
  18710. "\"filled\" : %i,%s"
  18711. "\"maxFilled\" : %i,%s"
  18712. "\"full\" : %s%s"
  18713. "}",
  18714. eol,
  18715. eol,
  18716. ctx->sq_size,
  18717. eol,
  18718. ctx->sq_head - ctx->sq_tail,
  18719. eol,
  18720. ctx->sq_max_fill,
  18721. eol,
  18722. (ctx->sq_blocked ? "true" : "false"),
  18723. eol);
  18724. context_info_length += mg_str_append(&buffer, end, block);
  18725. #endif
  18726. /* Requests information */
  18727. mg_snprintf(NULL,
  18728. NULL,
  18729. block,
  18730. sizeof(block),
  18731. ",%s\"requests\" : {%s"
  18732. "\"total\" : %lu%s"
  18733. "}",
  18734. eol,
  18735. eol,
  18736. (unsigned long)ctx->total_requests,
  18737. eol);
  18738. context_info_length += mg_str_append(&buffer, end, block);
  18739. /* Data information */
  18740. total_data_read =
  18741. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18742. total_data_written =
  18743. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18744. mg_snprintf(NULL,
  18745. NULL,
  18746. block,
  18747. sizeof(block),
  18748. ",%s\"data\" : {%s"
  18749. "\"read\" : %" INT64_FMT ",%s"
  18750. "\"written\" : %" INT64_FMT "%s"
  18751. "}",
  18752. eol,
  18753. eol,
  18754. total_data_read,
  18755. eol,
  18756. total_data_written,
  18757. eol);
  18758. context_info_length += mg_str_append(&buffer, end, block);
  18759. /* Execution time information */
  18760. gmt_time_string(start_time_str,
  18761. sizeof(start_time_str) - 1,
  18762. &start_time);
  18763. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18764. mg_snprintf(NULL,
  18765. NULL,
  18766. block,
  18767. sizeof(block),
  18768. ",%s\"time\" : {%s"
  18769. "\"uptime\" : %.0f,%s"
  18770. "\"start\" : \"%s\",%s"
  18771. "\"now\" : \"%s\"%s"
  18772. "}",
  18773. eol,
  18774. eol,
  18775. difftime(now, start_time),
  18776. eol,
  18777. start_time_str,
  18778. eol,
  18779. now_str,
  18780. eol);
  18781. context_info_length += mg_str_append(&buffer, end, block);
  18782. }
  18783. /* Terminate string */
  18784. if (append_eoobj) {
  18785. strcat(append_eoobj, eoobj);
  18786. }
  18787. context_info_length += sizeof(eoobj) - 1;
  18788. return (int)context_info_length;
  18789. #else
  18790. (void)ctx;
  18791. if ((buffer != NULL) && (buflen > 0)) {
  18792. *buffer = 0;
  18793. }
  18794. return 0;
  18795. #endif
  18796. }
  18797. void
  18798. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18799. {
  18800. /* https://github.com/civetweb/civetweb/issues/727 */
  18801. if (conn != NULL) {
  18802. conn->must_close = 1;
  18803. }
  18804. }
  18805. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18806. /* Get connection information. It can be printed or stored by the caller.
  18807. * Return the size of available information. */
  18808. int
  18809. mg_get_connection_info(const struct mg_context *ctx,
  18810. int idx,
  18811. char *buffer,
  18812. int buflen)
  18813. {
  18814. const struct mg_connection *conn;
  18815. const struct mg_request_info *ri;
  18816. char *end, *append_eoobj = NULL, block[256];
  18817. size_t connection_info_length = 0;
  18818. int state = 0;
  18819. const char *state_str = "unknown";
  18820. #if defined(_WIN32)
  18821. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18822. #else
  18823. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18824. #endif
  18825. if ((buffer == NULL) || (buflen < 1)) {
  18826. buflen = 0;
  18827. end = buffer;
  18828. } else {
  18829. *buffer = 0;
  18830. end = buffer + buflen;
  18831. }
  18832. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18833. /* has enough space to append eoobj */
  18834. append_eoobj = buffer;
  18835. end -= sizeof(eoobj) - 1;
  18836. }
  18837. if ((ctx == NULL) || (idx < 0)) {
  18838. /* Parameter error */
  18839. return 0;
  18840. }
  18841. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18842. /* Out of range */
  18843. return 0;
  18844. }
  18845. /* Take connection [idx]. This connection is not locked in
  18846. * any way, so some other thread might use it. */
  18847. conn = (ctx->worker_connections) + idx;
  18848. /* Initialize output string */
  18849. connection_info_length += mg_str_append(&buffer, end, "{");
  18850. /* Init variables */
  18851. ri = &(conn->request_info);
  18852. #if defined(USE_SERVER_STATS)
  18853. state = conn->conn_state;
  18854. /* State as string */
  18855. switch (state) {
  18856. case 0:
  18857. state_str = "undefined";
  18858. break;
  18859. case 1:
  18860. state_str = "not used";
  18861. break;
  18862. case 2:
  18863. state_str = "init";
  18864. break;
  18865. case 3:
  18866. state_str = "ready";
  18867. break;
  18868. case 4:
  18869. state_str = "processing";
  18870. break;
  18871. case 5:
  18872. state_str = "processed";
  18873. break;
  18874. case 6:
  18875. state_str = "to close";
  18876. break;
  18877. case 7:
  18878. state_str = "closing";
  18879. break;
  18880. case 8:
  18881. state_str = "closed";
  18882. break;
  18883. case 9:
  18884. state_str = "done";
  18885. break;
  18886. }
  18887. #endif
  18888. /* Connection info */
  18889. if ((state >= 3) && (state < 9)) {
  18890. mg_snprintf(NULL,
  18891. NULL,
  18892. block,
  18893. sizeof(block),
  18894. "%s\"connection\" : {%s"
  18895. "\"remote\" : {%s"
  18896. "\"protocol\" : \"%s\",%s"
  18897. "\"addr\" : \"%s\",%s"
  18898. "\"port\" : %u%s"
  18899. "},%s"
  18900. "\"handled_requests\" : %u%s"
  18901. "}",
  18902. eol,
  18903. eol,
  18904. eol,
  18905. get_proto_name(conn),
  18906. eol,
  18907. ri->remote_addr,
  18908. eol,
  18909. ri->remote_port,
  18910. eol,
  18911. eol,
  18912. conn->handled_requests,
  18913. eol);
  18914. connection_info_length += mg_str_append(&buffer, end, block);
  18915. }
  18916. /* Request info */
  18917. if ((state >= 4) && (state < 6)) {
  18918. mg_snprintf(NULL,
  18919. NULL,
  18920. block,
  18921. sizeof(block),
  18922. "%s%s\"request_info\" : {%s"
  18923. "\"method\" : \"%s\",%s"
  18924. "\"uri\" : \"%s\",%s"
  18925. "\"query\" : %s%s%s%s"
  18926. "}",
  18927. (connection_info_length > 1 ? "," : ""),
  18928. eol,
  18929. eol,
  18930. ri->request_method,
  18931. eol,
  18932. ri->request_uri,
  18933. eol,
  18934. ri->query_string ? "\"" : "",
  18935. ri->query_string ? ri->query_string : "null",
  18936. ri->query_string ? "\"" : "",
  18937. eol);
  18938. connection_info_length += mg_str_append(&buffer, end, block);
  18939. }
  18940. /* Execution time information */
  18941. if ((state >= 2) && (state < 9)) {
  18942. char start_time_str[64] = {0};
  18943. char close_time_str[64] = {0};
  18944. time_t start_time = conn->conn_birth_time;
  18945. time_t close_time = 0;
  18946. double time_diff;
  18947. gmt_time_string(start_time_str,
  18948. sizeof(start_time_str) - 1,
  18949. &start_time);
  18950. #if defined(USE_SERVER_STATS)
  18951. close_time = conn->conn_close_time;
  18952. #endif
  18953. if (close_time != 0) {
  18954. time_diff = difftime(close_time, start_time);
  18955. gmt_time_string(close_time_str,
  18956. sizeof(close_time_str) - 1,
  18957. &close_time);
  18958. } else {
  18959. time_t now = time(NULL);
  18960. time_diff = difftime(now, start_time);
  18961. close_time_str[0] = 0; /* or use "now" ? */
  18962. }
  18963. mg_snprintf(NULL,
  18964. NULL,
  18965. block,
  18966. sizeof(block),
  18967. "%s%s\"time\" : {%s"
  18968. "\"uptime\" : %.0f,%s"
  18969. "\"start\" : \"%s\",%s"
  18970. "\"closed\" : \"%s\"%s"
  18971. "}",
  18972. (connection_info_length > 1 ? "," : ""),
  18973. eol,
  18974. eol,
  18975. time_diff,
  18976. eol,
  18977. start_time_str,
  18978. eol,
  18979. close_time_str,
  18980. eol);
  18981. connection_info_length += mg_str_append(&buffer, end, block);
  18982. }
  18983. /* Remote user name */
  18984. if ((ri->remote_user) && (state < 9)) {
  18985. mg_snprintf(NULL,
  18986. NULL,
  18987. block,
  18988. sizeof(block),
  18989. "%s%s\"user\" : {%s"
  18990. "\"name\" : \"%s\",%s"
  18991. "}",
  18992. (connection_info_length > 1 ? "," : ""),
  18993. eol,
  18994. eol,
  18995. ri->remote_user,
  18996. eol);
  18997. connection_info_length += mg_str_append(&buffer, end, block);
  18998. }
  18999. /* Data block */
  19000. if (state >= 3) {
  19001. mg_snprintf(NULL,
  19002. NULL,
  19003. block,
  19004. sizeof(block),
  19005. "%s%s\"data\" : {%s"
  19006. "\"read\" : %" INT64_FMT ",%s"
  19007. "\"written\" : %" INT64_FMT "%s"
  19008. "}",
  19009. (connection_info_length > 1 ? "," : ""),
  19010. eol,
  19011. eol,
  19012. conn->consumed_content,
  19013. eol,
  19014. conn->num_bytes_sent,
  19015. eol);
  19016. connection_info_length += mg_str_append(&buffer, end, block);
  19017. }
  19018. /* State */
  19019. mg_snprintf(NULL,
  19020. NULL,
  19021. block,
  19022. sizeof(block),
  19023. "%s%s\"state\" : \"%s\"",
  19024. (connection_info_length > 1 ? "," : ""),
  19025. eol,
  19026. state_str);
  19027. connection_info_length += mg_str_append(&buffer, end, block);
  19028. /* Terminate string */
  19029. if (append_eoobj) {
  19030. strcat(append_eoobj, eoobj);
  19031. }
  19032. connection_info_length += sizeof(eoobj) - 1;
  19033. return (int)connection_info_length;
  19034. }
  19035. #if 0
  19036. /* Get handler information. It can be printed or stored by the caller.
  19037. * Return the size of available information. */
  19038. int
  19039. mg_get_handler_info(struct mg_context *ctx,
  19040. char *buffer,
  19041. int buflen)
  19042. {
  19043. int handler_info_len = 0;
  19044. struct mg_handler_info *tmp_rh;
  19045. mg_lock_context(ctx);
  19046. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19047. if (buflen > handler_info_len+ tmp_rh->uri_len) {
  19048. memcpy(buffer+handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19049. }
  19050. handler_info_len += tmp_rh->uri_len;
  19051. switch (tmp_rh->handler_type) {
  19052. case REQUEST_HANDLER:
  19053. (void)tmp_rh->handler;
  19054. break;
  19055. case WEBSOCKET_HANDLER:
  19056. (void)tmp_rh->connect_handler;
  19057. (void) tmp_rh->ready_handler;
  19058. (void) tmp_rh->data_handler;
  19059. (void) tmp_rh->close_handler;
  19060. break;
  19061. case AUTH_HANDLER:
  19062. (void) tmp_rh->auth_handler;
  19063. break;
  19064. }
  19065. (void)cbdata;
  19066. }
  19067. mg_unlock_context(ctx);
  19068. return handler_info_len;
  19069. }
  19070. #endif
  19071. #endif
  19072. /* Initialize this library. This function does not need to be thread safe.
  19073. */
  19074. unsigned
  19075. mg_init_library(unsigned features)
  19076. {
  19077. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19078. unsigned features_inited = features_to_init;
  19079. if (mg_init_library_called <= 0) {
  19080. /* Not initialized yet */
  19081. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19082. return 0;
  19083. }
  19084. }
  19085. mg_global_lock();
  19086. if (mg_init_library_called <= 0) {
  19087. #if defined(_WIN32)
  19088. int file_mutex_init = 1;
  19089. int wsa = 1;
  19090. #else
  19091. int mutexattr_init = 1;
  19092. #endif
  19093. int failed = 1;
  19094. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19095. if (key_create == 0) {
  19096. #if defined(_WIN32)
  19097. file_mutex_init =
  19098. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19099. if (file_mutex_init == 0) {
  19100. /* Start WinSock */
  19101. WSADATA data;
  19102. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19103. }
  19104. #else
  19105. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19106. if (mutexattr_init == 0) {
  19107. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19108. PTHREAD_MUTEX_RECURSIVE);
  19109. }
  19110. #endif
  19111. }
  19112. if (failed) {
  19113. #if defined(_WIN32)
  19114. if (wsa == 0) {
  19115. (void)WSACleanup();
  19116. }
  19117. if (file_mutex_init == 0) {
  19118. (void)pthread_mutex_destroy(&global_log_file_lock);
  19119. }
  19120. #else
  19121. if (mutexattr_init == 0) {
  19122. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19123. }
  19124. #endif
  19125. if (key_create == 0) {
  19126. (void)pthread_key_delete(sTlsKey);
  19127. }
  19128. mg_global_unlock();
  19129. (void)pthread_mutex_destroy(&global_lock_mutex);
  19130. return 0;
  19131. }
  19132. #if defined(USE_LUA)
  19133. lua_init_optional_libraries();
  19134. #endif
  19135. }
  19136. mg_global_unlock();
  19137. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19138. || defined(OPENSSL_API_3_0)) \
  19139. && !defined(NO_SSL)
  19140. if (features_to_init & MG_FEATURES_SSL) {
  19141. if (!mg_openssl_initialized) {
  19142. char ebuf[128];
  19143. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19144. mg_openssl_initialized = 1;
  19145. } else {
  19146. (void)ebuf;
  19147. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19148. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19149. }
  19150. } else {
  19151. /* ssl already initialized */
  19152. }
  19153. }
  19154. #endif
  19155. mg_global_lock();
  19156. if (mg_init_library_called <= 0) {
  19157. mg_init_library_called = 1;
  19158. } else {
  19159. mg_init_library_called++;
  19160. }
  19161. mg_global_unlock();
  19162. return features_inited;
  19163. }
  19164. /* Un-initialize this library. */
  19165. unsigned
  19166. mg_exit_library(void)
  19167. {
  19168. if (mg_init_library_called <= 0) {
  19169. return 0;
  19170. }
  19171. mg_global_lock();
  19172. mg_init_library_called--;
  19173. if (mg_init_library_called == 0) {
  19174. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19175. if (mg_openssl_initialized) {
  19176. uninitialize_openssl();
  19177. mg_openssl_initialized = 0;
  19178. }
  19179. #endif
  19180. #if defined(_WIN32)
  19181. (void)WSACleanup();
  19182. (void)pthread_mutex_destroy(&global_log_file_lock);
  19183. #else
  19184. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19185. #endif
  19186. (void)pthread_key_delete(sTlsKey);
  19187. #if defined(USE_LUA)
  19188. lua_exit_optional_libraries();
  19189. #endif
  19190. mg_global_unlock();
  19191. (void)pthread_mutex_destroy(&global_lock_mutex);
  19192. return 1;
  19193. }
  19194. mg_global_unlock();
  19195. return 1;
  19196. }
  19197. /* End of civetweb.c */