civetweb.c 568 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436
  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. #define CLOCK_MONOTONIC (1)
  311. #define CLOCK_REALTIME (2)
  312. #include <mach/clock.h>
  313. #include <mach/mach.h>
  314. #include <mach/mach_time.h>
  315. #include <sys/errno.h>
  316. #include <sys/time.h>
  317. /* clock_gettime is not implemented on OSX prior to 10.12 */
  318. static int
  319. _civet_clock_gettime(int clk_id, struct timespec *t)
  320. {
  321. memset(t, 0, sizeof(*t));
  322. if (clk_id == CLOCK_REALTIME) {
  323. struct timeval now;
  324. int rv = gettimeofday(&now, NULL);
  325. if (rv) {
  326. return rv;
  327. }
  328. t->tv_sec = now.tv_sec;
  329. t->tv_nsec = now.tv_usec * 1000;
  330. return 0;
  331. } else if (clk_id == CLOCK_MONOTONIC) {
  332. static uint64_t clock_start_time = 0;
  333. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  334. uint64_t now = mach_absolute_time();
  335. if (clock_start_time == 0) {
  336. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  337. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  338. /* appease "unused variable" warning for release builds */
  339. (void)mach_status;
  340. clock_start_time = now;
  341. }
  342. now = (uint64_t)((double)(now - clock_start_time)
  343. * (double)timebase_ifo.numer
  344. / (double)timebase_ifo.denom);
  345. t->tv_sec = now / 1000000000;
  346. t->tv_nsec = now % 1000000000;
  347. return 0;
  348. }
  349. return -1; /* EINVAL - Clock ID is unknown */
  350. }
  351. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  352. #if defined(__CLOCK_AVAILABILITY)
  353. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  354. * declared but it may be NULL at runtime. So we need to check before using
  355. * it. */
  356. static int
  357. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  358. {
  359. if (clock_gettime) {
  360. return clock_gettime(clk_id, t);
  361. }
  362. return _civet_clock_gettime(clk_id, t);
  363. }
  364. #define clock_gettime _civet_safe_clock_gettime
  365. #else
  366. #define clock_gettime _civet_clock_gettime
  367. #endif
  368. #endif
  369. #if !defined(_WIN32)
  370. /* Unix might return different error codes indicating to try again.
  371. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  372. * decades ago, but better check both and let the compile optimize it. */
  373. #define ERROR_TRY_AGAIN(err) \
  374. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  375. #endif
  376. #if defined(USE_ZLIB)
  377. #include "zconf.h"
  378. #include "zlib.h"
  379. #endif
  380. /********************************************************************/
  381. /* CivetWeb configuration defines */
  382. /********************************************************************/
  383. /* Maximum number of threads that can be configured.
  384. * The number of threads actually created depends on the "num_threads"
  385. * configuration parameter, but this is the upper limit. */
  386. #if !defined(MAX_WORKER_THREADS)
  387. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  388. #endif
  389. /* Timeout interval for select/poll calls.
  390. * The timeouts depend on "*_timeout_ms" configuration values, but long
  391. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  392. * This reduces the time required to stop the server. */
  393. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  394. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  395. #endif
  396. /* Do not try to compress files smaller than this limit. */
  397. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  398. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  399. #endif
  400. #if !defined(PASSWORDS_FILE_NAME)
  401. #define PASSWORDS_FILE_NAME ".htpasswd"
  402. #endif
  403. /* Initial buffer size for all CGI environment variables. In case there is
  404. * not enough space, another block is allocated. */
  405. #if !defined(CGI_ENVIRONMENT_SIZE)
  406. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  407. #endif
  408. /* Maximum number of environment variables. */
  409. #if !defined(MAX_CGI_ENVIR_VARS)
  410. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  411. #endif
  412. /* General purpose buffer size. */
  413. #if !defined(MG_BUF_LEN) /* in bytes */
  414. #define MG_BUF_LEN (1024 * 8)
  415. #endif
  416. /********************************************************************/
  417. /* Helper makros */
  418. #if !defined(ARRAY_SIZE)
  419. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  420. #endif
  421. #include <stdint.h>
  422. /* Standard defines */
  423. #if !defined(INT64_MAX)
  424. #define INT64_MAX (9223372036854775807)
  425. #endif
  426. #define SHUTDOWN_RD (0)
  427. #define SHUTDOWN_WR (1)
  428. #define SHUTDOWN_BOTH (2)
  429. mg_static_assert(MAX_WORKER_THREADS >= 1,
  430. "worker threads must be a positive number");
  431. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  432. "size_t data type size check");
  433. #if defined(_WIN32) /* WINDOWS include block */
  434. #include <malloc.h> /* *alloc( */
  435. #include <stdlib.h> /* *alloc( */
  436. #include <time.h> /* struct timespec */
  437. #include <windows.h>
  438. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  439. #include <ws2tcpip.h>
  440. typedef const char *SOCK_OPT_TYPE;
  441. /* For a detailed description of these *_PATH_MAX defines, see
  442. * https://github.com/civetweb/civetweb/issues/937. */
  443. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  444. * null termination, rounded up to the next 4 bytes boundary */
  445. #define UTF8_PATH_MAX (3 * 260)
  446. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  447. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  448. #define UTF16_PATH_MAX (260)
  449. #if !defined(_IN_PORT_T)
  450. #if !defined(in_port_t)
  451. #define in_port_t u_short
  452. #endif
  453. #endif
  454. #if defined(_WIN32_WCE)
  455. #error "WinCE support has ended"
  456. #endif
  457. #include <direct.h>
  458. #include <io.h>
  459. #include <process.h>
  460. #define MAKEUQUAD(lo, hi) \
  461. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  462. #define RATE_DIFF (10000000) /* 100 nsecs */
  463. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  464. #define SYS2UNIX_TIME(lo, hi) \
  465. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  466. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  467. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  468. * Also use _strtoui64 on modern M$ compilers */
  469. #if defined(_MSC_VER)
  470. #if (_MSC_VER < 1300)
  471. #define STRX(x) #x
  472. #define STR(x) STRX(x)
  473. #define __func__ __FILE__ ":" STR(__LINE__)
  474. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  475. #define strtoll(x, y, z) (_atoi64(x))
  476. #else
  477. #define __func__ __FUNCTION__
  478. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  479. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  480. #endif
  481. #endif /* _MSC_VER */
  482. #define ERRNO ((int)(GetLastError()))
  483. #define NO_SOCKLEN_T
  484. #if defined(_WIN64) || defined(__MINGW64__)
  485. #if !defined(SSL_LIB)
  486. #if defined(OPENSSL_API_3_0)
  487. #define SSL_LIB "libssl-3-x64.dll"
  488. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  489. #endif
  490. #if defined(OPENSSL_API_1_1)
  491. #define SSL_LIB "libssl-1_1-x64.dll"
  492. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  493. #endif /* OPENSSL_API_1_1 */
  494. #if defined(OPENSSL_API_1_0)
  495. #define SSL_LIB "ssleay64.dll"
  496. #define CRYPTO_LIB "libeay64.dll"
  497. #endif /* OPENSSL_API_1_0 */
  498. #endif
  499. #else /* defined(_WIN64) || defined(__MINGW64__) */
  500. #if !defined(SSL_LIB)
  501. #if defined(OPENSSL_API_3_0)
  502. #define SSL_LIB "libssl-3.dll"
  503. #define CRYPTO_LIB "libcrypto-3.dll"
  504. #endif
  505. #if defined(OPENSSL_API_1_1)
  506. #define SSL_LIB "libssl-1_1.dll"
  507. #define CRYPTO_LIB "libcrypto-1_1.dll"
  508. #endif /* OPENSSL_API_1_1 */
  509. #if defined(OPENSSL_API_1_0)
  510. #define SSL_LIB "ssleay32.dll"
  511. #define CRYPTO_LIB "libeay32.dll"
  512. #endif /* OPENSSL_API_1_0 */
  513. #endif /* SSL_LIB */
  514. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  515. #define O_NONBLOCK (0)
  516. #if !defined(W_OK)
  517. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  518. #endif
  519. #define _POSIX_
  520. #define INT64_FMT "I64d"
  521. #define UINT64_FMT "I64u"
  522. #define WINCDECL __cdecl
  523. #define vsnprintf_impl _vsnprintf
  524. #define access _access
  525. #define mg_sleep(x) (Sleep(x))
  526. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  527. #if !defined(popen)
  528. #define popen(x, y) (_popen(x, y))
  529. #endif
  530. #if !defined(pclose)
  531. #define pclose(x) (_pclose(x))
  532. #endif
  533. #define close(x) (_close(x))
  534. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  535. #define RTLD_LAZY (0)
  536. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  537. #define fdopen(x, y) (_fdopen((x), (y)))
  538. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  539. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  540. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  541. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  542. #define sleep(x) (Sleep((x)*1000))
  543. #define rmdir(x) (_rmdir(x))
  544. #if defined(_WIN64) || !defined(__MINGW32__)
  545. /* Only MinGW 32 bit is missing this function */
  546. #define timegm(x) (_mkgmtime(x))
  547. #else
  548. time_t timegm(struct tm *tm);
  549. #define NEED_TIMEGM
  550. #endif
  551. #if !defined(fileno)
  552. #define fileno(x) (_fileno(x))
  553. #endif /* !fileno MINGW #defines fileno */
  554. typedef struct {
  555. CRITICAL_SECTION sec; /* Immovable */
  556. } pthread_mutex_t;
  557. typedef DWORD pthread_key_t;
  558. typedef HANDLE pthread_t;
  559. typedef struct {
  560. pthread_mutex_t threadIdSec;
  561. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  562. } pthread_cond_t;
  563. #if !defined(__clockid_t_defined)
  564. typedef DWORD clockid_t;
  565. #endif
  566. #if !defined(CLOCK_MONOTONIC)
  567. #define CLOCK_MONOTONIC (1)
  568. #endif
  569. #if !defined(CLOCK_REALTIME)
  570. #define CLOCK_REALTIME (2)
  571. #endif
  572. #if !defined(CLOCK_THREAD)
  573. #define CLOCK_THREAD (3)
  574. #endif
  575. #if !defined(CLOCK_PROCESS)
  576. #define CLOCK_PROCESS (4)
  577. #endif
  578. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  579. #define _TIMESPEC_DEFINED
  580. #endif
  581. #if !defined(_TIMESPEC_DEFINED)
  582. struct timespec {
  583. time_t tv_sec; /* seconds */
  584. long tv_nsec; /* nanoseconds */
  585. };
  586. #endif
  587. #if !defined(WIN_PTHREADS_TIME_H)
  588. #define MUST_IMPLEMENT_CLOCK_GETTIME
  589. #endif
  590. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  591. #define clock_gettime mg_clock_gettime
  592. static int
  593. clock_gettime(clockid_t clk_id, struct timespec *tp)
  594. {
  595. FILETIME ft;
  596. ULARGE_INTEGER li, li2;
  597. BOOL ok = FALSE;
  598. double d;
  599. static double perfcnt_per_sec = 0.0;
  600. static BOOL initialized = FALSE;
  601. if (!initialized) {
  602. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  603. perfcnt_per_sec = 1.0 / li.QuadPart;
  604. initialized = TRUE;
  605. }
  606. if (tp) {
  607. memset(tp, 0, sizeof(*tp));
  608. if (clk_id == CLOCK_REALTIME) {
  609. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  610. GetSystemTimeAsFileTime(&ft);
  611. li.LowPart = ft.dwLowDateTime;
  612. li.HighPart = ft.dwHighDateTime;
  613. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  614. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  615. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  616. ok = TRUE;
  617. /* END: CLOCK_REALTIME */
  618. } else if (clk_id == CLOCK_MONOTONIC) {
  619. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  620. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  621. d = li.QuadPart * perfcnt_per_sec;
  622. tp->tv_sec = (time_t)d;
  623. d -= (double)tp->tv_sec;
  624. tp->tv_nsec = (long)(d * 1.0E9);
  625. ok = TRUE;
  626. /* END: CLOCK_MONOTONIC */
  627. } else if (clk_id == CLOCK_THREAD) {
  628. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  629. FILETIME t_create, t_exit, t_kernel, t_user;
  630. if (GetThreadTimes(GetCurrentThread(),
  631. &t_create,
  632. &t_exit,
  633. &t_kernel,
  634. &t_user)) {
  635. li.LowPart = t_user.dwLowDateTime;
  636. li.HighPart = t_user.dwHighDateTime;
  637. li2.LowPart = t_kernel.dwLowDateTime;
  638. li2.HighPart = t_kernel.dwHighDateTime;
  639. li.QuadPart += li2.QuadPart;
  640. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  641. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  642. ok = TRUE;
  643. }
  644. /* END: CLOCK_THREAD */
  645. } else if (clk_id == CLOCK_PROCESS) {
  646. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  647. FILETIME t_create, t_exit, t_kernel, t_user;
  648. if (GetProcessTimes(GetCurrentProcess(),
  649. &t_create,
  650. &t_exit,
  651. &t_kernel,
  652. &t_user)) {
  653. li.LowPart = t_user.dwLowDateTime;
  654. li.HighPart = t_user.dwHighDateTime;
  655. li2.LowPart = t_kernel.dwLowDateTime;
  656. li2.HighPart = t_kernel.dwHighDateTime;
  657. li.QuadPart += li2.QuadPart;
  658. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  659. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  660. ok = TRUE;
  661. }
  662. /* END: CLOCK_PROCESS */
  663. } else {
  664. /* BEGIN: unknown clock */
  665. /* ok = FALSE; already set by init */
  666. /* END: unknown clock */
  667. }
  668. }
  669. return ok ? 0 : -1;
  670. }
  671. #endif
  672. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  673. static int pthread_mutex_lock(pthread_mutex_t *);
  674. static int pthread_mutex_unlock(pthread_mutex_t *);
  675. static void path_to_unicode(const struct mg_connection *conn,
  676. const char *path,
  677. wchar_t *wbuf,
  678. size_t wbuf_len);
  679. /* All file operations need to be rewritten to solve #246. */
  680. struct mg_file;
  681. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  682. /* POSIX dirent interface */
  683. struct dirent {
  684. char d_name[UTF8_PATH_MAX];
  685. };
  686. typedef struct DIR {
  687. HANDLE handle;
  688. WIN32_FIND_DATAW info;
  689. struct dirent result;
  690. } DIR;
  691. #if defined(HAVE_POLL)
  692. #define mg_pollfd pollfd
  693. #else
  694. struct mg_pollfd {
  695. SOCKET fd;
  696. short events;
  697. short revents;
  698. };
  699. #endif
  700. /* Mark required libraries */
  701. #if defined(_MSC_VER)
  702. #pragma comment(lib, "Ws2_32.lib")
  703. #endif
  704. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  705. #include <inttypes.h>
  706. /* Linux & co. internally use UTF8 */
  707. #define UTF8_PATH_MAX (PATH_MAX)
  708. typedef const void *SOCK_OPT_TYPE;
  709. #if defined(ANDROID)
  710. typedef unsigned short int in_port_t;
  711. #endif
  712. #if !defined(__ZEPHYR__)
  713. #include <arpa/inet.h>
  714. #include <ctype.h>
  715. #include <dirent.h>
  716. #include <grp.h>
  717. #include <limits.h>
  718. #include <netdb.h>
  719. #include <netinet/in.h>
  720. #include <netinet/tcp.h>
  721. #include <pthread.h>
  722. #include <pwd.h>
  723. #include <stdarg.h>
  724. #include <stddef.h>
  725. #include <stdio.h>
  726. #include <stdlib.h>
  727. #include <string.h>
  728. #include <sys/poll.h>
  729. #include <sys/socket.h>
  730. #include <sys/time.h>
  731. #include <sys/utsname.h>
  732. #include <sys/wait.h>
  733. #include <time.h>
  734. #include <unistd.h>
  735. #if defined(USE_X_DOM_SOCKET)
  736. #include <sys/un.h>
  737. #endif
  738. #endif
  739. #define vsnprintf_impl vsnprintf
  740. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  741. #include <dlfcn.h>
  742. #endif
  743. #if defined(__MACH__)
  744. #define SSL_LIB "libssl.dylib"
  745. #define CRYPTO_LIB "libcrypto.dylib"
  746. #else
  747. #if !defined(SSL_LIB)
  748. #define SSL_LIB "libssl.so"
  749. #endif
  750. #if !defined(CRYPTO_LIB)
  751. #define CRYPTO_LIB "libcrypto.so"
  752. #endif
  753. #endif
  754. #if !defined(O_BINARY)
  755. #define O_BINARY (0)
  756. #endif /* O_BINARY */
  757. #define closesocket(a) (close(a))
  758. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  759. #define mg_remove(conn, x) (remove(x))
  760. #define mg_sleep(x) (usleep((x)*1000))
  761. #define mg_opendir(conn, x) (opendir(x))
  762. #define mg_closedir(x) (closedir(x))
  763. #define mg_readdir(x) (readdir(x))
  764. #define ERRNO (errno)
  765. #define INVALID_SOCKET (-1)
  766. #define INT64_FMT PRId64
  767. #define UINT64_FMT PRIu64
  768. typedef int SOCKET;
  769. #define WINCDECL
  770. #if defined(__hpux)
  771. /* HPUX 11 does not have monotonic, fall back to realtime */
  772. #if !defined(CLOCK_MONOTONIC)
  773. #define CLOCK_MONOTONIC CLOCK_REALTIME
  774. #endif
  775. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  776. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  777. * the prototypes use int* rather than socklen_t* which matches the
  778. * actual library expectation. When called with the wrong size arg
  779. * accept() returns a zero client inet addr and check_acl() always
  780. * fails. Since socklen_t is widely used below, just force replace
  781. * their typedef with int. - DTL
  782. */
  783. #define socklen_t int
  784. #endif /* hpux */
  785. #define mg_pollfd pollfd
  786. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  787. /* In case our C library is missing "timegm", provide an implementation */
  788. #if defined(NEED_TIMEGM)
  789. static inline int
  790. is_leap(int y)
  791. {
  792. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  793. }
  794. static inline int
  795. count_leap(int y)
  796. {
  797. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  798. }
  799. time_t
  800. timegm(struct tm *tm)
  801. {
  802. static const unsigned short ydays[] = {
  803. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  804. int year = tm->tm_year + 1900;
  805. int mon = tm->tm_mon;
  806. int mday = tm->tm_mday - 1;
  807. int hour = tm->tm_hour;
  808. int min = tm->tm_min;
  809. int sec = tm->tm_sec;
  810. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  811. || (mday >= ydays[mon + 1] - ydays[mon]
  812. + (mon == 1 && is_leap(year) ? 1 : 0))
  813. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  814. return -1;
  815. time_t res = year - 1970;
  816. res *= 365;
  817. res += mday;
  818. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  819. res += count_leap(year);
  820. res *= 24;
  821. res += hour;
  822. res *= 60;
  823. res += min;
  824. res *= 60;
  825. res += sec;
  826. return res;
  827. }
  828. #endif /* NEED_TIMEGM */
  829. /* va_copy should always be a macro, C99 and C++11 - DTL */
  830. #if !defined(va_copy)
  831. #define va_copy(x, y) ((x) = (y))
  832. #endif
  833. #if defined(_WIN32)
  834. /* Create substitutes for POSIX functions in Win32. */
  835. #if defined(GCC_DIAGNOSTIC)
  836. /* Show no warning in case system functions are not used. */
  837. #pragma GCC diagnostic push
  838. #pragma GCC diagnostic ignored "-Wunused-function"
  839. #endif
  840. static pthread_mutex_t global_log_file_lock;
  841. FUNCTION_MAY_BE_UNUSED
  842. static DWORD
  843. pthread_self(void)
  844. {
  845. return GetCurrentThreadId();
  846. }
  847. FUNCTION_MAY_BE_UNUSED
  848. static int
  849. pthread_key_create(
  850. pthread_key_t *key,
  851. void (*_ignored)(void *) /* destructor not supported for Windows */
  852. )
  853. {
  854. (void)_ignored;
  855. if ((key != 0)) {
  856. *key = TlsAlloc();
  857. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  858. }
  859. return -2;
  860. }
  861. FUNCTION_MAY_BE_UNUSED
  862. static int
  863. pthread_key_delete(pthread_key_t key)
  864. {
  865. return TlsFree(key) ? 0 : 1;
  866. }
  867. FUNCTION_MAY_BE_UNUSED
  868. static int
  869. pthread_setspecific(pthread_key_t key, void *value)
  870. {
  871. return TlsSetValue(key, value) ? 0 : 1;
  872. }
  873. FUNCTION_MAY_BE_UNUSED
  874. static void *
  875. pthread_getspecific(pthread_key_t key)
  876. {
  877. return TlsGetValue(key);
  878. }
  879. #if defined(GCC_DIAGNOSTIC)
  880. /* Enable unused function warning again */
  881. #pragma GCC diagnostic pop
  882. #endif
  883. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  884. #else
  885. static pthread_mutexattr_t pthread_mutex_attr;
  886. #endif /* _WIN32 */
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Show no warning in case system functions are not used. */
  889. #pragma GCC diagnostic push
  890. #pragma GCC diagnostic ignored "-Wunused-function"
  891. #endif /* defined(GCC_DIAGNOSTIC) */
  892. #if defined(__clang__)
  893. /* Show no warning in case system functions are not used. */
  894. #pragma clang diagnostic push
  895. #pragma clang diagnostic ignored "-Wunused-function"
  896. #endif
  897. static pthread_mutex_t global_lock_mutex;
  898. FUNCTION_MAY_BE_UNUSED
  899. static void
  900. mg_global_lock(void)
  901. {
  902. (void)pthread_mutex_lock(&global_lock_mutex);
  903. }
  904. FUNCTION_MAY_BE_UNUSED
  905. static void
  906. mg_global_unlock(void)
  907. {
  908. (void)pthread_mutex_unlock(&global_lock_mutex);
  909. }
  910. #if defined(_WIN64)
  911. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  912. #elif defined(_WIN32)
  913. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  914. #endif
  915. /* Atomic functions working on ptrdiff_t ("signed size_t").
  916. * Operations: Increment, Decrement, Add, Maximum.
  917. * Up to size_t, they do not an atomic "load" operation.
  918. */
  919. FUNCTION_MAY_BE_UNUSED
  920. static ptrdiff_t
  921. mg_atomic_inc(volatile ptrdiff_t *addr)
  922. {
  923. ptrdiff_t ret;
  924. #if defined(_WIN64) && !defined(NO_ATOMICS)
  925. ret = InterlockedIncrement64(addr);
  926. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  927. ret = InterlockedIncrement(addr);
  928. #elif defined(__GNUC__) \
  929. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  930. && !defined(NO_ATOMICS)
  931. ret = __sync_add_and_fetch(addr, 1);
  932. #else
  933. mg_global_lock();
  934. ret = (++(*addr));
  935. mg_global_unlock();
  936. #endif
  937. return ret;
  938. }
  939. FUNCTION_MAY_BE_UNUSED
  940. static ptrdiff_t
  941. mg_atomic_dec(volatile ptrdiff_t *addr)
  942. {
  943. ptrdiff_t ret;
  944. #if defined(_WIN64) && !defined(NO_ATOMICS)
  945. ret = InterlockedDecrement64(addr);
  946. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  947. ret = InterlockedDecrement(addr);
  948. #elif defined(__GNUC__) \
  949. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  950. && !defined(NO_ATOMICS)
  951. ret = __sync_sub_and_fetch(addr, 1);
  952. #else
  953. mg_global_lock();
  954. ret = (--(*addr));
  955. mg_global_unlock();
  956. #endif
  957. return ret;
  958. }
  959. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  960. static ptrdiff_t
  961. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  962. {
  963. ptrdiff_t ret;
  964. #if defined(_WIN64) && !defined(NO_ATOMICS)
  965. ret = InterlockedAdd64(addr, value);
  966. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  967. ret = InterlockedExchangeAdd(addr, value) + value;
  968. #elif defined(__GNUC__) \
  969. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  970. && !defined(NO_ATOMICS)
  971. ret = __sync_add_and_fetch(addr, value);
  972. #else
  973. mg_global_lock();
  974. *addr += value;
  975. ret = (*addr);
  976. mg_global_unlock();
  977. #endif
  978. return ret;
  979. }
  980. FUNCTION_MAY_BE_UNUSED
  981. static ptrdiff_t
  982. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  983. ptrdiff_t oldval,
  984. ptrdiff_t newval)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedCompareExchange64(addr, newval, oldval);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedCompareExchange(addr, newval, oldval);
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  995. #else
  996. mg_global_lock();
  997. ret = *addr;
  998. if ((ret != newval) && (ret == oldval)) {
  999. *addr = newval;
  1000. }
  1001. mg_global_unlock();
  1002. #endif
  1003. return ret;
  1004. }
  1005. static void
  1006. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1007. {
  1008. register ptrdiff_t tmp = *addr;
  1009. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1010. while (tmp < value) {
  1011. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1012. }
  1013. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1014. while (tmp < value) {
  1015. tmp = InterlockedCompareExchange(addr, value, tmp);
  1016. }
  1017. #elif defined(__GNUC__) \
  1018. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1019. && !defined(NO_ATOMICS)
  1020. while (tmp < value) {
  1021. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1022. }
  1023. #else
  1024. mg_global_lock();
  1025. if (*addr < value) {
  1026. *addr = value;
  1027. }
  1028. mg_global_unlock();
  1029. #endif
  1030. }
  1031. static int64_t
  1032. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1033. {
  1034. int64_t ret;
  1035. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1036. ret = InterlockedAdd64(addr, value);
  1037. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1038. ret = InterlockedExchangeAdd64(addr, value) + value;
  1039. #elif defined(__GNUC__) \
  1040. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1041. && !defined(NO_ATOMICS)
  1042. ret = __sync_add_and_fetch(addr, value);
  1043. #else
  1044. mg_global_lock();
  1045. *addr += value;
  1046. ret = (*addr);
  1047. mg_global_unlock();
  1048. #endif
  1049. return ret;
  1050. }
  1051. #endif
  1052. #if defined(GCC_DIAGNOSTIC)
  1053. /* Show no warning in case system functions are not used. */
  1054. #pragma GCC diagnostic pop
  1055. #endif /* defined(GCC_DIAGNOSTIC) */
  1056. #if defined(__clang__)
  1057. /* Show no warning in case system functions are not used. */
  1058. #pragma clang diagnostic pop
  1059. #endif
  1060. #if defined(USE_SERVER_STATS)
  1061. struct mg_memory_stat {
  1062. volatile ptrdiff_t totalMemUsed;
  1063. volatile ptrdiff_t maxMemUsed;
  1064. volatile ptrdiff_t blockCount;
  1065. };
  1066. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1067. static void *
  1068. mg_malloc_ex(size_t size,
  1069. struct mg_context *ctx,
  1070. const char *file,
  1071. unsigned line)
  1072. {
  1073. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1074. void *memory = 0;
  1075. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1076. #if defined(MEMORY_DEBUGGING)
  1077. char mallocStr[256];
  1078. #else
  1079. (void)file;
  1080. (void)line;
  1081. #endif
  1082. if (data) {
  1083. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1084. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1085. mg_atomic_inc(&mstat->blockCount);
  1086. ((uintptr_t *)data)[0] = size;
  1087. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1088. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1089. }
  1090. #if defined(MEMORY_DEBUGGING)
  1091. sprintf(mallocStr,
  1092. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1093. memory,
  1094. (unsigned long)size,
  1095. (unsigned long)mstat->totalMemUsed,
  1096. (unsigned long)mstat->blockCount,
  1097. file,
  1098. line);
  1099. DEBUG_TRACE("%s", mallocStr);
  1100. #endif
  1101. return memory;
  1102. }
  1103. static void *
  1104. mg_calloc_ex(size_t count,
  1105. size_t size,
  1106. struct mg_context *ctx,
  1107. const char *file,
  1108. unsigned line)
  1109. {
  1110. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1111. if (data) {
  1112. memset(data, 0, size * count);
  1113. }
  1114. return data;
  1115. }
  1116. static void
  1117. mg_free_ex(void *memory, const char *file, unsigned line)
  1118. {
  1119. #if defined(MEMORY_DEBUGGING)
  1120. char mallocStr[256];
  1121. #else
  1122. (void)file;
  1123. (void)line;
  1124. #endif
  1125. if (memory) {
  1126. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1127. uintptr_t size = ((uintptr_t *)data)[0];
  1128. struct mg_memory_stat *mstat =
  1129. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1130. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1131. mg_atomic_dec(&mstat->blockCount);
  1132. #if defined(MEMORY_DEBUGGING)
  1133. sprintf(mallocStr,
  1134. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1135. memory,
  1136. (unsigned long)size,
  1137. (unsigned long)mstat->totalMemUsed,
  1138. (unsigned long)mstat->blockCount,
  1139. file,
  1140. line);
  1141. DEBUG_TRACE("%s", mallocStr);
  1142. #endif
  1143. free(data);
  1144. }
  1145. }
  1146. static void *
  1147. mg_realloc_ex(void *memory,
  1148. size_t newsize,
  1149. struct mg_context *ctx,
  1150. const char *file,
  1151. unsigned line)
  1152. {
  1153. void *data;
  1154. void *_realloc;
  1155. uintptr_t oldsize;
  1156. #if defined(MEMORY_DEBUGGING)
  1157. char mallocStr[256];
  1158. #else
  1159. (void)file;
  1160. (void)line;
  1161. #endif
  1162. if (newsize) {
  1163. if (memory) {
  1164. /* Reallocate existing block */
  1165. struct mg_memory_stat *mstat;
  1166. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1167. oldsize = ((uintptr_t *)data)[0];
  1168. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1169. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1170. if (_realloc) {
  1171. data = _realloc;
  1172. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1173. #if defined(MEMORY_DEBUGGING)
  1174. sprintf(mallocStr,
  1175. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1176. memory,
  1177. (unsigned long)oldsize,
  1178. (unsigned long)mstat->totalMemUsed,
  1179. (unsigned long)mstat->blockCount,
  1180. file,
  1181. line);
  1182. DEBUG_TRACE("%s", mallocStr);
  1183. #endif
  1184. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1185. #if defined(MEMORY_DEBUGGING)
  1186. sprintf(mallocStr,
  1187. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1188. memory,
  1189. (unsigned long)newsize,
  1190. (unsigned long)mstat->totalMemUsed,
  1191. (unsigned long)mstat->blockCount,
  1192. file,
  1193. line);
  1194. DEBUG_TRACE("%s", mallocStr);
  1195. #endif
  1196. *(uintptr_t *)data = newsize;
  1197. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1198. } else {
  1199. #if defined(MEMORY_DEBUGGING)
  1200. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1201. #endif
  1202. return _realloc;
  1203. }
  1204. } else {
  1205. /* Allocate new block */
  1206. data = mg_malloc_ex(newsize, ctx, file, line);
  1207. }
  1208. } else {
  1209. /* Free existing block */
  1210. data = 0;
  1211. mg_free_ex(memory, file, line);
  1212. }
  1213. return data;
  1214. }
  1215. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1216. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1217. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1218. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1219. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1220. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1221. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1222. #else /* USE_SERVER_STATS */
  1223. static __inline void *
  1224. mg_malloc(size_t a)
  1225. {
  1226. return malloc(a);
  1227. }
  1228. static __inline void *
  1229. mg_calloc(size_t a, size_t b)
  1230. {
  1231. return calloc(a, b);
  1232. }
  1233. static __inline void *
  1234. mg_realloc(void *a, size_t b)
  1235. {
  1236. return realloc(a, b);
  1237. }
  1238. static __inline void
  1239. mg_free(void *a)
  1240. {
  1241. free(a);
  1242. }
  1243. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1246. #define mg_free_ctx(a, c) mg_free(a)
  1247. #endif /* USE_SERVER_STATS */
  1248. static void mg_vsnprintf(const struct mg_connection *conn,
  1249. int *truncated,
  1250. char *buf,
  1251. size_t buflen,
  1252. const char *fmt,
  1253. va_list ap);
  1254. static void mg_snprintf(const struct mg_connection *conn,
  1255. int *truncated,
  1256. char *buf,
  1257. size_t buflen,
  1258. PRINTF_FORMAT_STRING(const char *fmt),
  1259. ...) PRINTF_ARGS(5, 6);
  1260. /* This following lines are just meant as a reminder to use the mg-functions
  1261. * for memory management */
  1262. #if defined(malloc)
  1263. #undef malloc
  1264. #endif
  1265. #if defined(calloc)
  1266. #undef calloc
  1267. #endif
  1268. #if defined(realloc)
  1269. #undef realloc
  1270. #endif
  1271. #if defined(free)
  1272. #undef free
  1273. #endif
  1274. #if defined(snprintf)
  1275. #undef snprintf
  1276. #endif
  1277. #if defined(vsnprintf)
  1278. #undef vsnprintf
  1279. #endif
  1280. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1281. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1282. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1283. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1284. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1285. #if defined(_WIN32)
  1286. /* vsnprintf must not be used in any system,
  1287. * but this define only works well for Windows. */
  1288. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1289. #endif
  1290. /* mg_init_library counter */
  1291. static int mg_init_library_called = 0;
  1292. #if !defined(NO_SSL)
  1293. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1294. || defined(OPENSSL_API_3_0)
  1295. static int mg_openssl_initialized = 0;
  1296. #endif
  1297. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1298. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1299. #error "Please define OPENSSL_API_1_0 or OPENSSL_API_1_1"
  1300. #endif
  1301. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1) \
  1302. && defined(OPENSSL_API_3_0)
  1303. #error "Multiple OPENSSL_API versions defined"
  1304. #endif
  1305. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1306. || defined(OPENSSL_API_3_0)) \
  1307. && defined(USE_MBEDTLS)
  1308. #error "Multiple SSL libraries defined"
  1309. #endif
  1310. #endif
  1311. static pthread_key_t sTlsKey; /* Thread local storage index */
  1312. static volatile ptrdiff_t thread_idx_max = 0;
  1313. #if defined(MG_LEGACY_INTERFACE)
  1314. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1315. #endif
  1316. struct mg_workerTLS {
  1317. int is_master;
  1318. unsigned long thread_idx;
  1319. void *user_ptr;
  1320. #if defined(_WIN32)
  1321. HANDLE pthread_cond_helper_mutex;
  1322. struct mg_workerTLS *next_waiting_thread;
  1323. #endif
  1324. const char *alpn_proto;
  1325. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1326. char txtbuf[4];
  1327. #endif
  1328. };
  1329. #if defined(GCC_DIAGNOSTIC)
  1330. /* Show no warning in case system functions are not used. */
  1331. #pragma GCC diagnostic push
  1332. #pragma GCC diagnostic ignored "-Wunused-function"
  1333. #endif /* defined(GCC_DIAGNOSTIC) */
  1334. #if defined(__clang__)
  1335. /* Show no warning in case system functions are not used. */
  1336. #pragma clang diagnostic push
  1337. #pragma clang diagnostic ignored "-Wunused-function"
  1338. #endif
  1339. /* Get a unique thread ID as unsigned long, independent from the data type
  1340. * of thread IDs defined by the operating system API.
  1341. * If two calls to mg_current_thread_id return the same value, they calls
  1342. * are done from the same thread. If they return different values, they are
  1343. * done from different threads. (Provided this function is used in the same
  1344. * process context and threads are not repeatedly created and deleted, but
  1345. * CivetWeb does not do that).
  1346. * This function must match the signature required for SSL id callbacks:
  1347. * CRYPTO_set_id_callback
  1348. */
  1349. FUNCTION_MAY_BE_UNUSED
  1350. static unsigned long
  1351. mg_current_thread_id(void)
  1352. {
  1353. #if defined(_WIN32)
  1354. return GetCurrentThreadId();
  1355. #else
  1356. #if defined(__clang__)
  1357. #pragma clang diagnostic push
  1358. #pragma clang diagnostic ignored "-Wunreachable-code"
  1359. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1360. * or not, so one of the two conditions will be unreachable by construction.
  1361. * Unfortunately the C standard does not define a way to check this at
  1362. * compile time, since the #if preprocessor conditions can not use the
  1363. * sizeof operator as an argument. */
  1364. #endif
  1365. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1366. /* This is the problematic case for CRYPTO_set_id_callback:
  1367. * The OS pthread_t can not be cast to unsigned long. */
  1368. struct mg_workerTLS *tls =
  1369. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1370. if (tls == NULL) {
  1371. /* SSL called from an unknown thread: Create some thread index.
  1372. */
  1373. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1374. tls->is_master = -2; /* -2 means "3rd party thread" */
  1375. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1376. pthread_setspecific(sTlsKey, tls);
  1377. }
  1378. return tls->thread_idx;
  1379. } else {
  1380. /* pthread_t may be any data type, so a simple cast to unsigned long
  1381. * can rise a warning/error, depending on the platform.
  1382. * Here memcpy is used as an anything-to-anything cast. */
  1383. unsigned long ret = 0;
  1384. pthread_t t = pthread_self();
  1385. memcpy(&ret, &t, sizeof(pthread_t));
  1386. return ret;
  1387. }
  1388. #if defined(__clang__)
  1389. #pragma clang diagnostic pop
  1390. #endif
  1391. #endif
  1392. }
  1393. FUNCTION_MAY_BE_UNUSED
  1394. static uint64_t
  1395. mg_get_current_time_ns(void)
  1396. {
  1397. struct timespec tsnow;
  1398. clock_gettime(CLOCK_REALTIME, &tsnow);
  1399. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1400. }
  1401. #if defined(GCC_DIAGNOSTIC)
  1402. /* Show no warning in case system functions are not used. */
  1403. #pragma GCC diagnostic pop
  1404. #endif /* defined(GCC_DIAGNOSTIC) */
  1405. #if defined(__clang__)
  1406. /* Show no warning in case system functions are not used. */
  1407. #pragma clang diagnostic pop
  1408. #endif
  1409. #if defined(NEED_DEBUG_TRACE_FUNC)
  1410. static void
  1411. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1412. {
  1413. va_list args;
  1414. struct timespec tsnow;
  1415. /* Get some operating system independent thread id */
  1416. unsigned long thread_id = mg_current_thread_id();
  1417. clock_gettime(CLOCK_REALTIME, &tsnow);
  1418. flockfile(DEBUG_TRACE_STREAM);
  1419. fprintf(DEBUG_TRACE_STREAM,
  1420. "*** %lu.%09lu %lu %s:%u: ",
  1421. (unsigned long)tsnow.tv_sec,
  1422. (unsigned long)tsnow.tv_nsec,
  1423. thread_id,
  1424. func,
  1425. line);
  1426. va_start(args, fmt);
  1427. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1428. va_end(args);
  1429. putc('\n', DEBUG_TRACE_STREAM);
  1430. fflush(DEBUG_TRACE_STREAM);
  1431. funlockfile(DEBUG_TRACE_STREAM);
  1432. }
  1433. #endif /* NEED_DEBUG_TRACE_FUNC */
  1434. #define MD5_STATIC static
  1435. #include "md5.inl"
  1436. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1437. #if defined(NO_SOCKLEN_T)
  1438. typedef int socklen_t;
  1439. #endif /* NO_SOCKLEN_T */
  1440. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1441. #if !defined(MSG_NOSIGNAL)
  1442. #define MSG_NOSIGNAL (0)
  1443. #endif
  1444. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1445. #if defined(USE_MBEDTLS)
  1446. /* mbedTLS */
  1447. #include "mod_mbedtls.inl"
  1448. #elif defined(NO_SSL)
  1449. /* no SSL */
  1450. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1451. typedef struct SSL_CTX SSL_CTX;
  1452. #elif defined(NO_SSL_DL)
  1453. /* OpenSSL without dynamic loading */
  1454. #include <openssl/bn.h>
  1455. #include <openssl/conf.h>
  1456. #include <openssl/crypto.h>
  1457. #include <openssl/dh.h>
  1458. #include <openssl/engine.h>
  1459. #include <openssl/err.h>
  1460. #include <openssl/opensslv.h>
  1461. #include <openssl/pem.h>
  1462. #include <openssl/ssl.h>
  1463. #include <openssl/tls1.h>
  1464. #include <openssl/x509.h>
  1465. #if defined(WOLFSSL_VERSION)
  1466. /* Additional defines for WolfSSL, see
  1467. * https://github.com/civetweb/civetweb/issues/583 */
  1468. #include "wolfssl_extras.inl"
  1469. #endif
  1470. #if defined(OPENSSL_IS_BORINGSSL)
  1471. /* From boringssl/src/include/openssl/mem.h:
  1472. *
  1473. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1474. * However, that was written in a time before Valgrind and ASAN. Since we now
  1475. * have those tools, the OpenSSL allocation functions are simply macros around
  1476. * the standard memory functions.
  1477. *
  1478. * #define OPENSSL_free free */
  1479. #define free free
  1480. // disable for boringssl
  1481. #define CONF_modules_unload(a) ((void)0)
  1482. #define ENGINE_cleanup() ((void)0)
  1483. #endif
  1484. /* If OpenSSL headers are included, automatically select the API version */
  1485. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1486. #if !defined(OPENSSL_API_3_0)
  1487. #define OPENSSL_API_3_0
  1488. #endif
  1489. #else
  1490. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1491. #if !defined(OPENSSL_API_1_1)
  1492. #define OPENSSL_API_1_1
  1493. #endif
  1494. #define OPENSSL_REMOVE_THREAD_STATE()
  1495. #else
  1496. #if !defined(OPENSSL_API_1_0)
  1497. #define OPENSSL_API_1_0
  1498. #endif
  1499. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1500. #endif
  1501. #endif
  1502. #else
  1503. /* SSL loaded dynamically from DLL / shared object */
  1504. /* Add all prototypes here, to be independent from OpenSSL source
  1505. * installation. */
  1506. #include "openssl_dl.inl"
  1507. #endif /* Various SSL bindings */
  1508. #if !defined(NO_CACHING)
  1509. static const char month_names[][4] = {"Jan",
  1510. "Feb",
  1511. "Mar",
  1512. "Apr",
  1513. "May",
  1514. "Jun",
  1515. "Jul",
  1516. "Aug",
  1517. "Sep",
  1518. "Oct",
  1519. "Nov",
  1520. "Dec"};
  1521. #endif /* !NO_CACHING */
  1522. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1523. * the union u. */
  1524. union usa {
  1525. struct sockaddr sa;
  1526. struct sockaddr_in sin;
  1527. #if defined(USE_IPV6)
  1528. struct sockaddr_in6 sin6;
  1529. #endif
  1530. #if defined(USE_X_DOM_SOCKET)
  1531. struct sockaddr_un sun;
  1532. #endif
  1533. };
  1534. #if defined(USE_X_DOM_SOCKET)
  1535. static unsigned short
  1536. USA_IN_PORT_UNSAFE(union usa *s)
  1537. {
  1538. if (s->sa.sa_family == AF_INET)
  1539. return s->sin.sin_port;
  1540. #if defined(USE_IPV6)
  1541. if (s->sa.sa_family == AF_INET6)
  1542. return s->sin6.sin6_port;
  1543. #endif
  1544. return 0;
  1545. }
  1546. #endif
  1547. #if defined(USE_IPV6)
  1548. #define USA_IN_PORT_UNSAFE(s) \
  1549. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1550. #else
  1551. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1552. #endif
  1553. /* Describes a string (chunk of memory). */
  1554. struct vec {
  1555. const char *ptr;
  1556. size_t len;
  1557. };
  1558. struct mg_file_stat {
  1559. /* File properties filled by mg_stat: */
  1560. uint64_t size;
  1561. time_t last_modified;
  1562. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1563. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1564. * case we need a "Content-Eencoding: gzip" header */
  1565. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1566. };
  1567. struct mg_file_access {
  1568. /* File properties filled by mg_fopen: */
  1569. FILE *fp;
  1570. };
  1571. struct mg_file {
  1572. struct mg_file_stat stat;
  1573. struct mg_file_access access;
  1574. };
  1575. #define STRUCT_FILE_INITIALIZER \
  1576. { \
  1577. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1578. { \
  1579. (FILE *)NULL \
  1580. } \
  1581. }
  1582. /* Describes listening socket, or socket which was accept()-ed by the master
  1583. * thread and queued for future handling by the worker thread. */
  1584. struct socket {
  1585. SOCKET sock; /* Listening socket */
  1586. union usa lsa; /* Local socket address */
  1587. union usa rsa; /* Remote socket address */
  1588. unsigned char is_ssl; /* Is port SSL-ed */
  1589. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1590. * port */
  1591. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1592. };
  1593. /* Enum const for all options must be in sync with
  1594. * static struct mg_option config_options[]
  1595. * This is tested in the unit test (test/private.c)
  1596. * "Private Config Options"
  1597. */
  1598. enum {
  1599. /* Once for each server */
  1600. LISTENING_PORTS,
  1601. NUM_THREADS,
  1602. RUN_AS_USER,
  1603. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1604. * socket option typedef TCP_NODELAY. */
  1605. MAX_REQUEST_SIZE,
  1606. LINGER_TIMEOUT,
  1607. CONNECTION_QUEUE_SIZE,
  1608. LISTEN_BACKLOG_SIZE,
  1609. #if defined(__linux__)
  1610. ALLOW_SENDFILE_CALL,
  1611. #endif
  1612. #if defined(_WIN32)
  1613. CASE_SENSITIVE_FILES,
  1614. #endif
  1615. THROTTLE,
  1616. ENABLE_KEEP_ALIVE,
  1617. REQUEST_TIMEOUT,
  1618. KEEP_ALIVE_TIMEOUT,
  1619. #if defined(USE_WEBSOCKET)
  1620. WEBSOCKET_TIMEOUT,
  1621. ENABLE_WEBSOCKET_PING_PONG,
  1622. #endif
  1623. DECODE_URL,
  1624. #if defined(USE_LUA)
  1625. LUA_BACKGROUND_SCRIPT,
  1626. LUA_BACKGROUND_SCRIPT_PARAMS,
  1627. #endif
  1628. #if defined(USE_HTTP2)
  1629. ENABLE_HTTP2,
  1630. #endif
  1631. /* Once for each domain */
  1632. DOCUMENT_ROOT,
  1633. ACCESS_LOG_FILE,
  1634. ERROR_LOG_FILE,
  1635. CGI_EXTENSIONS,
  1636. CGI_ENVIRONMENT,
  1637. CGI_INTERPRETER,
  1638. CGI_INTERPRETER_ARGS,
  1639. #if defined(USE_TIMERS)
  1640. CGI_TIMEOUT,
  1641. #endif
  1642. CGI2_EXTENSIONS,
  1643. CGI2_ENVIRONMENT,
  1644. CGI2_INTERPRETER,
  1645. CGI2_INTERPRETER_ARGS,
  1646. #if defined(USE_TIMERS)
  1647. CGI2_TIMEOUT,
  1648. #endif
  1649. #if defined(USE_4_CGI)
  1650. CGI3_EXTENSIONS,
  1651. CGI3_ENVIRONMENT,
  1652. CGI3_INTERPRETER,
  1653. CGI3_INTERPRETER_ARGS,
  1654. #if defined(USE_TIMERS)
  1655. CGI3_TIMEOUT,
  1656. #endif
  1657. CGI4_EXTENSIONS,
  1658. CGI4_ENVIRONMENT,
  1659. CGI4_INTERPRETER,
  1660. CGI4_INTERPRETER_ARGS,
  1661. #if defined(USE_TIMERS)
  1662. CGI4_TIMEOUT,
  1663. #endif
  1664. #endif
  1665. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1666. PROTECT_URI,
  1667. AUTHENTICATION_DOMAIN,
  1668. ENABLE_AUTH_DOMAIN_CHECK,
  1669. SSI_EXTENSIONS,
  1670. ENABLE_DIRECTORY_LISTING,
  1671. GLOBAL_PASSWORDS_FILE,
  1672. INDEX_FILES,
  1673. ACCESS_CONTROL_LIST,
  1674. EXTRA_MIME_TYPES,
  1675. SSL_CERTIFICATE,
  1676. SSL_CERTIFICATE_CHAIN,
  1677. URL_REWRITE_PATTERN,
  1678. HIDE_FILES,
  1679. SSL_DO_VERIFY_PEER,
  1680. SSL_CACHE_TIMEOUT,
  1681. SSL_CA_PATH,
  1682. SSL_CA_FILE,
  1683. SSL_VERIFY_DEPTH,
  1684. SSL_DEFAULT_VERIFY_PATHS,
  1685. SSL_CIPHER_LIST,
  1686. SSL_PROTOCOL_VERSION,
  1687. SSL_SHORT_TRUST,
  1688. #if defined(USE_LUA)
  1689. LUA_PRELOAD_FILE,
  1690. LUA_SCRIPT_EXTENSIONS,
  1691. LUA_SERVER_PAGE_EXTENSIONS,
  1692. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1693. LUA_DEBUG_PARAMS,
  1694. #endif
  1695. #endif
  1696. #if defined(USE_DUKTAPE)
  1697. DUKTAPE_SCRIPT_EXTENSIONS,
  1698. #endif
  1699. #if defined(USE_WEBSOCKET)
  1700. WEBSOCKET_ROOT,
  1701. #endif
  1702. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1703. LUA_WEBSOCKET_EXTENSIONS,
  1704. #endif
  1705. ACCESS_CONTROL_ALLOW_ORIGIN,
  1706. ACCESS_CONTROL_ALLOW_METHODS,
  1707. ACCESS_CONTROL_ALLOW_HEADERS,
  1708. ERROR_PAGES,
  1709. #if !defined(NO_CACHING)
  1710. STATIC_FILE_MAX_AGE,
  1711. STATIC_FILE_CACHE_CONTROL,
  1712. #endif
  1713. #if !defined(NO_SSL)
  1714. STRICT_HTTPS_MAX_AGE,
  1715. #endif
  1716. ADDITIONAL_HEADER,
  1717. ALLOW_INDEX_SCRIPT_SUB_RES,
  1718. NUM_OPTIONS
  1719. };
  1720. /* Config option name, config types, default value.
  1721. * Must be in the same order as the enum const above.
  1722. */
  1723. static const struct mg_option config_options[] = {
  1724. /* Once for each server */
  1725. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1726. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1727. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1728. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1729. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1730. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1731. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1732. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1733. #if defined(__linux__)
  1734. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1735. #endif
  1736. #if defined(_WIN32)
  1737. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1738. #endif
  1739. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1740. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1741. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1742. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1743. #if defined(USE_WEBSOCKET)
  1744. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1745. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1746. #endif
  1747. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1748. #if defined(USE_LUA)
  1749. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1750. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1751. #endif
  1752. #if defined(USE_HTTP2)
  1753. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1754. #endif
  1755. /* Once for each domain */
  1756. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1757. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1758. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1759. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1760. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1761. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1762. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1763. #if defined(USE_TIMERS)
  1764. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1765. #endif
  1766. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1767. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1768. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1769. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1770. #if defined(USE_TIMERS)
  1771. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1772. #endif
  1773. #if defined(USE_4_CGI)
  1774. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1775. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1776. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1777. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1778. #if defined(USE_TIMERS)
  1779. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1780. #endif
  1781. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1782. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1783. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1784. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1785. #if defined(USE_TIMERS)
  1786. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1787. #endif
  1788. #endif
  1789. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1790. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1791. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1792. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1793. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1794. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1795. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1796. {"index_files",
  1797. MG_CONFIG_TYPE_STRING_LIST,
  1798. #if defined(USE_LUA)
  1799. "index.xhtml,index.html,index.htm,"
  1800. "index.lp,index.lsp,index.lua,index.cgi,"
  1801. "index.shtml,index.php"},
  1802. #else
  1803. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1804. #endif
  1805. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1806. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1808. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1809. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1810. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1811. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1812. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1813. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1814. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1815. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1816. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1817. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1818. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1819. * as a minimum in 2020 */
  1820. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1821. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1822. #if defined(USE_LUA)
  1823. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1824. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1825. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1826. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1827. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1828. #endif
  1829. #endif
  1830. #if defined(USE_DUKTAPE)
  1831. /* The support for duktape is still in alpha version state.
  1832. * The name of this config option might change. */
  1833. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1834. #endif
  1835. #if defined(USE_WEBSOCKET)
  1836. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1837. #endif
  1838. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1839. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1840. #endif
  1841. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1842. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1843. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1844. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1845. #if !defined(NO_CACHING)
  1846. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1847. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1848. #endif
  1849. #if !defined(NO_SSL)
  1850. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1851. #endif
  1852. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1853. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1854. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1855. /* Check if the config_options and the corresponding enum have compatible
  1856. * sizes. */
  1857. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1858. == (NUM_OPTIONS + 1),
  1859. "config_options and enum not sync");
  1860. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1861. struct mg_handler_info {
  1862. /* Name/Pattern of the URI. */
  1863. char *uri;
  1864. size_t uri_len;
  1865. /* handler type */
  1866. int handler_type;
  1867. /* Handler for http/https or authorization requests. */
  1868. mg_request_handler handler;
  1869. unsigned int refcount;
  1870. int removing;
  1871. /* Handler for ws/wss (websocket) requests. */
  1872. mg_websocket_connect_handler connect_handler;
  1873. mg_websocket_ready_handler ready_handler;
  1874. mg_websocket_data_handler data_handler;
  1875. mg_websocket_close_handler close_handler;
  1876. /* accepted subprotocols for ws/wss requests. */
  1877. struct mg_websocket_subprotocols *subprotocols;
  1878. /* Handler for authorization requests */
  1879. mg_authorization_handler auth_handler;
  1880. /* User supplied argument for the handler function. */
  1881. void *cbdata;
  1882. /* next handler in a linked list */
  1883. struct mg_handler_info *next;
  1884. };
  1885. enum {
  1886. CONTEXT_INVALID,
  1887. CONTEXT_SERVER,
  1888. CONTEXT_HTTP_CLIENT,
  1889. CONTEXT_WS_CLIENT
  1890. };
  1891. struct mg_domain_context {
  1892. SSL_CTX *ssl_ctx; /* SSL context */
  1893. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1894. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1895. int64_t ssl_cert_last_mtime;
  1896. /* Server nonce */
  1897. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1898. unsigned long nonce_count; /* Used nonces, used for authentication */
  1899. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1900. /* linked list of shared lua websockets */
  1901. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1902. #endif
  1903. /* Linked list of domains */
  1904. struct mg_domain_context *next;
  1905. };
  1906. /* Stop flag can be "volatile" or require a lock.
  1907. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1908. * states a read operation for int is always atomic. */
  1909. #if defined(STOP_FLAG_NEEDS_LOCK)
  1910. typedef ptrdiff_t volatile stop_flag_t;
  1911. static int
  1912. STOP_FLAG_IS_ZERO(stop_flag_t *f)
  1913. {
  1914. stop_flag_t sf = mg_atomic_add(f, 0);
  1915. return (sf == 0);
  1916. }
  1917. static int
  1918. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1919. {
  1920. stop_flag_t sf = mg_atomic_add(f, 0);
  1921. return (sf == 2);
  1922. }
  1923. static void
  1924. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1925. {
  1926. stop_flag_t sf;
  1927. do {
  1928. sf = mg_atomic_compare_and_swap(f, *f, v);
  1929. } while (sf != v);
  1930. }
  1931. #else /* STOP_FLAG_NEEDS_LOCK */
  1932. typedef int volatile stop_flag_t;
  1933. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1934. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1935. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1936. #endif /* STOP_FLAG_NEEDS_LOCK */
  1937. struct mg_context {
  1938. /* Part 1 - Physical context:
  1939. * This holds threads, ports, timeouts, ...
  1940. * set for the entire server, independent from the
  1941. * addressed hostname.
  1942. */
  1943. /* Connection related */
  1944. int context_type; /* See CONTEXT_* above */
  1945. struct socket *listening_sockets;
  1946. struct mg_pollfd *listening_socket_fds;
  1947. unsigned int num_listening_sockets;
  1948. struct mg_connection *worker_connections; /* The connection struct, pre-
  1949. * allocated for each worker */
  1950. #if defined(USE_SERVER_STATS)
  1951. volatile ptrdiff_t active_connections;
  1952. volatile ptrdiff_t max_active_connections;
  1953. volatile ptrdiff_t total_connections;
  1954. volatile ptrdiff_t total_requests;
  1955. volatile int64_t total_data_read;
  1956. volatile int64_t total_data_written;
  1957. #endif
  1958. /* Thread related */
  1959. stop_flag_t stop_flag; /* Should we stop event loop */
  1960. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  1961. pthread_t masterthreadid; /* The master thread ID */
  1962. unsigned int
  1963. cfg_worker_threads; /* The number of configured worker threads. */
  1964. pthread_t *worker_threadids; /* The worker thread IDs */
  1965. unsigned long starter_thread_idx; /* thread index which called mg_start */
  1966. /* Connection to thread dispatching */
  1967. #if defined(ALTERNATIVE_QUEUE)
  1968. struct socket *client_socks;
  1969. void **client_wait_events;
  1970. #else
  1971. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  1972. worker thread */
  1973. volatile int sq_head; /* Head of the socket queue */
  1974. volatile int sq_tail; /* Tail of the socket queue */
  1975. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1976. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1977. volatile int sq_blocked; /* Status information: sq is full */
  1978. int sq_size; /* No of elements in socket queue */
  1979. #if defined(USE_SERVER_STATS)
  1980. int sq_max_fill;
  1981. #endif /* USE_SERVER_STATS */
  1982. #endif /* ALTERNATIVE_QUEUE */
  1983. /* Memory related */
  1984. unsigned int max_request_size; /* The max request size */
  1985. #if defined(USE_SERVER_STATS)
  1986. struct mg_memory_stat ctx_memory;
  1987. #endif
  1988. /* Operating system related */
  1989. char *systemName; /* What operating system is running */
  1990. time_t start_time; /* Server start time, used for authentication
  1991. * and for diagnstics. */
  1992. #if defined(USE_TIMERS)
  1993. struct ttimers *timers;
  1994. #endif
  1995. /* Lua specific: Background operations and shared websockets */
  1996. #if defined(USE_LUA)
  1997. void *lua_background_state; /* lua_State (here as void *) */
  1998. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  1999. int lua_bg_log_available; /* Use Lua background state for access log */
  2000. #endif
  2001. /* Server nonce */
  2002. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2003. * ssl_cert_last_mtime, nonce_count, and
  2004. * next (linked list) */
  2005. /* Server callbacks */
  2006. struct mg_callbacks callbacks; /* User-defined callback function */
  2007. void *user_data; /* User-defined data */
  2008. /* Part 2 - Logical domain:
  2009. * This holds hostname, TLS certificate, document root, ...
  2010. * set for a domain hosted at the server.
  2011. * There may be multiple domains hosted at one physical server.
  2012. * The default domain "dd" is the first element of a list of
  2013. * domains.
  2014. */
  2015. struct mg_domain_context dd; /* default domain */
  2016. };
  2017. #if defined(USE_SERVER_STATS)
  2018. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2019. static struct mg_memory_stat *
  2020. get_memory_stat(struct mg_context *ctx)
  2021. {
  2022. if (ctx) {
  2023. return &(ctx->ctx_memory);
  2024. }
  2025. return &mg_common_memory;
  2026. }
  2027. #endif
  2028. enum {
  2029. CONNECTION_TYPE_INVALID = 0,
  2030. CONNECTION_TYPE_REQUEST = 1,
  2031. CONNECTION_TYPE_RESPONSE = 2
  2032. };
  2033. enum {
  2034. PROTOCOL_TYPE_HTTP1 = 0,
  2035. PROTOCOL_TYPE_WEBSOCKET = 1,
  2036. PROTOCOL_TYPE_HTTP2 = 2
  2037. };
  2038. #if defined(USE_HTTP2)
  2039. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2040. #define HTTP2_DYN_TABLE_SIZE (256)
  2041. #endif
  2042. struct mg_http2_connection {
  2043. uint32_t stream_id;
  2044. uint32_t dyn_table_size;
  2045. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2046. };
  2047. #endif
  2048. struct mg_connection {
  2049. int connection_type; /* see CONNECTION_TYPE_* above */
  2050. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2051. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2052. fully sent */
  2053. #if defined(USE_HTTP2)
  2054. struct mg_http2_connection http2;
  2055. #endif
  2056. struct mg_request_info request_info;
  2057. struct mg_response_info response_info;
  2058. struct mg_context *phys_ctx;
  2059. struct mg_domain_context *dom_ctx;
  2060. #if defined(USE_SERVER_STATS)
  2061. int conn_state; /* 0 = undef, numerical value may change in different
  2062. * versions. For the current definition, see
  2063. * mg_get_connection_info_impl */
  2064. #endif
  2065. SSL *ssl; /* SSL descriptor */
  2066. struct socket client; /* Connected client */
  2067. time_t conn_birth_time; /* Time (wall clock) when connection was
  2068. * established */
  2069. #if defined(USE_SERVER_STATS)
  2070. time_t conn_close_time; /* Time (wall clock) when connection was
  2071. * closed (or 0 if still open) */
  2072. double processing_time; /* Procesing time for one request. */
  2073. #endif
  2074. struct timespec req_time; /* Time (since system start) when the request
  2075. * was received */
  2076. int64_t num_bytes_sent; /* Total bytes sent to client */
  2077. int64_t content_len; /* How many bytes of content can be read
  2078. * !is_chunked: Content-Length header value
  2079. * or -1 (until connection closed,
  2080. * not allowed for a request)
  2081. * is_chunked: >= 0, appended gradually
  2082. */
  2083. int64_t consumed_content; /* How many bytes of content have been read */
  2084. int is_chunked; /* Transfer-Encoding is chunked:
  2085. * 0 = not chunked,
  2086. * 1 = chunked, not yet, or some data read,
  2087. * 2 = chunked, has error,
  2088. * 3 = chunked, all data read except trailer,
  2089. * 4 = chunked, all data read
  2090. */
  2091. char *buf; /* Buffer for received data */
  2092. char *path_info; /* PATH_INFO part of the URL */
  2093. int must_close; /* 1 if connection must be closed */
  2094. int accept_gzip; /* 1 if gzip encoding is accepted */
  2095. int in_error_handler; /* 1 if in handler for user defined error
  2096. * pages */
  2097. #if defined(USE_WEBSOCKET)
  2098. int in_websocket_handling; /* 1 if in read_websocket */
  2099. #endif
  2100. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2101. && defined(MG_EXPERIMENTAL_INTERFACES)
  2102. /* Parameters for websocket data compression according to rfc7692 */
  2103. int websocket_deflate_server_max_windows_bits;
  2104. int websocket_deflate_client_max_windows_bits;
  2105. int websocket_deflate_server_no_context_takeover;
  2106. int websocket_deflate_client_no_context_takeover;
  2107. int websocket_deflate_initialized;
  2108. int websocket_deflate_flush;
  2109. z_stream websocket_deflate_state;
  2110. z_stream websocket_inflate_state;
  2111. #endif
  2112. int handled_requests; /* Number of requests handled by this connection
  2113. */
  2114. int buf_size; /* Buffer size */
  2115. int request_len; /* Size of the request + headers in a buffer */
  2116. int data_len; /* Total size of data in a buffer */
  2117. int status_code; /* HTTP reply status code, e.g. 200 */
  2118. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2119. * throttle */
  2120. time_t last_throttle_time; /* Last time throttled data was sent */
  2121. int last_throttle_bytes; /* Bytes sent this second */
  2122. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2123. * atomic transmissions for websockets */
  2124. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2125. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2126. #endif
  2127. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2128. * for quick access */
  2129. };
  2130. /* Directory entry */
  2131. struct de {
  2132. struct mg_connection *conn;
  2133. char *file_name;
  2134. struct mg_file_stat file;
  2135. };
  2136. #define mg_cry_internal(conn, fmt, ...) \
  2137. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2138. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2139. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2140. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2141. struct mg_context *ctx,
  2142. const char *func,
  2143. unsigned line,
  2144. const char *fmt,
  2145. ...) PRINTF_ARGS(5, 6);
  2146. #if !defined(NO_THREAD_NAME)
  2147. #if defined(_WIN32) && defined(_MSC_VER)
  2148. /* Set the thread name for debugging purposes in Visual Studio
  2149. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2150. */
  2151. #pragma pack(push, 8)
  2152. typedef struct tagTHREADNAME_INFO {
  2153. DWORD dwType; /* Must be 0x1000. */
  2154. LPCSTR szName; /* Pointer to name (in user addr space). */
  2155. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2156. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2157. } THREADNAME_INFO;
  2158. #pragma pack(pop)
  2159. #elif defined(__linux__)
  2160. #include <sys/prctl.h>
  2161. #include <sys/sendfile.h>
  2162. #if defined(ALTERNATIVE_QUEUE)
  2163. #include <sys/eventfd.h>
  2164. #endif /* ALTERNATIVE_QUEUE */
  2165. #if defined(ALTERNATIVE_QUEUE)
  2166. static void *
  2167. event_create(void)
  2168. {
  2169. int evhdl = eventfd(0, EFD_CLOEXEC);
  2170. int *ret;
  2171. if (evhdl == -1) {
  2172. /* Linux uses -1 on error, Windows NULL. */
  2173. /* However, Linux does not return 0 on success either. */
  2174. return 0;
  2175. }
  2176. ret = (int *)mg_malloc(sizeof(int));
  2177. if (ret) {
  2178. *ret = evhdl;
  2179. } else {
  2180. (void)close(evhdl);
  2181. }
  2182. return (void *)ret;
  2183. }
  2184. static int
  2185. event_wait(void *eventhdl)
  2186. {
  2187. uint64_t u;
  2188. int evhdl, s;
  2189. if (!eventhdl) {
  2190. /* error */
  2191. return 0;
  2192. }
  2193. evhdl = *(int *)eventhdl;
  2194. s = (int)read(evhdl, &u, sizeof(u));
  2195. if (s != sizeof(u)) {
  2196. /* error */
  2197. return 0;
  2198. }
  2199. (void)u; /* the value is not required */
  2200. return 1;
  2201. }
  2202. static int
  2203. event_signal(void *eventhdl)
  2204. {
  2205. uint64_t u = 1;
  2206. int evhdl, s;
  2207. if (!eventhdl) {
  2208. /* error */
  2209. return 0;
  2210. }
  2211. evhdl = *(int *)eventhdl;
  2212. s = (int)write(evhdl, &u, sizeof(u));
  2213. if (s != sizeof(u)) {
  2214. /* error */
  2215. return 0;
  2216. }
  2217. return 1;
  2218. }
  2219. static void
  2220. event_destroy(void *eventhdl)
  2221. {
  2222. int evhdl;
  2223. if (!eventhdl) {
  2224. /* error */
  2225. return;
  2226. }
  2227. evhdl = *(int *)eventhdl;
  2228. close(evhdl);
  2229. mg_free(eventhdl);
  2230. }
  2231. #endif
  2232. #endif
  2233. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2234. struct posix_event {
  2235. pthread_mutex_t mutex;
  2236. pthread_cond_t cond;
  2237. int signaled;
  2238. };
  2239. static void *
  2240. event_create(void)
  2241. {
  2242. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2243. if (ret == 0) {
  2244. /* out of memory */
  2245. return 0;
  2246. }
  2247. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2248. /* pthread mutex not available */
  2249. mg_free(ret);
  2250. return 0;
  2251. }
  2252. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2253. /* pthread cond not available */
  2254. pthread_mutex_destroy(&(ret->mutex));
  2255. mg_free(ret);
  2256. return 0;
  2257. }
  2258. ret->signaled = 0;
  2259. return (void *)ret;
  2260. }
  2261. static int
  2262. event_wait(void *eventhdl)
  2263. {
  2264. struct posix_event *ev = (struct posix_event *)eventhdl;
  2265. pthread_mutex_lock(&(ev->mutex));
  2266. while (!ev->signaled) {
  2267. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2268. }
  2269. ev->signaled = 0;
  2270. pthread_mutex_unlock(&(ev->mutex));
  2271. return 1;
  2272. }
  2273. static int
  2274. event_signal(void *eventhdl)
  2275. {
  2276. struct posix_event *ev = (struct posix_event *)eventhdl;
  2277. pthread_mutex_lock(&(ev->mutex));
  2278. pthread_cond_signal(&(ev->cond));
  2279. ev->signaled = 1;
  2280. pthread_mutex_unlock(&(ev->mutex));
  2281. return 1;
  2282. }
  2283. static void
  2284. event_destroy(void *eventhdl)
  2285. {
  2286. struct posix_event *ev = (struct posix_event *)eventhdl;
  2287. pthread_cond_destroy(&(ev->cond));
  2288. pthread_mutex_destroy(&(ev->mutex));
  2289. mg_free(ev);
  2290. }
  2291. #endif
  2292. static void
  2293. mg_set_thread_name(const char *name)
  2294. {
  2295. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2296. mg_snprintf(
  2297. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2298. #if defined(_WIN32)
  2299. #if defined(_MSC_VER)
  2300. /* Windows and Visual Studio Compiler */
  2301. __try {
  2302. THREADNAME_INFO info;
  2303. info.dwType = 0x1000;
  2304. info.szName = threadName;
  2305. info.dwThreadID = ~0U;
  2306. info.dwFlags = 0;
  2307. RaiseException(0x406D1388,
  2308. 0,
  2309. sizeof(info) / sizeof(ULONG_PTR),
  2310. (ULONG_PTR *)&info);
  2311. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2312. }
  2313. #elif defined(__MINGW32__)
  2314. /* No option known to set thread name for MinGW known */
  2315. #endif
  2316. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2317. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2318. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2319. #if defined(__MACH__)
  2320. /* OS X only current thread name can be changed */
  2321. (void)pthread_setname_np(threadName);
  2322. #else
  2323. (void)pthread_setname_np(pthread_self(), threadName);
  2324. #endif
  2325. #elif defined(__linux__)
  2326. /* On Linux we can use the prctl function.
  2327. * When building for Linux Standard Base (LSB) use
  2328. * NO_THREAD_NAME. However, thread names are a big
  2329. * help for debugging, so the stadard is to set them.
  2330. */
  2331. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2332. #endif
  2333. }
  2334. #else /* !defined(NO_THREAD_NAME) */
  2335. void
  2336. mg_set_thread_name(const char *threadName)
  2337. {
  2338. }
  2339. #endif
  2340. const struct mg_option *
  2341. mg_get_valid_options(void)
  2342. {
  2343. return config_options;
  2344. }
  2345. /* Do not open file (unused) */
  2346. #define MG_FOPEN_MODE_NONE (0)
  2347. /* Open file for read only access */
  2348. #define MG_FOPEN_MODE_READ (1)
  2349. /* Open file for writing, create and overwrite */
  2350. #define MG_FOPEN_MODE_WRITE (2)
  2351. /* Open file for writing, create and append */
  2352. #define MG_FOPEN_MODE_APPEND (4)
  2353. static int
  2354. is_file_opened(const struct mg_file_access *fileacc)
  2355. {
  2356. if (!fileacc) {
  2357. return 0;
  2358. }
  2359. return (fileacc->fp != NULL);
  2360. }
  2361. #if !defined(NO_FILESYSTEMS)
  2362. static int mg_stat(const struct mg_connection *conn,
  2363. const char *path,
  2364. struct mg_file_stat *filep);
  2365. /* Reject files with special characters (for Windows) */
  2366. static int
  2367. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2368. {
  2369. const uint8_t *c = (const uint8_t *)path;
  2370. (void)conn; /* not used */
  2371. if ((c == NULL) || (c[0] == 0)) {
  2372. /* Null pointer or empty path --> suspicious */
  2373. return 1;
  2374. }
  2375. #if defined(_WIN32)
  2376. while (*c) {
  2377. if (*c < 32) {
  2378. /* Control character */
  2379. return 1;
  2380. }
  2381. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2382. /* stdin/stdout redirection character */
  2383. return 1;
  2384. }
  2385. if ((*c == '*') || (*c == '?')) {
  2386. /* Wildcard character */
  2387. return 1;
  2388. }
  2389. if (*c == '"') {
  2390. /* Windows quotation */
  2391. return 1;
  2392. }
  2393. c++;
  2394. }
  2395. #endif
  2396. /* Nothing suspicious found */
  2397. return 0;
  2398. }
  2399. /* mg_fopen will open a file either in memory or on the disk.
  2400. * The input parameter path is a string in UTF-8 encoding.
  2401. * The input parameter mode is MG_FOPEN_MODE_*
  2402. * On success, fp will be set in the output struct mg_file.
  2403. * All status members will also be set.
  2404. * The function returns 1 on success, 0 on error. */
  2405. static int
  2406. mg_fopen(const struct mg_connection *conn,
  2407. const char *path,
  2408. int mode,
  2409. struct mg_file *filep)
  2410. {
  2411. int found;
  2412. if (!filep) {
  2413. return 0;
  2414. }
  2415. filep->access.fp = NULL;
  2416. if (mg_path_suspicious(conn, path)) {
  2417. return 0;
  2418. }
  2419. /* filep is initialized in mg_stat: all fields with memset to,
  2420. * some fields like size and modification date with values */
  2421. found = mg_stat(conn, path, &(filep->stat));
  2422. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2423. /* file does not exist and will not be created */
  2424. return 0;
  2425. }
  2426. #if defined(_WIN32)
  2427. {
  2428. wchar_t wbuf[UTF16_PATH_MAX];
  2429. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2430. switch (mode) {
  2431. case MG_FOPEN_MODE_READ:
  2432. filep->access.fp = _wfopen(wbuf, L"rb");
  2433. break;
  2434. case MG_FOPEN_MODE_WRITE:
  2435. filep->access.fp = _wfopen(wbuf, L"wb");
  2436. break;
  2437. case MG_FOPEN_MODE_APPEND:
  2438. filep->access.fp = _wfopen(wbuf, L"ab");
  2439. break;
  2440. }
  2441. }
  2442. #else
  2443. /* Linux et al already use unicode. No need to convert. */
  2444. switch (mode) {
  2445. case MG_FOPEN_MODE_READ:
  2446. filep->access.fp = fopen(path, "r");
  2447. break;
  2448. case MG_FOPEN_MODE_WRITE:
  2449. filep->access.fp = fopen(path, "w");
  2450. break;
  2451. case MG_FOPEN_MODE_APPEND:
  2452. filep->access.fp = fopen(path, "a");
  2453. break;
  2454. }
  2455. #endif
  2456. if (!found) {
  2457. /* File did not exist before fopen was called.
  2458. * Maybe it has been created now. Get stat info
  2459. * like creation time now. */
  2460. found = mg_stat(conn, path, &(filep->stat));
  2461. (void)found;
  2462. }
  2463. /* return OK if file is opened */
  2464. return (filep->access.fp != NULL);
  2465. }
  2466. /* return 0 on success, just like fclose */
  2467. static int
  2468. mg_fclose(struct mg_file_access *fileacc)
  2469. {
  2470. int ret = -1;
  2471. if (fileacc != NULL) {
  2472. if (fileacc->fp != NULL) {
  2473. ret = fclose(fileacc->fp);
  2474. }
  2475. /* reset all members of fileacc */
  2476. memset(fileacc, 0, sizeof(*fileacc));
  2477. }
  2478. return ret;
  2479. }
  2480. #endif /* NO_FILESYSTEMS */
  2481. static void
  2482. mg_strlcpy(char *dst, const char *src, size_t n)
  2483. {
  2484. for (; *src != '\0' && n > 1; n--) {
  2485. *dst++ = *src++;
  2486. }
  2487. *dst = '\0';
  2488. }
  2489. static int
  2490. lowercase(const char *s)
  2491. {
  2492. return tolower((unsigned char)*s);
  2493. }
  2494. int
  2495. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2496. {
  2497. int diff = 0;
  2498. if (len > 0) {
  2499. do {
  2500. diff = lowercase(s1++) - lowercase(s2++);
  2501. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2502. }
  2503. return diff;
  2504. }
  2505. int
  2506. mg_strcasecmp(const char *s1, const char *s2)
  2507. {
  2508. int diff;
  2509. do {
  2510. diff = lowercase(s1++) - lowercase(s2++);
  2511. } while (diff == 0 && s1[-1] != '\0');
  2512. return diff;
  2513. }
  2514. static char *
  2515. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2516. {
  2517. char *p;
  2518. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2519. * defined */
  2520. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2521. mg_strlcpy(p, ptr, len + 1);
  2522. }
  2523. return p;
  2524. }
  2525. static char *
  2526. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2527. {
  2528. return mg_strndup_ctx(str, strlen(str), ctx);
  2529. }
  2530. static char *
  2531. mg_strdup(const char *str)
  2532. {
  2533. return mg_strndup_ctx(str, strlen(str), NULL);
  2534. }
  2535. static const char *
  2536. mg_strcasestr(const char *big_str, const char *small_str)
  2537. {
  2538. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2539. if (big_len >= small_len) {
  2540. for (i = 0; i <= (big_len - small_len); i++) {
  2541. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2542. return big_str + i;
  2543. }
  2544. }
  2545. }
  2546. return NULL;
  2547. }
  2548. /* Return null terminated string of given maximum length.
  2549. * Report errors if length is exceeded. */
  2550. static void
  2551. mg_vsnprintf(const struct mg_connection *conn,
  2552. int *truncated,
  2553. char *buf,
  2554. size_t buflen,
  2555. const char *fmt,
  2556. va_list ap)
  2557. {
  2558. int n, ok;
  2559. if (buflen == 0) {
  2560. if (truncated) {
  2561. *truncated = 1;
  2562. }
  2563. return;
  2564. }
  2565. #if defined(__clang__)
  2566. #pragma clang diagnostic push
  2567. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2568. /* Using fmt as a non-literal is intended here, since it is mostly called
  2569. * indirectly by mg_snprintf */
  2570. #endif
  2571. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2572. ok = (n >= 0) && ((size_t)n < buflen);
  2573. #if defined(__clang__)
  2574. #pragma clang diagnostic pop
  2575. #endif
  2576. if (ok) {
  2577. if (truncated) {
  2578. *truncated = 0;
  2579. }
  2580. } else {
  2581. if (truncated) {
  2582. *truncated = 1;
  2583. }
  2584. mg_cry_internal(conn,
  2585. "truncating vsnprintf buffer: [%.*s]",
  2586. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2587. buf);
  2588. n = (int)buflen - 1;
  2589. }
  2590. buf[n] = '\0';
  2591. }
  2592. static void
  2593. mg_snprintf(const struct mg_connection *conn,
  2594. int *truncated,
  2595. char *buf,
  2596. size_t buflen,
  2597. const char *fmt,
  2598. ...)
  2599. {
  2600. va_list ap;
  2601. va_start(ap, fmt);
  2602. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2603. va_end(ap);
  2604. }
  2605. static int
  2606. get_option_index(const char *name)
  2607. {
  2608. int i;
  2609. for (i = 0; config_options[i].name != NULL; i++) {
  2610. if (strcmp(config_options[i].name, name) == 0) {
  2611. return i;
  2612. }
  2613. }
  2614. return -1;
  2615. }
  2616. const char *
  2617. mg_get_option(const struct mg_context *ctx, const char *name)
  2618. {
  2619. int i;
  2620. if ((i = get_option_index(name)) == -1) {
  2621. return NULL;
  2622. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2623. return "";
  2624. } else {
  2625. return ctx->dd.config[i];
  2626. }
  2627. }
  2628. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2629. struct mg_context *
  2630. mg_get_context(const struct mg_connection *conn)
  2631. {
  2632. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2633. }
  2634. void *
  2635. mg_get_user_data(const struct mg_context *ctx)
  2636. {
  2637. return (ctx == NULL) ? NULL : ctx->user_data;
  2638. }
  2639. void *
  2640. mg_get_user_context_data(const struct mg_connection *conn)
  2641. {
  2642. return mg_get_user_data(mg_get_context(conn));
  2643. }
  2644. void *
  2645. mg_get_thread_pointer(const struct mg_connection *conn)
  2646. {
  2647. /* both methods should return the same pointer */
  2648. if (conn) {
  2649. /* quick access, in case conn is known */
  2650. return conn->tls_user_ptr;
  2651. } else {
  2652. /* otherwise get pointer from thread local storage (TLS) */
  2653. struct mg_workerTLS *tls =
  2654. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2655. return tls->user_ptr;
  2656. }
  2657. }
  2658. void
  2659. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2660. {
  2661. if (const_conn != NULL) {
  2662. /* Const cast, since "const struct mg_connection *" does not mean
  2663. * the connection object is not modified. Here "const" is used,
  2664. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2665. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2666. conn->request_info.conn_data = data;
  2667. }
  2668. }
  2669. void *
  2670. mg_get_user_connection_data(const struct mg_connection *conn)
  2671. {
  2672. if (conn != NULL) {
  2673. return conn->request_info.conn_data;
  2674. }
  2675. return NULL;
  2676. }
  2677. #if defined(MG_LEGACY_INTERFACE)
  2678. /* Deprecated: Use mg_get_server_ports instead. */
  2679. size_t
  2680. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2681. {
  2682. size_t i;
  2683. if (!ctx) {
  2684. return 0;
  2685. }
  2686. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2687. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2688. ports[i] = ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2689. }
  2690. return i;
  2691. }
  2692. #endif
  2693. int
  2694. mg_get_server_ports(const struct mg_context *ctx,
  2695. int size,
  2696. struct mg_server_port *ports)
  2697. {
  2698. int i, cnt = 0;
  2699. if (size <= 0) {
  2700. return -1;
  2701. }
  2702. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2703. if (!ctx) {
  2704. return -1;
  2705. }
  2706. if (!ctx->listening_sockets) {
  2707. return -1;
  2708. }
  2709. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2710. ports[cnt].port =
  2711. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2712. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2713. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2714. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2715. /* IPv4 */
  2716. ports[cnt].protocol = 1;
  2717. cnt++;
  2718. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2719. /* IPv6 */
  2720. ports[cnt].protocol = 3;
  2721. cnt++;
  2722. }
  2723. }
  2724. return cnt;
  2725. }
  2726. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2727. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2728. #endif
  2729. static void
  2730. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2731. {
  2732. buf[0] = '\0';
  2733. if (!usa) {
  2734. return;
  2735. }
  2736. if (usa->sa.sa_family == AF_INET) {
  2737. getnameinfo(&usa->sa,
  2738. sizeof(usa->sin),
  2739. buf,
  2740. (unsigned)len,
  2741. NULL,
  2742. 0,
  2743. NI_NUMERICHOST);
  2744. }
  2745. #if defined(USE_IPV6)
  2746. else if (usa->sa.sa_family == AF_INET6) {
  2747. getnameinfo(&usa->sa,
  2748. sizeof(usa->sin6),
  2749. buf,
  2750. (unsigned)len,
  2751. NULL,
  2752. 0,
  2753. NI_NUMERICHOST);
  2754. }
  2755. #endif
  2756. #if defined(USE_X_DOM_SOCKET)
  2757. else if (usa->sa.sa_family == AF_UNIX) {
  2758. /* TODO: Define a remote address for unix domain sockets.
  2759. * This code will always return "localhost", identical to http+tcp:
  2760. getnameinfo(&usa->sa,
  2761. sizeof(usa->sun),
  2762. buf,
  2763. (unsigned)len,
  2764. NULL,
  2765. 0,
  2766. NI_NUMERICHOST);
  2767. */
  2768. strncpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2769. buf[len] = 0;
  2770. }
  2771. #endif
  2772. }
  2773. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2774. * included in all responses other than 100, 101, 5xx. */
  2775. static void
  2776. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2777. {
  2778. #if !defined(REENTRANT_TIME)
  2779. struct tm *tm;
  2780. tm = ((t != NULL) ? gmtime(t) : NULL);
  2781. if (tm != NULL) {
  2782. #else
  2783. struct tm _tm;
  2784. struct tm *tm = &_tm;
  2785. if (t != NULL) {
  2786. gmtime_r(t, tm);
  2787. #endif
  2788. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2789. } else {
  2790. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2791. buf[buf_len - 1] = '\0';
  2792. }
  2793. }
  2794. /* difftime for struct timespec. Return value is in seconds. */
  2795. static double
  2796. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2797. {
  2798. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2799. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2800. }
  2801. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2802. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2803. const char *func,
  2804. unsigned line,
  2805. const char *fmt,
  2806. va_list ap);
  2807. #include "external_mg_cry_internal_impl.inl"
  2808. #elif !defined(NO_FILESYSTEMS)
  2809. /* Print error message to the opened error log stream. */
  2810. static void
  2811. mg_cry_internal_impl(const struct mg_connection *conn,
  2812. const char *func,
  2813. unsigned line,
  2814. const char *fmt,
  2815. va_list ap)
  2816. {
  2817. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2818. struct mg_file fi;
  2819. time_t timestamp;
  2820. /* Unused, in the RELEASE build */
  2821. (void)func;
  2822. (void)line;
  2823. #if defined(GCC_DIAGNOSTIC)
  2824. #pragma GCC diagnostic push
  2825. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2826. #endif
  2827. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2828. #if defined(GCC_DIAGNOSTIC)
  2829. #pragma GCC diagnostic pop
  2830. #endif
  2831. buf[sizeof(buf) - 1] = 0;
  2832. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2833. if (!conn) {
  2834. puts(buf);
  2835. return;
  2836. }
  2837. /* Do not lock when getting the callback value, here and below.
  2838. * I suppose this is fine, since function cannot disappear in the
  2839. * same way string option can. */
  2840. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2841. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2842. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2843. if (mg_fopen(conn,
  2844. conn->dom_ctx->config[ERROR_LOG_FILE],
  2845. MG_FOPEN_MODE_APPEND,
  2846. &fi)
  2847. == 0) {
  2848. fi.access.fp = NULL;
  2849. }
  2850. } else {
  2851. fi.access.fp = NULL;
  2852. }
  2853. if (fi.access.fp != NULL) {
  2854. flockfile(fi.access.fp);
  2855. timestamp = time(NULL);
  2856. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2857. fprintf(fi.access.fp,
  2858. "[%010lu] [error] [client %s] ",
  2859. (unsigned long)timestamp,
  2860. src_addr);
  2861. if (conn->request_info.request_method != NULL) {
  2862. fprintf(fi.access.fp,
  2863. "%s %s: ",
  2864. conn->request_info.request_method,
  2865. conn->request_info.request_uri
  2866. ? conn->request_info.request_uri
  2867. : "");
  2868. }
  2869. fprintf(fi.access.fp, "%s", buf);
  2870. fputc('\n', fi.access.fp);
  2871. fflush(fi.access.fp);
  2872. funlockfile(fi.access.fp);
  2873. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2874. * mg_cry here anyway ;-) */
  2875. }
  2876. }
  2877. }
  2878. #else
  2879. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2880. #endif /* Externally provided function */
  2881. /* Construct fake connection structure. Used for logging, if connection
  2882. * is not applicable at the moment of logging. */
  2883. static struct mg_connection *
  2884. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2885. {
  2886. static const struct mg_connection conn_zero = {0};
  2887. *fc = conn_zero;
  2888. fc->phys_ctx = ctx;
  2889. fc->dom_ctx = &(ctx->dd);
  2890. return fc;
  2891. }
  2892. static void
  2893. mg_cry_internal_wrap(const struct mg_connection *conn,
  2894. struct mg_context *ctx,
  2895. const char *func,
  2896. unsigned line,
  2897. const char *fmt,
  2898. ...)
  2899. {
  2900. va_list ap;
  2901. va_start(ap, fmt);
  2902. if (!conn && ctx) {
  2903. struct mg_connection fc;
  2904. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2905. } else {
  2906. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2907. }
  2908. va_end(ap);
  2909. }
  2910. void
  2911. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2912. {
  2913. va_list ap;
  2914. va_start(ap, fmt);
  2915. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2916. va_end(ap);
  2917. }
  2918. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2919. const char *
  2920. mg_version(void)
  2921. {
  2922. return CIVETWEB_VERSION;
  2923. }
  2924. const struct mg_request_info *
  2925. mg_get_request_info(const struct mg_connection *conn)
  2926. {
  2927. if (!conn) {
  2928. return NULL;
  2929. }
  2930. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2931. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2932. char txt[16];
  2933. struct mg_workerTLS *tls =
  2934. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2935. sprintf(txt, "%03i", conn->response_info.status_code);
  2936. if (strlen(txt) == 3) {
  2937. memcpy(tls->txtbuf, txt, 4);
  2938. } else {
  2939. strcpy(tls->txtbuf, "ERR");
  2940. }
  2941. ((struct mg_connection *)conn)->request_info.local_uri =
  2942. tls->txtbuf; /* use thread safe buffer */
  2943. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  2944. tls->txtbuf; /* use the same thread safe buffer */
  2945. ((struct mg_connection *)conn)->request_info.request_uri =
  2946. tls->txtbuf; /* use the same thread safe buffer */
  2947. ((struct mg_connection *)conn)->request_info.num_headers =
  2948. conn->response_info.num_headers;
  2949. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2950. conn->response_info.http_headers,
  2951. sizeof(conn->response_info.http_headers));
  2952. } else
  2953. #endif
  2954. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2955. return NULL;
  2956. }
  2957. return &conn->request_info;
  2958. }
  2959. const struct mg_response_info *
  2960. mg_get_response_info(const struct mg_connection *conn)
  2961. {
  2962. if (!conn) {
  2963. return NULL;
  2964. }
  2965. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2966. return NULL;
  2967. }
  2968. return &conn->response_info;
  2969. }
  2970. static const char *
  2971. get_proto_name(const struct mg_connection *conn)
  2972. {
  2973. #if defined(__clang__)
  2974. #pragma clang diagnostic push
  2975. #pragma clang diagnostic ignored "-Wunreachable-code"
  2976. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2977. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2978. * unreachable, but splitting into four different #ifdef clauses here is
  2979. * more complicated.
  2980. */
  2981. #endif
  2982. const struct mg_request_info *ri = &conn->request_info;
  2983. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  2984. ? (ri->is_ssl ? "wss" : "ws")
  2985. : (ri->is_ssl ? "https" : "http"));
  2986. return proto;
  2987. #if defined(__clang__)
  2988. #pragma clang diagnostic pop
  2989. #endif
  2990. }
  2991. static int
  2992. mg_construct_local_link(const struct mg_connection *conn,
  2993. char *buf,
  2994. size_t buflen,
  2995. const char *define_proto,
  2996. int define_port,
  2997. const char *define_uri)
  2998. {
  2999. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3000. return -1;
  3001. } else {
  3002. int truncated = 0;
  3003. const struct mg_request_info *ri = &conn->request_info;
  3004. const char *proto =
  3005. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3006. const char *uri =
  3007. (define_uri != NULL)
  3008. ? define_uri
  3009. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3010. int port = (define_port > 0) ? define_port : ri->server_port;
  3011. int default_port = 80;
  3012. if (uri == NULL) {
  3013. return -1;
  3014. }
  3015. #if defined(USE_X_DOM_SOCKET)
  3016. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3017. /* TODO: Define and document a link for UNIX domain sockets. */
  3018. /* There seems to be no official standard for this.
  3019. * Common uses seem to be "httpunix://", "http.unix://" or
  3020. * "http+unix://" as a protocol definition string, followed by
  3021. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3022. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3023. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3024. * "" (completely skipping the server name part). In any case, the
  3025. * last part is the server local path. */
  3026. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3027. mg_snprintf(conn,
  3028. &truncated,
  3029. buf,
  3030. buflen,
  3031. "%s.unix://%s%s",
  3032. proto,
  3033. server_name,
  3034. ri->local_uri);
  3035. default_port = 0;
  3036. return 0;
  3037. }
  3038. #endif
  3039. if (define_proto) {
  3040. /* If we got a protocol name, use the default port accordingly. */
  3041. if ((0 == strcmp(define_proto, "https"))
  3042. || (0 == strcmp(define_proto, "wss"))) {
  3043. default_port = 443;
  3044. }
  3045. } else if (ri->is_ssl) {
  3046. /* If we did not get a protocol name, use TLS as default if it is
  3047. * already used. */
  3048. default_port = 443;
  3049. }
  3050. {
  3051. #if defined(USE_IPV6)
  3052. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3053. #endif
  3054. int auth_domain_check_enabled =
  3055. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3056. && (!mg_strcasecmp(
  3057. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3058. const char *server_domain =
  3059. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3060. char portstr[16];
  3061. char server_ip[48];
  3062. if (port != default_port) {
  3063. sprintf(portstr, ":%u", (unsigned)port);
  3064. } else {
  3065. portstr[0] = 0;
  3066. }
  3067. if (!auth_domain_check_enabled || !server_domain) {
  3068. sockaddr_to_string(server_ip,
  3069. sizeof(server_ip),
  3070. &conn->client.lsa);
  3071. server_domain = server_ip;
  3072. }
  3073. mg_snprintf(conn,
  3074. &truncated,
  3075. buf,
  3076. buflen,
  3077. #if defined(USE_IPV6)
  3078. "%s://%s%s%s%s%s",
  3079. proto,
  3080. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3081. server_domain,
  3082. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3083. #else
  3084. "%s://%s%s%s",
  3085. proto,
  3086. server_domain,
  3087. #endif
  3088. portstr,
  3089. ri->local_uri);
  3090. if (truncated) {
  3091. return -1;
  3092. }
  3093. return 0;
  3094. }
  3095. }
  3096. }
  3097. int
  3098. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3099. {
  3100. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3101. }
  3102. /* Skip the characters until one of the delimiters characters found.
  3103. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3104. * Advance pointer to buffer to the next word. Return found 0-terminated
  3105. * word.
  3106. * Delimiters can be quoted with quotechar. */
  3107. static char *
  3108. skip_quoted(char **buf,
  3109. const char *delimiters,
  3110. const char *whitespace,
  3111. char quotechar)
  3112. {
  3113. char *p, *begin_word, *end_word, *end_whitespace;
  3114. begin_word = *buf;
  3115. end_word = begin_word + strcspn(begin_word, delimiters);
  3116. /* Check for quotechar */
  3117. if (end_word > begin_word) {
  3118. p = end_word - 1;
  3119. while (*p == quotechar) {
  3120. /* While the delimiter is quoted, look for the next delimiter.
  3121. */
  3122. /* This happens, e.g., in calls from parse_auth_header,
  3123. * if the user name contains a " character. */
  3124. /* If there is anything beyond end_word, copy it. */
  3125. if (*end_word != '\0') {
  3126. size_t end_off = strcspn(end_word + 1, delimiters);
  3127. memmove(p, end_word, end_off + 1);
  3128. p += end_off; /* p must correspond to end_word - 1 */
  3129. end_word += end_off + 1;
  3130. } else {
  3131. *p = '\0';
  3132. break;
  3133. }
  3134. }
  3135. for (p++; p < end_word; p++) {
  3136. *p = '\0';
  3137. }
  3138. }
  3139. if (*end_word == '\0') {
  3140. *buf = end_word;
  3141. } else {
  3142. #if defined(GCC_DIAGNOSTIC)
  3143. /* Disable spurious conversion warning for GCC */
  3144. #pragma GCC diagnostic push
  3145. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3146. #endif /* defined(GCC_DIAGNOSTIC) */
  3147. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3148. #if defined(GCC_DIAGNOSTIC)
  3149. #pragma GCC diagnostic pop
  3150. #endif /* defined(GCC_DIAGNOSTIC) */
  3151. for (p = end_word; p < end_whitespace; p++) {
  3152. *p = '\0';
  3153. }
  3154. *buf = end_whitespace;
  3155. }
  3156. return begin_word;
  3157. }
  3158. /* Return HTTP header value, or NULL if not found. */
  3159. static const char *
  3160. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3161. {
  3162. int i;
  3163. for (i = 0; i < num_hdr; i++) {
  3164. if (!mg_strcasecmp(name, hdr[i].name)) {
  3165. return hdr[i].value;
  3166. }
  3167. }
  3168. return NULL;
  3169. }
  3170. #if defined(USE_WEBSOCKET)
  3171. /* Retrieve requested HTTP header multiple values, and return the number of
  3172. * found occurrences */
  3173. static int
  3174. get_req_headers(const struct mg_request_info *ri,
  3175. const char *name,
  3176. const char **output,
  3177. int output_max_size)
  3178. {
  3179. int i;
  3180. int cnt = 0;
  3181. if (ri) {
  3182. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3183. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3184. output[cnt++] = ri->http_headers[i].value;
  3185. }
  3186. }
  3187. }
  3188. return cnt;
  3189. }
  3190. #endif
  3191. const char *
  3192. mg_get_header(const struct mg_connection *conn, const char *name)
  3193. {
  3194. if (!conn) {
  3195. return NULL;
  3196. }
  3197. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3198. return get_header(conn->request_info.http_headers,
  3199. conn->request_info.num_headers,
  3200. name);
  3201. }
  3202. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3203. return get_header(conn->response_info.http_headers,
  3204. conn->response_info.num_headers,
  3205. name);
  3206. }
  3207. return NULL;
  3208. }
  3209. static const char *
  3210. get_http_version(const struct mg_connection *conn)
  3211. {
  3212. if (!conn) {
  3213. return NULL;
  3214. }
  3215. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3216. return conn->request_info.http_version;
  3217. }
  3218. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3219. return conn->response_info.http_version;
  3220. }
  3221. return NULL;
  3222. }
  3223. /* A helper function for traversing a comma separated list of values.
  3224. * It returns a list pointer shifted to the next value, or NULL if the end
  3225. * of the list found.
  3226. * Value is stored in val vector. If value has form "x=y", then eq_val
  3227. * vector is initialized to point to the "y" part, and val vector length
  3228. * is adjusted to point only to "x". */
  3229. static const char *
  3230. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3231. {
  3232. int end;
  3233. reparse:
  3234. if (val == NULL || list == NULL || *list == '\0') {
  3235. /* End of the list */
  3236. return NULL;
  3237. }
  3238. /* Skip over leading LWS */
  3239. while (*list == ' ' || *list == '\t')
  3240. list++;
  3241. val->ptr = list;
  3242. if ((list = strchr(val->ptr, ',')) != NULL) {
  3243. /* Comma found. Store length and shift the list ptr */
  3244. val->len = ((size_t)(list - val->ptr));
  3245. list++;
  3246. } else {
  3247. /* This value is the last one */
  3248. list = val->ptr + strlen(val->ptr);
  3249. val->len = ((size_t)(list - val->ptr));
  3250. }
  3251. /* Adjust length for trailing LWS */
  3252. end = (int)val->len - 1;
  3253. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3254. end--;
  3255. val->len = (size_t)(end) + (size_t)(1);
  3256. if (val->len == 0) {
  3257. /* Ignore any empty entries. */
  3258. goto reparse;
  3259. }
  3260. if (eq_val != NULL) {
  3261. /* Value has form "x=y", adjust pointers and lengths
  3262. * so that val points to "x", and eq_val points to "y". */
  3263. eq_val->len = 0;
  3264. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3265. if (eq_val->ptr != NULL) {
  3266. eq_val->ptr++; /* Skip over '=' character */
  3267. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3268. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3269. }
  3270. }
  3271. return list;
  3272. }
  3273. /* A helper function for checking if a comma separated list of values
  3274. * contains
  3275. * the given option (case insensitvely).
  3276. * 'header' can be NULL, in which case false is returned. */
  3277. static int
  3278. header_has_option(const char *header, const char *option)
  3279. {
  3280. struct vec opt_vec;
  3281. struct vec eq_vec;
  3282. DEBUG_ASSERT(option != NULL);
  3283. DEBUG_ASSERT(option[0] != '\0');
  3284. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3285. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3286. return 1;
  3287. }
  3288. return 0;
  3289. }
  3290. /* Perform case-insensitive match of string against pattern */
  3291. static ptrdiff_t
  3292. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3293. {
  3294. const char *or_str;
  3295. ptrdiff_t i, j, len, res;
  3296. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3297. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3298. return (res > 0) ? res
  3299. : match_prefix(or_str + 1,
  3300. (size_t)((pattern + pattern_len)
  3301. - (or_str + 1)),
  3302. str);
  3303. }
  3304. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3305. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3306. continue;
  3307. } else if (pattern[i] == '$') {
  3308. return (str[j] == '\0') ? j : -1;
  3309. } else if (pattern[i] == '*') {
  3310. i++;
  3311. if (pattern[i] == '*') {
  3312. i++;
  3313. len = (ptrdiff_t)strlen(str + j);
  3314. } else {
  3315. len = (ptrdiff_t)strcspn(str + j, "/");
  3316. }
  3317. if (i == (ptrdiff_t)pattern_len) {
  3318. return j + len;
  3319. }
  3320. do {
  3321. res = match_prefix(pattern + i,
  3322. (pattern_len - (size_t)i),
  3323. str + j + len);
  3324. } while (res == -1 && len-- > 0);
  3325. return (res == -1) ? -1 : j + res + len;
  3326. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3327. return -1;
  3328. }
  3329. }
  3330. return (ptrdiff_t)j;
  3331. }
  3332. static ptrdiff_t
  3333. match_prefix_strlen(const char *pattern, const char *str)
  3334. {
  3335. if (pattern == NULL) {
  3336. return -1;
  3337. }
  3338. return match_prefix(pattern, strlen(pattern), str);
  3339. }
  3340. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3341. * This function must tolerate situations when connection info is not
  3342. * set up, for example if request parsing failed. */
  3343. static int
  3344. should_keep_alive(const struct mg_connection *conn)
  3345. {
  3346. const char *http_version;
  3347. const char *header;
  3348. /* First satisfy needs of the server */
  3349. if ((conn == NULL) || conn->must_close) {
  3350. /* Close, if civetweb framework needs to close */
  3351. return 0;
  3352. }
  3353. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3354. /* Close, if keep alive is not enabled */
  3355. return 0;
  3356. }
  3357. /* Check explicit wish of the client */
  3358. header = mg_get_header(conn, "Connection");
  3359. if (header) {
  3360. /* If there is a connection header from the client, obey */
  3361. if (header_has_option(header, "keep-alive")) {
  3362. return 1;
  3363. }
  3364. return 0;
  3365. }
  3366. /* Use default of the standard */
  3367. http_version = get_http_version(conn);
  3368. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3369. /* HTTP 1.1 default is keep alive */
  3370. return 1;
  3371. }
  3372. /* HTTP 1.0 (and earlier) default is to close the connection */
  3373. return 0;
  3374. }
  3375. static int
  3376. should_decode_url(const struct mg_connection *conn)
  3377. {
  3378. if (!conn || !conn->dom_ctx) {
  3379. return 0;
  3380. }
  3381. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3382. }
  3383. static const char *
  3384. suggest_connection_header(const struct mg_connection *conn)
  3385. {
  3386. return should_keep_alive(conn) ? "keep-alive" : "close";
  3387. }
  3388. #include "response.inl"
  3389. static void
  3390. send_no_cache_header(struct mg_connection *conn)
  3391. {
  3392. /* Send all current and obsolete cache opt-out directives. */
  3393. mg_response_header_add(conn,
  3394. "Cache-Control",
  3395. "no-cache, no-store, "
  3396. "must-revalidate, private, max-age=0",
  3397. -1);
  3398. mg_response_header_add(conn, "Expires", "0", -1);
  3399. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3400. /* Obsolete, but still send it for HTTP/1.0 */
  3401. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3402. }
  3403. }
  3404. static void
  3405. send_static_cache_header(struct mg_connection *conn)
  3406. {
  3407. #if !defined(NO_CACHING)
  3408. int max_age;
  3409. char val[64];
  3410. const char *cache_control =
  3411. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3412. /* If there is a full cache-control option configured,0 use it */
  3413. if (cache_control != NULL) {
  3414. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3415. return;
  3416. }
  3417. /* Read the server config to check how long a file may be cached.
  3418. * The configuration is in seconds. */
  3419. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3420. if (max_age <= 0) {
  3421. /* 0 means "do not cache". All values <0 are reserved
  3422. * and may be used differently in the future. */
  3423. /* If a file should not be cached, do not only send
  3424. * max-age=0, but also pragmas and Expires headers. */
  3425. send_no_cache_header(conn);
  3426. return;
  3427. }
  3428. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3429. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3430. /* See also https://www.mnot.net/cache_docs/ */
  3431. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3432. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3433. * leap
  3434. * year to 31622400 seconds. For the moment, we just send whatever has
  3435. * been configured, still the behavior for >1 year should be considered
  3436. * as undefined. */
  3437. mg_snprintf(
  3438. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3439. mg_response_header_add(conn, "Cache-Control", val, -1);
  3440. #else /* NO_CACHING */
  3441. send_no_cache_header(conn);
  3442. #endif /* !NO_CACHING */
  3443. }
  3444. static void
  3445. send_additional_header(struct mg_connection *conn)
  3446. {
  3447. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3448. #if !defined(NO_SSL)
  3449. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3450. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3451. if (max_age >= 0) {
  3452. char val[64];
  3453. mg_snprintf(conn,
  3454. NULL,
  3455. val,
  3456. sizeof(val),
  3457. "max-age=%lu",
  3458. (unsigned long)max_age);
  3459. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3460. }
  3461. }
  3462. #endif
  3463. if (header && header[0]) {
  3464. mg_response_header_add_lines(conn, header);
  3465. }
  3466. }
  3467. #if !defined(NO_FILESYSTEMS)
  3468. static void handle_file_based_request(struct mg_connection *conn,
  3469. const char *path,
  3470. struct mg_file *filep);
  3471. #endif /* NO_FILESYSTEMS */
  3472. const char *
  3473. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3474. {
  3475. /* See IANA HTTP status code assignment:
  3476. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3477. */
  3478. switch (response_code) {
  3479. /* RFC2616 Section 10.1 - Informational 1xx */
  3480. case 100:
  3481. return "Continue"; /* RFC2616 Section 10.1.1 */
  3482. case 101:
  3483. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3484. case 102:
  3485. return "Processing"; /* RFC2518 Section 10.1 */
  3486. /* RFC2616 Section 10.2 - Successful 2xx */
  3487. case 200:
  3488. return "OK"; /* RFC2616 Section 10.2.1 */
  3489. case 201:
  3490. return "Created"; /* RFC2616 Section 10.2.2 */
  3491. case 202:
  3492. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3493. case 203:
  3494. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3495. case 204:
  3496. return "No Content"; /* RFC2616 Section 10.2.5 */
  3497. case 205:
  3498. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3499. case 206:
  3500. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3501. case 207:
  3502. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3503. */
  3504. case 208:
  3505. return "Already Reported"; /* RFC5842 Section 7.1 */
  3506. case 226:
  3507. return "IM used"; /* RFC3229 Section 10.4.1 */
  3508. /* RFC2616 Section 10.3 - Redirection 3xx */
  3509. case 300:
  3510. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3511. case 301:
  3512. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3513. case 302:
  3514. return "Found"; /* RFC2616 Section 10.3.3 */
  3515. case 303:
  3516. return "See Other"; /* RFC2616 Section 10.3.4 */
  3517. case 304:
  3518. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3519. case 305:
  3520. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3521. case 307:
  3522. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3523. case 308:
  3524. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3525. /* RFC2616 Section 10.4 - Client Error 4xx */
  3526. case 400:
  3527. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3528. case 401:
  3529. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3530. case 402:
  3531. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3532. case 403:
  3533. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3534. case 404:
  3535. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3536. case 405:
  3537. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3538. case 406:
  3539. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3540. case 407:
  3541. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3542. case 408:
  3543. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3544. case 409:
  3545. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3546. case 410:
  3547. return "Gone"; /* RFC2616 Section 10.4.11 */
  3548. case 411:
  3549. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3550. case 412:
  3551. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3552. case 413:
  3553. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3554. case 414:
  3555. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3556. case 415:
  3557. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3558. case 416:
  3559. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3560. */
  3561. case 417:
  3562. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3563. case 421:
  3564. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3565. case 422:
  3566. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3567. * Section 11.2 */
  3568. case 423:
  3569. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3570. case 424:
  3571. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3572. * Section 11.4 */
  3573. case 426:
  3574. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3575. case 428:
  3576. return "Precondition Required"; /* RFC 6585, Section 3 */
  3577. case 429:
  3578. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3579. case 431:
  3580. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3581. case 451:
  3582. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3583. * Section 3 */
  3584. /* RFC2616 Section 10.5 - Server Error 5xx */
  3585. case 500:
  3586. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3587. case 501:
  3588. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3589. case 502:
  3590. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3591. case 503:
  3592. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3593. case 504:
  3594. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3595. case 505:
  3596. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3597. case 506:
  3598. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3599. case 507:
  3600. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3601. * Section 11.5 */
  3602. case 508:
  3603. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3604. case 510:
  3605. return "Not Extended"; /* RFC 2774, Section 7 */
  3606. case 511:
  3607. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3608. /* Other status codes, not shown in the IANA HTTP status code
  3609. * assignment.
  3610. * E.g., "de facto" standards due to common use, ... */
  3611. case 418:
  3612. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3613. case 419:
  3614. return "Authentication Timeout"; /* common use */
  3615. case 420:
  3616. return "Enhance Your Calm"; /* common use */
  3617. case 440:
  3618. return "Login Timeout"; /* common use */
  3619. case 509:
  3620. return "Bandwidth Limit Exceeded"; /* common use */
  3621. default:
  3622. /* This error code is unknown. This should not happen. */
  3623. if (conn) {
  3624. mg_cry_internal(conn,
  3625. "Unknown HTTP response code: %u",
  3626. response_code);
  3627. }
  3628. /* Return at least a category according to RFC 2616 Section 10. */
  3629. if (response_code >= 100 && response_code < 200) {
  3630. /* Unknown informational status code */
  3631. return "Information";
  3632. }
  3633. if (response_code >= 200 && response_code < 300) {
  3634. /* Unknown success code */
  3635. return "Success";
  3636. }
  3637. if (response_code >= 300 && response_code < 400) {
  3638. /* Unknown redirection code */
  3639. return "Redirection";
  3640. }
  3641. if (response_code >= 400 && response_code < 500) {
  3642. /* Unknown request error code */
  3643. return "Client Error";
  3644. }
  3645. if (response_code >= 500 && response_code < 600) {
  3646. /* Unknown server error code */
  3647. return "Server Error";
  3648. }
  3649. /* Response code not even within reasonable range */
  3650. return "";
  3651. }
  3652. }
  3653. static int
  3654. mg_send_http_error_impl(struct mg_connection *conn,
  3655. int status,
  3656. const char *fmt,
  3657. va_list args)
  3658. {
  3659. char errmsg_buf[MG_BUF_LEN];
  3660. va_list ap;
  3661. int has_body;
  3662. #if !defined(NO_FILESYSTEMS)
  3663. char path_buf[UTF8_PATH_MAX];
  3664. int len, i, page_handler_found, scope, truncated;
  3665. const char *error_handler = NULL;
  3666. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3667. const char *error_page_file_ext, *tstr;
  3668. #endif /* NO_FILESYSTEMS */
  3669. int handled_by_callback = 0;
  3670. if ((conn == NULL) || (fmt == NULL)) {
  3671. return -2;
  3672. }
  3673. /* Set status (for log) */
  3674. conn->status_code = status;
  3675. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3676. has_body = ((status > 199) && (status != 204) && (status != 304));
  3677. /* Prepare message in buf, if required */
  3678. if (has_body
  3679. || (!conn->in_error_handler
  3680. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3681. /* Store error message in errmsg_buf */
  3682. va_copy(ap, args);
  3683. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3684. va_end(ap);
  3685. /* In a debug build, print all html errors */
  3686. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3687. }
  3688. /* If there is a http_error callback, call it.
  3689. * But don't do it recursively, if callback calls mg_send_http_error again.
  3690. */
  3691. if (!conn->in_error_handler
  3692. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3693. /* Mark in_error_handler to avoid recursion and call user callback. */
  3694. conn->in_error_handler = 1;
  3695. handled_by_callback =
  3696. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3697. == 0);
  3698. conn->in_error_handler = 0;
  3699. }
  3700. if (!handled_by_callback) {
  3701. /* Check for recursion */
  3702. if (conn->in_error_handler) {
  3703. DEBUG_TRACE(
  3704. "Recursion when handling error %u - fall back to default",
  3705. status);
  3706. #if !defined(NO_FILESYSTEMS)
  3707. } else {
  3708. /* Send user defined error pages, if defined */
  3709. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3710. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3711. page_handler_found = 0;
  3712. if (error_handler != NULL) {
  3713. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3714. switch (scope) {
  3715. case 1: /* Handler for specific error, e.g. 404 error */
  3716. mg_snprintf(conn,
  3717. &truncated,
  3718. path_buf,
  3719. sizeof(path_buf) - 32,
  3720. "%serror%03u.",
  3721. error_handler,
  3722. status);
  3723. break;
  3724. case 2: /* Handler for error group, e.g., 5xx error
  3725. * handler
  3726. * for all server errors (500-599) */
  3727. mg_snprintf(conn,
  3728. &truncated,
  3729. path_buf,
  3730. sizeof(path_buf) - 32,
  3731. "%serror%01uxx.",
  3732. error_handler,
  3733. status / 100);
  3734. break;
  3735. default: /* Handler for all errors */
  3736. mg_snprintf(conn,
  3737. &truncated,
  3738. path_buf,
  3739. sizeof(path_buf) - 32,
  3740. "%serror.",
  3741. error_handler);
  3742. break;
  3743. }
  3744. /* String truncation in buf may only occur if
  3745. * error_handler is too long. This string is
  3746. * from the config, not from a client. */
  3747. (void)truncated;
  3748. /* The following code is redundant, but it should avoid
  3749. * false positives in static source code analyzers and
  3750. * vulnerability scanners.
  3751. */
  3752. path_buf[sizeof(path_buf) - 32] = 0;
  3753. len = (int)strlen(path_buf);
  3754. if (len > (int)sizeof(path_buf) - 32) {
  3755. len = (int)sizeof(path_buf) - 32;
  3756. }
  3757. /* Start with the file extenstion from the configuration. */
  3758. tstr = strchr(error_page_file_ext, '.');
  3759. while (tstr) {
  3760. for (i = 1;
  3761. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3762. i++) {
  3763. /* buffer overrun is not possible here, since
  3764. * (i < 32) && (len < sizeof(path_buf) - 32)
  3765. * ==> (i + len) < sizeof(path_buf) */
  3766. path_buf[len + i - 1] = tstr[i];
  3767. }
  3768. /* buffer overrun is not possible here, since
  3769. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3770. * ==> (i + len) <= sizeof(path_buf) */
  3771. path_buf[len + i - 1] = 0;
  3772. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3773. DEBUG_TRACE("Check error page %s - found",
  3774. path_buf);
  3775. page_handler_found = 1;
  3776. break;
  3777. }
  3778. DEBUG_TRACE("Check error page %s - not found",
  3779. path_buf);
  3780. /* Continue with the next file extenstion from the
  3781. * configuration (if there is a next one). */
  3782. tstr = strchr(tstr + i, '.');
  3783. }
  3784. }
  3785. }
  3786. if (page_handler_found) {
  3787. conn->in_error_handler = 1;
  3788. handle_file_based_request(conn, path_buf, &error_page_file);
  3789. conn->in_error_handler = 0;
  3790. return 0;
  3791. }
  3792. #endif /* NO_FILESYSTEMS */
  3793. }
  3794. /* No custom error page. Send default error page. */
  3795. conn->must_close = 1;
  3796. mg_response_header_start(conn, status);
  3797. send_no_cache_header(conn);
  3798. send_additional_header(conn);
  3799. if (has_body) {
  3800. mg_response_header_add(conn,
  3801. "Content-Type",
  3802. "text/plain; charset=utf-8",
  3803. -1);
  3804. }
  3805. mg_response_header_send(conn);
  3806. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3807. if (has_body) {
  3808. /* For other errors, send a generic error message. */
  3809. const char *status_text = mg_get_response_code_text(conn, status);
  3810. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3811. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3812. } else {
  3813. /* No body allowed. Close the connection. */
  3814. DEBUG_TRACE("Error %i", status);
  3815. }
  3816. }
  3817. return 0;
  3818. }
  3819. int
  3820. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3821. {
  3822. va_list ap;
  3823. int ret;
  3824. va_start(ap, fmt);
  3825. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3826. va_end(ap);
  3827. return ret;
  3828. }
  3829. int
  3830. mg_send_http_ok(struct mg_connection *conn,
  3831. const char *mime_type,
  3832. long long content_length)
  3833. {
  3834. if ((mime_type == NULL) || (*mime_type == 0)) {
  3835. /* No content type defined: default to text/html */
  3836. mime_type = "text/html";
  3837. }
  3838. mg_response_header_start(conn, 200);
  3839. send_no_cache_header(conn);
  3840. send_additional_header(conn);
  3841. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3842. if (content_length < 0) {
  3843. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3844. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3845. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3846. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3847. }
  3848. } else {
  3849. char len[32];
  3850. int trunc = 0;
  3851. mg_snprintf(conn,
  3852. &trunc,
  3853. len,
  3854. sizeof(len),
  3855. "%" UINT64_FMT,
  3856. (uint64_t)content_length);
  3857. if (!trunc) {
  3858. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3859. * !trunc is always true */
  3860. mg_response_header_add(conn, "Content-Length", len, -1);
  3861. }
  3862. }
  3863. mg_response_header_send(conn);
  3864. return 0;
  3865. }
  3866. int
  3867. mg_send_http_redirect(struct mg_connection *conn,
  3868. const char *target_url,
  3869. int redirect_code)
  3870. {
  3871. /* Send a 30x redirect response.
  3872. *
  3873. * Redirect types (status codes):
  3874. *
  3875. * Status | Perm/Temp | Method | Version
  3876. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3877. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3878. * 303 | temporary | always use GET | HTTP/1.1
  3879. * 307 | temporary | always keep method | HTTP/1.1
  3880. * 308 | permanent | always keep method | HTTP/1.1
  3881. */
  3882. const char *redirect_text;
  3883. int ret;
  3884. size_t content_len = 0;
  3885. #if defined(MG_SEND_REDIRECT_BODY)
  3886. char reply[MG_BUF_LEN];
  3887. #endif
  3888. /* In case redirect_code=0, use 307. */
  3889. if (redirect_code == 0) {
  3890. redirect_code = 307;
  3891. }
  3892. /* In case redirect_code is none of the above, return error. */
  3893. if ((redirect_code != 301) && (redirect_code != 302)
  3894. && (redirect_code != 303) && (redirect_code != 307)
  3895. && (redirect_code != 308)) {
  3896. /* Parameter error */
  3897. return -2;
  3898. }
  3899. /* Get proper text for response code */
  3900. redirect_text = mg_get_response_code_text(conn, redirect_code);
  3901. /* If target_url is not defined, redirect to "/". */
  3902. if ((target_url == NULL) || (*target_url == 0)) {
  3903. target_url = "/";
  3904. }
  3905. #if defined(MG_SEND_REDIRECT_BODY)
  3906. /* TODO: condition name? */
  3907. /* Prepare a response body with a hyperlink.
  3908. *
  3909. * According to RFC2616 (and RFC1945 before):
  3910. * Unless the request method was HEAD, the entity of the
  3911. * response SHOULD contain a short hypertext note with a hyperlink to
  3912. * the new URI(s).
  3913. *
  3914. * However, this response body is not useful in M2M communication.
  3915. * Probably the original reason in the RFC was, clients not supporting
  3916. * a 30x HTTP redirect could still show the HTML page and let the user
  3917. * press the link. Since current browsers support 30x HTTP, the additional
  3918. * HTML body does not seem to make sense anymore.
  3919. *
  3920. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  3921. * but it only notes:
  3922. * The server's response payload usually contains a short
  3923. * hypertext note with a hyperlink to the new URI(s).
  3924. *
  3925. * Deactivated by default. If you need the 30x body, set the define.
  3926. */
  3927. mg_snprintf(
  3928. conn,
  3929. NULL /* ignore truncation */,
  3930. reply,
  3931. sizeof(reply),
  3932. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  3933. redirect_text,
  3934. target_url,
  3935. target_url);
  3936. content_len = strlen(reply);
  3937. #endif
  3938. /* Do not send any additional header. For all other options,
  3939. * including caching, there are suitable defaults. */
  3940. ret = mg_printf(conn,
  3941. "HTTP/1.1 %i %s\r\n"
  3942. "Location: %s\r\n"
  3943. "Content-Length: %u\r\n"
  3944. "Connection: %s\r\n\r\n",
  3945. redirect_code,
  3946. redirect_text,
  3947. target_url,
  3948. (unsigned int)content_len,
  3949. suggest_connection_header(conn));
  3950. #if defined(MG_SEND_REDIRECT_BODY)
  3951. /* Send response body */
  3952. if (ret > 0) {
  3953. /* ... unless it is a HEAD request */
  3954. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  3955. ret = mg_write(conn, reply, content_len);
  3956. }
  3957. }
  3958. #endif
  3959. return (ret > 0) ? ret : -1;
  3960. }
  3961. #if defined(_WIN32)
  3962. /* Create substitutes for POSIX functions in Win32. */
  3963. #if defined(GCC_DIAGNOSTIC)
  3964. /* Show no warning in case system functions are not used. */
  3965. #pragma GCC diagnostic push
  3966. #pragma GCC diagnostic ignored "-Wunused-function"
  3967. #endif
  3968. static int
  3969. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3970. {
  3971. (void)unused;
  3972. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  3973. InitializeCriticalSection(&mutex->sec);
  3974. return 0;
  3975. }
  3976. static int
  3977. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3978. {
  3979. DeleteCriticalSection(&mutex->sec);
  3980. return 0;
  3981. }
  3982. static int
  3983. pthread_mutex_lock(pthread_mutex_t *mutex)
  3984. {
  3985. EnterCriticalSection(&mutex->sec);
  3986. return 0;
  3987. }
  3988. static int
  3989. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3990. {
  3991. LeaveCriticalSection(&mutex->sec);
  3992. return 0;
  3993. }
  3994. FUNCTION_MAY_BE_UNUSED
  3995. static int
  3996. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3997. {
  3998. (void)unused;
  3999. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4000. cv->waiting_thread = NULL;
  4001. return 0;
  4002. }
  4003. FUNCTION_MAY_BE_UNUSED
  4004. static int
  4005. pthread_cond_timedwait(pthread_cond_t *cv,
  4006. pthread_mutex_t *mutex,
  4007. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4008. {
  4009. struct mg_workerTLS **ptls,
  4010. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4011. int ok;
  4012. uint64_t nsnow, nswaitabs;
  4013. int64_t nswaitrel;
  4014. DWORD mswaitrel;
  4015. pthread_mutex_lock(&cv->threadIdSec);
  4016. /* Add this thread to cv's waiting list */
  4017. ptls = &cv->waiting_thread;
  4018. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4019. ;
  4020. tls->next_waiting_thread = NULL;
  4021. *ptls = tls;
  4022. pthread_mutex_unlock(&cv->threadIdSec);
  4023. if (abstime) {
  4024. nsnow = mg_get_current_time_ns();
  4025. nswaitabs =
  4026. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4027. nswaitrel = nswaitabs - nsnow;
  4028. if (nswaitrel < 0) {
  4029. nswaitrel = 0;
  4030. }
  4031. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4032. } else {
  4033. mswaitrel = (DWORD)INFINITE;
  4034. }
  4035. pthread_mutex_unlock(mutex);
  4036. ok = (WAIT_OBJECT_0
  4037. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4038. if (!ok) {
  4039. ok = 1;
  4040. pthread_mutex_lock(&cv->threadIdSec);
  4041. ptls = &cv->waiting_thread;
  4042. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4043. if (*ptls == tls) {
  4044. *ptls = tls->next_waiting_thread;
  4045. ok = 0;
  4046. break;
  4047. }
  4048. }
  4049. pthread_mutex_unlock(&cv->threadIdSec);
  4050. if (ok) {
  4051. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4052. (DWORD)INFINITE);
  4053. }
  4054. }
  4055. /* This thread has been removed from cv's waiting list */
  4056. pthread_mutex_lock(mutex);
  4057. return ok ? 0 : -1;
  4058. }
  4059. FUNCTION_MAY_BE_UNUSED
  4060. static int
  4061. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4062. {
  4063. return pthread_cond_timedwait(cv, mutex, NULL);
  4064. }
  4065. FUNCTION_MAY_BE_UNUSED
  4066. static int
  4067. pthread_cond_signal(pthread_cond_t *cv)
  4068. {
  4069. HANDLE wkup = NULL;
  4070. BOOL ok = FALSE;
  4071. pthread_mutex_lock(&cv->threadIdSec);
  4072. if (cv->waiting_thread) {
  4073. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4074. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4075. ok = SetEvent(wkup);
  4076. DEBUG_ASSERT(ok);
  4077. }
  4078. pthread_mutex_unlock(&cv->threadIdSec);
  4079. return ok ? 0 : 1;
  4080. }
  4081. FUNCTION_MAY_BE_UNUSED
  4082. static int
  4083. pthread_cond_broadcast(pthread_cond_t *cv)
  4084. {
  4085. pthread_mutex_lock(&cv->threadIdSec);
  4086. while (cv->waiting_thread) {
  4087. pthread_cond_signal(cv);
  4088. }
  4089. pthread_mutex_unlock(&cv->threadIdSec);
  4090. return 0;
  4091. }
  4092. FUNCTION_MAY_BE_UNUSED
  4093. static int
  4094. pthread_cond_destroy(pthread_cond_t *cv)
  4095. {
  4096. pthread_mutex_lock(&cv->threadIdSec);
  4097. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4098. pthread_mutex_unlock(&cv->threadIdSec);
  4099. pthread_mutex_destroy(&cv->threadIdSec);
  4100. return 0;
  4101. }
  4102. #if defined(ALTERNATIVE_QUEUE)
  4103. FUNCTION_MAY_BE_UNUSED
  4104. static void *
  4105. event_create(void)
  4106. {
  4107. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4108. }
  4109. FUNCTION_MAY_BE_UNUSED
  4110. static int
  4111. event_wait(void *eventhdl)
  4112. {
  4113. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4114. return (res == WAIT_OBJECT_0);
  4115. }
  4116. FUNCTION_MAY_BE_UNUSED
  4117. static int
  4118. event_signal(void *eventhdl)
  4119. {
  4120. return (int)SetEvent((HANDLE)eventhdl);
  4121. }
  4122. FUNCTION_MAY_BE_UNUSED
  4123. static void
  4124. event_destroy(void *eventhdl)
  4125. {
  4126. CloseHandle((HANDLE)eventhdl);
  4127. }
  4128. #endif
  4129. #if defined(GCC_DIAGNOSTIC)
  4130. /* Enable unused function warning again */
  4131. #pragma GCC diagnostic pop
  4132. #endif
  4133. /* For Windows, change all slashes to backslashes in path names. */
  4134. static void
  4135. change_slashes_to_backslashes(char *path)
  4136. {
  4137. int i;
  4138. for (i = 0; path[i] != '\0'; i++) {
  4139. if (path[i] == '/') {
  4140. path[i] = '\\';
  4141. }
  4142. /* remove double backslash (check i > 0 to preserve UNC paths,
  4143. * like \\server\file.txt) */
  4144. if ((i > 0) && (path[i] == '\\')) {
  4145. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4146. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4147. }
  4148. }
  4149. }
  4150. }
  4151. static int
  4152. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4153. {
  4154. int diff;
  4155. do {
  4156. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4157. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4158. s1++;
  4159. s2++;
  4160. } while ((diff == 0) && (s1[-1] != L'\0'));
  4161. return diff;
  4162. }
  4163. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4164. * wbuf and wbuf_len is a target buffer and its length. */
  4165. static void
  4166. path_to_unicode(const struct mg_connection *conn,
  4167. const char *path,
  4168. wchar_t *wbuf,
  4169. size_t wbuf_len)
  4170. {
  4171. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4172. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4173. DWORD long_len, err;
  4174. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4175. mg_strlcpy(buf, path, sizeof(buf));
  4176. change_slashes_to_backslashes(buf);
  4177. /* Convert to Unicode and back. If doubly-converted string does not
  4178. * match the original, something is fishy, reject. */
  4179. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4180. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4181. WideCharToMultiByte(
  4182. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4183. if (strcmp(buf, buf2) != 0) {
  4184. wbuf[0] = L'\0';
  4185. }
  4186. /* Windows file systems are not case sensitive, but you can still use
  4187. * uppercase and lowercase letters (on all modern file systems).
  4188. * The server can check if the URI uses the same upper/lowercase
  4189. * letters an the file system, effectively making Windows servers
  4190. * case sensitive (like Linux servers are). It is still not possible
  4191. * to use two files with the same name in different cases on Windows
  4192. * (like /a and /A) - this would be possible in Linux.
  4193. * As a default, Windows is not case sensitive, but the case sensitive
  4194. * file name check can be activated by an additional configuration. */
  4195. if (conn) {
  4196. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4197. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4198. "yes")) {
  4199. /* Use case sensitive compare function */
  4200. fcompare = wcscmp;
  4201. }
  4202. }
  4203. (void)conn; /* conn is currently unused */
  4204. /* Only accept a full file path, not a Windows short (8.3) path. */
  4205. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4206. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4207. if (long_len == 0) {
  4208. err = GetLastError();
  4209. if (err == ERROR_FILE_NOT_FOUND) {
  4210. /* File does not exist. This is not always a problem here. */
  4211. return;
  4212. }
  4213. }
  4214. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4215. /* Short name is used. */
  4216. wbuf[0] = L'\0';
  4217. }
  4218. }
  4219. #if !defined(NO_FILESYSTEMS)
  4220. /* Get file information, return 1 if file exists, 0 if not */
  4221. static int
  4222. mg_stat(const struct mg_connection *conn,
  4223. const char *path,
  4224. struct mg_file_stat *filep)
  4225. {
  4226. wchar_t wbuf[UTF16_PATH_MAX];
  4227. WIN32_FILE_ATTRIBUTE_DATA info;
  4228. time_t creation_time;
  4229. size_t len;
  4230. if (!filep) {
  4231. return 0;
  4232. }
  4233. memset(filep, 0, sizeof(*filep));
  4234. if (mg_path_suspicious(conn, path)) {
  4235. return 0;
  4236. }
  4237. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4238. /* Windows happily opens files with some garbage at the end of file name.
  4239. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4240. * "a.cgi", despite one would expect an error back. */
  4241. len = strlen(path);
  4242. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4243. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4244. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4245. filep->last_modified =
  4246. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4247. info.ftLastWriteTime.dwHighDateTime);
  4248. /* On Windows, the file creation time can be higher than the
  4249. * modification time, e.g. when a file is copied.
  4250. * Since the Last-Modified timestamp is used for caching
  4251. * it should be based on the most recent timestamp. */
  4252. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4253. info.ftCreationTime.dwHighDateTime);
  4254. if (creation_time > filep->last_modified) {
  4255. filep->last_modified = creation_time;
  4256. }
  4257. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4258. return 1;
  4259. }
  4260. return 0;
  4261. }
  4262. #endif
  4263. static int
  4264. mg_remove(const struct mg_connection *conn, const char *path)
  4265. {
  4266. wchar_t wbuf[UTF16_PATH_MAX];
  4267. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4268. return DeleteFileW(wbuf) ? 0 : -1;
  4269. }
  4270. static int
  4271. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4272. {
  4273. wchar_t wbuf[UTF16_PATH_MAX];
  4274. (void)mode;
  4275. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4276. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4277. }
  4278. /* Create substitutes for POSIX functions in Win32. */
  4279. #if defined(GCC_DIAGNOSTIC)
  4280. /* Show no warning in case system functions are not used. */
  4281. #pragma GCC diagnostic push
  4282. #pragma GCC diagnostic ignored "-Wunused-function"
  4283. #endif
  4284. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4285. FUNCTION_MAY_BE_UNUSED
  4286. static DIR *
  4287. mg_opendir(const struct mg_connection *conn, const char *name)
  4288. {
  4289. DIR *dir = NULL;
  4290. wchar_t wpath[UTF16_PATH_MAX];
  4291. DWORD attrs;
  4292. if (name == NULL) {
  4293. SetLastError(ERROR_BAD_ARGUMENTS);
  4294. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4295. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4296. } else {
  4297. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4298. attrs = GetFileAttributesW(wpath);
  4299. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4300. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4301. (void)wcscat(wpath, L"\\*");
  4302. dir->handle = FindFirstFileW(wpath, &dir->info);
  4303. dir->result.d_name[0] = '\0';
  4304. } else {
  4305. mg_free(dir);
  4306. dir = NULL;
  4307. }
  4308. }
  4309. return dir;
  4310. }
  4311. FUNCTION_MAY_BE_UNUSED
  4312. static int
  4313. mg_closedir(DIR *dir)
  4314. {
  4315. int result = 0;
  4316. if (dir != NULL) {
  4317. if (dir->handle != INVALID_HANDLE_VALUE)
  4318. result = FindClose(dir->handle) ? 0 : -1;
  4319. mg_free(dir);
  4320. } else {
  4321. result = -1;
  4322. SetLastError(ERROR_BAD_ARGUMENTS);
  4323. }
  4324. return result;
  4325. }
  4326. FUNCTION_MAY_BE_UNUSED
  4327. static struct dirent *
  4328. mg_readdir(DIR *dir)
  4329. {
  4330. struct dirent *result = 0;
  4331. if (dir) {
  4332. if (dir->handle != INVALID_HANDLE_VALUE) {
  4333. result = &dir->result;
  4334. (void)WideCharToMultiByte(CP_UTF8,
  4335. 0,
  4336. dir->info.cFileName,
  4337. -1,
  4338. result->d_name,
  4339. sizeof(result->d_name),
  4340. NULL,
  4341. NULL);
  4342. if (!FindNextFileW(dir->handle, &dir->info)) {
  4343. (void)FindClose(dir->handle);
  4344. dir->handle = INVALID_HANDLE_VALUE;
  4345. }
  4346. } else {
  4347. SetLastError(ERROR_FILE_NOT_FOUND);
  4348. }
  4349. } else {
  4350. SetLastError(ERROR_BAD_ARGUMENTS);
  4351. }
  4352. return result;
  4353. }
  4354. #if !defined(HAVE_POLL)
  4355. #undef POLLIN
  4356. #undef POLLPRI
  4357. #undef POLLOUT
  4358. #undef POLLERR
  4359. #define POLLIN (1) /* Data ready - read will not block. */
  4360. #define POLLPRI (2) /* Priority data ready. */
  4361. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4362. #define POLLERR (8) /* Error event */
  4363. FUNCTION_MAY_BE_UNUSED
  4364. static int
  4365. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4366. {
  4367. struct timeval tv;
  4368. fd_set rset;
  4369. fd_set wset;
  4370. fd_set eset;
  4371. unsigned int i;
  4372. int result;
  4373. SOCKET maxfd = 0;
  4374. memset(&tv, 0, sizeof(tv));
  4375. tv.tv_sec = milliseconds / 1000;
  4376. tv.tv_usec = (milliseconds % 1000) * 1000;
  4377. FD_ZERO(&rset);
  4378. FD_ZERO(&wset);
  4379. FD_ZERO(&eset);
  4380. for (i = 0; i < n; i++) {
  4381. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4382. if (pfd[i].events & POLLIN) {
  4383. FD_SET(pfd[i].fd, &rset);
  4384. }
  4385. if (pfd[i].events & POLLOUT) {
  4386. FD_SET(pfd[i].fd, &wset);
  4387. }
  4388. /* Check for errors for any FD in the set */
  4389. FD_SET(pfd[i].fd, &eset);
  4390. }
  4391. pfd[i].revents = 0;
  4392. if (pfd[i].fd > maxfd) {
  4393. maxfd = pfd[i].fd;
  4394. }
  4395. }
  4396. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4397. for (i = 0; i < n; i++) {
  4398. if (FD_ISSET(pfd[i].fd, &rset)) {
  4399. pfd[i].revents |= POLLIN;
  4400. }
  4401. if (FD_ISSET(pfd[i].fd, &wset)) {
  4402. pfd[i].revents |= POLLOUT;
  4403. }
  4404. if (FD_ISSET(pfd[i].fd, &eset)) {
  4405. pfd[i].revents |= POLLERR;
  4406. }
  4407. }
  4408. }
  4409. /* We should subtract the time used in select from remaining
  4410. * "milliseconds", in particular if called from mg_poll with a
  4411. * timeout quantum.
  4412. * Unfortunately, the remaining time is not stored in "tv" in all
  4413. * implementations, so the result in "tv" must be considered undefined.
  4414. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4415. return result;
  4416. }
  4417. #endif /* HAVE_POLL */
  4418. #if defined(GCC_DIAGNOSTIC)
  4419. /* Enable unused function warning again */
  4420. #pragma GCC diagnostic pop
  4421. #endif
  4422. static void
  4423. set_close_on_exec(SOCKET sock,
  4424. const struct mg_connection *conn /* may be null */,
  4425. struct mg_context *ctx /* may be null */)
  4426. {
  4427. (void)conn; /* Unused. */
  4428. (void)ctx;
  4429. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4430. }
  4431. int
  4432. mg_start_thread(mg_thread_func_t f, void *p)
  4433. {
  4434. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4435. /* Compile-time option to control stack size, e.g.
  4436. * -DUSE_STACK_SIZE=16384
  4437. */
  4438. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4439. == ((uintptr_t)(-1L)))
  4440. ? -1
  4441. : 0);
  4442. #else
  4443. return (
  4444. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4445. ? -1
  4446. : 0);
  4447. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4448. }
  4449. /* Start a thread storing the thread context. */
  4450. static int
  4451. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4452. void *p,
  4453. pthread_t *threadidptr)
  4454. {
  4455. uintptr_t uip;
  4456. HANDLE threadhandle;
  4457. int result = -1;
  4458. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4459. threadhandle = (HANDLE)uip;
  4460. if ((uip != 0) && (threadidptr != NULL)) {
  4461. *threadidptr = threadhandle;
  4462. result = 0;
  4463. }
  4464. return result;
  4465. }
  4466. /* Wait for a thread to finish. */
  4467. static int
  4468. mg_join_thread(pthread_t threadid)
  4469. {
  4470. int result;
  4471. DWORD dwevent;
  4472. result = -1;
  4473. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4474. if (dwevent == WAIT_FAILED) {
  4475. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4476. } else {
  4477. if (dwevent == WAIT_OBJECT_0) {
  4478. CloseHandle(threadid);
  4479. result = 0;
  4480. }
  4481. }
  4482. return result;
  4483. }
  4484. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4485. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4486. /* Create substitutes for POSIX functions in Win32. */
  4487. #if defined(GCC_DIAGNOSTIC)
  4488. /* Show no warning in case system functions are not used. */
  4489. #pragma GCC diagnostic push
  4490. #pragma GCC diagnostic ignored "-Wunused-function"
  4491. #endif
  4492. FUNCTION_MAY_BE_UNUSED
  4493. static HANDLE
  4494. dlopen(const char *dll_name, int flags)
  4495. {
  4496. wchar_t wbuf[UTF16_PATH_MAX];
  4497. (void)flags;
  4498. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4499. return LoadLibraryW(wbuf);
  4500. }
  4501. FUNCTION_MAY_BE_UNUSED
  4502. static int
  4503. dlclose(void *handle)
  4504. {
  4505. int result;
  4506. if (FreeLibrary((HMODULE)handle) != 0) {
  4507. result = 0;
  4508. } else {
  4509. result = -1;
  4510. }
  4511. return result;
  4512. }
  4513. #if defined(GCC_DIAGNOSTIC)
  4514. /* Enable unused function warning again */
  4515. #pragma GCC diagnostic pop
  4516. #endif
  4517. #endif
  4518. #if !defined(NO_CGI)
  4519. #define SIGKILL (0)
  4520. static int
  4521. kill(pid_t pid, int sig_num)
  4522. {
  4523. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4524. (void)CloseHandle((HANDLE)pid);
  4525. return 0;
  4526. }
  4527. #if !defined(WNOHANG)
  4528. #define WNOHANG (1)
  4529. #endif
  4530. static pid_t
  4531. waitpid(pid_t pid, int *status, int flags)
  4532. {
  4533. DWORD timeout = INFINITE;
  4534. DWORD waitres;
  4535. (void)status; /* Currently not used by any client here */
  4536. if ((flags | WNOHANG) == WNOHANG) {
  4537. timeout = 0;
  4538. }
  4539. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4540. if (waitres == WAIT_OBJECT_0) {
  4541. return pid;
  4542. }
  4543. if (waitres == WAIT_TIMEOUT) {
  4544. return 0;
  4545. }
  4546. return (pid_t)-1;
  4547. }
  4548. static void
  4549. trim_trailing_whitespaces(char *s)
  4550. {
  4551. char *e = s + strlen(s);
  4552. while ((e > s) && isspace((unsigned char)e[-1])) {
  4553. *(--e) = '\0';
  4554. }
  4555. }
  4556. static pid_t
  4557. spawn_process(struct mg_connection *conn,
  4558. const char *prog,
  4559. char *envblk,
  4560. char *envp[],
  4561. int fdin[2],
  4562. int fdout[2],
  4563. int fderr[2],
  4564. const char *dir,
  4565. unsigned char cgi_config_idx)
  4566. {
  4567. HANDLE me;
  4568. char *interp;
  4569. char *interp_arg = 0;
  4570. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4571. int truncated;
  4572. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4573. STARTUPINFOA si;
  4574. PROCESS_INFORMATION pi = {0};
  4575. (void)envp;
  4576. memset(&si, 0, sizeof(si));
  4577. si.cb = sizeof(si);
  4578. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4579. si.wShowWindow = SW_HIDE;
  4580. me = GetCurrentProcess();
  4581. DuplicateHandle(me,
  4582. (HANDLE)_get_osfhandle(fdin[0]),
  4583. me,
  4584. &si.hStdInput,
  4585. 0,
  4586. TRUE,
  4587. DUPLICATE_SAME_ACCESS);
  4588. DuplicateHandle(me,
  4589. (HANDLE)_get_osfhandle(fdout[1]),
  4590. me,
  4591. &si.hStdOutput,
  4592. 0,
  4593. TRUE,
  4594. DUPLICATE_SAME_ACCESS);
  4595. DuplicateHandle(me,
  4596. (HANDLE)_get_osfhandle(fderr[1]),
  4597. me,
  4598. &si.hStdError,
  4599. 0,
  4600. TRUE,
  4601. DUPLICATE_SAME_ACCESS);
  4602. /* Mark handles that should not be inherited. See
  4603. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4604. */
  4605. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4606. HANDLE_FLAG_INHERIT,
  4607. 0);
  4608. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4609. HANDLE_FLAG_INHERIT,
  4610. 0);
  4611. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4612. HANDLE_FLAG_INHERIT,
  4613. 0);
  4614. /* First check, if there is a CGI interpreter configured for all CGI
  4615. * scripts. */
  4616. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4617. if (interp != NULL) {
  4618. /* If there is a configured interpreter, check for additional arguments
  4619. */
  4620. interp_arg =
  4621. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4622. } else {
  4623. /* Otherwise, the interpreter must be stated in the first line of the
  4624. * CGI script file, after a #! (shebang) mark. */
  4625. buf[0] = buf[1] = '\0';
  4626. /* Get the full script path */
  4627. mg_snprintf(
  4628. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4629. if (truncated) {
  4630. pi.hProcess = (pid_t)-1;
  4631. goto spawn_cleanup;
  4632. }
  4633. /* Open the script file, to read the first line */
  4634. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4635. /* Read the first line of the script into the buffer */
  4636. mg_fgets(buf, sizeof(buf), &file);
  4637. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4638. buf[sizeof(buf) - 1] = '\0';
  4639. }
  4640. if ((buf[0] == '#') && (buf[1] == '!')) {
  4641. trim_trailing_whitespaces(buf + 2);
  4642. } else {
  4643. buf[2] = '\0';
  4644. }
  4645. interp = buf + 2;
  4646. }
  4647. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4648. if (interp[0] != '\0') {
  4649. /* This is an interpreted script file. We must call the interpreter. */
  4650. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4651. mg_snprintf(conn,
  4652. &truncated,
  4653. cmdline,
  4654. sizeof(cmdline),
  4655. "\"%s\" %s \"%s\\%s\"",
  4656. interp,
  4657. interp_arg,
  4658. full_dir,
  4659. prog);
  4660. } else {
  4661. mg_snprintf(conn,
  4662. &truncated,
  4663. cmdline,
  4664. sizeof(cmdline),
  4665. "\"%s\" \"%s\\%s\"",
  4666. interp,
  4667. full_dir,
  4668. prog);
  4669. }
  4670. } else {
  4671. /* This is (probably) a compiled program. We call it directly. */
  4672. mg_snprintf(conn,
  4673. &truncated,
  4674. cmdline,
  4675. sizeof(cmdline),
  4676. "\"%s\\%s\"",
  4677. full_dir,
  4678. prog);
  4679. }
  4680. if (truncated) {
  4681. pi.hProcess = (pid_t)-1;
  4682. goto spawn_cleanup;
  4683. }
  4684. DEBUG_TRACE("Running [%s]", cmdline);
  4685. if (CreateProcessA(NULL,
  4686. cmdline,
  4687. NULL,
  4688. NULL,
  4689. TRUE,
  4690. CREATE_NEW_PROCESS_GROUP,
  4691. envblk,
  4692. NULL,
  4693. &si,
  4694. &pi)
  4695. == 0) {
  4696. mg_cry_internal(
  4697. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4698. pi.hProcess = (pid_t)-1;
  4699. /* goto spawn_cleanup; */
  4700. }
  4701. spawn_cleanup:
  4702. (void)CloseHandle(si.hStdOutput);
  4703. (void)CloseHandle(si.hStdError);
  4704. (void)CloseHandle(si.hStdInput);
  4705. if (pi.hThread != NULL) {
  4706. (void)CloseHandle(pi.hThread);
  4707. }
  4708. return (pid_t)pi.hProcess;
  4709. }
  4710. #endif /* !NO_CGI */
  4711. static int
  4712. set_blocking_mode(SOCKET sock)
  4713. {
  4714. unsigned long non_blocking = 0;
  4715. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4716. }
  4717. static int
  4718. set_non_blocking_mode(SOCKET sock)
  4719. {
  4720. unsigned long non_blocking = 1;
  4721. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4722. }
  4723. #else
  4724. #if !defined(NO_FILESYSTEMS)
  4725. static int
  4726. mg_stat(const struct mg_connection *conn,
  4727. const char *path,
  4728. struct mg_file_stat *filep)
  4729. {
  4730. struct stat st;
  4731. if (!filep) {
  4732. return 0;
  4733. }
  4734. memset(filep, 0, sizeof(*filep));
  4735. if (mg_path_suspicious(conn, path)) {
  4736. return 0;
  4737. }
  4738. if (0 == stat(path, &st)) {
  4739. filep->size = (uint64_t)(st.st_size);
  4740. filep->last_modified = st.st_mtime;
  4741. filep->is_directory = S_ISDIR(st.st_mode);
  4742. return 1;
  4743. }
  4744. return 0;
  4745. }
  4746. #endif /* NO_FILESYSTEMS */
  4747. static void
  4748. set_close_on_exec(int fd,
  4749. const struct mg_connection *conn /* may be null */,
  4750. struct mg_context *ctx /* may be null */)
  4751. {
  4752. #if defined(__ZEPHYR__)
  4753. (void)fd;
  4754. (void)conn;
  4755. (void)ctx;
  4756. #else
  4757. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4758. if (conn || ctx) {
  4759. struct mg_connection fc;
  4760. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4761. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4762. __func__,
  4763. strerror(ERRNO));
  4764. }
  4765. }
  4766. #endif
  4767. }
  4768. int
  4769. mg_start_thread(mg_thread_func_t func, void *param)
  4770. {
  4771. pthread_t thread_id;
  4772. pthread_attr_t attr;
  4773. int result;
  4774. (void)pthread_attr_init(&attr);
  4775. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4776. #if defined(__ZEPHYR__)
  4777. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4778. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4779. /* Compile-time option to control stack size,
  4780. * e.g. -DUSE_STACK_SIZE=16384 */
  4781. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4782. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4783. result = pthread_create(&thread_id, &attr, func, param);
  4784. pthread_attr_destroy(&attr);
  4785. return result;
  4786. }
  4787. /* Start a thread storing the thread context. */
  4788. static int
  4789. mg_start_thread_with_id(mg_thread_func_t func,
  4790. void *param,
  4791. pthread_t *threadidptr)
  4792. {
  4793. pthread_t thread_id;
  4794. pthread_attr_t attr;
  4795. int result;
  4796. (void)pthread_attr_init(&attr);
  4797. #if defined(__ZEPHYR__)
  4798. pthread_attr_setstack(&attr,
  4799. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4800. ZEPHYR_STACK_SIZE);
  4801. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4802. /* Compile-time option to control stack size,
  4803. * e.g. -DUSE_STACK_SIZE=16384 */
  4804. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4805. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4806. result = pthread_create(&thread_id, &attr, func, param);
  4807. pthread_attr_destroy(&attr);
  4808. if ((result == 0) && (threadidptr != NULL)) {
  4809. *threadidptr = thread_id;
  4810. }
  4811. return result;
  4812. }
  4813. /* Wait for a thread to finish. */
  4814. static int
  4815. mg_join_thread(pthread_t threadid)
  4816. {
  4817. int result;
  4818. result = pthread_join(threadid, NULL);
  4819. return result;
  4820. }
  4821. #if !defined(NO_CGI)
  4822. static pid_t
  4823. spawn_process(struct mg_connection *conn,
  4824. const char *prog,
  4825. char *envblk,
  4826. char *envp[],
  4827. int fdin[2],
  4828. int fdout[2],
  4829. int fderr[2],
  4830. const char *dir,
  4831. unsigned char cgi_config_idx)
  4832. {
  4833. pid_t pid;
  4834. const char *interp;
  4835. (void)envblk;
  4836. if ((pid = fork()) == -1) {
  4837. /* Parent */
  4838. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4839. } else if (pid != 0) {
  4840. /* Make sure children close parent-side descriptors.
  4841. * The caller will close the child-side immediately. */
  4842. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4843. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4844. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4845. } else {
  4846. /* Child */
  4847. if (chdir(dir) != 0) {
  4848. mg_cry_internal(
  4849. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4850. } else if (dup2(fdin[0], 0) == -1) {
  4851. mg_cry_internal(conn,
  4852. "%s: dup2(%d, 0): %s",
  4853. __func__,
  4854. fdin[0],
  4855. strerror(ERRNO));
  4856. } else if (dup2(fdout[1], 1) == -1) {
  4857. mg_cry_internal(conn,
  4858. "%s: dup2(%d, 1): %s",
  4859. __func__,
  4860. fdout[1],
  4861. strerror(ERRNO));
  4862. } else if (dup2(fderr[1], 2) == -1) {
  4863. mg_cry_internal(conn,
  4864. "%s: dup2(%d, 2): %s",
  4865. __func__,
  4866. fderr[1],
  4867. strerror(ERRNO));
  4868. } else {
  4869. struct sigaction sa;
  4870. /* Keep stderr and stdout in two different pipes.
  4871. * Stdout will be sent back to the client,
  4872. * stderr should go into a server error log. */
  4873. (void)close(fdin[0]);
  4874. (void)close(fdout[1]);
  4875. (void)close(fderr[1]);
  4876. /* Close write end fdin and read end fdout and fderr */
  4877. (void)close(fdin[1]);
  4878. (void)close(fdout[0]);
  4879. (void)close(fderr[0]);
  4880. /* After exec, all signal handlers are restored to their default
  4881. * values, with one exception of SIGCHLD. According to
  4882. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4883. * will leave unchanged after exec if it was set to be ignored.
  4884. * Restore it to default action. */
  4885. memset(&sa, 0, sizeof(sa));
  4886. sa.sa_handler = SIG_DFL;
  4887. sigaction(SIGCHLD, &sa, NULL);
  4888. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4889. if (interp == NULL) {
  4890. /* no interpreter configured, call the programm directly */
  4891. (void)execle(prog, prog, NULL, envp);
  4892. mg_cry_internal(conn,
  4893. "%s: execle(%s): %s",
  4894. __func__,
  4895. prog,
  4896. strerror(ERRNO));
  4897. } else {
  4898. /* call the configured interpreter */
  4899. const char *interp_args =
  4900. conn->dom_ctx
  4901. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4902. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  4903. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  4904. } else {
  4905. (void)execle(interp, interp, prog, NULL, envp);
  4906. }
  4907. mg_cry_internal(conn,
  4908. "%s: execle(%s %s): %s",
  4909. __func__,
  4910. interp,
  4911. prog,
  4912. strerror(ERRNO));
  4913. }
  4914. }
  4915. exit(EXIT_FAILURE);
  4916. }
  4917. return pid;
  4918. }
  4919. #endif /* !NO_CGI */
  4920. static int
  4921. set_non_blocking_mode(SOCKET sock)
  4922. {
  4923. int flags = fcntl(sock, F_GETFL, 0);
  4924. if (flags < 0) {
  4925. return -1;
  4926. }
  4927. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4928. return -1;
  4929. }
  4930. return 0;
  4931. }
  4932. static int
  4933. set_blocking_mode(SOCKET sock)
  4934. {
  4935. int flags = fcntl(sock, F_GETFL, 0);
  4936. if (flags < 0) {
  4937. return -1;
  4938. }
  4939. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4940. return -1;
  4941. }
  4942. return 0;
  4943. }
  4944. #endif /* _WIN32 / else */
  4945. /* End of initial operating system specific define block. */
  4946. /* Get a random number (independent of C rand function) */
  4947. static uint64_t
  4948. get_random(void)
  4949. {
  4950. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4951. static uint64_t lcg = 0; /* Linear congruential generator */
  4952. uint64_t now = mg_get_current_time_ns();
  4953. if (lfsr == 0) {
  4954. /* lfsr will be only 0 if has not been initialized,
  4955. * so this code is called only once. */
  4956. lfsr = mg_get_current_time_ns();
  4957. lcg = mg_get_current_time_ns();
  4958. } else {
  4959. /* Get the next step of both random number generators. */
  4960. lfsr = (lfsr >> 1)
  4961. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4962. << 63);
  4963. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4964. }
  4965. /* Combining two pseudo-random number generators and a high resolution
  4966. * part
  4967. * of the current server time will make it hard (impossible?) to guess
  4968. * the
  4969. * next number. */
  4970. return (lfsr ^ lcg ^ now);
  4971. }
  4972. static int
  4973. mg_poll(struct mg_pollfd *pfd,
  4974. unsigned int n,
  4975. int milliseconds,
  4976. stop_flag_t *stop_flag)
  4977. {
  4978. /* Call poll, but only for a maximum time of a few seconds.
  4979. * This will allow to stop the server after some seconds, instead
  4980. * of having to wait for a long socket timeout. */
  4981. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4982. int check_pollerr = 0;
  4983. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  4984. /* If we wait for only one file descriptor, wait on error as well */
  4985. pfd[0].events |= POLLERR;
  4986. check_pollerr = 1;
  4987. }
  4988. do {
  4989. int result;
  4990. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  4991. /* Shut down signal */
  4992. return -2;
  4993. }
  4994. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4995. ms_now = milliseconds;
  4996. }
  4997. result = poll(pfd, n, ms_now);
  4998. if (result != 0) {
  4999. /* Poll returned either success (1) or error (-1).
  5000. * Forward both to the caller. */
  5001. if ((check_pollerr)
  5002. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5003. == POLLERR)) {
  5004. /* One and only file descriptor returned error */
  5005. return -1;
  5006. }
  5007. return result;
  5008. }
  5009. /* Poll returned timeout (0). */
  5010. if (milliseconds > 0) {
  5011. milliseconds -= ms_now;
  5012. }
  5013. } while (milliseconds > 0);
  5014. /* timeout: return 0 */
  5015. return 0;
  5016. }
  5017. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5018. * descriptor.
  5019. * Return value:
  5020. * >=0 .. number of bytes successfully written
  5021. * -1 .. timeout
  5022. * -2 .. error
  5023. */
  5024. static int
  5025. push_inner(struct mg_context *ctx,
  5026. FILE *fp,
  5027. SOCKET sock,
  5028. SSL *ssl,
  5029. const char *buf,
  5030. int len,
  5031. double timeout)
  5032. {
  5033. uint64_t start = 0, now = 0, timeout_ns = 0;
  5034. int n, err;
  5035. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5036. #if defined(_WIN32)
  5037. typedef int len_t;
  5038. #else
  5039. typedef size_t len_t;
  5040. #endif
  5041. if (timeout > 0) {
  5042. now = mg_get_current_time_ns();
  5043. start = now;
  5044. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5045. }
  5046. if (ctx == NULL) {
  5047. return -2;
  5048. }
  5049. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5050. if (ssl) {
  5051. return -2;
  5052. }
  5053. #endif
  5054. /* Try to read until it succeeds, fails, times out, or the server
  5055. * shuts down. */
  5056. for (;;) {
  5057. #if defined(USE_MBEDTLS)
  5058. if (ssl != NULL) {
  5059. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5060. if (n <= 0) {
  5061. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5062. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5063. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5064. n = 0;
  5065. } else {
  5066. fprintf(stderr, "SSL write failed, error %d\n", n);
  5067. return -2;
  5068. }
  5069. } else {
  5070. err = 0;
  5071. }
  5072. } else
  5073. #elif !defined(NO_SSL)
  5074. if (ssl != NULL) {
  5075. ERR_clear_error();
  5076. n = SSL_write(ssl, buf, len);
  5077. if (n <= 0) {
  5078. err = SSL_get_error(ssl, n);
  5079. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5080. err = ERRNO;
  5081. } else if ((err == SSL_ERROR_WANT_READ)
  5082. || (err == SSL_ERROR_WANT_WRITE)) {
  5083. n = 0;
  5084. } else {
  5085. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5086. ERR_clear_error();
  5087. return -2;
  5088. }
  5089. ERR_clear_error();
  5090. } else {
  5091. err = 0;
  5092. }
  5093. } else
  5094. #endif
  5095. if (fp != NULL) {
  5096. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5097. if (ferror(fp)) {
  5098. n = -1;
  5099. err = ERRNO;
  5100. } else {
  5101. err = 0;
  5102. }
  5103. } else {
  5104. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5105. err = (n < 0) ? ERRNO : 0;
  5106. #if defined(_WIN32)
  5107. if (err == WSAEWOULDBLOCK) {
  5108. err = 0;
  5109. n = 0;
  5110. }
  5111. #else
  5112. if (ERROR_TRY_AGAIN(err)) {
  5113. err = 0;
  5114. n = 0;
  5115. }
  5116. #endif
  5117. if (n < 0) {
  5118. /* shutdown of the socket at client side */
  5119. return -2;
  5120. }
  5121. }
  5122. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5123. return -2;
  5124. }
  5125. if ((n > 0) || ((n == 0) && (len == 0))) {
  5126. /* some data has been read, or no data was requested */
  5127. return n;
  5128. }
  5129. if (n < 0) {
  5130. /* socket error - check errno */
  5131. DEBUG_TRACE("send() failed, error %d", err);
  5132. /* TODO (mid): error handling depending on the error code.
  5133. * These codes are different between Windows and Linux.
  5134. * Currently there is no problem with failing send calls,
  5135. * if there is a reproducible situation, it should be
  5136. * investigated in detail.
  5137. */
  5138. return -2;
  5139. }
  5140. /* Only in case n=0 (timeout), repeat calling the write function */
  5141. /* If send failed, wait before retry */
  5142. if (fp != NULL) {
  5143. /* For files, just wait a fixed time.
  5144. * Maybe it helps, maybe not. */
  5145. mg_sleep(5);
  5146. } else {
  5147. /* For sockets, wait for the socket using poll */
  5148. struct mg_pollfd pfd[1];
  5149. int pollres;
  5150. pfd[0].fd = sock;
  5151. pfd[0].events = POLLOUT;
  5152. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5153. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5154. return -2;
  5155. }
  5156. if (pollres > 0) {
  5157. continue;
  5158. }
  5159. }
  5160. if (timeout > 0) {
  5161. now = mg_get_current_time_ns();
  5162. if ((now - start) > timeout_ns) {
  5163. /* Timeout */
  5164. break;
  5165. }
  5166. }
  5167. }
  5168. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5169. used */
  5170. return -1;
  5171. }
  5172. static int
  5173. push_all(struct mg_context *ctx,
  5174. FILE *fp,
  5175. SOCKET sock,
  5176. SSL *ssl,
  5177. const char *buf,
  5178. int len)
  5179. {
  5180. double timeout = -1.0;
  5181. int n, nwritten = 0;
  5182. if (ctx == NULL) {
  5183. return -1;
  5184. }
  5185. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5186. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5187. }
  5188. if (timeout <= 0.0) {
  5189. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5190. }
  5191. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5192. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5193. if (n < 0) {
  5194. if (nwritten == 0) {
  5195. nwritten = -1; /* Propagate the error */
  5196. }
  5197. break;
  5198. } else if (n == 0) {
  5199. break; /* No more data to write */
  5200. } else {
  5201. nwritten += n;
  5202. len -= n;
  5203. }
  5204. }
  5205. return nwritten;
  5206. }
  5207. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5208. * Return value:
  5209. * >=0 .. number of bytes successfully read
  5210. * -1 .. timeout
  5211. * -2 .. error
  5212. */
  5213. static int
  5214. pull_inner(FILE *fp,
  5215. struct mg_connection *conn,
  5216. char *buf,
  5217. int len,
  5218. double timeout)
  5219. {
  5220. int nread, err = 0;
  5221. #if defined(_WIN32)
  5222. typedef int len_t;
  5223. #else
  5224. typedef size_t len_t;
  5225. #endif
  5226. /* We need an additional wait loop around this, because in some cases
  5227. * with TLSwe may get data from the socket but not from SSL_read.
  5228. * In this case we need to repeat at least once.
  5229. */
  5230. if (fp != NULL) {
  5231. /* Use read() instead of fread(), because if we're reading from the
  5232. * CGI pipe, fread() may block until IO buffer is filled up. We
  5233. * cannot afford to block and must pass all read bytes immediately
  5234. * to the client. */
  5235. nread = (int)read(fileno(fp), buf, (size_t)len);
  5236. err = (nread < 0) ? ERRNO : 0;
  5237. if ((nread == 0) && (len > 0)) {
  5238. /* Should get data, but got EOL */
  5239. return -2;
  5240. }
  5241. #if defined(USE_MBEDTLS)
  5242. } else if (conn->ssl != NULL) {
  5243. struct mg_pollfd pfd[1];
  5244. int to_read;
  5245. int pollres;
  5246. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5247. if (to_read > 0) {
  5248. /* We already know there is no more data buffered in conn->buf
  5249. * but there is more available in the SSL layer. So don't poll
  5250. * conn->client.sock yet. */
  5251. pollres = 1;
  5252. if (to_read > len)
  5253. to_read = len;
  5254. } else {
  5255. pfd[0].fd = conn->client.sock;
  5256. pfd[0].events = POLLIN;
  5257. to_read = len;
  5258. pollres = mg_poll(pfd,
  5259. 1,
  5260. (int)(timeout * 1000.0),
  5261. &(conn->phys_ctx->stop_flag));
  5262. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5263. return -2;
  5264. }
  5265. }
  5266. if (pollres > 0) {
  5267. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5268. if (nread <= 0) {
  5269. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5270. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5271. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5272. nread = 0;
  5273. } else {
  5274. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5275. return -2;
  5276. }
  5277. } else {
  5278. err = 0;
  5279. }
  5280. } else if (pollres < 0) {
  5281. /* Error */
  5282. return -2;
  5283. } else {
  5284. /* pollres = 0 means timeout */
  5285. nread = 0;
  5286. }
  5287. #elif !defined(NO_SSL)
  5288. } else if (conn->ssl != NULL) {
  5289. int ssl_pending;
  5290. struct mg_pollfd pfd[1];
  5291. int pollres;
  5292. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5293. /* We already know there is no more data buffered in conn->buf
  5294. * but there is more available in the SSL layer. So don't poll
  5295. * conn->client.sock yet. */
  5296. if (ssl_pending > len) {
  5297. ssl_pending = len;
  5298. }
  5299. pollres = 1;
  5300. } else {
  5301. pfd[0].fd = conn->client.sock;
  5302. pfd[0].events = POLLIN;
  5303. pollres = mg_poll(pfd,
  5304. 1,
  5305. (int)(timeout * 1000.0),
  5306. &(conn->phys_ctx->stop_flag));
  5307. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5308. return -2;
  5309. }
  5310. }
  5311. if (pollres > 0) {
  5312. ERR_clear_error();
  5313. nread =
  5314. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5315. if (nread <= 0) {
  5316. err = SSL_get_error(conn->ssl, nread);
  5317. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5318. err = ERRNO;
  5319. } else if ((err == SSL_ERROR_WANT_READ)
  5320. || (err == SSL_ERROR_WANT_WRITE)) {
  5321. nread = 0;
  5322. } else {
  5323. /* All errors should return -2 */
  5324. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5325. ERR_clear_error();
  5326. return -2;
  5327. }
  5328. ERR_clear_error();
  5329. } else {
  5330. err = 0;
  5331. }
  5332. } else if (pollres < 0) {
  5333. /* Error */
  5334. return -2;
  5335. } else {
  5336. /* pollres = 0 means timeout */
  5337. nread = 0;
  5338. }
  5339. #endif
  5340. } else {
  5341. struct mg_pollfd pfd[1];
  5342. int pollres;
  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. if (pollres > 0) {
  5353. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5354. err = (nread < 0) ? ERRNO : 0;
  5355. if (nread <= 0) {
  5356. /* shutdown of the socket at client side */
  5357. return -2;
  5358. }
  5359. } else if (pollres < 0) {
  5360. /* error callint poll */
  5361. return -2;
  5362. } else {
  5363. /* pollres = 0 means timeout */
  5364. nread = 0;
  5365. }
  5366. }
  5367. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5368. return -2;
  5369. }
  5370. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5371. /* some data has been read, or no data was requested */
  5372. return nread;
  5373. }
  5374. if (nread < 0) {
  5375. /* socket error - check errno */
  5376. #if defined(_WIN32)
  5377. if (err == WSAEWOULDBLOCK) {
  5378. /* TODO (low): check if this is still required */
  5379. /* standard case if called from close_socket_gracefully */
  5380. return -2;
  5381. } else if (err == WSAETIMEDOUT) {
  5382. /* TODO (low): check if this is still required */
  5383. /* timeout is handled by the while loop */
  5384. return 0;
  5385. } else if (err == WSAECONNABORTED) {
  5386. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5387. return -2;
  5388. } else {
  5389. DEBUG_TRACE("recv() failed, error %d", err);
  5390. return -2;
  5391. }
  5392. #else
  5393. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5394. * if the timeout is reached and if the socket was set to non-
  5395. * blocking in close_socket_gracefully, so we can not distinguish
  5396. * here. We have to wait for the timeout in both cases for now.
  5397. */
  5398. if (ERROR_TRY_AGAIN(err)) {
  5399. /* TODO (low): check if this is still required */
  5400. /* EAGAIN/EWOULDBLOCK:
  5401. * standard case if called from close_socket_gracefully
  5402. * => should return -1 */
  5403. /* or timeout occurred
  5404. * => the code must stay in the while loop */
  5405. /* EINTR can be generated on a socket with a timeout set even
  5406. * when SA_RESTART is effective for all relevant signals
  5407. * (see signal(7)).
  5408. * => stay in the while loop */
  5409. } else {
  5410. DEBUG_TRACE("recv() failed, error %d", err);
  5411. return -2;
  5412. }
  5413. #endif
  5414. }
  5415. /* Timeout occurred, but no data available. */
  5416. return -1;
  5417. }
  5418. static int
  5419. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5420. {
  5421. int n, nread = 0;
  5422. double timeout = -1.0;
  5423. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5424. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5425. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5426. }
  5427. if (timeout <= 0.0) {
  5428. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  5429. }
  5430. start_time = mg_get_current_time_ns();
  5431. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5432. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5433. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5434. if (n == -2) {
  5435. if (nread == 0) {
  5436. nread = -1; /* Propagate the error */
  5437. }
  5438. break;
  5439. } else if (n == -1) {
  5440. /* timeout */
  5441. if (timeout >= 0.0) {
  5442. now = mg_get_current_time_ns();
  5443. if ((now - start_time) <= timeout_ns) {
  5444. continue;
  5445. }
  5446. }
  5447. break;
  5448. } else if (n == 0) {
  5449. break; /* No more data to read */
  5450. } else {
  5451. nread += n;
  5452. len -= n;
  5453. }
  5454. }
  5455. return nread;
  5456. }
  5457. static void
  5458. discard_unread_request_data(struct mg_connection *conn)
  5459. {
  5460. char buf[MG_BUF_LEN];
  5461. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5462. ;
  5463. }
  5464. static int
  5465. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5466. {
  5467. int64_t content_len, n, buffered_len, nread;
  5468. int64_t len64 =
  5469. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5470. * int, we may not read more
  5471. * bytes */
  5472. const char *body;
  5473. if (conn == NULL) {
  5474. return 0;
  5475. }
  5476. /* If Content-Length is not set for a response with body data,
  5477. * we do not know in advance how much data should be read. */
  5478. content_len = conn->content_len;
  5479. if (content_len < 0) {
  5480. /* The body data is completed when the connection is closed. */
  5481. content_len = INT64_MAX;
  5482. }
  5483. nread = 0;
  5484. if (conn->consumed_content < content_len) {
  5485. /* Adjust number of bytes to read. */
  5486. int64_t left_to_read = content_len - conn->consumed_content;
  5487. if (left_to_read < len64) {
  5488. /* Do not read more than the total content length of the
  5489. * request.
  5490. */
  5491. len64 = left_to_read;
  5492. }
  5493. /* Return buffered data */
  5494. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5495. - conn->consumed_content;
  5496. if (buffered_len > 0) {
  5497. if (len64 < buffered_len) {
  5498. buffered_len = len64;
  5499. }
  5500. body = conn->buf + conn->request_len + conn->consumed_content;
  5501. memcpy(buf, body, (size_t)buffered_len);
  5502. len64 -= buffered_len;
  5503. conn->consumed_content += buffered_len;
  5504. nread += buffered_len;
  5505. buf = (char *)buf + buffered_len;
  5506. }
  5507. /* We have returned all buffered data. Read new data from the remote
  5508. * socket.
  5509. */
  5510. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5511. conn->consumed_content += n;
  5512. nread += n;
  5513. } else {
  5514. nread = ((nread > 0) ? nread : n);
  5515. }
  5516. }
  5517. return (int)nread;
  5518. }
  5519. /* Forward declarations */
  5520. static void handle_request(struct mg_connection *);
  5521. static void log_access(const struct mg_connection *);
  5522. /* Handle request, update statistics and call access log */
  5523. static void
  5524. handle_request_stat_log(struct mg_connection *conn)
  5525. {
  5526. #if defined(USE_SERVER_STATS)
  5527. struct timespec tnow;
  5528. conn->conn_state = 4; /* processing */
  5529. #endif
  5530. handle_request(conn);
  5531. #if defined(USE_SERVER_STATS)
  5532. conn->conn_state = 5; /* processed */
  5533. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5534. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5535. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5536. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5537. conn->num_bytes_sent);
  5538. #endif
  5539. DEBUG_TRACE("%s", "handle_request done");
  5540. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5541. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5542. DEBUG_TRACE("%s", "end_request callback done");
  5543. }
  5544. log_access(conn);
  5545. }
  5546. #if defined(USE_HTTP2)
  5547. #if defined(NO_SSL)
  5548. #error "HTTP2 requires ALPN, APLN requires SSL/TLS"
  5549. #endif
  5550. #define USE_ALPN
  5551. #include "mod_http2.inl"
  5552. /* Not supported with HTTP/2 */
  5553. #define HTTP1_only \
  5554. { \
  5555. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5556. http2_must_use_http1(conn); \
  5557. return; \
  5558. } \
  5559. }
  5560. #else
  5561. #define HTTP1_only
  5562. #endif
  5563. int
  5564. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5565. {
  5566. if (len > INT_MAX) {
  5567. len = INT_MAX;
  5568. }
  5569. if (conn == NULL) {
  5570. return 0;
  5571. }
  5572. if (conn->is_chunked) {
  5573. size_t all_read = 0;
  5574. while (len > 0) {
  5575. if (conn->is_chunked >= 3) {
  5576. /* No more data left to read */
  5577. return 0;
  5578. }
  5579. if (conn->is_chunked != 1) {
  5580. /* Has error */
  5581. return -1;
  5582. }
  5583. if (conn->consumed_content != conn->content_len) {
  5584. /* copy from the current chunk */
  5585. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5586. if (read_ret < 1) {
  5587. /* read error */
  5588. conn->is_chunked = 2;
  5589. return -1;
  5590. }
  5591. all_read += (size_t)read_ret;
  5592. len -= (size_t)read_ret;
  5593. if (conn->consumed_content == conn->content_len) {
  5594. /* Add data bytes in the current chunk have been read,
  5595. * so we are expecting \r\n now. */
  5596. char x[2];
  5597. conn->content_len += 2;
  5598. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5599. || (x[1] != '\n')) {
  5600. /* Protocol violation */
  5601. conn->is_chunked = 2;
  5602. return -1;
  5603. }
  5604. }
  5605. } else {
  5606. /* fetch a new chunk */
  5607. size_t i;
  5608. char lenbuf[64];
  5609. char *end = NULL;
  5610. unsigned long chunkSize = 0;
  5611. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5612. conn->content_len++;
  5613. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5614. lenbuf[i] = 0;
  5615. }
  5616. if ((i > 0) && (lenbuf[i] == '\r')
  5617. && (lenbuf[i - 1] != '\r')) {
  5618. continue;
  5619. }
  5620. if ((i > 1) && (lenbuf[i] == '\n')
  5621. && (lenbuf[i - 1] == '\r')) {
  5622. lenbuf[i + 1] = 0;
  5623. chunkSize = strtoul(lenbuf, &end, 16);
  5624. if (chunkSize == 0) {
  5625. /* regular end of content */
  5626. conn->is_chunked = 3;
  5627. }
  5628. break;
  5629. }
  5630. if (!isxdigit((unsigned char)lenbuf[i])) {
  5631. /* illegal character for chunk length */
  5632. conn->is_chunked = 2;
  5633. return -1;
  5634. }
  5635. }
  5636. if ((end == NULL) || (*end != '\r')) {
  5637. /* chunksize not set correctly */
  5638. conn->is_chunked = 2;
  5639. return -1;
  5640. }
  5641. if (chunkSize == 0) {
  5642. /* try discarding trailer for keep-alive */
  5643. conn->content_len += 2;
  5644. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5645. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5646. conn->is_chunked = 4;
  5647. }
  5648. break;
  5649. }
  5650. /* append a new chunk */
  5651. conn->content_len += (int64_t)chunkSize;
  5652. }
  5653. }
  5654. return (int)all_read;
  5655. }
  5656. return mg_read_inner(conn, buf, len);
  5657. }
  5658. int
  5659. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5660. {
  5661. time_t now;
  5662. int n, total, allowed;
  5663. if (conn == NULL) {
  5664. return 0;
  5665. }
  5666. if (len > INT_MAX) {
  5667. return -1;
  5668. }
  5669. /* Mark connection as "data sent" */
  5670. conn->request_state = 10;
  5671. #if defined(USE_HTTP2)
  5672. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5673. http2_data_frame_head(conn, len, 0);
  5674. }
  5675. #endif
  5676. if (conn->throttle > 0) {
  5677. if ((now = time(NULL)) != conn->last_throttle_time) {
  5678. conn->last_throttle_time = now;
  5679. conn->last_throttle_bytes = 0;
  5680. }
  5681. allowed = conn->throttle - conn->last_throttle_bytes;
  5682. if (allowed > (int)len) {
  5683. allowed = (int)len;
  5684. }
  5685. total = push_all(conn->phys_ctx,
  5686. NULL,
  5687. conn->client.sock,
  5688. conn->ssl,
  5689. (const char *)buf,
  5690. allowed);
  5691. if (total == allowed) {
  5692. buf = (const char *)buf + total;
  5693. conn->last_throttle_bytes += total;
  5694. while ((total < (int)len)
  5695. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5696. allowed = (conn->throttle > ((int)len - total))
  5697. ? (int)len - total
  5698. : conn->throttle;
  5699. n = push_all(conn->phys_ctx,
  5700. NULL,
  5701. conn->client.sock,
  5702. conn->ssl,
  5703. (const char *)buf,
  5704. allowed);
  5705. if (n != allowed) {
  5706. break;
  5707. }
  5708. sleep(1);
  5709. conn->last_throttle_bytes = allowed;
  5710. conn->last_throttle_time = time(NULL);
  5711. buf = (const char *)buf + n;
  5712. total += n;
  5713. }
  5714. }
  5715. } else {
  5716. total = push_all(conn->phys_ctx,
  5717. NULL,
  5718. conn->client.sock,
  5719. conn->ssl,
  5720. (const char *)buf,
  5721. (int)len);
  5722. }
  5723. if (total > 0) {
  5724. conn->num_bytes_sent += total;
  5725. }
  5726. return total;
  5727. }
  5728. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5729. int
  5730. mg_send_chunk(struct mg_connection *conn,
  5731. const char *chunk,
  5732. unsigned int chunk_len)
  5733. {
  5734. char lenbuf[16];
  5735. size_t lenbuf_len;
  5736. int ret;
  5737. int t;
  5738. /* First store the length information in a text buffer. */
  5739. sprintf(lenbuf, "%x\r\n", chunk_len);
  5740. lenbuf_len = strlen(lenbuf);
  5741. /* Then send length information, chunk and terminating \r\n. */
  5742. ret = mg_write(conn, lenbuf, lenbuf_len);
  5743. if (ret != (int)lenbuf_len) {
  5744. return -1;
  5745. }
  5746. t = ret;
  5747. ret = mg_write(conn, chunk, chunk_len);
  5748. if (ret != (int)chunk_len) {
  5749. return -1;
  5750. }
  5751. t += ret;
  5752. ret = mg_write(conn, "\r\n", 2);
  5753. if (ret != 2) {
  5754. return -1;
  5755. }
  5756. t += ret;
  5757. return t;
  5758. }
  5759. #if defined(GCC_DIAGNOSTIC)
  5760. /* This block forwards format strings to printf implementations,
  5761. * so we need to disable the format-nonliteral warning. */
  5762. #pragma GCC diagnostic push
  5763. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5764. #endif
  5765. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5766. static int
  5767. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5768. {
  5769. va_list ap_copy;
  5770. size_t size = MG_BUF_LEN / 4;
  5771. int len = -1;
  5772. *buf = NULL;
  5773. while (len < 0) {
  5774. if (*buf) {
  5775. mg_free(*buf);
  5776. }
  5777. size *= 4;
  5778. *buf = (char *)mg_malloc(size);
  5779. if (!*buf) {
  5780. break;
  5781. }
  5782. va_copy(ap_copy, ap);
  5783. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5784. va_end(ap_copy);
  5785. (*buf)[size - 1] = 0;
  5786. }
  5787. return len;
  5788. }
  5789. /* Print message to buffer. If buffer is large enough to hold the message,
  5790. * return buffer. If buffer is to small, allocate large enough buffer on
  5791. * heap,
  5792. * and return allocated buffer. */
  5793. static int
  5794. alloc_vprintf(char **out_buf,
  5795. char *prealloc_buf,
  5796. size_t prealloc_size,
  5797. const char *fmt,
  5798. va_list ap)
  5799. {
  5800. va_list ap_copy;
  5801. int len;
  5802. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5803. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5804. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5805. * Therefore, we make two passes: on first pass, get required message
  5806. * length.
  5807. * On second pass, actually print the message. */
  5808. va_copy(ap_copy, ap);
  5809. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5810. va_end(ap_copy);
  5811. if (len < 0) {
  5812. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5813. * Switch to alternative code path that uses incremental
  5814. * allocations.
  5815. */
  5816. va_copy(ap_copy, ap);
  5817. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5818. va_end(ap_copy);
  5819. } else if ((size_t)(len) >= prealloc_size) {
  5820. /* The pre-allocated buffer not large enough. */
  5821. /* Allocate a new buffer. */
  5822. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5823. if (!*out_buf) {
  5824. /* Allocation failed. Return -1 as "out of memory" error. */
  5825. return -1;
  5826. }
  5827. /* Buffer allocation successful. Store the string there. */
  5828. va_copy(ap_copy, ap);
  5829. IGNORE_UNUSED_RESULT(
  5830. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5831. va_end(ap_copy);
  5832. } else {
  5833. /* The pre-allocated buffer is large enough.
  5834. * Use it to store the string and return the address. */
  5835. va_copy(ap_copy, ap);
  5836. IGNORE_UNUSED_RESULT(
  5837. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5838. va_end(ap_copy);
  5839. *out_buf = prealloc_buf;
  5840. }
  5841. return len;
  5842. }
  5843. #if defined(GCC_DIAGNOSTIC)
  5844. /* Enable format-nonliteral warning again. */
  5845. #pragma GCC diagnostic pop
  5846. #endif
  5847. static int
  5848. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5849. {
  5850. char mem[MG_BUF_LEN];
  5851. char *buf = NULL;
  5852. int len;
  5853. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5854. len = mg_write(conn, buf, (size_t)len);
  5855. }
  5856. if (buf != mem) {
  5857. mg_free(buf);
  5858. }
  5859. return len;
  5860. }
  5861. int
  5862. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5863. {
  5864. va_list ap;
  5865. int result;
  5866. va_start(ap, fmt);
  5867. result = mg_vprintf(conn, fmt, ap);
  5868. va_end(ap);
  5869. return result;
  5870. }
  5871. int
  5872. mg_url_decode(const char *src,
  5873. int src_len,
  5874. char *dst,
  5875. int dst_len,
  5876. int is_form_url_encoded)
  5877. {
  5878. int i, j, a, b;
  5879. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5880. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5881. if ((i < src_len - 2) && (src[i] == '%')
  5882. && isxdigit((unsigned char)src[i + 1])
  5883. && isxdigit((unsigned char)src[i + 2])) {
  5884. a = tolower((unsigned char)src[i + 1]);
  5885. b = tolower((unsigned char)src[i + 2]);
  5886. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5887. i += 2;
  5888. } else if (is_form_url_encoded && (src[i] == '+')) {
  5889. dst[j] = ' ';
  5890. } else {
  5891. dst[j] = src[i];
  5892. }
  5893. }
  5894. dst[j] = '\0'; /* Null-terminate the destination */
  5895. return (i >= src_len) ? j : -1;
  5896. }
  5897. /* form url decoding of an entire string */
  5898. static void
  5899. url_decode_in_place(char *buf)
  5900. {
  5901. int len = (int)strlen(buf);
  5902. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  5903. }
  5904. int
  5905. mg_get_var(const char *data,
  5906. size_t data_len,
  5907. const char *name,
  5908. char *dst,
  5909. size_t dst_len)
  5910. {
  5911. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5912. }
  5913. int
  5914. mg_get_var2(const char *data,
  5915. size_t data_len,
  5916. const char *name,
  5917. char *dst,
  5918. size_t dst_len,
  5919. size_t occurrence)
  5920. {
  5921. const char *p, *e, *s;
  5922. size_t name_len;
  5923. int len;
  5924. if ((dst == NULL) || (dst_len == 0)) {
  5925. len = -2;
  5926. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5927. len = -1;
  5928. dst[0] = '\0';
  5929. } else {
  5930. name_len = strlen(name);
  5931. e = data + data_len;
  5932. len = -1;
  5933. dst[0] = '\0';
  5934. /* data is "var1=val1&var2=val2...". Find variable first */
  5935. for (p = data; p + name_len < e; p++) {
  5936. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5937. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5938. /* Point p to variable value */
  5939. p += name_len + 1;
  5940. /* Point s to the end of the value */
  5941. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5942. if (s == NULL) {
  5943. s = e;
  5944. }
  5945. DEBUG_ASSERT(s >= p);
  5946. if (s < p) {
  5947. return -3;
  5948. }
  5949. /* Decode variable into destination buffer */
  5950. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5951. /* Redirect error code from -1 to -2 (destination buffer too
  5952. * small). */
  5953. if (len == -1) {
  5954. len = -2;
  5955. }
  5956. break;
  5957. }
  5958. }
  5959. }
  5960. return len;
  5961. }
  5962. /* split a string "key1=val1&key2=val2" into key/value pairs */
  5963. int
  5964. mg_split_form_urlencoded(char *data,
  5965. struct mg_header *form_fields,
  5966. unsigned num_form_fields)
  5967. {
  5968. char *b;
  5969. int i;
  5970. int num = 0;
  5971. if (data == NULL) {
  5972. /* parameter error */
  5973. return -1;
  5974. }
  5975. if ((form_fields == NULL) && (num_form_fields == 0)) {
  5976. /* determine the number of expected fields */
  5977. if (data[0] == 0) {
  5978. return 0;
  5979. }
  5980. /* count number of & to return the number of key-value-pairs */
  5981. num = 1;
  5982. while (*data) {
  5983. if (*data == '&') {
  5984. num++;
  5985. }
  5986. data++;
  5987. }
  5988. return num;
  5989. }
  5990. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  5991. /* parameter error */
  5992. return -1;
  5993. }
  5994. for (i = 0; i < (int)num_form_fields; i++) {
  5995. /* extract key-value pairs from input data */
  5996. while ((*data == ' ') || (*data == '\t')) {
  5997. /* skip initial spaces */
  5998. data++;
  5999. }
  6000. if (*data == 0) {
  6001. /* end of string reached */
  6002. break;
  6003. }
  6004. form_fields[num].name = data;
  6005. /* find & or = */
  6006. b = data;
  6007. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6008. b++;
  6009. }
  6010. if (*b == 0) {
  6011. /* last key without value */
  6012. form_fields[num].value = NULL;
  6013. } else if (*b == '&') {
  6014. /* mid key without value */
  6015. form_fields[num].value = NULL;
  6016. } else {
  6017. /* terminate string */
  6018. *b = 0;
  6019. /* value starts after '=' */
  6020. data = b + 1;
  6021. form_fields[num].value = data;
  6022. }
  6023. /* new field is stored */
  6024. num++;
  6025. /* find a next key */
  6026. b = strchr(data, '&');
  6027. if (b == 0) {
  6028. /* no more data */
  6029. break;
  6030. } else {
  6031. /* terminate value of last field at '&' */
  6032. *b = 0;
  6033. /* next key-value-pairs starts after '&' */
  6034. data = b + 1;
  6035. }
  6036. }
  6037. /* Decode all values */
  6038. for (i = 0; i < num; i++) {
  6039. if (form_fields[i].name) {
  6040. url_decode_in_place((char *)form_fields[i].name);
  6041. }
  6042. if (form_fields[i].value) {
  6043. url_decode_in_place((char *)form_fields[i].value);
  6044. }
  6045. }
  6046. /* return number of fields found */
  6047. return num;
  6048. }
  6049. /* HCP24: some changes to compare hole var_name */
  6050. int
  6051. mg_get_cookie(const char *cookie_header,
  6052. const char *var_name,
  6053. char *dst,
  6054. size_t dst_size)
  6055. {
  6056. const char *s, *p, *end;
  6057. int name_len, len = -1;
  6058. if ((dst == NULL) || (dst_size == 0)) {
  6059. return -2;
  6060. }
  6061. dst[0] = '\0';
  6062. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6063. return -1;
  6064. }
  6065. name_len = (int)strlen(var_name);
  6066. end = s + strlen(s);
  6067. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6068. if (s[name_len] == '=') {
  6069. /* HCP24: now check is it a substring or a full cookie name */
  6070. if ((s == cookie_header) || (s[-1] == ' ')) {
  6071. s += name_len + 1;
  6072. if ((p = strchr(s, ' ')) == NULL) {
  6073. p = end;
  6074. }
  6075. if (p[-1] == ';') {
  6076. p--;
  6077. }
  6078. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6079. s++;
  6080. p--;
  6081. }
  6082. if ((size_t)(p - s) < dst_size) {
  6083. len = (int)(p - s);
  6084. mg_strlcpy(dst, s, (size_t)len + 1);
  6085. } else {
  6086. len = -3;
  6087. }
  6088. break;
  6089. }
  6090. }
  6091. }
  6092. return len;
  6093. }
  6094. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6095. static void
  6096. base64_encode(const unsigned char *src, int src_len, char *dst)
  6097. {
  6098. static const char *b64 =
  6099. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6100. int i, j, a, b, c;
  6101. for (i = j = 0; i < src_len; i += 3) {
  6102. a = src[i];
  6103. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6104. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6105. dst[j++] = b64[a >> 2];
  6106. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6107. if (i + 1 < src_len) {
  6108. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6109. }
  6110. if (i + 2 < src_len) {
  6111. dst[j++] = b64[c & 63];
  6112. }
  6113. }
  6114. while (j % 4 != 0) {
  6115. dst[j++] = '=';
  6116. }
  6117. dst[j++] = '\0';
  6118. }
  6119. #endif
  6120. #if defined(USE_LUA)
  6121. static unsigned char
  6122. b64reverse(char letter)
  6123. {
  6124. if ((letter >= 'A') && (letter <= 'Z')) {
  6125. return letter - 'A';
  6126. }
  6127. if ((letter >= 'a') && (letter <= 'z')) {
  6128. return letter - 'a' + 26;
  6129. }
  6130. if ((letter >= '0') && (letter <= '9')) {
  6131. return letter - '0' + 52;
  6132. }
  6133. if (letter == '+') {
  6134. return 62;
  6135. }
  6136. if (letter == '/') {
  6137. return 63;
  6138. }
  6139. if (letter == '=') {
  6140. return 255; /* normal end */
  6141. }
  6142. return 254; /* error */
  6143. }
  6144. static int
  6145. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6146. {
  6147. int i;
  6148. unsigned char a, b, c, d;
  6149. *dst_len = 0;
  6150. for (i = 0; i < src_len; i += 4) {
  6151. a = b64reverse(src[i]);
  6152. if (a >= 254) {
  6153. return i;
  6154. }
  6155. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6156. if (b >= 254) {
  6157. return i + 1;
  6158. }
  6159. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6160. if (c == 254) {
  6161. return i + 2;
  6162. }
  6163. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6164. if (d == 254) {
  6165. return i + 3;
  6166. }
  6167. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6168. if (c != 255) {
  6169. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6170. if (d != 255) {
  6171. dst[(*dst_len)++] = (c << 6) + d;
  6172. }
  6173. }
  6174. }
  6175. return -1;
  6176. }
  6177. #endif
  6178. static int
  6179. is_put_or_delete_method(const struct mg_connection *conn)
  6180. {
  6181. if (conn) {
  6182. const char *s = conn->request_info.request_method;
  6183. return (s != NULL)
  6184. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6185. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6186. }
  6187. return 0;
  6188. }
  6189. #if !defined(NO_FILES)
  6190. static int
  6191. extention_matches_script(
  6192. struct mg_connection *conn, /* in: request (must be valid) */
  6193. const char *filename /* in: filename (must be valid) */
  6194. )
  6195. {
  6196. #if !defined(NO_CGI)
  6197. unsigned char cgi_config_idx, inc, max;
  6198. #endif
  6199. #if defined(USE_LUA)
  6200. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6201. filename)
  6202. > 0) {
  6203. return 1;
  6204. }
  6205. #endif
  6206. #if defined(USE_DUKTAPE)
  6207. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6208. filename)
  6209. > 0) {
  6210. return 1;
  6211. }
  6212. #endif
  6213. #if !defined(NO_CGI)
  6214. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6215. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6216. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6217. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6218. && (match_prefix_strlen(
  6219. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6220. filename)
  6221. > 0)) {
  6222. return 1;
  6223. }
  6224. }
  6225. #endif
  6226. /* filename and conn could be unused, if all preocessor conditions
  6227. * are false (no script language supported). */
  6228. (void)filename;
  6229. (void)conn;
  6230. return 0;
  6231. }
  6232. static int
  6233. extention_matches_template_text(
  6234. struct mg_connection *conn, /* in: request (must be valid) */
  6235. const char *filename /* in: filename (must be valid) */
  6236. )
  6237. {
  6238. #if defined(USE_LUA)
  6239. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6240. filename)
  6241. > 0) {
  6242. return 1;
  6243. }
  6244. #endif
  6245. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6246. > 0) {
  6247. return 1;
  6248. }
  6249. return 0;
  6250. }
  6251. /* For given directory path, substitute it to valid index file.
  6252. * Return 1 if index file has been found, 0 if not found.
  6253. * If the file is found, it's stats is returned in stp. */
  6254. static int
  6255. substitute_index_file(struct mg_connection *conn,
  6256. char *path,
  6257. size_t path_len,
  6258. struct mg_file_stat *filestat)
  6259. {
  6260. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6261. struct vec filename_vec;
  6262. size_t n = strlen(path);
  6263. int found = 0;
  6264. /* The 'path' given to us points to the directory. Remove all trailing
  6265. * directory separator characters from the end of the path, and
  6266. * then append single directory separator character. */
  6267. while ((n > 0) && (path[n - 1] == '/')) {
  6268. n--;
  6269. }
  6270. path[n] = '/';
  6271. /* Traverse index files list. For each entry, append it to the given
  6272. * path and see if the file exists. If it exists, break the loop */
  6273. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6274. /* Ignore too long entries that may overflow path buffer */
  6275. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6276. continue;
  6277. }
  6278. /* Prepare full path to the index file */
  6279. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6280. /* Does it exist? */
  6281. if (mg_stat(conn, path, filestat)) {
  6282. /* Yes it does, break the loop */
  6283. found = 1;
  6284. break;
  6285. }
  6286. }
  6287. /* If no index file exists, restore directory path */
  6288. if (!found) {
  6289. path[n] = '\0';
  6290. }
  6291. return found;
  6292. }
  6293. #endif
  6294. static void
  6295. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6296. char *filename, /* out: filename */
  6297. size_t filename_buf_len, /* in: size of filename buffer */
  6298. struct mg_file_stat *filestat, /* out: file status structure */
  6299. int *is_found, /* out: file found (directly) */
  6300. int *is_script_resource, /* out: handled by a script? */
  6301. int *is_websocket_request, /* out: websocket connetion? */
  6302. int *is_put_or_delete_request, /* out: put/delete a file? */
  6303. int *is_template_text /* out: SSI file or LSP file? */
  6304. )
  6305. {
  6306. char const *accept_encoding;
  6307. #if !defined(NO_FILES)
  6308. const char *uri = conn->request_info.local_uri;
  6309. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6310. const char *rewrite;
  6311. struct vec a, b;
  6312. ptrdiff_t match_len;
  6313. char gz_path[UTF8_PATH_MAX];
  6314. int truncated;
  6315. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6316. char *tmp_str;
  6317. size_t tmp_str_len, sep_pos;
  6318. int allow_substitute_script_subresources;
  6319. #endif
  6320. #else
  6321. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6322. #endif
  6323. /* Step 1: Set all initially unknown outputs to zero */
  6324. memset(filestat, 0, sizeof(*filestat));
  6325. *filename = 0;
  6326. *is_found = 0;
  6327. *is_script_resource = 0;
  6328. *is_template_text = 0;
  6329. /* Step 2: Check if the request attempts to modify the file system */
  6330. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6331. /* Step 3: Check if it is a websocket request, and modify the document
  6332. * root if required */
  6333. #if defined(USE_WEBSOCKET)
  6334. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6335. #if !defined(NO_FILES)
  6336. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6337. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6338. }
  6339. #endif /* !NO_FILES */
  6340. #else /* USE_WEBSOCKET */
  6341. *is_websocket_request = 0;
  6342. #endif /* USE_WEBSOCKET */
  6343. /* Step 4: Check if gzip encoded response is allowed */
  6344. conn->accept_gzip = 0;
  6345. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6346. if (strstr(accept_encoding, "gzip") != NULL) {
  6347. conn->accept_gzip = 1;
  6348. }
  6349. }
  6350. #if !defined(NO_FILES)
  6351. /* Step 5: If there is no root directory, don't look for files. */
  6352. /* Note that root == NULL is a regular use case here. This occurs,
  6353. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6354. * config is not required. */
  6355. if (root == NULL) {
  6356. /* all file related outputs have already been set to 0, just return
  6357. */
  6358. return;
  6359. }
  6360. /* Step 6: Determine the local file path from the root path and the
  6361. * request uri. */
  6362. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6363. * part of the path one byte on the right. */
  6364. truncated = 0;
  6365. mg_snprintf(
  6366. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6367. if (truncated) {
  6368. goto interpret_cleanup;
  6369. }
  6370. /* Step 7: URI rewriting */
  6371. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6372. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6373. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6374. mg_snprintf(conn,
  6375. &truncated,
  6376. filename,
  6377. filename_buf_len - 1,
  6378. "%.*s%s",
  6379. (int)b.len,
  6380. b.ptr,
  6381. uri + match_len);
  6382. break;
  6383. }
  6384. }
  6385. if (truncated) {
  6386. goto interpret_cleanup;
  6387. }
  6388. /* Step 8: Check if the file exists at the server */
  6389. /* Local file path and name, corresponding to requested URI
  6390. * is now stored in "filename" variable. */
  6391. if (mg_stat(conn, filename, filestat)) {
  6392. int uri_len = (int)strlen(uri);
  6393. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6394. /* 8.1: File exists. */
  6395. *is_found = 1;
  6396. /* 8.2: Check if it is a script type. */
  6397. if (extention_matches_script(conn, filename)) {
  6398. /* The request addresses a CGI resource, Lua script or
  6399. * server-side javascript.
  6400. * The URI corresponds to the script itself (like
  6401. * /path/script.cgi), and there is no additional resource
  6402. * path (like /path/script.cgi/something).
  6403. * Requests that modify (replace or delete) a resource, like
  6404. * PUT and DELETE requests, should replace/delete the script
  6405. * file.
  6406. * Requests that read or write from/to a resource, like GET and
  6407. * POST requests, should call the script and return the
  6408. * generated response. */
  6409. *is_script_resource = (!*is_put_or_delete_request);
  6410. }
  6411. /* 8.3: Check for SSI and LSP files */
  6412. if (extention_matches_template_text(conn, filename)) {
  6413. /* Same as above, but for *.lsp and *.shtml files. */
  6414. /* A "template text" is a file delivered directly to the client,
  6415. * but with some text tags replaced by dynamic content.
  6416. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6417. * (LP, LSP) file. */
  6418. *is_template_text = (!*is_put_or_delete_request);
  6419. }
  6420. /* 8.4: If the request target is a directory, there could be
  6421. * a substitute file (index.html, index.cgi, ...). */
  6422. if (filestat->is_directory && is_uri_end_slash) {
  6423. /* Use a local copy here, since substitute_index_file will
  6424. * change the content of the file status */
  6425. struct mg_file_stat tmp_filestat;
  6426. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6427. if (substitute_index_file(
  6428. conn, filename, filename_buf_len, &tmp_filestat)) {
  6429. /* Substitute file found. Copy stat to the output, then
  6430. * check if the file is a script file */
  6431. *filestat = tmp_filestat;
  6432. if (extention_matches_script(conn, filename)) {
  6433. /* Substitute file is a script file */
  6434. *is_script_resource = 1;
  6435. } else if (extention_matches_template_text(conn, filename)) {
  6436. /* Substitute file is a LSP or SSI file */
  6437. *is_template_text = 1;
  6438. } else {
  6439. /* Substitute file is a regular file */
  6440. *is_script_resource = 0;
  6441. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6442. }
  6443. }
  6444. /* If there is no substitute file, the server could return
  6445. * a directory listing in a later step */
  6446. }
  6447. return;
  6448. }
  6449. /* Step 9: Check for zipped files: */
  6450. /* If we can't find the actual file, look for the file
  6451. * with the same name but a .gz extension. If we find it,
  6452. * use that and set the gzipped flag in the file struct
  6453. * to indicate that the response need to have the content-
  6454. * encoding: gzip header.
  6455. * We can only do this if the browser declares support. */
  6456. if (conn->accept_gzip) {
  6457. mg_snprintf(
  6458. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6459. if (truncated) {
  6460. goto interpret_cleanup;
  6461. }
  6462. if (mg_stat(conn, gz_path, filestat)) {
  6463. if (filestat) {
  6464. filestat->is_gzipped = 1;
  6465. *is_found = 1;
  6466. }
  6467. /* Currently gz files can not be scripts. */
  6468. return;
  6469. }
  6470. }
  6471. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6472. /* Step 10: Script resources may handle sub-resources */
  6473. /* Support PATH_INFO for CGI scripts. */
  6474. tmp_str_len = strlen(filename);
  6475. tmp_str =
  6476. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6477. if (!tmp_str) {
  6478. /* Out of memory */
  6479. goto interpret_cleanup;
  6480. }
  6481. memcpy(tmp_str, filename, tmp_str_len + 1);
  6482. /* Check config, if index scripts may have sub-resources */
  6483. allow_substitute_script_subresources =
  6484. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6485. "yes");
  6486. sep_pos = tmp_str_len;
  6487. while (sep_pos > 0) {
  6488. sep_pos--;
  6489. if (tmp_str[sep_pos] == '/') {
  6490. int is_script = 0, does_exist = 0;
  6491. tmp_str[sep_pos] = 0;
  6492. if (tmp_str[0]) {
  6493. is_script = extention_matches_script(conn, tmp_str);
  6494. does_exist = mg_stat(conn, tmp_str, filestat);
  6495. }
  6496. if (does_exist && is_script) {
  6497. filename[sep_pos] = 0;
  6498. memmove(filename + sep_pos + 2,
  6499. filename + sep_pos + 1,
  6500. strlen(filename + sep_pos + 1) + 1);
  6501. conn->path_info = filename + sep_pos + 1;
  6502. filename[sep_pos + 1] = '/';
  6503. *is_script_resource = 1;
  6504. *is_found = 1;
  6505. break;
  6506. }
  6507. if (allow_substitute_script_subresources) {
  6508. if (substitute_index_file(
  6509. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6510. /* some intermediate directory has an index file */
  6511. if (extention_matches_script(conn, tmp_str)) {
  6512. size_t script_name_len = strlen(tmp_str);
  6513. /* subres_name read before this memory locatio will be
  6514. overwritten */
  6515. char *subres_name = filename + sep_pos;
  6516. size_t subres_name_len = strlen(subres_name);
  6517. DEBUG_TRACE("Substitute script %s serving path %s",
  6518. tmp_str,
  6519. filename);
  6520. /* this index file is a script */
  6521. if ((script_name_len + subres_name_len + 2)
  6522. >= filename_buf_len) {
  6523. mg_free(tmp_str);
  6524. goto interpret_cleanup;
  6525. }
  6526. conn->path_info =
  6527. filename + script_name_len + 1; /* new target */
  6528. memmove(conn->path_info, subres_name, subres_name_len);
  6529. conn->path_info[subres_name_len] = 0;
  6530. memcpy(filename, tmp_str, script_name_len + 1);
  6531. *is_script_resource = 1;
  6532. *is_found = 1;
  6533. break;
  6534. } else {
  6535. DEBUG_TRACE("Substitute file %s serving path %s",
  6536. tmp_str,
  6537. filename);
  6538. /* non-script files will not have sub-resources */
  6539. filename[sep_pos] = 0;
  6540. conn->path_info = 0;
  6541. *is_script_resource = 0;
  6542. *is_found = 0;
  6543. break;
  6544. }
  6545. }
  6546. }
  6547. tmp_str[sep_pos] = '/';
  6548. }
  6549. }
  6550. mg_free(tmp_str);
  6551. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6552. #endif /* !defined(NO_FILES) */
  6553. return;
  6554. #if !defined(NO_FILES)
  6555. /* Reset all outputs */
  6556. interpret_cleanup:
  6557. memset(filestat, 0, sizeof(*filestat));
  6558. *filename = 0;
  6559. *is_found = 0;
  6560. *is_script_resource = 0;
  6561. *is_websocket_request = 0;
  6562. *is_put_or_delete_request = 0;
  6563. #endif /* !defined(NO_FILES) */
  6564. }
  6565. /* Check whether full request is buffered. Return:
  6566. * -1 if request or response is malformed
  6567. * 0 if request or response is not yet fully buffered
  6568. * >0 actual request length, including last \r\n\r\n */
  6569. static int
  6570. get_http_header_len(const char *buf, int buflen)
  6571. {
  6572. int i;
  6573. for (i = 0; i < buflen; i++) {
  6574. /* Do an unsigned comparison in some conditions below */
  6575. const unsigned char c = (unsigned char)buf[i];
  6576. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6577. && !isprint(c)) {
  6578. /* abort scan as soon as one malformed character is found */
  6579. return -1;
  6580. }
  6581. if (i < buflen - 1) {
  6582. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6583. /* Two newline, no carriage return - not standard compliant,
  6584. * but it should be accepted */
  6585. return i + 2;
  6586. }
  6587. }
  6588. if (i < buflen - 3) {
  6589. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6590. && (buf[i + 3] == '\n')) {
  6591. /* Two \r\n - standard compliant */
  6592. return i + 4;
  6593. }
  6594. }
  6595. }
  6596. return 0;
  6597. }
  6598. #if !defined(NO_CACHING)
  6599. /* Convert month to the month number. Return -1 on error, or month number */
  6600. static int
  6601. get_month_index(const char *s)
  6602. {
  6603. size_t i;
  6604. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6605. if (!strcmp(s, month_names[i])) {
  6606. return (int)i;
  6607. }
  6608. }
  6609. return -1;
  6610. }
  6611. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6612. static time_t
  6613. parse_date_string(const char *datetime)
  6614. {
  6615. char month_str[32] = {0};
  6616. int second, minute, hour, day, month, year;
  6617. time_t result = (time_t)0;
  6618. struct tm tm;
  6619. if ((sscanf(datetime,
  6620. "%d/%3s/%d %d:%d:%d",
  6621. &day,
  6622. month_str,
  6623. &year,
  6624. &hour,
  6625. &minute,
  6626. &second)
  6627. == 6)
  6628. || (sscanf(datetime,
  6629. "%d %3s %d %d:%d:%d",
  6630. &day,
  6631. month_str,
  6632. &year,
  6633. &hour,
  6634. &minute,
  6635. &second)
  6636. == 6)
  6637. || (sscanf(datetime,
  6638. "%*3s, %d %3s %d %d:%d:%d",
  6639. &day,
  6640. month_str,
  6641. &year,
  6642. &hour,
  6643. &minute,
  6644. &second)
  6645. == 6)
  6646. || (sscanf(datetime,
  6647. "%d-%3s-%d %d:%d:%d",
  6648. &day,
  6649. month_str,
  6650. &year,
  6651. &hour,
  6652. &minute,
  6653. &second)
  6654. == 6)) {
  6655. month = get_month_index(month_str);
  6656. if ((month >= 0) && (year >= 1970)) {
  6657. memset(&tm, 0, sizeof(tm));
  6658. tm.tm_year = year - 1900;
  6659. tm.tm_mon = month;
  6660. tm.tm_mday = day;
  6661. tm.tm_hour = hour;
  6662. tm.tm_min = minute;
  6663. tm.tm_sec = second;
  6664. result = timegm(&tm);
  6665. }
  6666. }
  6667. return result;
  6668. }
  6669. #endif /* !NO_CACHING */
  6670. /* Pre-process URIs according to RFC + protect against directory disclosure
  6671. * attacks by removing '..', excessive '/' and '\' characters */
  6672. static void
  6673. remove_dot_segments(char *inout)
  6674. {
  6675. /* Windows backend protection
  6676. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6677. * in URI by slash */
  6678. char *out_end = inout;
  6679. char *in = inout;
  6680. if (!in) {
  6681. /* Param error. */
  6682. return;
  6683. }
  6684. while (*in) {
  6685. if (*in == '\\') {
  6686. *in = '/';
  6687. }
  6688. in++;
  6689. }
  6690. /* Algorithm "remove_dot_segments" from
  6691. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  6692. /* Step 1:
  6693. * The input buffer is initialized.
  6694. * The output buffer is initialized to the empty string.
  6695. */
  6696. in = inout;
  6697. /* Step 2:
  6698. * While the input buffer is not empty, loop as follows:
  6699. */
  6700. /* Less than out_end of the inout buffer is used as output, so keep
  6701. * condition: out_end <= in */
  6702. while (*in) {
  6703. /* Step 2a:
  6704. * If the input buffer begins with a prefix of "../" or "./",
  6705. * then remove that prefix from the input buffer;
  6706. */
  6707. if (!strncmp(in, "../", 3)) {
  6708. in += 3;
  6709. } else if (!strncmp(in, "./", 2)) {
  6710. in += 2;
  6711. }
  6712. /* otherwise */
  6713. /* Step 2b:
  6714. * if the input buffer begins with a prefix of "/./" or "/.",
  6715. * where "." is a complete path segment, then replace that
  6716. * prefix with "/" in the input buffer;
  6717. */
  6718. else if (!strncmp(in, "/./", 3)) {
  6719. in += 2;
  6720. } else if (!strcmp(in, "/.")) {
  6721. in[1] = 0;
  6722. }
  6723. /* otherwise */
  6724. /* Step 2c:
  6725. * if the input buffer begins with a prefix of "/../" or "/..",
  6726. * where ".." is a complete path segment, then replace that
  6727. * prefix with "/" in the input buffer and remove the last
  6728. * segment and its preceding "/" (if any) from the output
  6729. * buffer;
  6730. */
  6731. else if (!strncmp(in, "/../", 4)) {
  6732. in += 3;
  6733. if (inout != out_end) {
  6734. /* remove last segment */
  6735. do {
  6736. out_end--;
  6737. } while ((inout != out_end) && (*out_end != '/'));
  6738. }
  6739. } else if (!strcmp(in, "/..")) {
  6740. in[1] = 0;
  6741. if (inout != out_end) {
  6742. /* remove last segment */
  6743. do {
  6744. out_end--;
  6745. } while ((inout != out_end) && (*out_end != '/'));
  6746. }
  6747. }
  6748. /* otherwise */
  6749. /* Step 2d:
  6750. * if the input buffer consists only of "." or "..", then remove
  6751. * that from the input buffer;
  6752. */
  6753. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  6754. *in = 0;
  6755. }
  6756. /* otherwise */
  6757. /* Step 2e:
  6758. * move the first path segment in the input buffer to the end of
  6759. * the output buffer, including the initial "/" character (if
  6760. * any) and any subsequent characters up to, but not including,
  6761. * the next "/" character or the end of the input buffer.
  6762. */
  6763. else {
  6764. do {
  6765. *out_end = *in;
  6766. out_end++;
  6767. in++;
  6768. } while ((*in != 0) && (*in != '/'));
  6769. }
  6770. }
  6771. /* Step 3:
  6772. * Finally, the output buffer is returned as the result of
  6773. * remove_dot_segments.
  6774. */
  6775. /* Terminate output */
  6776. *out_end = 0;
  6777. /* For Windows, the files/folders "x" and "x." (with a dot but without
  6778. * extension) are identical. Replace all "./" by "/" and remove a "." at
  6779. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  6780. * or "//" anymore.
  6781. */
  6782. out_end = in = inout;
  6783. while (*in) {
  6784. if (*in == '.') {
  6785. /* remove . at the end or preceding of / */
  6786. char *in_ahead = in;
  6787. do {
  6788. in_ahead++;
  6789. } while (*in_ahead == '.');
  6790. if (*in_ahead == '/') {
  6791. in = in_ahead;
  6792. if ((out_end != inout) && (out_end[-1] == '/')) {
  6793. /* remove generated // */
  6794. out_end--;
  6795. }
  6796. } else if (*in_ahead == 0) {
  6797. in = in_ahead;
  6798. } else {
  6799. do {
  6800. *out_end++ = '.';
  6801. in++;
  6802. } while (in != in_ahead);
  6803. }
  6804. } else if (*in == '/') {
  6805. /* replace // by / */
  6806. *out_end++ = '/';
  6807. do {
  6808. in++;
  6809. } while (*in == '/');
  6810. } else {
  6811. *out_end++ = *in;
  6812. in++;
  6813. }
  6814. }
  6815. *out_end = 0;
  6816. }
  6817. static const struct {
  6818. const char *extension;
  6819. size_t ext_len;
  6820. const char *mime_type;
  6821. } builtin_mime_types[] = {
  6822. /* IANA registered MIME types
  6823. * (http://www.iana.org/assignments/media-types)
  6824. * application types */
  6825. {".bin", 4, "application/octet-stream"},
  6826. {".deb", 4, "application/octet-stream"},
  6827. {".dmg", 4, "application/octet-stream"},
  6828. {".dll", 4, "application/octet-stream"},
  6829. {".doc", 4, "application/msword"},
  6830. {".eps", 4, "application/postscript"},
  6831. {".exe", 4, "application/octet-stream"},
  6832. {".iso", 4, "application/octet-stream"},
  6833. {".js", 3, "application/javascript"},
  6834. {".json", 5, "application/json"},
  6835. {".msi", 4, "application/octet-stream"},
  6836. {".pdf", 4, "application/pdf"},
  6837. {".ps", 3, "application/postscript"},
  6838. {".rtf", 4, "application/rtf"},
  6839. {".xhtml", 6, "application/xhtml+xml"},
  6840. {".xsl", 4, "application/xml"},
  6841. {".xslt", 5, "application/xml"},
  6842. /* fonts */
  6843. {".ttf", 4, "application/font-sfnt"},
  6844. {".cff", 4, "application/font-sfnt"},
  6845. {".otf", 4, "application/font-sfnt"},
  6846. {".aat", 4, "application/font-sfnt"},
  6847. {".sil", 4, "application/font-sfnt"},
  6848. {".pfr", 4, "application/font-tdpfr"},
  6849. {".woff", 5, "application/font-woff"},
  6850. {".woff2", 6, "application/font-woff2"},
  6851. /* audio */
  6852. {".mp3", 4, "audio/mpeg"},
  6853. {".oga", 4, "audio/ogg"},
  6854. {".ogg", 4, "audio/ogg"},
  6855. /* image */
  6856. {".gif", 4, "image/gif"},
  6857. {".ief", 4, "image/ief"},
  6858. {".jpeg", 5, "image/jpeg"},
  6859. {".jpg", 4, "image/jpeg"},
  6860. {".jpm", 4, "image/jpm"},
  6861. {".jpx", 4, "image/jpx"},
  6862. {".png", 4, "image/png"},
  6863. {".svg", 4, "image/svg+xml"},
  6864. {".tif", 4, "image/tiff"},
  6865. {".tiff", 5, "image/tiff"},
  6866. /* model */
  6867. {".wrl", 4, "model/vrml"},
  6868. /* text */
  6869. {".css", 4, "text/css"},
  6870. {".csv", 4, "text/csv"},
  6871. {".htm", 4, "text/html"},
  6872. {".html", 5, "text/html"},
  6873. {".sgm", 4, "text/sgml"},
  6874. {".shtm", 5, "text/html"},
  6875. {".shtml", 6, "text/html"},
  6876. {".txt", 4, "text/plain"},
  6877. {".xml", 4, "text/xml"},
  6878. /* video */
  6879. {".mov", 4, "video/quicktime"},
  6880. {".mp4", 4, "video/mp4"},
  6881. {".mpeg", 5, "video/mpeg"},
  6882. {".mpg", 4, "video/mpeg"},
  6883. {".ogv", 4, "video/ogg"},
  6884. {".qt", 3, "video/quicktime"},
  6885. /* not registered types
  6886. * (http://reference.sitepoint.com/html/mime-types-full,
  6887. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6888. {".arj", 4, "application/x-arj-compressed"},
  6889. {".gz", 3, "application/x-gunzip"},
  6890. {".rar", 4, "application/x-arj-compressed"},
  6891. {".swf", 4, "application/x-shockwave-flash"},
  6892. {".tar", 4, "application/x-tar"},
  6893. {".tgz", 4, "application/x-tar-gz"},
  6894. {".torrent", 8, "application/x-bittorrent"},
  6895. {".ppt", 4, "application/x-mspowerpoint"},
  6896. {".xls", 4, "application/x-msexcel"},
  6897. {".zip", 4, "application/x-zip-compressed"},
  6898. {".aac",
  6899. 4,
  6900. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6901. {".flac", 5, "audio/flac"},
  6902. {".aif", 4, "audio/x-aif"},
  6903. {".m3u", 4, "audio/x-mpegurl"},
  6904. {".mid", 4, "audio/x-midi"},
  6905. {".ra", 3, "audio/x-pn-realaudio"},
  6906. {".ram", 4, "audio/x-pn-realaudio"},
  6907. {".wav", 4, "audio/x-wav"},
  6908. {".bmp", 4, "image/bmp"},
  6909. {".ico", 4, "image/x-icon"},
  6910. {".pct", 4, "image/x-pct"},
  6911. {".pict", 5, "image/pict"},
  6912. {".rgb", 4, "image/x-rgb"},
  6913. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6914. {".asf", 4, "video/x-ms-asf"},
  6915. {".avi", 4, "video/x-msvideo"},
  6916. {".m4v", 4, "video/x-m4v"},
  6917. {NULL, 0, NULL}};
  6918. const char *
  6919. mg_get_builtin_mime_type(const char *path)
  6920. {
  6921. const char *ext;
  6922. size_t i, path_len;
  6923. path_len = strlen(path);
  6924. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6925. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6926. if ((path_len > builtin_mime_types[i].ext_len)
  6927. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6928. return builtin_mime_types[i].mime_type;
  6929. }
  6930. }
  6931. return "text/plain";
  6932. }
  6933. /* Look at the "path" extension and figure what mime type it has.
  6934. * Store mime type in the vector. */
  6935. static void
  6936. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6937. {
  6938. struct vec ext_vec, mime_vec;
  6939. const char *list, *ext;
  6940. size_t path_len;
  6941. path_len = strlen(path);
  6942. if ((conn == NULL) || (vec == NULL)) {
  6943. if (vec != NULL) {
  6944. memset(vec, '\0', sizeof(struct vec));
  6945. }
  6946. return;
  6947. }
  6948. /* Scan user-defined mime types first, in case user wants to
  6949. * override default mime types. */
  6950. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6951. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6952. /* ext now points to the path suffix */
  6953. ext = path + path_len - ext_vec.len;
  6954. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6955. *vec = mime_vec;
  6956. return;
  6957. }
  6958. }
  6959. vec->ptr = mg_get_builtin_mime_type(path);
  6960. vec->len = strlen(vec->ptr);
  6961. }
  6962. /* Stringify binary data. Output buffer must be twice as big as input,
  6963. * because each byte takes 2 bytes in string representation */
  6964. static void
  6965. bin2str(char *to, const unsigned char *p, size_t len)
  6966. {
  6967. static const char *hex = "0123456789abcdef";
  6968. for (; len--; p++) {
  6969. *to++ = hex[p[0] >> 4];
  6970. *to++ = hex[p[0] & 0x0f];
  6971. }
  6972. *to = '\0';
  6973. }
  6974. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6975. */
  6976. char *
  6977. mg_md5(char buf[33], ...)
  6978. {
  6979. md5_byte_t hash[16];
  6980. const char *p;
  6981. va_list ap;
  6982. md5_state_t ctx;
  6983. md5_init(&ctx);
  6984. va_start(ap, buf);
  6985. while ((p = va_arg(ap, const char *)) != NULL) {
  6986. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6987. }
  6988. va_end(ap);
  6989. md5_finish(&ctx, hash);
  6990. bin2str(buf, hash, sizeof(hash));
  6991. return buf;
  6992. }
  6993. /* Check the user's password, return 1 if OK */
  6994. static int
  6995. check_password(const char *method,
  6996. const char *ha1,
  6997. const char *uri,
  6998. const char *nonce,
  6999. const char *nc,
  7000. const char *cnonce,
  7001. const char *qop,
  7002. const char *response)
  7003. {
  7004. char ha2[32 + 1], expected_response[32 + 1];
  7005. /* Some of the parameters may be NULL */
  7006. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7007. || (qop == NULL) || (response == NULL)) {
  7008. return 0;
  7009. }
  7010. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7011. if (strlen(response) != 32) {
  7012. return 0;
  7013. }
  7014. mg_md5(ha2, method, ":", uri, NULL);
  7015. mg_md5(expected_response,
  7016. ha1,
  7017. ":",
  7018. nonce,
  7019. ":",
  7020. nc,
  7021. ":",
  7022. cnonce,
  7023. ":",
  7024. qop,
  7025. ":",
  7026. ha2,
  7027. NULL);
  7028. return mg_strcasecmp(response, expected_response) == 0;
  7029. }
  7030. #if !defined(NO_FILESYSTEMS)
  7031. /* Use the global passwords file, if specified by auth_gpass option,
  7032. * or search for .htpasswd in the requested directory. */
  7033. static void
  7034. open_auth_file(struct mg_connection *conn,
  7035. const char *path,
  7036. struct mg_file *filep)
  7037. {
  7038. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7039. char name[UTF8_PATH_MAX];
  7040. const char *p, *e,
  7041. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7042. int truncated;
  7043. if (gpass != NULL) {
  7044. /* Use global passwords file */
  7045. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7046. #if defined(DEBUG)
  7047. /* Use mg_cry_internal here, since gpass has been
  7048. * configured. */
  7049. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7050. #endif
  7051. }
  7052. /* Important: using local struct mg_file to test path for
  7053. * is_directory flag. If filep is used, mg_stat() makes it
  7054. * appear as if auth file was opened.
  7055. * TODO(mid): Check if this is still required after rewriting
  7056. * mg_stat */
  7057. } else if (mg_stat(conn, path, &filep->stat)
  7058. && filep->stat.is_directory) {
  7059. mg_snprintf(conn,
  7060. &truncated,
  7061. name,
  7062. sizeof(name),
  7063. "%s/%s",
  7064. path,
  7065. PASSWORDS_FILE_NAME);
  7066. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7067. #if defined(DEBUG)
  7068. /* Don't use mg_cry_internal here, but only a trace, since
  7069. * this is a typical case. It will occur for every directory
  7070. * without a password file. */
  7071. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7072. #endif
  7073. }
  7074. } else {
  7075. /* Try to find .htpasswd in requested directory. */
  7076. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7077. if (e[0] == '/') {
  7078. break;
  7079. }
  7080. }
  7081. mg_snprintf(conn,
  7082. &truncated,
  7083. name,
  7084. sizeof(name),
  7085. "%.*s/%s",
  7086. (int)(e - p),
  7087. p,
  7088. PASSWORDS_FILE_NAME);
  7089. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7090. #if defined(DEBUG)
  7091. /* Don't use mg_cry_internal here, but only a trace, since
  7092. * this is a typical case. It will occur for every directory
  7093. * without a password file. */
  7094. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7095. #endif
  7096. }
  7097. }
  7098. }
  7099. }
  7100. #endif /* NO_FILESYSTEMS */
  7101. /* Parsed Authorization header */
  7102. struct ah {
  7103. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  7104. };
  7105. /* Return 1 on success. Always initializes the ah structure. */
  7106. static int
  7107. parse_auth_header(struct mg_connection *conn,
  7108. char *buf,
  7109. size_t buf_size,
  7110. struct ah *ah)
  7111. {
  7112. char *name, *value, *s;
  7113. const char *auth_header;
  7114. uint64_t nonce;
  7115. if (!ah || !conn) {
  7116. return 0;
  7117. }
  7118. (void)memset(ah, 0, sizeof(*ah));
  7119. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  7120. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  7121. return 0;
  7122. }
  7123. /* Make modifiable copy of the auth header */
  7124. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7125. s = buf;
  7126. /* Parse authorization header */
  7127. for (;;) {
  7128. /* Gobble initial spaces */
  7129. while (isspace((unsigned char)*s)) {
  7130. s++;
  7131. }
  7132. name = skip_quoted(&s, "=", " ", 0);
  7133. /* Value is either quote-delimited, or ends at first comma or space.
  7134. */
  7135. if (s[0] == '\"') {
  7136. s++;
  7137. value = skip_quoted(&s, "\"", " ", '\\');
  7138. if (s[0] == ',') {
  7139. s++;
  7140. }
  7141. } else {
  7142. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7143. * uses spaces */
  7144. }
  7145. if (*name == '\0') {
  7146. break;
  7147. }
  7148. if (!strcmp(name, "username")) {
  7149. ah->user = value;
  7150. } else if (!strcmp(name, "cnonce")) {
  7151. ah->cnonce = value;
  7152. } else if (!strcmp(name, "response")) {
  7153. ah->response = value;
  7154. } else if (!strcmp(name, "uri")) {
  7155. ah->uri = value;
  7156. } else if (!strcmp(name, "qop")) {
  7157. ah->qop = value;
  7158. } else if (!strcmp(name, "nc")) {
  7159. ah->nc = value;
  7160. } else if (!strcmp(name, "nonce")) {
  7161. ah->nonce = value;
  7162. }
  7163. }
  7164. #if !defined(NO_NONCE_CHECK)
  7165. /* Read the nonce from the response. */
  7166. if (ah->nonce == NULL) {
  7167. return 0;
  7168. }
  7169. s = NULL;
  7170. nonce = strtoull(ah->nonce, &s, 10);
  7171. if ((s == NULL) || (*s != 0)) {
  7172. return 0;
  7173. }
  7174. /* Convert the nonce from the client to a number. */
  7175. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7176. /* The converted number corresponds to the time the nounce has been
  7177. * created. This should not be earlier than the server start. */
  7178. /* Server side nonce check is valuable in all situations but one:
  7179. * if the server restarts frequently, but the client should not see
  7180. * that, so the server should accept nonces from previous starts. */
  7181. /* However, the reasonable default is to not accept a nonce from a
  7182. * previous start, so if anyone changed the access rights between
  7183. * two restarts, a new login is required. */
  7184. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7185. /* nonce is from a previous start of the server and no longer valid
  7186. * (replay attack?) */
  7187. return 0;
  7188. }
  7189. /* Check if the nonce is too high, so it has not (yet) been used by the
  7190. * server. */
  7191. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7192. + conn->dom_ctx->nonce_count)) {
  7193. return 0;
  7194. }
  7195. #else
  7196. (void)nonce;
  7197. #endif
  7198. /* CGI needs it as REMOTE_USER */
  7199. if (ah->user != NULL) {
  7200. conn->request_info.remote_user =
  7201. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7202. } else {
  7203. return 0;
  7204. }
  7205. return 1;
  7206. }
  7207. static const char *
  7208. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7209. {
  7210. if (!filep) {
  7211. return NULL;
  7212. }
  7213. if (filep->access.fp != NULL) {
  7214. return fgets(buf, (int)size, filep->access.fp);
  7215. } else {
  7216. return NULL;
  7217. }
  7218. }
  7219. /* Define the initial recursion depth for procesesing htpasswd files that
  7220. * include other htpasswd
  7221. * (or even the same) files. It is not difficult to provide a file or files
  7222. * s.t. they force civetweb
  7223. * to infinitely recurse and then crash.
  7224. */
  7225. #define INITIAL_DEPTH 9
  7226. #if INITIAL_DEPTH <= 0
  7227. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7228. #endif
  7229. #if !defined(NO_FILESYSTEMS)
  7230. struct read_auth_file_struct {
  7231. struct mg_connection *conn;
  7232. struct ah ah;
  7233. const char *domain;
  7234. char buf[256 + 256 + 40];
  7235. const char *f_user;
  7236. const char *f_domain;
  7237. const char *f_ha1;
  7238. };
  7239. static int
  7240. read_auth_file(struct mg_file *filep,
  7241. struct read_auth_file_struct *workdata,
  7242. int depth)
  7243. {
  7244. int is_authorized = 0;
  7245. struct mg_file fp;
  7246. size_t l;
  7247. if (!filep || !workdata || (0 == depth)) {
  7248. return 0;
  7249. }
  7250. /* Loop over passwords file */
  7251. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7252. l = strlen(workdata->buf);
  7253. while (l > 0) {
  7254. if (isspace((unsigned char)workdata->buf[l - 1])
  7255. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7256. l--;
  7257. workdata->buf[l] = 0;
  7258. } else
  7259. break;
  7260. }
  7261. if (l < 1) {
  7262. continue;
  7263. }
  7264. workdata->f_user = workdata->buf;
  7265. if (workdata->f_user[0] == ':') {
  7266. /* user names may not contain a ':' and may not be empty,
  7267. * so lines starting with ':' may be used for a special purpose
  7268. */
  7269. if (workdata->f_user[1] == '#') {
  7270. /* :# is a comment */
  7271. continue;
  7272. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7273. if (mg_fopen(workdata->conn,
  7274. workdata->f_user + 9,
  7275. MG_FOPEN_MODE_READ,
  7276. &fp)) {
  7277. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7278. (void)mg_fclose(
  7279. &fp.access); /* ignore error on read only file */
  7280. /* No need to continue processing files once we have a
  7281. * match, since nothing will reset it back
  7282. * to 0.
  7283. */
  7284. if (is_authorized) {
  7285. return is_authorized;
  7286. }
  7287. } else {
  7288. mg_cry_internal(workdata->conn,
  7289. "%s: cannot open authorization file: %s",
  7290. __func__,
  7291. workdata->buf);
  7292. }
  7293. continue;
  7294. }
  7295. /* everything is invalid for the moment (might change in the
  7296. * future) */
  7297. mg_cry_internal(workdata->conn,
  7298. "%s: syntax error in authorization file: %s",
  7299. __func__,
  7300. workdata->buf);
  7301. continue;
  7302. }
  7303. workdata->f_domain = strchr(workdata->f_user, ':');
  7304. if (workdata->f_domain == NULL) {
  7305. mg_cry_internal(workdata->conn,
  7306. "%s: syntax error in authorization file: %s",
  7307. __func__,
  7308. workdata->buf);
  7309. continue;
  7310. }
  7311. *(char *)(workdata->f_domain) = 0;
  7312. (workdata->f_domain)++;
  7313. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7314. if (workdata->f_ha1 == NULL) {
  7315. mg_cry_internal(workdata->conn,
  7316. "%s: syntax error in authorization file: %s",
  7317. __func__,
  7318. workdata->buf);
  7319. continue;
  7320. }
  7321. *(char *)(workdata->f_ha1) = 0;
  7322. (workdata->f_ha1)++;
  7323. if (!strcmp(workdata->ah.user, workdata->f_user)
  7324. && !strcmp(workdata->domain, workdata->f_domain)) {
  7325. return check_password(workdata->conn->request_info.request_method,
  7326. workdata->f_ha1,
  7327. workdata->ah.uri,
  7328. workdata->ah.nonce,
  7329. workdata->ah.nc,
  7330. workdata->ah.cnonce,
  7331. workdata->ah.qop,
  7332. workdata->ah.response);
  7333. }
  7334. }
  7335. return is_authorized;
  7336. }
  7337. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7338. static int
  7339. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7340. {
  7341. struct read_auth_file_struct workdata;
  7342. char buf[MG_BUF_LEN];
  7343. if (!conn || !conn->dom_ctx) {
  7344. return 0;
  7345. }
  7346. memset(&workdata, 0, sizeof(workdata));
  7347. workdata.conn = conn;
  7348. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7349. return 0;
  7350. }
  7351. if (realm) {
  7352. workdata.domain = realm;
  7353. } else {
  7354. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7355. }
  7356. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7357. }
  7358. /* Public function to check http digest authentication header */
  7359. int
  7360. mg_check_digest_access_authentication(struct mg_connection *conn,
  7361. const char *realm,
  7362. const char *filename)
  7363. {
  7364. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7365. int auth;
  7366. if (!conn || !filename) {
  7367. return -1;
  7368. }
  7369. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7370. return -2;
  7371. }
  7372. auth = authorize(conn, &file, realm);
  7373. mg_fclose(&file.access);
  7374. return auth;
  7375. }
  7376. #endif /* NO_FILESYSTEMS */
  7377. /* Return 1 if request is authorised, 0 otherwise. */
  7378. static int
  7379. check_authorization(struct mg_connection *conn, const char *path)
  7380. {
  7381. #if !defined(NO_FILESYSTEMS)
  7382. char fname[UTF8_PATH_MAX];
  7383. struct vec uri_vec, filename_vec;
  7384. const char *list;
  7385. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7386. int authorized = 1, truncated;
  7387. if (!conn || !conn->dom_ctx) {
  7388. return 0;
  7389. }
  7390. list = conn->dom_ctx->config[PROTECT_URI];
  7391. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7392. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7393. mg_snprintf(conn,
  7394. &truncated,
  7395. fname,
  7396. sizeof(fname),
  7397. "%.*s",
  7398. (int)filename_vec.len,
  7399. filename_vec.ptr);
  7400. if (truncated
  7401. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7402. mg_cry_internal(conn,
  7403. "%s: cannot open %s: %s",
  7404. __func__,
  7405. fname,
  7406. strerror(errno));
  7407. }
  7408. break;
  7409. }
  7410. }
  7411. if (!is_file_opened(&file.access)) {
  7412. open_auth_file(conn, path, &file);
  7413. }
  7414. if (is_file_opened(&file.access)) {
  7415. authorized = authorize(conn, &file, NULL);
  7416. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7417. }
  7418. return authorized;
  7419. #else
  7420. (void)conn;
  7421. (void)path;
  7422. return 1;
  7423. #endif /* NO_FILESYSTEMS */
  7424. }
  7425. /* Internal function. Assumes conn is valid */
  7426. static void
  7427. send_authorization_request(struct mg_connection *conn, const char *realm)
  7428. {
  7429. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7430. int trunc = 0;
  7431. char buf[128];
  7432. if (!realm) {
  7433. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7434. }
  7435. mg_lock_context(conn->phys_ctx);
  7436. nonce += conn->dom_ctx->nonce_count;
  7437. ++conn->dom_ctx->nonce_count;
  7438. mg_unlock_context(conn->phys_ctx);
  7439. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7440. conn->must_close = 1;
  7441. /* Create 401 response */
  7442. mg_response_header_start(conn, 401);
  7443. send_no_cache_header(conn);
  7444. send_additional_header(conn);
  7445. mg_response_header_add(conn, "Content-Length", "0", -1);
  7446. /* Content for "WWW-Authenticate" header */
  7447. mg_snprintf(conn,
  7448. &trunc,
  7449. buf,
  7450. sizeof(buf),
  7451. "Digest qop=\"auth\", realm=\"%s\", "
  7452. "nonce=\"%" UINT64_FMT "\"",
  7453. realm,
  7454. nonce);
  7455. if (!trunc) {
  7456. /* !trunc should always be true */
  7457. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7458. }
  7459. /* Send all headers */
  7460. mg_response_header_send(conn);
  7461. }
  7462. /* Interface function. Parameters are provided by the user, so do
  7463. * at least some basic checks.
  7464. */
  7465. int
  7466. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7467. const char *realm)
  7468. {
  7469. if (conn && conn->dom_ctx) {
  7470. send_authorization_request(conn, realm);
  7471. return 0;
  7472. }
  7473. return -1;
  7474. }
  7475. #if !defined(NO_FILES)
  7476. static int
  7477. is_authorized_for_put(struct mg_connection *conn)
  7478. {
  7479. if (conn) {
  7480. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7481. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7482. int ret = 0;
  7483. if (passfile != NULL
  7484. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7485. ret = authorize(conn, &file, NULL);
  7486. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7487. }
  7488. return ret;
  7489. }
  7490. return 0;
  7491. }
  7492. #endif
  7493. int
  7494. mg_modify_passwords_file(const char *fname,
  7495. const char *domain,
  7496. const char *user,
  7497. const char *pass)
  7498. {
  7499. int found, i;
  7500. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[UTF8_PATH_MAX + 8];
  7501. FILE *fp, *fp2;
  7502. found = 0;
  7503. fp = fp2 = NULL;
  7504. /* Regard empty password as no password - remove user record. */
  7505. if ((pass != NULL) && (pass[0] == '\0')) {
  7506. pass = NULL;
  7507. }
  7508. /* Other arguments must not be empty */
  7509. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7510. return 0;
  7511. }
  7512. /* Using the given file format, user name and domain must not contain
  7513. * ':'
  7514. */
  7515. if (strchr(user, ':') != NULL) {
  7516. return 0;
  7517. }
  7518. if (strchr(domain, ':') != NULL) {
  7519. return 0;
  7520. }
  7521. /* Do not allow control characters like newline in user name and domain.
  7522. * Do not allow excessively long names either. */
  7523. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7524. if (iscntrl((unsigned char)user[i])) {
  7525. return 0;
  7526. }
  7527. }
  7528. if (user[i]) {
  7529. return 0;
  7530. }
  7531. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7532. if (iscntrl((unsigned char)domain[i])) {
  7533. return 0;
  7534. }
  7535. }
  7536. if (domain[i]) {
  7537. return 0;
  7538. }
  7539. /* The maximum length of the path to the password file is limited */
  7540. if ((strlen(fname) + 4) >= UTF8_PATH_MAX) {
  7541. return 0;
  7542. }
  7543. /* Create a temporary file name. Length has been checked before. */
  7544. strcpy(tmp, fname);
  7545. strcat(tmp, ".tmp");
  7546. /* Create the file if does not exist */
  7547. /* Use of fopen here is OK, since fname is only ASCII */
  7548. if ((fp = fopen(fname, "a+")) != NULL) {
  7549. (void)fclose(fp);
  7550. }
  7551. /* Open the given file and temporary file */
  7552. if ((fp = fopen(fname, "r")) == NULL) {
  7553. return 0;
  7554. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7555. fclose(fp);
  7556. return 0;
  7557. }
  7558. /* Copy the stuff to temporary file */
  7559. while (fgets(line, sizeof(line), fp) != NULL) {
  7560. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7561. continue;
  7562. }
  7563. u[255] = 0;
  7564. d[255] = 0;
  7565. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7566. found++;
  7567. if (pass != NULL) {
  7568. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7569. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7570. }
  7571. } else {
  7572. fprintf(fp2, "%s", line);
  7573. }
  7574. }
  7575. /* If new user, just add it */
  7576. if (!found && (pass != NULL)) {
  7577. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7578. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7579. }
  7580. /* Close files */
  7581. fclose(fp);
  7582. fclose(fp2);
  7583. /* Put the temp file in place of real file */
  7584. IGNORE_UNUSED_RESULT(remove(fname));
  7585. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7586. return 1;
  7587. }
  7588. static int
  7589. is_valid_port(unsigned long port)
  7590. {
  7591. return (port <= 0xffff);
  7592. }
  7593. static int
  7594. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  7595. {
  7596. struct addrinfo hints, *res, *ressave;
  7597. int func_ret = 0;
  7598. int gai_ret;
  7599. memset(&hints, 0, sizeof(struct addrinfo));
  7600. hints.ai_family = af;
  7601. if (!resolve_src) {
  7602. hints.ai_flags = AI_NUMERICHOST;
  7603. }
  7604. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7605. if (gai_ret != 0) {
  7606. /* gai_strerror could be used to convert gai_ret to a string */
  7607. /* POSIX return values: see
  7608. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7609. */
  7610. /* Windows return values: see
  7611. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7612. */
  7613. return 0;
  7614. }
  7615. ressave = res;
  7616. while (res) {
  7617. if ((dstlen >= (size_t)res->ai_addrlen)
  7618. && (res->ai_addr->sa_family == af)) {
  7619. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7620. func_ret = 1;
  7621. }
  7622. res = res->ai_next;
  7623. }
  7624. freeaddrinfo(ressave);
  7625. return func_ret;
  7626. }
  7627. static int
  7628. connect_socket(
  7629. struct mg_context *ctx /* may be NULL */,
  7630. const char *host,
  7631. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  7632. int use_ssl, /* 0 or 1 */
  7633. char *ebuf,
  7634. size_t ebuf_len,
  7635. SOCKET *sock /* output: socket, must not be NULL */,
  7636. union usa *sa /* output: socket address, must not be NULL */
  7637. )
  7638. {
  7639. int ip_ver = 0;
  7640. int conn_ret = -1;
  7641. int sockerr = 0;
  7642. *sock = INVALID_SOCKET;
  7643. memset(sa, 0, sizeof(*sa));
  7644. if (ebuf_len > 0) {
  7645. *ebuf = 0;
  7646. }
  7647. if (host == NULL) {
  7648. mg_snprintf(NULL,
  7649. NULL, /* No truncation check for ebuf */
  7650. ebuf,
  7651. ebuf_len,
  7652. "%s",
  7653. "NULL host");
  7654. return 0;
  7655. }
  7656. #if defined(USE_X_DOM_SOCKET)
  7657. if (port == -99) {
  7658. /* Unix domain socket */
  7659. size_t hostlen = strlen(host);
  7660. if (hostlen >= sizeof(sa->sun.sun_path)) {
  7661. mg_snprintf(NULL,
  7662. NULL, /* No truncation check for ebuf */
  7663. ebuf,
  7664. ebuf_len,
  7665. "%s",
  7666. "host length exceeds limit");
  7667. return 0;
  7668. }
  7669. } else
  7670. #endif
  7671. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7672. mg_snprintf(NULL,
  7673. NULL, /* No truncation check for ebuf */
  7674. ebuf,
  7675. ebuf_len,
  7676. "%s",
  7677. "invalid port");
  7678. return 0;
  7679. }
  7680. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  7681. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  7682. if (use_ssl && (TLS_client_method == NULL)) {
  7683. mg_snprintf(NULL,
  7684. NULL, /* No truncation check for ebuf */
  7685. ebuf,
  7686. ebuf_len,
  7687. "%s",
  7688. "SSL is not initialized");
  7689. return 0;
  7690. }
  7691. #else
  7692. if (use_ssl && (SSLv23_client_method == NULL)) {
  7693. mg_snprintf(NULL,
  7694. NULL, /* No truncation check for ebuf */
  7695. ebuf,
  7696. ebuf_len,
  7697. "%s",
  7698. "SSL is not initialized");
  7699. return 0;
  7700. }
  7701. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  7702. #else
  7703. (void)use_ssl;
  7704. #endif /* NO SSL */
  7705. #if defined(USE_X_DOM_SOCKET)
  7706. if (port == -99) {
  7707. size_t hostlen = strlen(host);
  7708. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  7709. ip_ver = -99;
  7710. sa->sun.sun_family = AF_UNIX;
  7711. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  7712. memcpy(sa->sun.sun_path, host, hostlen);
  7713. } else
  7714. #endif
  7715. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  7716. sa->sin.sin_port = htons((uint16_t)port);
  7717. ip_ver = 4;
  7718. #if defined(USE_IPV6)
  7719. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  7720. sa->sin6.sin6_port = htons((uint16_t)port);
  7721. ip_ver = 6;
  7722. } else if (host[0] == '[') {
  7723. /* While getaddrinfo on Windows will work with [::1],
  7724. * getaddrinfo on Linux only works with ::1 (without []). */
  7725. size_t l = strlen(host + 1);
  7726. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7727. if (h) {
  7728. h[l - 1] = 0;
  7729. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  7730. sa->sin6.sin6_port = htons((uint16_t)port);
  7731. ip_ver = 6;
  7732. }
  7733. mg_free(h);
  7734. }
  7735. #endif
  7736. }
  7737. if (ip_ver == 0) {
  7738. mg_snprintf(NULL,
  7739. NULL, /* No truncation check for ebuf */
  7740. ebuf,
  7741. ebuf_len,
  7742. "%s",
  7743. "host not found");
  7744. return 0;
  7745. }
  7746. if (ip_ver == 4) {
  7747. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7748. }
  7749. #if defined(USE_IPV6)
  7750. else if (ip_ver == 6) {
  7751. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7752. }
  7753. #endif
  7754. #if defined(USE_X_DOM_SOCKET)
  7755. else if (ip_ver == -99) {
  7756. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  7757. }
  7758. #endif
  7759. if (*sock == INVALID_SOCKET) {
  7760. mg_snprintf(NULL,
  7761. NULL, /* No truncation check for ebuf */
  7762. ebuf,
  7763. ebuf_len,
  7764. "socket(): %s",
  7765. strerror(ERRNO));
  7766. return 0;
  7767. }
  7768. if (0 != set_non_blocking_mode(*sock)) {
  7769. mg_snprintf(NULL,
  7770. NULL, /* No truncation check for ebuf */
  7771. ebuf,
  7772. ebuf_len,
  7773. "Cannot set socket to non-blocking: %s",
  7774. strerror(ERRNO));
  7775. closesocket(*sock);
  7776. *sock = INVALID_SOCKET;
  7777. return 0;
  7778. }
  7779. set_close_on_exec(*sock, NULL, ctx);
  7780. if (ip_ver == 4) {
  7781. /* connected with IPv4 */
  7782. conn_ret = connect(*sock,
  7783. (struct sockaddr *)((void *)&sa->sin),
  7784. sizeof(sa->sin));
  7785. }
  7786. #if defined(USE_IPV6)
  7787. else if (ip_ver == 6) {
  7788. /* connected with IPv6 */
  7789. conn_ret = connect(*sock,
  7790. (struct sockaddr *)((void *)&sa->sin6),
  7791. sizeof(sa->sin6));
  7792. }
  7793. #endif
  7794. #if defined(USE_X_DOM_SOCKET)
  7795. else if (ip_ver == -99) {
  7796. /* connected to domain socket */
  7797. conn_ret = connect(*sock,
  7798. (struct sockaddr *)((void *)&sa->sun),
  7799. sizeof(sa->sun));
  7800. }
  7801. #endif
  7802. if (conn_ret != 0) {
  7803. sockerr = ERRNO;
  7804. }
  7805. #if defined(_WIN32)
  7806. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7807. #else
  7808. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7809. #endif
  7810. /* Data for getsockopt */
  7811. void *psockerr = &sockerr;
  7812. int ret;
  7813. #if defined(_WIN32)
  7814. int len = (int)sizeof(sockerr);
  7815. #else
  7816. socklen_t len = (socklen_t)sizeof(sockerr);
  7817. #endif
  7818. /* Data for poll */
  7819. struct mg_pollfd pfd[1];
  7820. int pollres;
  7821. int ms_wait = 10000; /* 10 second timeout */
  7822. stop_flag_t nonstop;
  7823. STOP_FLAG_ASSIGN(&nonstop, 0);
  7824. /* For a non-blocking socket, the connect sequence is:
  7825. * 1) call connect (will not block)
  7826. * 2) wait until the socket is ready for writing (select or poll)
  7827. * 3) check connection state with getsockopt
  7828. */
  7829. pfd[0].fd = *sock;
  7830. pfd[0].events = POLLOUT;
  7831. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7832. if (pollres != 1) {
  7833. /* Not connected */
  7834. mg_snprintf(NULL,
  7835. NULL, /* No truncation check for ebuf */
  7836. ebuf,
  7837. ebuf_len,
  7838. "connect(%s:%d): timeout",
  7839. host,
  7840. port);
  7841. closesocket(*sock);
  7842. *sock = INVALID_SOCKET;
  7843. return 0;
  7844. }
  7845. #if defined(_WIN32)
  7846. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7847. #else
  7848. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7849. #endif
  7850. if ((ret == 0) && (sockerr == 0)) {
  7851. conn_ret = 0;
  7852. }
  7853. }
  7854. if (conn_ret != 0) {
  7855. /* Not connected */
  7856. mg_snprintf(NULL,
  7857. NULL, /* No truncation check for ebuf */
  7858. ebuf,
  7859. ebuf_len,
  7860. "connect(%s:%d): error %s",
  7861. host,
  7862. port,
  7863. strerror(sockerr));
  7864. closesocket(*sock);
  7865. *sock = INVALID_SOCKET;
  7866. return 0;
  7867. }
  7868. return 1;
  7869. }
  7870. int
  7871. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7872. {
  7873. static const char *dont_escape = "._-$,;~()";
  7874. static const char *hex = "0123456789abcdef";
  7875. char *pos = dst;
  7876. const char *end = dst + dst_len - 1;
  7877. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7878. if (isalnum((unsigned char)*src)
  7879. || (strchr(dont_escape, *src) != NULL)) {
  7880. *pos = *src;
  7881. } else if (pos + 2 < end) {
  7882. pos[0] = '%';
  7883. pos[1] = hex[(unsigned char)*src >> 4];
  7884. pos[2] = hex[(unsigned char)*src & 0xf];
  7885. pos += 2;
  7886. } else {
  7887. break;
  7888. }
  7889. }
  7890. *pos = '\0';
  7891. return (*src == '\0') ? (int)(pos - dst) : -1;
  7892. }
  7893. /* Return 0 on success, non-zero if an error occurs. */
  7894. static int
  7895. print_dir_entry(struct de *de)
  7896. {
  7897. size_t namesize, escsize, i;
  7898. char *href, *esc, *p;
  7899. char size[64], mod[64];
  7900. #if defined(REENTRANT_TIME)
  7901. struct tm _tm;
  7902. struct tm *tm = &_tm;
  7903. #else
  7904. struct tm *tm;
  7905. #endif
  7906. /* Estimate worst case size for encoding and escaping */
  7907. namesize = strlen(de->file_name) + 1;
  7908. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7909. href = (char *)mg_malloc(namesize * 3 + escsize);
  7910. if (href == NULL) {
  7911. return -1;
  7912. }
  7913. mg_url_encode(de->file_name, href, namesize * 3);
  7914. esc = NULL;
  7915. if (escsize > 0) {
  7916. /* HTML escaping needed */
  7917. esc = href + namesize * 3;
  7918. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7919. mg_strlcpy(p, de->file_name + i, 2);
  7920. if (*p == '&') {
  7921. strcpy(p, "&amp;");
  7922. } else if (*p == '<') {
  7923. strcpy(p, "&lt;");
  7924. } else if (*p == '>') {
  7925. strcpy(p, "&gt;");
  7926. }
  7927. }
  7928. }
  7929. if (de->file.is_directory) {
  7930. mg_snprintf(de->conn,
  7931. NULL, /* Buffer is big enough */
  7932. size,
  7933. sizeof(size),
  7934. "%s",
  7935. "[DIRECTORY]");
  7936. } else {
  7937. /* We use (signed) cast below because MSVC 6 compiler cannot
  7938. * convert unsigned __int64 to double. Sigh. */
  7939. if (de->file.size < 1024) {
  7940. mg_snprintf(de->conn,
  7941. NULL, /* Buffer is big enough */
  7942. size,
  7943. sizeof(size),
  7944. "%d",
  7945. (int)de->file.size);
  7946. } else if (de->file.size < 0x100000) {
  7947. mg_snprintf(de->conn,
  7948. NULL, /* Buffer is big enough */
  7949. size,
  7950. sizeof(size),
  7951. "%.1fk",
  7952. (double)de->file.size / 1024.0);
  7953. } else if (de->file.size < 0x40000000) {
  7954. mg_snprintf(de->conn,
  7955. NULL, /* Buffer is big enough */
  7956. size,
  7957. sizeof(size),
  7958. "%.1fM",
  7959. (double)de->file.size / 1048576);
  7960. } else {
  7961. mg_snprintf(de->conn,
  7962. NULL, /* Buffer is big enough */
  7963. size,
  7964. sizeof(size),
  7965. "%.1fG",
  7966. (double)de->file.size / 1073741824);
  7967. }
  7968. }
  7969. /* Note: mg_snprintf will not cause a buffer overflow above.
  7970. * So, string truncation checks are not required here. */
  7971. #if defined(REENTRANT_TIME)
  7972. localtime_r(&de->file.last_modified, tm);
  7973. #else
  7974. tm = localtime(&de->file.last_modified);
  7975. #endif
  7976. if (tm != NULL) {
  7977. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7978. } else {
  7979. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7980. mod[sizeof(mod) - 1] = '\0';
  7981. }
  7982. mg_printf(de->conn,
  7983. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7984. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7985. href,
  7986. de->file.is_directory ? "/" : "",
  7987. esc ? esc : de->file_name,
  7988. de->file.is_directory ? "/" : "",
  7989. mod,
  7990. size);
  7991. mg_free(href);
  7992. return 0;
  7993. }
  7994. /* This function is called from send_directory() and used for
  7995. * sorting directory entries by size, or name, or modification time.
  7996. * On windows, __cdecl specification is needed in case if project is built
  7997. * with __stdcall convention. qsort always requires __cdels callback. */
  7998. static int WINCDECL
  7999. compare_dir_entries(const void *p1, const void *p2)
  8000. {
  8001. if (p1 && p2) {
  8002. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8003. const char *query_string = a->conn->request_info.query_string;
  8004. int cmp_result = 0;
  8005. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8006. query_string = "n";
  8007. }
  8008. if (a->file.is_directory && !b->file.is_directory) {
  8009. return -1; /* Always put directories on top */
  8010. } else if (!a->file.is_directory && b->file.is_directory) {
  8011. return 1; /* Always put directories on top */
  8012. } else if (*query_string == 'n') {
  8013. cmp_result = strcmp(a->file_name, b->file_name);
  8014. } else if (*query_string == 's') {
  8015. cmp_result = (a->file.size == b->file.size)
  8016. ? 0
  8017. : ((a->file.size > b->file.size) ? 1 : -1);
  8018. } else if (*query_string == 'd') {
  8019. cmp_result =
  8020. (a->file.last_modified == b->file.last_modified)
  8021. ? 0
  8022. : ((a->file.last_modified > b->file.last_modified) ? 1
  8023. : -1);
  8024. }
  8025. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8026. }
  8027. return 0;
  8028. }
  8029. static int
  8030. must_hide_file(struct mg_connection *conn, const char *path)
  8031. {
  8032. if (conn && conn->dom_ctx) {
  8033. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8034. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8035. return (match_prefix_strlen(pw_pattern, path) > 0)
  8036. || (match_prefix_strlen(pattern, path) > 0);
  8037. }
  8038. return 0;
  8039. }
  8040. #if !defined(NO_FILESYSTEMS)
  8041. static int
  8042. scan_directory(struct mg_connection *conn,
  8043. const char *dir,
  8044. void *data,
  8045. int (*cb)(struct de *, void *))
  8046. {
  8047. char path[UTF8_PATH_MAX];
  8048. struct dirent *dp;
  8049. DIR *dirp;
  8050. struct de de;
  8051. int truncated;
  8052. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8053. return 0;
  8054. } else {
  8055. de.conn = conn;
  8056. while ((dp = mg_readdir(dirp)) != NULL) {
  8057. /* Do not show current dir and hidden files */
  8058. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8059. || must_hide_file(conn, dp->d_name)) {
  8060. continue;
  8061. }
  8062. mg_snprintf(
  8063. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8064. /* If we don't memset stat structure to zero, mtime will have
  8065. * garbage and strftime() will segfault later on in
  8066. * print_dir_entry(). memset is required only if mg_stat()
  8067. * fails. For more details, see
  8068. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8069. memset(&de.file, 0, sizeof(de.file));
  8070. if (truncated) {
  8071. /* If the path is not complete, skip processing. */
  8072. continue;
  8073. }
  8074. if (!mg_stat(conn, path, &de.file)) {
  8075. mg_cry_internal(conn,
  8076. "%s: mg_stat(%s) failed: %s",
  8077. __func__,
  8078. path,
  8079. strerror(ERRNO));
  8080. }
  8081. de.file_name = dp->d_name;
  8082. if (cb(&de, data)) {
  8083. /* stopped */
  8084. break;
  8085. }
  8086. }
  8087. (void)mg_closedir(dirp);
  8088. }
  8089. return 1;
  8090. }
  8091. #endif /* NO_FILESYSTEMS */
  8092. #if !defined(NO_FILES)
  8093. static int
  8094. remove_directory(struct mg_connection *conn, const char *dir)
  8095. {
  8096. char path[UTF8_PATH_MAX];
  8097. struct dirent *dp;
  8098. DIR *dirp;
  8099. struct de de;
  8100. int truncated;
  8101. int ok = 1;
  8102. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8103. return 0;
  8104. } else {
  8105. de.conn = conn;
  8106. while ((dp = mg_readdir(dirp)) != NULL) {
  8107. /* Do not show current dir (but show hidden files as they will
  8108. * also be removed) */
  8109. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8110. continue;
  8111. }
  8112. mg_snprintf(
  8113. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8114. /* If we don't memset stat structure to zero, mtime will have
  8115. * garbage and strftime() will segfault later on in
  8116. * print_dir_entry(). memset is required only if mg_stat()
  8117. * fails. For more details, see
  8118. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8119. memset(&de.file, 0, sizeof(de.file));
  8120. if (truncated) {
  8121. /* Do not delete anything shorter */
  8122. ok = 0;
  8123. continue;
  8124. }
  8125. if (!mg_stat(conn, path, &de.file)) {
  8126. mg_cry_internal(conn,
  8127. "%s: mg_stat(%s) failed: %s",
  8128. __func__,
  8129. path,
  8130. strerror(ERRNO));
  8131. ok = 0;
  8132. }
  8133. if (de.file.is_directory) {
  8134. if (remove_directory(conn, path) == 0) {
  8135. ok = 0;
  8136. }
  8137. } else {
  8138. /* This will fail file is the file is in memory */
  8139. if (mg_remove(conn, path) == 0) {
  8140. ok = 0;
  8141. }
  8142. }
  8143. }
  8144. (void)mg_closedir(dirp);
  8145. IGNORE_UNUSED_RESULT(rmdir(dir));
  8146. }
  8147. return ok;
  8148. }
  8149. #endif
  8150. struct dir_scan_data {
  8151. struct de *entries;
  8152. size_t num_entries;
  8153. size_t arr_size;
  8154. };
  8155. #if !defined(NO_FILESYSTEMS)
  8156. static int
  8157. dir_scan_callback(struct de *de, void *data)
  8158. {
  8159. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8160. struct de *entries = dsd->entries;
  8161. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8162. /* Here "entries" is a temporary pointer and can be replaced,
  8163. * "dsd->entries" is the original pointer */
  8164. entries =
  8165. (struct de *)mg_realloc(entries,
  8166. dsd->arr_size * 2 * sizeof(entries[0]));
  8167. if (entries == NULL) {
  8168. /* stop scan */
  8169. return 1;
  8170. }
  8171. dsd->entries = entries;
  8172. dsd->arr_size *= 2;
  8173. }
  8174. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8175. if (entries[dsd->num_entries].file_name == NULL) {
  8176. /* stop scan */
  8177. return 1;
  8178. }
  8179. entries[dsd->num_entries].file = de->file;
  8180. entries[dsd->num_entries].conn = de->conn;
  8181. dsd->num_entries++;
  8182. return 0;
  8183. }
  8184. static void
  8185. handle_directory_request(struct mg_connection *conn, const char *dir)
  8186. {
  8187. size_t i;
  8188. int sort_direction;
  8189. struct dir_scan_data data = {NULL, 0, 128};
  8190. char date[64], *esc, *p;
  8191. const char *title;
  8192. time_t curtime = time(NULL);
  8193. if (!conn) {
  8194. return;
  8195. }
  8196. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8197. mg_send_http_error(conn,
  8198. 500,
  8199. "Error: Cannot open directory\nopendir(%s): %s",
  8200. dir,
  8201. strerror(ERRNO));
  8202. return;
  8203. }
  8204. gmt_time_string(date, sizeof(date), &curtime);
  8205. esc = NULL;
  8206. title = conn->request_info.local_uri;
  8207. if (title[strcspn(title, "&<>")]) {
  8208. /* HTML escaping needed */
  8209. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8210. if (esc) {
  8211. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8212. mg_strlcpy(p, title + i, 2);
  8213. if (*p == '&') {
  8214. strcpy(p, "&amp;");
  8215. } else if (*p == '<') {
  8216. strcpy(p, "&lt;");
  8217. } else if (*p == '>') {
  8218. strcpy(p, "&gt;");
  8219. }
  8220. }
  8221. } else {
  8222. title = "";
  8223. }
  8224. }
  8225. sort_direction = ((conn->request_info.query_string != NULL)
  8226. && (conn->request_info.query_string[0] != '\0')
  8227. && (conn->request_info.query_string[1] == 'd'))
  8228. ? 'a'
  8229. : 'd';
  8230. conn->must_close = 1;
  8231. /* Create 200 OK response */
  8232. mg_response_header_start(conn, 200);
  8233. send_static_cache_header(conn);
  8234. send_additional_header(conn);
  8235. mg_response_header_add(conn,
  8236. "Content-Type",
  8237. "text/html; charset=utf-8",
  8238. -1);
  8239. /* Send all headers */
  8240. mg_response_header_send(conn);
  8241. /* Body */
  8242. mg_printf(conn,
  8243. "<html><head><title>Index of %s</title>"
  8244. "<style>th {text-align: left;}</style></head>"
  8245. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8246. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8247. "<th><a href=\"?d%c\">Modified</a></th>"
  8248. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8249. "<tr><td colspan=\"3\"><hr></td></tr>",
  8250. esc ? esc : title,
  8251. esc ? esc : title,
  8252. sort_direction,
  8253. sort_direction,
  8254. sort_direction);
  8255. mg_free(esc);
  8256. /* Print first entry - link to a parent directory */
  8257. mg_printf(conn,
  8258. "<tr><td><a href=\"%s\">%s</a></td>"
  8259. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8260. "..",
  8261. "Parent directory",
  8262. "-",
  8263. "-");
  8264. /* Sort and print directory entries */
  8265. if (data.entries != NULL) {
  8266. qsort(data.entries,
  8267. data.num_entries,
  8268. sizeof(data.entries[0]),
  8269. compare_dir_entries);
  8270. for (i = 0; i < data.num_entries; i++) {
  8271. print_dir_entry(&data.entries[i]);
  8272. mg_free(data.entries[i].file_name);
  8273. }
  8274. mg_free(data.entries);
  8275. }
  8276. mg_printf(conn, "%s", "</table></pre></body></html>");
  8277. conn->status_code = 200;
  8278. }
  8279. #endif /* NO_FILESYSTEMS */
  8280. /* Send len bytes from the opened file to the client. */
  8281. static void
  8282. send_file_data(struct mg_connection *conn,
  8283. struct mg_file *filep,
  8284. int64_t offset,
  8285. int64_t len)
  8286. {
  8287. char buf[MG_BUF_LEN];
  8288. int to_read, num_read, num_written;
  8289. int64_t size;
  8290. if (!filep || !conn) {
  8291. return;
  8292. }
  8293. /* Sanity check the offset */
  8294. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8295. : (int64_t)(filep->stat.size);
  8296. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8297. if (len > 0 && filep->access.fp != NULL) {
  8298. /* file stored on disk */
  8299. #if defined(__linux__)
  8300. /* sendfile is only available for Linux */
  8301. if ((conn->ssl == 0) && (conn->throttle == 0)
  8302. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8303. "yes"))) {
  8304. off_t sf_offs = (off_t)offset;
  8305. ssize_t sf_sent;
  8306. int sf_file = fileno(filep->access.fp);
  8307. int loop_cnt = 0;
  8308. do {
  8309. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8310. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8311. size_t sf_tosend =
  8312. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8313. sf_sent =
  8314. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8315. if (sf_sent > 0) {
  8316. len -= sf_sent;
  8317. offset += sf_sent;
  8318. } else if (loop_cnt == 0) {
  8319. /* This file can not be sent using sendfile.
  8320. * This might be the case for pseudo-files in the
  8321. * /sys/ and /proc/ file system.
  8322. * Use the regular user mode copy code instead. */
  8323. break;
  8324. } else if (sf_sent == 0) {
  8325. /* No error, but 0 bytes sent. May be EOF? */
  8326. return;
  8327. }
  8328. loop_cnt++;
  8329. } while ((len > 0) && (sf_sent >= 0));
  8330. if (sf_sent > 0) {
  8331. return; /* OK */
  8332. }
  8333. /* sf_sent<0 means error, thus fall back to the classic way */
  8334. /* This is always the case, if sf_file is not a "normal" file,
  8335. * e.g., for sending data from the output of a CGI process. */
  8336. offset = (int64_t)sf_offs;
  8337. }
  8338. #endif
  8339. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8340. mg_cry_internal(conn,
  8341. "%s: fseeko() failed: %s",
  8342. __func__,
  8343. strerror(ERRNO));
  8344. mg_send_http_error(
  8345. conn,
  8346. 500,
  8347. "%s",
  8348. "Error: Unable to access file at requested position.");
  8349. } else {
  8350. while (len > 0) {
  8351. /* Calculate how much to read from the file in the buffer */
  8352. to_read = sizeof(buf);
  8353. if ((int64_t)to_read > len) {
  8354. to_read = (int)len;
  8355. }
  8356. /* Read from file, exit the loop on error */
  8357. if ((num_read =
  8358. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8359. <= 0) {
  8360. break;
  8361. }
  8362. /* Send read bytes to the client, exit the loop on error */
  8363. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8364. != num_read) {
  8365. break;
  8366. }
  8367. /* Both read and were successful, adjust counters */
  8368. len -= num_written;
  8369. }
  8370. }
  8371. }
  8372. }
  8373. static int
  8374. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8375. {
  8376. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8377. }
  8378. static void
  8379. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8380. {
  8381. if ((filestat != NULL) && (buf != NULL)) {
  8382. mg_snprintf(NULL,
  8383. NULL, /* All calls to construct_etag use 64 byte buffer */
  8384. buf,
  8385. buf_len,
  8386. "\"%lx.%" INT64_FMT "\"",
  8387. (unsigned long)filestat->last_modified,
  8388. filestat->size);
  8389. }
  8390. }
  8391. static void
  8392. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8393. {
  8394. if (filep != NULL && filep->fp != NULL) {
  8395. #if defined(_WIN32)
  8396. (void)conn; /* Unused. */
  8397. #else
  8398. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8399. mg_cry_internal(conn,
  8400. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8401. __func__,
  8402. strerror(ERRNO));
  8403. }
  8404. #endif
  8405. }
  8406. }
  8407. #if defined(USE_ZLIB)
  8408. #include "mod_zlib.inl"
  8409. #endif
  8410. #if !defined(NO_FILESYSTEMS)
  8411. static void
  8412. handle_static_file_request(struct mg_connection *conn,
  8413. const char *path,
  8414. struct mg_file *filep,
  8415. const char *mime_type,
  8416. const char *additional_headers)
  8417. {
  8418. char lm[64], etag[64];
  8419. char range[128]; /* large enough, so there will be no overflow */
  8420. const char *range_hdr;
  8421. int64_t cl, r1, r2;
  8422. struct vec mime_vec;
  8423. int n, truncated;
  8424. char gz_path[UTF8_PATH_MAX];
  8425. const char *encoding = 0;
  8426. const char *origin_hdr;
  8427. const char *cors_orig_cfg;
  8428. const char *cors1, *cors2;
  8429. int is_head_request;
  8430. #if defined(USE_ZLIB)
  8431. /* Compression is allowed, unless there is a reason not to use
  8432. * compression. If the file is already compressed, too small or a
  8433. * "range" request was made, on the fly compression is not possible. */
  8434. int allow_on_the_fly_compression = 1;
  8435. #endif
  8436. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8437. return;
  8438. }
  8439. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8440. if (mime_type == NULL) {
  8441. get_mime_type(conn, path, &mime_vec);
  8442. } else {
  8443. mime_vec.ptr = mime_type;
  8444. mime_vec.len = strlen(mime_type);
  8445. }
  8446. if (filep->stat.size > INT64_MAX) {
  8447. mg_send_http_error(conn,
  8448. 500,
  8449. "Error: File size is too large to send\n%" INT64_FMT,
  8450. filep->stat.size);
  8451. return;
  8452. }
  8453. cl = (int64_t)filep->stat.size;
  8454. conn->status_code = 200;
  8455. range[0] = '\0';
  8456. #if defined(USE_ZLIB)
  8457. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8458. * it's important to rewrite the filename after resolving
  8459. * the mime type from it, to preserve the actual file's type */
  8460. if (!conn->accept_gzip) {
  8461. allow_on_the_fly_compression = 0;
  8462. }
  8463. #endif
  8464. /* Check if there is a range header */
  8465. range_hdr = mg_get_header(conn, "Range");
  8466. /* For gzipped files, add *.gz */
  8467. if (filep->stat.is_gzipped) {
  8468. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8469. if (truncated) {
  8470. mg_send_http_error(conn,
  8471. 500,
  8472. "Error: Path of zipped file too long (%s)",
  8473. path);
  8474. return;
  8475. }
  8476. path = gz_path;
  8477. encoding = "gzip";
  8478. #if defined(USE_ZLIB)
  8479. /* File is already compressed. No "on the fly" compression. */
  8480. allow_on_the_fly_compression = 0;
  8481. #endif
  8482. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8483. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8484. struct mg_file_stat file_stat;
  8485. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8486. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8487. && !file_stat.is_directory) {
  8488. file_stat.is_gzipped = 1;
  8489. filep->stat = file_stat;
  8490. cl = (int64_t)filep->stat.size;
  8491. path = gz_path;
  8492. encoding = "gzip";
  8493. #if defined(USE_ZLIB)
  8494. /* File is already compressed. No "on the fly" compression. */
  8495. allow_on_the_fly_compression = 0;
  8496. #endif
  8497. }
  8498. }
  8499. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8500. mg_send_http_error(conn,
  8501. 500,
  8502. "Error: Cannot open file\nfopen(%s): %s",
  8503. path,
  8504. strerror(ERRNO));
  8505. return;
  8506. }
  8507. fclose_on_exec(&filep->access, conn);
  8508. /* If "Range" request was made: parse header, send only selected part
  8509. * of the file. */
  8510. r1 = r2 = 0;
  8511. if ((range_hdr != NULL)
  8512. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8513. && (r2 >= 0)) {
  8514. /* actually, range requests don't play well with a pre-gzipped
  8515. * file (since the range is specified in the uncompressed space) */
  8516. if (filep->stat.is_gzipped) {
  8517. mg_send_http_error(
  8518. conn,
  8519. 416, /* 416 = Range Not Satisfiable */
  8520. "%s",
  8521. "Error: Range requests in gzipped files are not supported");
  8522. (void)mg_fclose(
  8523. &filep->access); /* ignore error on read only file */
  8524. return;
  8525. }
  8526. conn->status_code = 206;
  8527. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8528. mg_snprintf(conn,
  8529. NULL, /* range buffer is big enough */
  8530. range,
  8531. sizeof(range),
  8532. "bytes "
  8533. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  8534. r1,
  8535. r1 + cl - 1,
  8536. filep->stat.size);
  8537. #if defined(USE_ZLIB)
  8538. /* Do not compress ranges. */
  8539. allow_on_the_fly_compression = 0;
  8540. #endif
  8541. }
  8542. /* Do not compress small files. Small files do not benefit from file
  8543. * compression, but there is still some overhead. */
  8544. #if defined(USE_ZLIB)
  8545. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8546. /* File is below the size limit. */
  8547. allow_on_the_fly_compression = 0;
  8548. }
  8549. #endif
  8550. /* Standard CORS header */
  8551. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8552. origin_hdr = mg_get_header(conn, "Origin");
  8553. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8554. /* Cross-origin resource sharing (CORS), see
  8555. * http://www.html5rocks.com/en/tutorials/cors/,
  8556. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8557. * -
  8558. * preflight is not supported for files. */
  8559. cors1 = "Access-Control-Allow-Origin";
  8560. cors2 = cors_orig_cfg;
  8561. } else {
  8562. cors1 = cors2 = "";
  8563. }
  8564. /* Prepare Etag, and Last-Modified headers. */
  8565. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8566. construct_etag(etag, sizeof(etag), &filep->stat);
  8567. /* Create 2xx (200, 206) response */
  8568. mg_response_header_start(conn, conn->status_code);
  8569. send_static_cache_header(conn);
  8570. send_additional_header(conn);
  8571. mg_response_header_add(conn,
  8572. "Content-Type",
  8573. mime_vec.ptr,
  8574. (int)mime_vec.len);
  8575. if (cors1[0] != 0) {
  8576. mg_response_header_add(conn, cors1, cors2, -1);
  8577. }
  8578. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8579. mg_response_header_add(conn, "Etag", etag, -1);
  8580. #if defined(USE_ZLIB)
  8581. /* On the fly compression allowed */
  8582. if (allow_on_the_fly_compression) {
  8583. /* For on the fly compression, we don't know the content size in
  8584. * advance, so we have to use chunked encoding */
  8585. encoding = "gzip";
  8586. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  8587. /* HTTP/2 is always using "chunks" (frames) */
  8588. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  8589. }
  8590. } else
  8591. #endif
  8592. {
  8593. /* Without on-the-fly compression, we know the content-length
  8594. * and we can use ranges (with on-the-fly compression we cannot).
  8595. * So we send these response headers only in this case. */
  8596. char len[32];
  8597. int trunc = 0;
  8598. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  8599. if (!trunc) {
  8600. mg_response_header_add(conn, "Content-Length", len, -1);
  8601. }
  8602. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  8603. }
  8604. if (encoding) {
  8605. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  8606. }
  8607. if (range[0] != 0) {
  8608. mg_response_header_add(conn, "Content-Range", range, -1);
  8609. }
  8610. /* The code above does not add any header starting with X- to make
  8611. * sure no one of the additional_headers is included twice */
  8612. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  8613. mg_response_header_add_lines(conn, additional_headers);
  8614. }
  8615. /* Send all headers */
  8616. mg_response_header_send(conn);
  8617. if (!is_head_request) {
  8618. #if defined(USE_ZLIB)
  8619. if (allow_on_the_fly_compression) {
  8620. /* Compress and send */
  8621. send_compressed_data(conn, filep);
  8622. } else
  8623. #endif
  8624. {
  8625. /* Send file directly */
  8626. send_file_data(conn, filep, r1, cl);
  8627. }
  8628. }
  8629. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8630. }
  8631. int
  8632. mg_send_file_body(struct mg_connection *conn, const char *path)
  8633. {
  8634. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8635. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8636. return -1;
  8637. }
  8638. fclose_on_exec(&file.access, conn);
  8639. send_file_data(conn, &file, 0, INT64_MAX);
  8640. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8641. return 0; /* >= 0 for OK */
  8642. }
  8643. #endif /* NO_FILESYSTEMS */
  8644. #if !defined(NO_CACHING)
  8645. /* Return True if we should reply 304 Not Modified. */
  8646. static int
  8647. is_not_modified(const struct mg_connection *conn,
  8648. const struct mg_file_stat *filestat)
  8649. {
  8650. char etag[64];
  8651. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8652. const char *inm = mg_get_header(conn, "If-None-Match");
  8653. construct_etag(etag, sizeof(etag), filestat);
  8654. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8655. || ((ims != NULL)
  8656. && (filestat->last_modified <= parse_date_string(ims)));
  8657. }
  8658. static void
  8659. handle_not_modified_static_file_request(struct mg_connection *conn,
  8660. struct mg_file *filep)
  8661. {
  8662. char lm[64], etag[64];
  8663. if ((conn == NULL) || (filep == NULL)) {
  8664. return;
  8665. }
  8666. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8667. construct_etag(etag, sizeof(etag), &filep->stat);
  8668. /* Create 304 "not modified" response */
  8669. mg_response_header_start(conn, 304);
  8670. send_static_cache_header(conn);
  8671. send_additional_header(conn);
  8672. mg_response_header_add(conn, "Last-Modified", lm, -1);
  8673. mg_response_header_add(conn, "Etag", etag, -1);
  8674. /* Send all headers */
  8675. mg_response_header_send(conn);
  8676. }
  8677. #endif
  8678. #if !defined(NO_FILESYSTEMS)
  8679. void
  8680. mg_send_file(struct mg_connection *conn, const char *path)
  8681. {
  8682. mg_send_mime_file2(conn, path, NULL, NULL);
  8683. }
  8684. void
  8685. mg_send_mime_file(struct mg_connection *conn,
  8686. const char *path,
  8687. const char *mime_type)
  8688. {
  8689. mg_send_mime_file2(conn, path, mime_type, NULL);
  8690. }
  8691. void
  8692. mg_send_mime_file2(struct mg_connection *conn,
  8693. const char *path,
  8694. const char *mime_type,
  8695. const char *additional_headers)
  8696. {
  8697. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8698. if (!conn) {
  8699. /* No conn */
  8700. return;
  8701. }
  8702. if (mg_stat(conn, path, &file.stat)) {
  8703. #if !defined(NO_CACHING)
  8704. if (is_not_modified(conn, &file.stat)) {
  8705. /* Send 304 "Not Modified" - this must not send any body data */
  8706. handle_not_modified_static_file_request(conn, &file);
  8707. } else
  8708. #endif /* NO_CACHING */
  8709. if (file.stat.is_directory) {
  8710. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8711. "yes")) {
  8712. handle_directory_request(conn, path);
  8713. } else {
  8714. mg_send_http_error(conn,
  8715. 403,
  8716. "%s",
  8717. "Error: Directory listing denied");
  8718. }
  8719. } else {
  8720. handle_static_file_request(
  8721. conn, path, &file, mime_type, additional_headers);
  8722. }
  8723. } else {
  8724. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8725. }
  8726. }
  8727. /* For a given PUT path, create all intermediate subdirectories.
  8728. * Return 0 if the path itself is a directory.
  8729. * Return 1 if the path leads to a file.
  8730. * Return -1 for if the path is too long.
  8731. * Return -2 if path can not be created.
  8732. */
  8733. static int
  8734. put_dir(struct mg_connection *conn, const char *path)
  8735. {
  8736. char buf[UTF8_PATH_MAX];
  8737. const char *s, *p;
  8738. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8739. size_t len;
  8740. int res = 1;
  8741. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8742. len = (size_t)(p - path);
  8743. if (len >= sizeof(buf)) {
  8744. /* path too long */
  8745. res = -1;
  8746. break;
  8747. }
  8748. memcpy(buf, path, len);
  8749. buf[len] = '\0';
  8750. /* Try to create intermediate directory */
  8751. DEBUG_TRACE("mkdir(%s)", buf);
  8752. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8753. /* path does not exixt and can not be created */
  8754. res = -2;
  8755. break;
  8756. }
  8757. /* Is path itself a directory? */
  8758. if (p[1] == '\0') {
  8759. res = 0;
  8760. }
  8761. }
  8762. return res;
  8763. }
  8764. static void
  8765. remove_bad_file(const struct mg_connection *conn, const char *path)
  8766. {
  8767. int r = mg_remove(conn, path);
  8768. if (r != 0) {
  8769. mg_cry_internal(conn,
  8770. "%s: Cannot remove invalid file %s",
  8771. __func__,
  8772. path);
  8773. }
  8774. }
  8775. long long
  8776. mg_store_body(struct mg_connection *conn, const char *path)
  8777. {
  8778. char buf[MG_BUF_LEN];
  8779. long long len = 0;
  8780. int ret, n;
  8781. struct mg_file fi;
  8782. if (conn->consumed_content != 0) {
  8783. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8784. return -11;
  8785. }
  8786. ret = put_dir(conn, path);
  8787. if (ret < 0) {
  8788. /* -1 for path too long,
  8789. * -2 for path can not be created. */
  8790. return ret;
  8791. }
  8792. if (ret != 1) {
  8793. /* Return 0 means, path itself is a directory. */
  8794. return 0;
  8795. }
  8796. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8797. return -12;
  8798. }
  8799. ret = mg_read(conn, buf, sizeof(buf));
  8800. while (ret > 0) {
  8801. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8802. if (n != ret) {
  8803. (void)mg_fclose(
  8804. &fi.access); /* File is bad and will be removed anyway. */
  8805. remove_bad_file(conn, path);
  8806. return -13;
  8807. }
  8808. len += ret;
  8809. ret = mg_read(conn, buf, sizeof(buf));
  8810. }
  8811. /* File is open for writing. If fclose fails, there was probably an
  8812. * error flushing the buffer to disk, so the file on disk might be
  8813. * broken. Delete it and return an error to the caller. */
  8814. if (mg_fclose(&fi.access) != 0) {
  8815. remove_bad_file(conn, path);
  8816. return -14;
  8817. }
  8818. return len;
  8819. }
  8820. #endif /* NO_FILESYSTEMS */
  8821. /* Parse a buffer:
  8822. * Forward the string pointer till the end of a word, then
  8823. * terminate it and forward till the begin of the next word.
  8824. */
  8825. static int
  8826. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8827. {
  8828. /* Forward until a space is found - use isgraph here */
  8829. /* See http://www.cplusplus.com/reference/cctype/ */
  8830. while (isgraph((unsigned char)**ppw)) {
  8831. (*ppw)++;
  8832. }
  8833. /* Check end of word */
  8834. if (eol) {
  8835. /* must be a end of line */
  8836. if ((**ppw != '\r') && (**ppw != '\n')) {
  8837. return -1;
  8838. }
  8839. } else {
  8840. /* must be a end of a word, but not a line */
  8841. if (**ppw != ' ') {
  8842. return -1;
  8843. }
  8844. }
  8845. /* Terminate and forward to the next word */
  8846. do {
  8847. **ppw = 0;
  8848. (*ppw)++;
  8849. } while (isspace((unsigned char)**ppw));
  8850. /* Check after term */
  8851. if (!eol) {
  8852. /* if it's not the end of line, there must be a next word */
  8853. if (!isgraph((unsigned char)**ppw)) {
  8854. return -1;
  8855. }
  8856. }
  8857. /* ok */
  8858. return 1;
  8859. }
  8860. /* Parse HTTP headers from the given buffer, advance buf pointer
  8861. * to the point where parsing stopped.
  8862. * All parameters must be valid pointers (not NULL).
  8863. * Return <0 on error. */
  8864. static int
  8865. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8866. {
  8867. int i;
  8868. int num_headers = 0;
  8869. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8870. char *dp = *buf;
  8871. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8872. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8873. dp++;
  8874. }
  8875. if (dp == *buf) {
  8876. /* End of headers reached. */
  8877. break;
  8878. }
  8879. /* Drop all spaces after header name before : */
  8880. while (*dp == ' ') {
  8881. *dp = 0;
  8882. dp++;
  8883. }
  8884. if (*dp != ':') {
  8885. /* This is not a valid field. */
  8886. return -1;
  8887. }
  8888. /* End of header key (*dp == ':') */
  8889. /* Truncate here and set the key name */
  8890. *dp = 0;
  8891. hdr[i].name = *buf;
  8892. /* Skip all spaces */
  8893. do {
  8894. dp++;
  8895. } while ((*dp == ' ') || (*dp == '\t'));
  8896. /* The rest of the line is the value */
  8897. hdr[i].value = dp;
  8898. /* Find end of line */
  8899. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8900. dp++;
  8901. };
  8902. /* eliminate \r */
  8903. if (*dp == '\r') {
  8904. *dp = 0;
  8905. dp++;
  8906. if (*dp != '\n') {
  8907. /* This is not a valid line. */
  8908. return -1;
  8909. }
  8910. }
  8911. /* here *dp is either 0 or '\n' */
  8912. /* in any case, we have a new header */
  8913. num_headers = i + 1;
  8914. if (*dp) {
  8915. *dp = 0;
  8916. dp++;
  8917. *buf = dp;
  8918. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8919. /* This is the end of the header */
  8920. break;
  8921. }
  8922. } else {
  8923. *buf = dp;
  8924. break;
  8925. }
  8926. }
  8927. return num_headers;
  8928. }
  8929. struct mg_http_method_info {
  8930. const char *name;
  8931. int request_has_body;
  8932. int response_has_body;
  8933. int is_safe;
  8934. int is_idempotent;
  8935. int is_cacheable;
  8936. };
  8937. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8938. static const struct mg_http_method_info http_methods[] = {
  8939. /* HTTP (RFC 2616) */
  8940. {"GET", 0, 1, 1, 1, 1},
  8941. {"POST", 1, 1, 0, 0, 0},
  8942. {"PUT", 1, 0, 0, 1, 0},
  8943. {"DELETE", 0, 0, 0, 1, 0},
  8944. {"HEAD", 0, 0, 1, 1, 1},
  8945. {"OPTIONS", 0, 0, 1, 1, 0},
  8946. {"CONNECT", 1, 1, 0, 0, 0},
  8947. /* TRACE method (RFC 2616) is not supported for security reasons */
  8948. /* PATCH method (RFC 5789) */
  8949. {"PATCH", 1, 0, 0, 0, 0},
  8950. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8951. /* WEBDAV (RFC 2518) */
  8952. {"PROPFIND", 0, 1, 1, 1, 0},
  8953. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8954. * Some PROPFIND results MAY be cached, with care,
  8955. * as there is no cache validation mechanism for
  8956. * most properties. This method is both safe and
  8957. * idempotent (see Section 9.1 of [RFC2616]). */
  8958. {"MKCOL", 0, 0, 0, 1, 0},
  8959. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8960. * When MKCOL is invoked without a request body,
  8961. * the newly created collection SHOULD have no
  8962. * members. A MKCOL request message may contain
  8963. * a message body. The precise behavior of a MKCOL
  8964. * request when the body is present is undefined,
  8965. * ... ==> We do not support MKCOL with body data.
  8966. * This method is idempotent, but not safe (see
  8967. * Section 9.1 of [RFC2616]). Responses to this
  8968. * method MUST NOT be cached. */
  8969. /* Methods for write access to files on WEBDAV (RFC 2518) */
  8970. {"LOCK", 1, 1, 0, 0, 0},
  8971. {"UNLOCK", 1, 0, 0, 0, 0},
  8972. {"PROPPATCH", 1, 1, 0, 0, 0},
  8973. /* Unsupported WEBDAV Methods: */
  8974. /* COPY, MOVE (RFC 2518) */
  8975. /* + 11 methods from RFC 3253 */
  8976. /* ORDERPATCH (RFC 3648) */
  8977. /* ACL (RFC 3744) */
  8978. /* SEARCH (RFC 5323) */
  8979. /* + MicroSoft extensions
  8980. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8981. /* REPORT method (RFC 3253) */
  8982. {"REPORT", 1, 1, 1, 1, 1},
  8983. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8984. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8985. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8986. * to be useful for REST in case a "GET request with body" is
  8987. * required. */
  8988. {NULL, 0, 0, 0, 0, 0}
  8989. /* end of list */
  8990. };
  8991. static const struct mg_http_method_info *
  8992. get_http_method_info(const char *method)
  8993. {
  8994. /* Check if the method is known to the server. The list of all known
  8995. * HTTP methods can be found here at
  8996. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8997. */
  8998. const struct mg_http_method_info *m = http_methods;
  8999. while (m->name) {
  9000. if (!strcmp(m->name, method)) {
  9001. return m;
  9002. }
  9003. m++;
  9004. }
  9005. return NULL;
  9006. }
  9007. static int
  9008. is_valid_http_method(const char *method)
  9009. {
  9010. return (get_http_method_info(method) != NULL);
  9011. }
  9012. /* Parse HTTP request, fill in mg_request_info structure.
  9013. * This function modifies the buffer by NUL-terminating
  9014. * HTTP request components, header names and header values.
  9015. * Parameters:
  9016. * buf (in/out): pointer to the HTTP header to parse and split
  9017. * len (in): length of HTTP header buffer
  9018. * re (out): parsed header as mg_request_info
  9019. * buf and ri must be valid pointers (not NULL), len>0.
  9020. * Returns <0 on error. */
  9021. static int
  9022. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9023. {
  9024. int request_length;
  9025. int init_skip = 0;
  9026. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9027. * remote_port */
  9028. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9029. NULL;
  9030. ri->num_headers = 0;
  9031. /* RFC says that all initial whitespaces should be ingored */
  9032. /* This included all leading \r and \n (isspace) */
  9033. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9034. while ((len > 0) && isspace((unsigned char)*buf)) {
  9035. buf++;
  9036. len--;
  9037. init_skip++;
  9038. }
  9039. if (len == 0) {
  9040. /* Incomplete request */
  9041. return 0;
  9042. }
  9043. /* Control characters are not allowed, including zero */
  9044. if (iscntrl((unsigned char)*buf)) {
  9045. return -1;
  9046. }
  9047. /* Find end of HTTP header */
  9048. request_length = get_http_header_len(buf, len);
  9049. if (request_length <= 0) {
  9050. return request_length;
  9051. }
  9052. buf[request_length - 1] = '\0';
  9053. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9054. return -1;
  9055. }
  9056. /* The first word has to be the HTTP method */
  9057. ri->request_method = buf;
  9058. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9059. return -1;
  9060. }
  9061. /* Check for a valid http method */
  9062. if (!is_valid_http_method(ri->request_method)) {
  9063. return -1;
  9064. }
  9065. /* The second word is the URI */
  9066. ri->request_uri = buf;
  9067. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9068. return -1;
  9069. }
  9070. /* Next would be the HTTP version */
  9071. ri->http_version = buf;
  9072. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9073. return -1;
  9074. }
  9075. /* Check for a valid HTTP version key */
  9076. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9077. /* Invalid request */
  9078. return -1;
  9079. }
  9080. ri->http_version += 5;
  9081. /* Parse all HTTP headers */
  9082. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9083. if (ri->num_headers < 0) {
  9084. /* Error while parsing headers */
  9085. return -1;
  9086. }
  9087. return request_length + init_skip;
  9088. }
  9089. static int
  9090. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9091. {
  9092. int response_length;
  9093. int init_skip = 0;
  9094. char *tmp, *tmp2;
  9095. long l;
  9096. /* Initialize elements. */
  9097. ri->http_version = ri->status_text = NULL;
  9098. ri->num_headers = ri->status_code = 0;
  9099. /* RFC says that all initial whitespaces should be ingored */
  9100. /* This included all leading \r and \n (isspace) */
  9101. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9102. while ((len > 0) && isspace((unsigned char)*buf)) {
  9103. buf++;
  9104. len--;
  9105. init_skip++;
  9106. }
  9107. if (len == 0) {
  9108. /* Incomplete request */
  9109. return 0;
  9110. }
  9111. /* Control characters are not allowed, including zero */
  9112. if (iscntrl((unsigned char)*buf)) {
  9113. return -1;
  9114. }
  9115. /* Find end of HTTP header */
  9116. response_length = get_http_header_len(buf, len);
  9117. if (response_length <= 0) {
  9118. return response_length;
  9119. }
  9120. buf[response_length - 1] = '\0';
  9121. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9122. return -1;
  9123. }
  9124. /* The first word is the HTTP version */
  9125. /* Check for a valid HTTP version key */
  9126. if (strncmp(buf, "HTTP/", 5) != 0) {
  9127. /* Invalid request */
  9128. return -1;
  9129. }
  9130. buf += 5;
  9131. if (!isgraph((unsigned char)buf[0])) {
  9132. /* Invalid request */
  9133. return -1;
  9134. }
  9135. ri->http_version = buf;
  9136. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9137. return -1;
  9138. }
  9139. /* The second word is the status as a number */
  9140. tmp = buf;
  9141. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9142. return -1;
  9143. }
  9144. l = strtol(tmp, &tmp2, 10);
  9145. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9146. /* Everything else but a 3 digit code is invalid */
  9147. return -1;
  9148. }
  9149. ri->status_code = (int)l;
  9150. /* The rest of the line is the status text */
  9151. ri->status_text = buf;
  9152. /* Find end of status text */
  9153. /* isgraph or isspace = isprint */
  9154. while (isprint((unsigned char)*buf)) {
  9155. buf++;
  9156. }
  9157. if ((*buf != '\r') && (*buf != '\n')) {
  9158. return -1;
  9159. }
  9160. /* Terminate string and forward buf to next line */
  9161. do {
  9162. *buf = 0;
  9163. buf++;
  9164. } while (isspace((unsigned char)*buf));
  9165. /* Parse all HTTP headers */
  9166. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9167. if (ri->num_headers < 0) {
  9168. /* Error while parsing headers */
  9169. return -1;
  9170. }
  9171. return response_length + init_skip;
  9172. }
  9173. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9174. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9175. * buffer (which marks the end of HTTP request). Buffer buf may already
  9176. * have some data. The length of the data is stored in nread.
  9177. * Upon every read operation, increase nread by the number of bytes read. */
  9178. static int
  9179. read_message(FILE *fp,
  9180. struct mg_connection *conn,
  9181. char *buf,
  9182. int bufsiz,
  9183. int *nread)
  9184. {
  9185. int request_len, n = 0;
  9186. struct timespec last_action_time;
  9187. double request_timeout;
  9188. if (!conn) {
  9189. return 0;
  9190. }
  9191. memset(&last_action_time, 0, sizeof(last_action_time));
  9192. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9193. /* value of request_timeout is in seconds, config in milliseconds */
  9194. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9195. } else {
  9196. request_timeout =
  9197. atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  9198. }
  9199. if (conn->handled_requests > 0) {
  9200. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9201. request_timeout =
  9202. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9203. }
  9204. }
  9205. request_len = get_http_header_len(buf, *nread);
  9206. while (request_len == 0) {
  9207. /* Full request not yet received */
  9208. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9209. /* Server is to be stopped. */
  9210. return -1;
  9211. }
  9212. if (*nread >= bufsiz) {
  9213. /* Request too long */
  9214. return -2;
  9215. }
  9216. n = pull_inner(
  9217. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9218. if (n == -2) {
  9219. /* Receive error */
  9220. return -1;
  9221. }
  9222. /* update clock after every read request */
  9223. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9224. if (n > 0) {
  9225. *nread += n;
  9226. request_len = get_http_header_len(buf, *nread);
  9227. }
  9228. if ((request_len == 0) && (request_timeout >= 0)) {
  9229. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9230. > request_timeout) {
  9231. /* Timeout */
  9232. return -1;
  9233. }
  9234. }
  9235. }
  9236. return request_len;
  9237. }
  9238. #if !defined(NO_CGI) || !defined(NO_FILES)
  9239. static int
  9240. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9241. {
  9242. const char *expect;
  9243. char buf[MG_BUF_LEN];
  9244. int success = 0;
  9245. if (!conn) {
  9246. return 0;
  9247. }
  9248. expect = mg_get_header(conn, "Expect");
  9249. DEBUG_ASSERT(fp != NULL);
  9250. if (!fp) {
  9251. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9252. return 0;
  9253. }
  9254. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9255. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9256. */
  9257. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9258. } else {
  9259. if (expect != NULL) {
  9260. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9261. conn->status_code = 100;
  9262. } else {
  9263. conn->status_code = 200;
  9264. }
  9265. DEBUG_ASSERT(conn->consumed_content == 0);
  9266. if (conn->consumed_content != 0) {
  9267. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9268. return 0;
  9269. }
  9270. for (;;) {
  9271. int nread = mg_read(conn, buf, sizeof(buf));
  9272. if (nread <= 0) {
  9273. success = (nread == 0);
  9274. break;
  9275. }
  9276. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9277. break;
  9278. }
  9279. }
  9280. /* Each error code path in this function must send an error */
  9281. if (!success) {
  9282. /* NOTE: Maybe some data has already been sent. */
  9283. /* TODO (low): If some data has been sent, a correct error
  9284. * reply can no longer be sent, so just close the connection */
  9285. mg_send_http_error(conn, 500, "%s", "");
  9286. }
  9287. }
  9288. return success;
  9289. }
  9290. #endif
  9291. #if defined(USE_TIMERS)
  9292. #define TIMER_API static
  9293. #include "timer.inl"
  9294. #endif /* USE_TIMERS */
  9295. #if !defined(NO_CGI)
  9296. /* This structure helps to create an environment for the spawned CGI
  9297. * program.
  9298. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9299. * last element must be NULL.
  9300. * However, on Windows there is a requirement that all these
  9301. * VARIABLE=VALUE\0
  9302. * strings must reside in a contiguous buffer. The end of the buffer is
  9303. * marked by two '\0' characters.
  9304. * We satisfy both worlds: we create an envp array (which is vars), all
  9305. * entries are actually pointers inside buf. */
  9306. struct cgi_environment {
  9307. struct mg_connection *conn;
  9308. /* Data block */
  9309. char *buf; /* Environment buffer */
  9310. size_t buflen; /* Space available in buf */
  9311. size_t bufused; /* Space taken in buf */
  9312. /* Index block */
  9313. char **var; /* char **envp */
  9314. size_t varlen; /* Number of variables available in var */
  9315. size_t varused; /* Number of variables stored in var */
  9316. };
  9317. static void addenv(struct cgi_environment *env,
  9318. PRINTF_FORMAT_STRING(const char *fmt),
  9319. ...) PRINTF_ARGS(2, 3);
  9320. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9321. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9322. static void
  9323. addenv(struct cgi_environment *env, const char *fmt, ...)
  9324. {
  9325. size_t i, n, space;
  9326. int truncated = 0;
  9327. char *added;
  9328. va_list ap;
  9329. if ((env->varlen - env->varused) < 2) {
  9330. mg_cry_internal(env->conn,
  9331. "%s: Cannot register CGI variable [%s]",
  9332. __func__,
  9333. fmt);
  9334. return;
  9335. }
  9336. /* Calculate how much space is left in the buffer */
  9337. space = (env->buflen - env->bufused);
  9338. do {
  9339. /* Space for "\0\0" is always needed. */
  9340. if (space <= 2) {
  9341. /* Allocate new buffer */
  9342. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9343. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9344. if (!added) {
  9345. /* Out of memory */
  9346. mg_cry_internal(
  9347. env->conn,
  9348. "%s: Cannot allocate memory for CGI variable [%s]",
  9349. __func__,
  9350. fmt);
  9351. return;
  9352. }
  9353. /* Retarget pointers */
  9354. env->buf = added;
  9355. env->buflen = n;
  9356. for (i = 0, n = 0; i < env->varused; i++) {
  9357. env->var[i] = added + n;
  9358. n += strlen(added + n) + 1;
  9359. }
  9360. space = (env->buflen - env->bufused);
  9361. }
  9362. /* Make a pointer to the free space int the buffer */
  9363. added = env->buf + env->bufused;
  9364. /* Copy VARIABLE=VALUE\0 string into the free space */
  9365. va_start(ap, fmt);
  9366. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9367. va_end(ap);
  9368. /* Do not add truncated strings to the environment */
  9369. if (truncated) {
  9370. /* Reallocate the buffer */
  9371. space = 0;
  9372. }
  9373. } while (truncated);
  9374. /* Calculate number of bytes added to the environment */
  9375. n = strlen(added) + 1;
  9376. env->bufused += n;
  9377. /* Append a pointer to the added string into the envp array */
  9378. env->var[env->varused] = added;
  9379. env->varused++;
  9380. }
  9381. /* Return 0 on success, non-zero if an error occurs. */
  9382. static int
  9383. prepare_cgi_environment(struct mg_connection *conn,
  9384. const char *prog,
  9385. struct cgi_environment *env,
  9386. unsigned char cgi_config_idx)
  9387. {
  9388. const char *s;
  9389. struct vec var_vec;
  9390. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9391. int i, truncated, uri_len;
  9392. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9393. return -1;
  9394. }
  9395. env->conn = conn;
  9396. env->buflen = CGI_ENVIRONMENT_SIZE;
  9397. env->bufused = 0;
  9398. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9399. if (env->buf == NULL) {
  9400. mg_cry_internal(conn,
  9401. "%s: Not enough memory for environmental buffer",
  9402. __func__);
  9403. return -1;
  9404. }
  9405. env->varlen = MAX_CGI_ENVIR_VARS;
  9406. env->varused = 0;
  9407. env->var =
  9408. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9409. if (env->var == NULL) {
  9410. mg_cry_internal(conn,
  9411. "%s: Not enough memory for environmental variables",
  9412. __func__);
  9413. mg_free(env->buf);
  9414. return -1;
  9415. }
  9416. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9417. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9418. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9419. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9420. /* Prepare the environment block */
  9421. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9422. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9423. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9424. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9425. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9426. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9427. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9428. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9429. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9430. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9431. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9432. /* SCRIPT_NAME */
  9433. uri_len = (int)strlen(conn->request_info.local_uri);
  9434. if (conn->path_info == NULL) {
  9435. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9436. /* URI: /path_to_script/script.cgi */
  9437. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9438. } else {
  9439. /* URI: /path_to_script/ ... using index.cgi */
  9440. const char *index_file = strrchr(prog, '/');
  9441. if (index_file) {
  9442. addenv(env,
  9443. "SCRIPT_NAME=%s%s",
  9444. conn->request_info.local_uri,
  9445. index_file + 1);
  9446. }
  9447. }
  9448. } else {
  9449. /* URI: /path_to_script/script.cgi/path_info */
  9450. addenv(env,
  9451. "SCRIPT_NAME=%.*s",
  9452. uri_len - (int)strlen(conn->path_info),
  9453. conn->request_info.local_uri);
  9454. }
  9455. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9456. if (conn->path_info == NULL) {
  9457. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9458. } else {
  9459. addenv(env,
  9460. "PATH_TRANSLATED=%s%s",
  9461. conn->dom_ctx->config[DOCUMENT_ROOT],
  9462. conn->path_info);
  9463. }
  9464. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9465. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9466. addenv(env, "CONTENT_TYPE=%s", s);
  9467. }
  9468. if (conn->request_info.query_string != NULL) {
  9469. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9470. }
  9471. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9472. addenv(env, "CONTENT_LENGTH=%s", s);
  9473. }
  9474. if ((s = getenv("PATH")) != NULL) {
  9475. addenv(env, "PATH=%s", s);
  9476. }
  9477. if (conn->path_info != NULL) {
  9478. addenv(env, "PATH_INFO=%s", conn->path_info);
  9479. }
  9480. if (conn->status_code > 0) {
  9481. /* CGI error handler should show the status code */
  9482. addenv(env, "STATUS=%d", conn->status_code);
  9483. }
  9484. #if defined(_WIN32)
  9485. if ((s = getenv("COMSPEC")) != NULL) {
  9486. addenv(env, "COMSPEC=%s", s);
  9487. }
  9488. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9489. addenv(env, "SYSTEMROOT=%s", s);
  9490. }
  9491. if ((s = getenv("SystemDrive")) != NULL) {
  9492. addenv(env, "SystemDrive=%s", s);
  9493. }
  9494. if ((s = getenv("ProgramFiles")) != NULL) {
  9495. addenv(env, "ProgramFiles=%s", s);
  9496. }
  9497. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9498. addenv(env, "ProgramFiles(x86)=%s", s);
  9499. }
  9500. #else
  9501. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9502. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9503. }
  9504. #endif /* _WIN32 */
  9505. if ((s = getenv("PERLLIB")) != NULL) {
  9506. addenv(env, "PERLLIB=%s", s);
  9507. }
  9508. if (conn->request_info.remote_user != NULL) {
  9509. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9510. addenv(env, "%s", "AUTH_TYPE=Digest");
  9511. }
  9512. /* Add all headers as HTTP_* variables */
  9513. for (i = 0; i < conn->request_info.num_headers; i++) {
  9514. (void)mg_snprintf(conn,
  9515. &truncated,
  9516. http_var_name,
  9517. sizeof(http_var_name),
  9518. "HTTP_%s",
  9519. conn->request_info.http_headers[i].name);
  9520. if (truncated) {
  9521. mg_cry_internal(conn,
  9522. "%s: HTTP header variable too long [%s]",
  9523. __func__,
  9524. conn->request_info.http_headers[i].name);
  9525. continue;
  9526. }
  9527. /* Convert variable name into uppercase, and change - to _ */
  9528. for (p = http_var_name; *p != '\0'; p++) {
  9529. if (*p == '-') {
  9530. *p = '_';
  9531. }
  9532. *p = (char)toupper((unsigned char)*p);
  9533. }
  9534. addenv(env,
  9535. "%s=%s",
  9536. http_var_name,
  9537. conn->request_info.http_headers[i].value);
  9538. }
  9539. /* Add user-specified variables */
  9540. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  9541. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9542. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9543. }
  9544. env->var[env->varused] = NULL;
  9545. env->buf[env->bufused] = '\0';
  9546. return 0;
  9547. }
  9548. /* Data for CGI process control: PID and number of references */
  9549. struct process_control_data {
  9550. pid_t pid;
  9551. ptrdiff_t references;
  9552. };
  9553. static int
  9554. abort_cgi_process(void *data)
  9555. {
  9556. /* Waitpid checks for child status and won't work for a pid that does
  9557. * not identify a child of the current process. Thus, if the pid is
  9558. * reused, we will not affect a different process. */
  9559. struct process_control_data *proc = (struct process_control_data *)data;
  9560. int status = 0;
  9561. ptrdiff_t refs;
  9562. pid_t ret_pid;
  9563. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9564. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9565. /* Stop child process */
  9566. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9567. kill(proc->pid, SIGABRT);
  9568. /* Wait until process is terminated (don't leave zombies) */
  9569. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9570. ;
  9571. } else {
  9572. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9573. }
  9574. /* Dec reference counter */
  9575. refs = mg_atomic_dec(&proc->references);
  9576. if (refs == 0) {
  9577. /* no more references - free data */
  9578. mg_free(data);
  9579. }
  9580. return 0;
  9581. }
  9582. /* Local (static) function assumes all arguments are valid. */
  9583. static void
  9584. handle_cgi_request(struct mg_connection *conn,
  9585. const char *prog,
  9586. unsigned char cgi_config_idx)
  9587. {
  9588. char *buf;
  9589. size_t buflen;
  9590. int headers_len, data_len, i, truncated;
  9591. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9592. const char *status, *status_text, *connection_state;
  9593. char *pbuf, dir[UTF8_PATH_MAX], *p;
  9594. struct mg_request_info ri;
  9595. struct cgi_environment blk;
  9596. FILE *in = NULL, *out = NULL, *err = NULL;
  9597. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9598. pid_t pid = (pid_t)-1;
  9599. struct process_control_data *proc = NULL;
  9600. #if defined(USE_TIMERS)
  9601. double cgi_timeout;
  9602. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  9603. /* Get timeout in seconds */
  9604. cgi_timeout =
  9605. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  9606. } else {
  9607. cgi_timeout =
  9608. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  9609. }
  9610. #endif
  9611. buf = NULL;
  9612. buflen = conn->phys_ctx->max_request_size;
  9613. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  9614. if (i != 0) {
  9615. blk.buf = NULL;
  9616. blk.var = NULL;
  9617. goto done;
  9618. }
  9619. /* CGI must be executed in its own directory. 'dir' must point to the
  9620. * directory containing executable program, 'p' must point to the
  9621. * executable program name relative to 'dir'. */
  9622. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9623. if (truncated) {
  9624. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9625. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9626. goto done;
  9627. }
  9628. if ((p = strrchr(dir, '/')) != NULL) {
  9629. *p++ = '\0';
  9630. } else {
  9631. dir[0] = '.';
  9632. dir[1] = '\0';
  9633. p = (char *)prog;
  9634. }
  9635. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9636. status = strerror(ERRNO);
  9637. mg_cry_internal(
  9638. conn,
  9639. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9640. prog,
  9641. status);
  9642. mg_send_http_error(conn,
  9643. 500,
  9644. "Error: Cannot create CGI pipe: %s",
  9645. status);
  9646. goto done;
  9647. }
  9648. proc = (struct process_control_data *)
  9649. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9650. if (proc == NULL) {
  9651. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9652. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9653. goto done;
  9654. }
  9655. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9656. pid = spawn_process(
  9657. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  9658. if (pid == (pid_t)-1) {
  9659. status = strerror(ERRNO);
  9660. mg_cry_internal(
  9661. conn,
  9662. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9663. prog,
  9664. status);
  9665. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  9666. mg_free(proc);
  9667. proc = NULL;
  9668. goto done;
  9669. }
  9670. /* Store data in shared process_control_data */
  9671. proc->pid = pid;
  9672. proc->references = 1;
  9673. #if defined(USE_TIMERS)
  9674. if (cgi_timeout > 0.0) {
  9675. proc->references = 2;
  9676. // Start a timer for CGI
  9677. timer_add(conn->phys_ctx,
  9678. cgi_timeout /* in seconds */,
  9679. 0.0,
  9680. 1,
  9681. abort_cgi_process,
  9682. (void *)proc,
  9683. NULL);
  9684. }
  9685. #endif
  9686. /* Parent closes only one side of the pipes.
  9687. * If we don't mark them as closed, close() attempt before
  9688. * return from this function throws an exception on Windows.
  9689. * Windows does not like when closed descriptor is closed again. */
  9690. (void)close(fdin[0]);
  9691. (void)close(fdout[1]);
  9692. (void)close(fderr[1]);
  9693. fdin[0] = fdout[1] = fderr[1] = -1;
  9694. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9695. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9696. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9697. status = strerror(ERRNO);
  9698. mg_cry_internal(conn,
  9699. "Error: CGI program \"%s\": Can not open fd: %s",
  9700. prog,
  9701. status);
  9702. mg_send_http_error(conn,
  9703. 500,
  9704. "Error: CGI can not open fd\nfdopen: %s",
  9705. status);
  9706. goto done;
  9707. }
  9708. setbuf(in, NULL);
  9709. setbuf(out, NULL);
  9710. setbuf(err, NULL);
  9711. fout.access.fp = out;
  9712. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9713. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9714. conn->content_len);
  9715. /* This is a POST/PUT request, or another request with body data. */
  9716. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9717. /* Error sending the body data */
  9718. mg_cry_internal(
  9719. conn,
  9720. "Error: CGI program \"%s\": Forward body data failed",
  9721. prog);
  9722. goto done;
  9723. }
  9724. }
  9725. /* Close so child gets an EOF. */
  9726. fclose(in);
  9727. in = NULL;
  9728. fdin[1] = -1;
  9729. /* Now read CGI reply into a buffer. We need to set correct
  9730. * status code, thus we need to see all HTTP headers first.
  9731. * Do not send anything back to client, until we buffer in all
  9732. * HTTP headers. */
  9733. data_len = 0;
  9734. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9735. if (buf == NULL) {
  9736. mg_send_http_error(conn,
  9737. 500,
  9738. "Error: Not enough memory for CGI buffer (%u bytes)",
  9739. (unsigned int)buflen);
  9740. mg_cry_internal(
  9741. conn,
  9742. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9743. "bytes)",
  9744. prog,
  9745. (unsigned int)buflen);
  9746. goto done;
  9747. }
  9748. DEBUG_TRACE("CGI: %s", "wait for response");
  9749. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9750. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9751. if (headers_len <= 0) {
  9752. /* Could not parse the CGI response. Check if some error message on
  9753. * stderr. */
  9754. i = pull_all(err, conn, buf, (int)buflen);
  9755. if (i > 0) {
  9756. /* CGI program explicitly sent an error */
  9757. /* Write the error message to the internal log */
  9758. mg_cry_internal(conn,
  9759. "Error: CGI program \"%s\" sent error "
  9760. "message: [%.*s]",
  9761. prog,
  9762. i,
  9763. buf);
  9764. /* Don't send the error message back to the client */
  9765. mg_send_http_error(conn,
  9766. 500,
  9767. "Error: CGI program \"%s\" failed.",
  9768. prog);
  9769. } else {
  9770. /* CGI program did not explicitly send an error, but a broken
  9771. * respon header */
  9772. mg_cry_internal(conn,
  9773. "Error: CGI program sent malformed or too big "
  9774. "(>%u bytes) HTTP headers: [%.*s]",
  9775. (unsigned)buflen,
  9776. data_len,
  9777. buf);
  9778. mg_send_http_error(conn,
  9779. 500,
  9780. "Error: CGI program sent malformed or too big "
  9781. "(>%u bytes) HTTP headers: [%.*s]",
  9782. (unsigned)buflen,
  9783. data_len,
  9784. buf);
  9785. }
  9786. /* in both cases, abort processing CGI */
  9787. goto done;
  9788. }
  9789. pbuf = buf;
  9790. buf[headers_len - 1] = '\0';
  9791. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9792. /* Make up and send the status line */
  9793. status_text = "OK";
  9794. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9795. != NULL) {
  9796. conn->status_code = atoi(status);
  9797. status_text = status;
  9798. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9799. status_text++;
  9800. }
  9801. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9802. != NULL) {
  9803. conn->status_code = 307;
  9804. } else {
  9805. conn->status_code = 200;
  9806. }
  9807. connection_state =
  9808. get_header(ri.http_headers, ri.num_headers, "Connection");
  9809. if (!header_has_option(connection_state, "keep-alive")) {
  9810. conn->must_close = 1;
  9811. }
  9812. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9813. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9814. /* Send headers */
  9815. for (i = 0; i < ri.num_headers; i++) {
  9816. DEBUG_TRACE("CGI header: %s: %s",
  9817. ri.http_headers[i].name,
  9818. ri.http_headers[i].value);
  9819. mg_printf(conn,
  9820. "%s: %s\r\n",
  9821. ri.http_headers[i].name,
  9822. ri.http_headers[i].value);
  9823. }
  9824. mg_write(conn, "\r\n", 2);
  9825. /* Send chunk of data that may have been read after the headers */
  9826. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9827. /* Read the rest of CGI output and send to the client */
  9828. DEBUG_TRACE("CGI: %s", "forward all data");
  9829. send_file_data(conn, &fout, 0, INT64_MAX);
  9830. DEBUG_TRACE("CGI: %s", "all data sent");
  9831. done:
  9832. mg_free(blk.var);
  9833. mg_free(blk.buf);
  9834. if (pid != (pid_t)-1) {
  9835. abort_cgi_process((void *)proc);
  9836. }
  9837. if (fdin[0] != -1) {
  9838. close(fdin[0]);
  9839. }
  9840. if (fdout[1] != -1) {
  9841. close(fdout[1]);
  9842. }
  9843. if (fderr[1] != -1) {
  9844. close(fderr[1]);
  9845. }
  9846. if (in != NULL) {
  9847. fclose(in);
  9848. } else if (fdin[1] != -1) {
  9849. close(fdin[1]);
  9850. }
  9851. if (out != NULL) {
  9852. fclose(out);
  9853. } else if (fdout[0] != -1) {
  9854. close(fdout[0]);
  9855. }
  9856. if (err != NULL) {
  9857. fclose(err);
  9858. } else if (fderr[0] != -1) {
  9859. close(fderr[0]);
  9860. }
  9861. mg_free(buf);
  9862. }
  9863. #endif /* !NO_CGI */
  9864. #if !defined(NO_FILES)
  9865. static void
  9866. mkcol(struct mg_connection *conn, const char *path)
  9867. {
  9868. int rc, body_len;
  9869. struct de de;
  9870. if (conn == NULL) {
  9871. return;
  9872. }
  9873. /* TODO (mid): Check the mg_send_http_error situations in this function
  9874. */
  9875. memset(&de.file, 0, sizeof(de.file));
  9876. if (!mg_stat(conn, path, &de.file)) {
  9877. mg_cry_internal(conn,
  9878. "%s: mg_stat(%s) failed: %s",
  9879. __func__,
  9880. path,
  9881. strerror(ERRNO));
  9882. }
  9883. if (de.file.last_modified) {
  9884. /* TODO (mid): This check does not seem to make any sense ! */
  9885. /* TODO (mid): Add a webdav unit test first, before changing
  9886. * anything here. */
  9887. mg_send_http_error(
  9888. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9889. return;
  9890. }
  9891. body_len = conn->data_len - conn->request_len;
  9892. if (body_len > 0) {
  9893. mg_send_http_error(
  9894. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9895. return;
  9896. }
  9897. rc = mg_mkdir(conn, path, 0755);
  9898. if (rc == 0) {
  9899. /* Create 201 "Created" response */
  9900. mg_response_header_start(conn, 201);
  9901. send_static_cache_header(conn);
  9902. send_additional_header(conn);
  9903. mg_response_header_add(conn, "Content-Length", "0", -1);
  9904. /* Send all headers - there is no body */
  9905. mg_response_header_send(conn);
  9906. } else {
  9907. if (errno == EEXIST) {
  9908. mg_send_http_error(
  9909. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9910. } else if (errno == EACCES) {
  9911. mg_send_http_error(
  9912. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9913. } else if (errno == ENOENT) {
  9914. mg_send_http_error(
  9915. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9916. } else {
  9917. mg_send_http_error(
  9918. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9919. }
  9920. }
  9921. }
  9922. static void
  9923. put_file(struct mg_connection *conn, const char *path)
  9924. {
  9925. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9926. const char *range;
  9927. int64_t r1, r2;
  9928. int rc;
  9929. if (conn == NULL) {
  9930. return;
  9931. }
  9932. if (mg_stat(conn, path, &file.stat)) {
  9933. /* File already exists */
  9934. conn->status_code = 200;
  9935. if (file.stat.is_directory) {
  9936. /* This is an already existing directory,
  9937. * so there is nothing to do for the server. */
  9938. rc = 0;
  9939. } else {
  9940. /* File exists and is not a directory. */
  9941. /* Can it be replaced? */
  9942. /* Check if the server may write this file */
  9943. if (access(path, W_OK) == 0) {
  9944. /* Access granted */
  9945. rc = 1;
  9946. } else {
  9947. mg_send_http_error(
  9948. conn,
  9949. 403,
  9950. "Error: Put not possible\nReplacing %s is not allowed",
  9951. path);
  9952. return;
  9953. }
  9954. }
  9955. } else {
  9956. /* File should be created */
  9957. conn->status_code = 201;
  9958. rc = put_dir(conn, path);
  9959. }
  9960. if (rc == 0) {
  9961. /* put_dir returns 0 if path is a directory */
  9962. /* Create response */
  9963. mg_response_header_start(conn, conn->status_code);
  9964. send_no_cache_header(conn);
  9965. send_additional_header(conn);
  9966. mg_response_header_add(conn, "Content-Length", "0", -1);
  9967. /* Send all headers - there is no body */
  9968. mg_response_header_send(conn);
  9969. /* Request to create a directory has been fulfilled successfully.
  9970. * No need to put a file. */
  9971. return;
  9972. }
  9973. if (rc == -1) {
  9974. /* put_dir returns -1 if the path is too long */
  9975. mg_send_http_error(conn,
  9976. 414,
  9977. "Error: Path too long\nput_dir(%s): %s",
  9978. path,
  9979. strerror(ERRNO));
  9980. return;
  9981. }
  9982. if (rc == -2) {
  9983. /* put_dir returns -2 if the directory can not be created */
  9984. mg_send_http_error(conn,
  9985. 500,
  9986. "Error: Can not create directory\nput_dir(%s): %s",
  9987. path,
  9988. strerror(ERRNO));
  9989. return;
  9990. }
  9991. /* A file should be created or overwritten. */
  9992. /* Currently CivetWeb does not nead read+write access. */
  9993. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9994. || file.access.fp == NULL) {
  9995. (void)mg_fclose(&file.access);
  9996. mg_send_http_error(conn,
  9997. 500,
  9998. "Error: Can not create file\nfopen(%s): %s",
  9999. path,
  10000. strerror(ERRNO));
  10001. return;
  10002. }
  10003. fclose_on_exec(&file.access, conn);
  10004. range = mg_get_header(conn, "Content-Range");
  10005. r1 = r2 = 0;
  10006. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10007. conn->status_code = 206; /* Partial content */
  10008. fseeko(file.access.fp, r1, SEEK_SET);
  10009. }
  10010. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10011. /* forward_body_data failed.
  10012. * The error code has already been sent to the client,
  10013. * and conn->status_code is already set. */
  10014. (void)mg_fclose(&file.access);
  10015. return;
  10016. }
  10017. if (mg_fclose(&file.access) != 0) {
  10018. /* fclose failed. This might have different reasons, but a likely
  10019. * one is "no space on disk", http 507. */
  10020. conn->status_code = 507;
  10021. }
  10022. /* Create response (status_code has been set before) */
  10023. mg_response_header_start(conn, conn->status_code);
  10024. send_no_cache_header(conn);
  10025. send_additional_header(conn);
  10026. mg_response_header_add(conn, "Content-Length", "0", -1);
  10027. /* Send all headers - there is no body */
  10028. mg_response_header_send(conn);
  10029. }
  10030. static void
  10031. delete_file(struct mg_connection *conn, const char *path)
  10032. {
  10033. struct de de;
  10034. memset(&de.file, 0, sizeof(de.file));
  10035. if (!mg_stat(conn, path, &de.file)) {
  10036. /* mg_stat returns 0 if the file does not exist */
  10037. mg_send_http_error(conn,
  10038. 404,
  10039. "Error: Cannot delete file\nFile %s not found",
  10040. path);
  10041. return;
  10042. }
  10043. if (de.file.is_directory) {
  10044. if (remove_directory(conn, path)) {
  10045. /* Delete is successful: Return 204 without content. */
  10046. mg_send_http_error(conn, 204, "%s", "");
  10047. } else {
  10048. /* Delete is not successful: Return 500 (Server error). */
  10049. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10050. }
  10051. return;
  10052. }
  10053. /* This is an existing file (not a directory).
  10054. * Check if write permission is granted. */
  10055. if (access(path, W_OK) != 0) {
  10056. /* File is read only */
  10057. mg_send_http_error(
  10058. conn,
  10059. 403,
  10060. "Error: Delete not possible\nDeleting %s is not allowed",
  10061. path);
  10062. return;
  10063. }
  10064. /* Try to delete it. */
  10065. if (mg_remove(conn, path) == 0) {
  10066. /* Delete was successful: Return 204 without content. */
  10067. mg_response_header_start(conn, 204);
  10068. send_no_cache_header(conn);
  10069. send_additional_header(conn);
  10070. mg_response_header_add(conn, "Content-Length", "0", -1);
  10071. mg_response_header_send(conn);
  10072. } else {
  10073. /* Delete not successful (file locked). */
  10074. mg_send_http_error(conn,
  10075. 423,
  10076. "Error: Cannot delete file\nremove(%s): %s",
  10077. path,
  10078. strerror(ERRNO));
  10079. }
  10080. }
  10081. #endif /* !NO_FILES */
  10082. #if !defined(NO_FILESYSTEMS)
  10083. static void
  10084. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10085. static void
  10086. do_ssi_include(struct mg_connection *conn,
  10087. const char *ssi,
  10088. char *tag,
  10089. int include_level)
  10090. {
  10091. char file_name[MG_BUF_LEN], path[512], *p;
  10092. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10093. size_t len;
  10094. int truncated = 0;
  10095. if (conn == NULL) {
  10096. return;
  10097. }
  10098. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10099. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10100. * always < MG_BUF_LEN. */
  10101. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10102. /* File name is relative to the webserver root */
  10103. file_name[511] = 0;
  10104. (void)mg_snprintf(conn,
  10105. &truncated,
  10106. path,
  10107. sizeof(path),
  10108. "%s/%s",
  10109. conn->dom_ctx->config[DOCUMENT_ROOT],
  10110. file_name);
  10111. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10112. /* File name is relative to the webserver working directory
  10113. * or it is absolute system path */
  10114. file_name[511] = 0;
  10115. (void)
  10116. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10117. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10118. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10119. /* File name is relative to the currect document */
  10120. file_name[511] = 0;
  10121. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10122. if (!truncated) {
  10123. if ((p = strrchr(path, '/')) != NULL) {
  10124. p[1] = '\0';
  10125. }
  10126. len = strlen(path);
  10127. (void)mg_snprintf(conn,
  10128. &truncated,
  10129. path + len,
  10130. sizeof(path) - len,
  10131. "%s",
  10132. file_name);
  10133. }
  10134. } else {
  10135. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10136. return;
  10137. }
  10138. if (truncated) {
  10139. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10140. return;
  10141. }
  10142. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10143. mg_cry_internal(conn,
  10144. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10145. tag,
  10146. path,
  10147. strerror(ERRNO));
  10148. } else {
  10149. fclose_on_exec(&file.access, conn);
  10150. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10151. > 0) {
  10152. send_ssi_file(conn, path, &file, include_level + 1);
  10153. } else {
  10154. send_file_data(conn, &file, 0, INT64_MAX);
  10155. }
  10156. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10157. }
  10158. }
  10159. #if !defined(NO_POPEN)
  10160. static void
  10161. do_ssi_exec(struct mg_connection *conn, char *tag)
  10162. {
  10163. char cmd[1024] = "";
  10164. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10165. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10166. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10167. } else {
  10168. cmd[1023] = 0;
  10169. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10170. mg_cry_internal(conn,
  10171. "Cannot SSI #exec: [%s]: %s",
  10172. cmd,
  10173. strerror(ERRNO));
  10174. } else {
  10175. send_file_data(conn, &file, 0, INT64_MAX);
  10176. pclose(file.access.fp);
  10177. }
  10178. }
  10179. }
  10180. #endif /* !NO_POPEN */
  10181. static int
  10182. mg_fgetc(struct mg_file *filep)
  10183. {
  10184. if (filep == NULL) {
  10185. return EOF;
  10186. }
  10187. if (filep->access.fp != NULL) {
  10188. return fgetc(filep->access.fp);
  10189. } else {
  10190. return EOF;
  10191. }
  10192. }
  10193. static void
  10194. send_ssi_file(struct mg_connection *conn,
  10195. const char *path,
  10196. struct mg_file *filep,
  10197. int include_level)
  10198. {
  10199. char buf[MG_BUF_LEN];
  10200. int ch, len, in_tag, in_ssi_tag;
  10201. if (include_level > 10) {
  10202. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10203. return;
  10204. }
  10205. in_tag = in_ssi_tag = len = 0;
  10206. /* Read file, byte by byte, and look for SSI include tags */
  10207. while ((ch = mg_fgetc(filep)) != EOF) {
  10208. if (in_tag) {
  10209. /* We are in a tag, either SSI tag or html tag */
  10210. if (ch == '>') {
  10211. /* Tag is closing */
  10212. buf[len++] = '>';
  10213. if (in_ssi_tag) {
  10214. /* Handle SSI tag */
  10215. buf[len] = 0;
  10216. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10217. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10218. #if !defined(NO_POPEN)
  10219. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10220. do_ssi_exec(conn, buf + 9);
  10221. #endif /* !NO_POPEN */
  10222. } else {
  10223. mg_cry_internal(conn,
  10224. "%s: unknown SSI "
  10225. "command: \"%s\"",
  10226. path,
  10227. buf);
  10228. }
  10229. len = 0;
  10230. in_ssi_tag = in_tag = 0;
  10231. } else {
  10232. /* Not an SSI tag */
  10233. /* Flush buffer */
  10234. (void)mg_write(conn, buf, (size_t)len);
  10235. len = 0;
  10236. in_tag = 0;
  10237. }
  10238. } else {
  10239. /* Tag is still open */
  10240. buf[len++] = (char)(ch & 0xff);
  10241. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10242. /* All SSI tags start with <!--# */
  10243. in_ssi_tag = 1;
  10244. }
  10245. if ((len + 2) > (int)sizeof(buf)) {
  10246. /* Tag to long for buffer */
  10247. mg_cry_internal(conn, "%s: tag is too large", path);
  10248. return;
  10249. }
  10250. }
  10251. } else {
  10252. /* We are not in a tag yet. */
  10253. if (ch == '<') {
  10254. /* Tag is opening */
  10255. in_tag = 1;
  10256. if (len > 0) {
  10257. /* Flush current buffer.
  10258. * Buffer is filled with "len" bytes. */
  10259. (void)mg_write(conn, buf, (size_t)len);
  10260. }
  10261. /* Store the < */
  10262. len = 1;
  10263. buf[0] = '<';
  10264. } else {
  10265. /* No Tag */
  10266. /* Add data to buffer */
  10267. buf[len++] = (char)(ch & 0xff);
  10268. /* Flush if buffer is full */
  10269. if (len == (int)sizeof(buf)) {
  10270. mg_write(conn, buf, (size_t)len);
  10271. len = 0;
  10272. }
  10273. }
  10274. }
  10275. }
  10276. /* Send the rest of buffered data */
  10277. if (len > 0) {
  10278. mg_write(conn, buf, (size_t)len);
  10279. }
  10280. }
  10281. static void
  10282. handle_ssi_file_request(struct mg_connection *conn,
  10283. const char *path,
  10284. struct mg_file *filep)
  10285. {
  10286. char date[64];
  10287. time_t curtime = time(NULL);
  10288. const char *cors_orig_cfg;
  10289. const char *cors1, *cors2;
  10290. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10291. return;
  10292. }
  10293. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10294. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10295. /* Cross-origin resource sharing (CORS). */
  10296. cors1 = "Access-Control-Allow-Origin";
  10297. cors2 = cors_orig_cfg;
  10298. } else {
  10299. cors1 = cors2 = "";
  10300. }
  10301. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10302. /* File exists (precondition for calling this function),
  10303. * but can not be opened by the server. */
  10304. mg_send_http_error(conn,
  10305. 500,
  10306. "Error: Cannot read file\nfopen(%s): %s",
  10307. path,
  10308. strerror(ERRNO));
  10309. } else {
  10310. /* Set "must_close" for HTTP/1.x, since we do not know the
  10311. * content length */
  10312. conn->must_close = 1;
  10313. gmt_time_string(date, sizeof(date), &curtime);
  10314. fclose_on_exec(&filep->access, conn);
  10315. /* 200 OK response */
  10316. mg_response_header_start(conn, 200);
  10317. send_no_cache_header(conn);
  10318. send_additional_header(conn);
  10319. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10320. if (cors1[0]) {
  10321. mg_response_header_add(conn, cors1, cors2, -1);
  10322. }
  10323. mg_response_header_send(conn);
  10324. /* Header sent, now send body */
  10325. send_ssi_file(conn, path, filep, 0);
  10326. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10327. }
  10328. }
  10329. #endif /* NO_FILESYSTEMS */
  10330. #if !defined(NO_FILES)
  10331. static void
  10332. send_options(struct mg_connection *conn)
  10333. {
  10334. if (!conn) {
  10335. return;
  10336. }
  10337. /* We do not set a "Cache-Control" header here, but leave the default.
  10338. * Since browsers do not send an OPTIONS request, we can not test the
  10339. * effect anyway. */
  10340. mg_response_header_start(conn, 200);
  10341. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10342. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10343. /* Use the same as before */
  10344. mg_response_header_add(
  10345. conn,
  10346. "Allow",
  10347. "GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL",
  10348. -1);
  10349. mg_response_header_add(conn, "DAV", "1", -1);
  10350. } else {
  10351. /* TODO: Check this later for HTTP/2 */
  10352. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10353. }
  10354. send_additional_header(conn);
  10355. mg_response_header_send(conn);
  10356. }
  10357. /* Writes PROPFIND properties for a collection element */
  10358. static int
  10359. print_props(struct mg_connection *conn,
  10360. const char *uri,
  10361. const char *name,
  10362. struct mg_file_stat *filep)
  10363. {
  10364. size_t href_size, i, j;
  10365. int len;
  10366. char *href, mtime[64];
  10367. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10368. return 0;
  10369. }
  10370. /* Estimate worst case size for encoding */
  10371. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10372. href = (char *)mg_malloc(href_size);
  10373. if (href == NULL) {
  10374. return 0;
  10375. }
  10376. len = mg_url_encode(uri, href, href_size);
  10377. if (len >= 0) {
  10378. /* Append an extra string */
  10379. mg_url_encode(name, href + len, href_size - (size_t)len);
  10380. }
  10381. /* Directory separator should be preserved. */
  10382. for (i = j = 0; href[i]; j++) {
  10383. if (!strncmp(href + i, "%2f", 3)) {
  10384. href[j] = '/';
  10385. i += 3;
  10386. } else {
  10387. href[j] = href[i++];
  10388. }
  10389. }
  10390. href[j] = '\0';
  10391. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10392. mg_printf(conn,
  10393. "<d:response>"
  10394. "<d:href>%s</d:href>"
  10395. "<d:propstat>"
  10396. "<d:prop>"
  10397. "<d:resourcetype>%s</d:resourcetype>"
  10398. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10399. "<d:getlastmodified>%s</d:getlastmodified>"
  10400. "</d:prop>"
  10401. "<d:status>HTTP/1.1 200 OK</d:status>"
  10402. "</d:propstat>"
  10403. "</d:response>\n",
  10404. href,
  10405. filep->is_directory ? "<d:collection/>" : "",
  10406. filep->size,
  10407. mtime);
  10408. mg_free(href);
  10409. return 1;
  10410. }
  10411. static int
  10412. print_dav_dir_entry(struct de *de, void *data)
  10413. {
  10414. struct mg_connection *conn = (struct mg_connection *)data;
  10415. if (!de || !conn
  10416. || !print_props(
  10417. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10418. /* stop scan */
  10419. return 1;
  10420. }
  10421. return 0;
  10422. }
  10423. static void
  10424. handle_propfind(struct mg_connection *conn,
  10425. const char *path,
  10426. struct mg_file_stat *filep)
  10427. {
  10428. const char *depth = mg_get_header(conn, "Depth");
  10429. char date[64];
  10430. time_t curtime = time(NULL);
  10431. gmt_time_string(date, sizeof(date), &curtime);
  10432. if (!conn || !path || !filep || !conn->dom_ctx) {
  10433. return;
  10434. }
  10435. conn->must_close = 1;
  10436. /* return 207 "Multi-Status" */
  10437. mg_response_header_start(conn, 207);
  10438. send_static_cache_header(conn);
  10439. send_additional_header(conn);
  10440. mg_response_header_add(conn, "Content-Type", "text/xml; charset=utf-8", -1);
  10441. mg_response_header_send(conn);
  10442. /* Content */
  10443. mg_printf(conn,
  10444. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10445. "<d:multistatus xmlns:d='DAV:'>\n");
  10446. /* Print properties for the requested resource itself */
  10447. print_props(conn, conn->request_info.local_uri, "", filep);
  10448. /* If it is a directory, print directory entries too if Depth is not 0
  10449. */
  10450. if (filep->is_directory
  10451. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10452. "yes")
  10453. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10454. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10455. }
  10456. mg_printf(conn, "%s\n", "</d:multistatus>");
  10457. }
  10458. #endif
  10459. void
  10460. mg_lock_connection(struct mg_connection *conn)
  10461. {
  10462. if (conn) {
  10463. (void)pthread_mutex_lock(&conn->mutex);
  10464. }
  10465. }
  10466. void
  10467. mg_unlock_connection(struct mg_connection *conn)
  10468. {
  10469. if (conn) {
  10470. (void)pthread_mutex_unlock(&conn->mutex);
  10471. }
  10472. }
  10473. void
  10474. mg_lock_context(struct mg_context *ctx)
  10475. {
  10476. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10477. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10478. }
  10479. }
  10480. void
  10481. mg_unlock_context(struct mg_context *ctx)
  10482. {
  10483. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  10484. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10485. }
  10486. }
  10487. #if defined(USE_LUA)
  10488. #include "mod_lua.inl"
  10489. #endif /* USE_LUA */
  10490. #if defined(USE_DUKTAPE)
  10491. #include "mod_duktape.inl"
  10492. #endif /* USE_DUKTAPE */
  10493. #if defined(USE_WEBSOCKET)
  10494. #if !defined(NO_SSL_DL)
  10495. #define SHA_API static
  10496. #include "sha1.inl"
  10497. #endif
  10498. static int
  10499. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10500. {
  10501. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10502. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10503. SHA_CTX sha_ctx;
  10504. int truncated;
  10505. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10506. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10507. if (truncated) {
  10508. conn->must_close = 1;
  10509. return 0;
  10510. }
  10511. DEBUG_TRACE("%s", "Send websocket handshake");
  10512. SHA1_Init(&sha_ctx);
  10513. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10514. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10515. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10516. mg_printf(conn,
  10517. "HTTP/1.1 101 Switching Protocols\r\n"
  10518. "Upgrade: websocket\r\n"
  10519. "Connection: Upgrade\r\n"
  10520. "Sec-WebSocket-Accept: %s\r\n",
  10521. b64_sha);
  10522. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10523. // Send negotiated compression extension parameters
  10524. websocket_deflate_response(conn);
  10525. #endif
  10526. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10527. mg_printf(conn,
  10528. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10529. conn->request_info.acceptedWebSocketSubprotocol);
  10530. } else {
  10531. mg_printf(conn, "%s", "\r\n");
  10532. }
  10533. return 1;
  10534. }
  10535. #if !defined(MG_MAX_UNANSWERED_PING)
  10536. /* Configuration of the maximum number of websocket PINGs that might
  10537. * stay unanswered before the connection is considered broken.
  10538. * Note: The name of this define may still change (until it is
  10539. * defined as a compile parameter in a documentation).
  10540. */
  10541. #define MG_MAX_UNANSWERED_PING (5)
  10542. #endif
  10543. static void
  10544. read_websocket(struct mg_connection *conn,
  10545. mg_websocket_data_handler ws_data_handler,
  10546. void *callback_data)
  10547. {
  10548. /* Pointer to the beginning of the portion of the incoming websocket
  10549. * message queue.
  10550. * The original websocket upgrade request is never removed, so the queue
  10551. * begins after it. */
  10552. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10553. int n, error, exit_by_callback;
  10554. int ret;
  10555. /* body_len is the length of the entire queue in bytes
  10556. * len is the length of the current message
  10557. * data_len is the length of the current message's data payload
  10558. * header_len is the length of the current message's header */
  10559. size_t i, len, mask_len = 0, header_len, body_len;
  10560. uint64_t data_len = 0;
  10561. /* "The masking key is a 32-bit value chosen at random by the client."
  10562. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10563. */
  10564. unsigned char mask[4];
  10565. /* data points to the place where the message is stored when passed to
  10566. * the websocket_data callback. This is either mem on the stack, or a
  10567. * dynamically allocated buffer if it is too large. */
  10568. unsigned char mem[4096];
  10569. unsigned char mop; /* mask flag and opcode */
  10570. /* Variables used for connection monitoring */
  10571. double timeout = -1.0;
  10572. int enable_ping_pong = 0;
  10573. int ping_count = 0;
  10574. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10575. enable_ping_pong =
  10576. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10577. "yes");
  10578. }
  10579. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10580. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10581. }
  10582. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10583. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10584. }
  10585. if (timeout <= 0.0) {
  10586. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  10587. }
  10588. /* Enter data processing loop */
  10589. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10590. conn->request_info.remote_addr,
  10591. conn->request_info.remote_port);
  10592. conn->in_websocket_handling = 1;
  10593. mg_set_thread_name("wsock");
  10594. /* Loop continuously, reading messages from the socket, invoking the
  10595. * callback, and waiting repeatedly until an error occurs. */
  10596. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10597. && (!conn->must_close)) {
  10598. header_len = 0;
  10599. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10600. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10601. len = buf[1] & 127;
  10602. mask_len = (buf[1] & 128) ? 4 : 0;
  10603. if ((len < 126) && (body_len >= mask_len)) {
  10604. /* inline 7-bit length field */
  10605. data_len = len;
  10606. header_len = 2 + mask_len;
  10607. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10608. /* 16-bit length field */
  10609. header_len = 4 + mask_len;
  10610. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10611. } else if (body_len >= (10 + mask_len)) {
  10612. /* 64-bit length field */
  10613. uint32_t l1, l2;
  10614. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10615. memcpy(&l2, &buf[6], 4);
  10616. header_len = 10 + mask_len;
  10617. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10618. if (data_len > (uint64_t)0x7FFF0000ul) {
  10619. /* no can do */
  10620. mg_cry_internal(
  10621. conn,
  10622. "%s",
  10623. "websocket out of memory; closing connection");
  10624. break;
  10625. }
  10626. }
  10627. }
  10628. if ((header_len > 0) && (body_len >= header_len)) {
  10629. /* Allocate space to hold websocket payload */
  10630. unsigned char *data = mem;
  10631. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10632. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10633. conn->phys_ctx);
  10634. if (data == NULL) {
  10635. /* Allocation failed, exit the loop and then close the
  10636. * connection */
  10637. mg_cry_internal(
  10638. conn,
  10639. "%s",
  10640. "websocket out of memory; closing connection");
  10641. break;
  10642. }
  10643. }
  10644. /* Copy the mask before we shift the queue and destroy it */
  10645. if (mask_len > 0) {
  10646. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10647. } else {
  10648. memset(mask, 0, sizeof(mask));
  10649. }
  10650. /* Read frame payload from the first message in the queue into
  10651. * data and advance the queue by moving the memory in place. */
  10652. DEBUG_ASSERT(body_len >= header_len);
  10653. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10654. mop = buf[0]; /* current mask and opcode */
  10655. /* Overflow case */
  10656. len = body_len - header_len;
  10657. memcpy(data, buf + header_len, len);
  10658. error = 0;
  10659. while ((uint64_t)len < data_len) {
  10660. n = pull_inner(NULL,
  10661. conn,
  10662. (char *)(data + len),
  10663. (int)(data_len - len),
  10664. timeout);
  10665. if (n <= -2) {
  10666. error = 1;
  10667. break;
  10668. } else if (n > 0) {
  10669. len += (size_t)n;
  10670. } else {
  10671. /* Timeout: should retry */
  10672. /* TODO: retry condition */
  10673. }
  10674. }
  10675. if (error) {
  10676. mg_cry_internal(
  10677. conn,
  10678. "%s",
  10679. "Websocket pull failed; closing connection");
  10680. if (data != mem) {
  10681. mg_free(data);
  10682. }
  10683. break;
  10684. }
  10685. conn->data_len = conn->request_len;
  10686. } else {
  10687. mop = buf[0]; /* current mask and opcode, overwritten by
  10688. * memmove() */
  10689. /* Length of the message being read at the front of the
  10690. * queue. Cast to 31 bit is OK, since we limited
  10691. * data_len before. */
  10692. len = (size_t)data_len + header_len;
  10693. /* Copy the data payload into the data pointer for the
  10694. * callback. Cast to 31 bit is OK, since we
  10695. * limited data_len */
  10696. memcpy(data, buf + header_len, (size_t)data_len);
  10697. /* Move the queue forward len bytes */
  10698. memmove(buf, buf + len, body_len - len);
  10699. /* Mark the queue as advanced */
  10700. conn->data_len -= (int)len;
  10701. }
  10702. /* Apply mask if necessary */
  10703. if (mask_len > 0) {
  10704. for (i = 0; i < (size_t)data_len; i++) {
  10705. data[i] ^= mask[i & 3];
  10706. }
  10707. }
  10708. exit_by_callback = 0;
  10709. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10710. /* filter PONG messages */
  10711. DEBUG_TRACE("PONG from %s:%u",
  10712. conn->request_info.remote_addr,
  10713. conn->request_info.remote_port);
  10714. /* No unanwered PINGs left */
  10715. ping_count = 0;
  10716. } else if (enable_ping_pong
  10717. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10718. /* reply PING messages */
  10719. DEBUG_TRACE("Reply PING from %s:%u",
  10720. conn->request_info.remote_addr,
  10721. conn->request_info.remote_port);
  10722. ret = mg_websocket_write(conn,
  10723. MG_WEBSOCKET_OPCODE_PONG,
  10724. (char *)data,
  10725. (size_t)data_len);
  10726. if (ret <= 0) {
  10727. /* Error: send failed */
  10728. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10729. break;
  10730. }
  10731. } else {
  10732. /* Exit the loop if callback signals to exit (server side),
  10733. * or "connection close" opcode received (client side). */
  10734. if (ws_data_handler != NULL) {
  10735. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10736. if (mop & 0x40) {
  10737. /* Inflate the data received if bit RSV1 is set. */
  10738. if (!conn->websocket_deflate_initialized) {
  10739. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10740. exit_by_callback = 1;
  10741. }
  10742. if (!exit_by_callback) {
  10743. size_t inflate_buf_size_old = 0;
  10744. size_t inflate_buf_size =
  10745. data_len
  10746. * 4; // Initial guess of the inflated message
  10747. // size. We double the memory when needed.
  10748. Bytef *inflated = NULL;
  10749. Bytef *new_mem = NULL;
  10750. conn->websocket_inflate_state.avail_in =
  10751. (uInt)(data_len + 4);
  10752. conn->websocket_inflate_state.next_in = data;
  10753. // Add trailing 0x00 0x00 0xff 0xff bytes
  10754. data[data_len] = '\x00';
  10755. data[data_len + 1] = '\x00';
  10756. data[data_len + 2] = '\xff';
  10757. data[data_len + 3] = '\xff';
  10758. do {
  10759. if (inflate_buf_size_old == 0) {
  10760. new_mem =
  10761. (Bytef *)mg_calloc(inflate_buf_size,
  10762. sizeof(Bytef));
  10763. } else {
  10764. inflate_buf_size *= 2;
  10765. new_mem =
  10766. (Bytef *)mg_realloc(inflated,
  10767. inflate_buf_size);
  10768. }
  10769. if (new_mem == NULL) {
  10770. mg_cry_internal(
  10771. conn,
  10772. "Out of memory: Cannot allocate "
  10773. "inflate buffer of %lu bytes",
  10774. (unsigned long)inflate_buf_size);
  10775. exit_by_callback = 1;
  10776. break;
  10777. }
  10778. inflated = new_mem;
  10779. conn->websocket_inflate_state.avail_out =
  10780. (uInt)(inflate_buf_size
  10781. - inflate_buf_size_old);
  10782. conn->websocket_inflate_state.next_out =
  10783. inflated + inflate_buf_size_old;
  10784. ret = inflate(&conn->websocket_inflate_state,
  10785. Z_SYNC_FLUSH);
  10786. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  10787. || ret == Z_MEM_ERROR) {
  10788. mg_cry_internal(
  10789. conn,
  10790. "ZLIB inflate error: %i %s",
  10791. ret,
  10792. (conn->websocket_inflate_state.msg
  10793. ? conn->websocket_inflate_state.msg
  10794. : "<no error message>"));
  10795. exit_by_callback = 1;
  10796. break;
  10797. }
  10798. inflate_buf_size_old = inflate_buf_size;
  10799. } while (conn->websocket_inflate_state.avail_out
  10800. == 0);
  10801. inflate_buf_size -=
  10802. conn->websocket_inflate_state.avail_out;
  10803. if (!ws_data_handler(conn,
  10804. mop,
  10805. (char *)inflated,
  10806. inflate_buf_size,
  10807. callback_data)) {
  10808. exit_by_callback = 1;
  10809. }
  10810. mg_free(inflated);
  10811. }
  10812. } else
  10813. #endif
  10814. if (!ws_data_handler(conn,
  10815. mop,
  10816. (char *)data,
  10817. (size_t)data_len,
  10818. callback_data)) {
  10819. exit_by_callback = 1;
  10820. }
  10821. }
  10822. }
  10823. /* It a buffer has been allocated, free it again */
  10824. if (data != mem) {
  10825. mg_free(data);
  10826. }
  10827. if (exit_by_callback) {
  10828. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10829. conn->request_info.remote_addr,
  10830. conn->request_info.remote_port);
  10831. break;
  10832. }
  10833. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10834. /* Opcode == 8, connection close */
  10835. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10836. conn->request_info.remote_addr,
  10837. conn->request_info.remote_port);
  10838. break;
  10839. }
  10840. /* Not breaking the loop, process next websocket frame. */
  10841. } else {
  10842. /* Read from the socket into the next available location in the
  10843. * message queue. */
  10844. n = pull_inner(NULL,
  10845. conn,
  10846. conn->buf + conn->data_len,
  10847. conn->buf_size - conn->data_len,
  10848. timeout);
  10849. if (n <= -2) {
  10850. /* Error, no bytes read */
  10851. DEBUG_TRACE("PULL from %s:%u failed",
  10852. conn->request_info.remote_addr,
  10853. conn->request_info.remote_port);
  10854. break;
  10855. }
  10856. if (n > 0) {
  10857. conn->data_len += n;
  10858. /* Reset open PING count */
  10859. ping_count = 0;
  10860. } else {
  10861. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  10862. && (!conn->must_close)) {
  10863. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10864. /* Stop sending PING */
  10865. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10866. "- closing connection",
  10867. ping_count,
  10868. conn->request_info.remote_addr,
  10869. conn->request_info.remote_port);
  10870. break;
  10871. }
  10872. if (enable_ping_pong) {
  10873. /* Send Websocket PING message */
  10874. DEBUG_TRACE("PING to %s:%u",
  10875. conn->request_info.remote_addr,
  10876. conn->request_info.remote_port);
  10877. ret = mg_websocket_write(conn,
  10878. MG_WEBSOCKET_OPCODE_PING,
  10879. NULL,
  10880. 0);
  10881. if (ret <= 0) {
  10882. /* Error: send failed */
  10883. DEBUG_TRACE("Send PING failed (%i)", ret);
  10884. break;
  10885. }
  10886. ping_count++;
  10887. }
  10888. }
  10889. /* Timeout: should retry */
  10890. /* TODO: get timeout def */
  10891. }
  10892. }
  10893. }
  10894. /* Leave data processing loop */
  10895. mg_set_thread_name("worker");
  10896. conn->in_websocket_handling = 0;
  10897. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10898. conn->request_info.remote_addr,
  10899. conn->request_info.remote_port);
  10900. }
  10901. static int
  10902. mg_websocket_write_exec(struct mg_connection *conn,
  10903. int opcode,
  10904. const char *data,
  10905. size_t dataLen,
  10906. uint32_t masking_key)
  10907. {
  10908. unsigned char header[14];
  10909. size_t headerLen;
  10910. int retval;
  10911. #if defined(GCC_DIAGNOSTIC)
  10912. /* Disable spurious conversion warning for GCC */
  10913. #pragma GCC diagnostic push
  10914. #pragma GCC diagnostic ignored "-Wconversion"
  10915. #endif
  10916. /* Note that POSIX/Winsock's send() is threadsafe
  10917. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10918. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10919. * push(), although that is only a problem if the packet is large or
  10920. * outgoing buffer is full). */
  10921. /* TODO: Check if this lock should be moved to user land.
  10922. * Currently the server sets this lock for websockets, but
  10923. * not for any other connection. It must be set for every
  10924. * conn read/written by more than one thread, no matter if
  10925. * it is a websocket or regular connection. */
  10926. (void)mg_lock_connection(conn);
  10927. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10928. size_t deflated_size = 0;
  10929. Bytef *deflated = 0;
  10930. // Deflate websocket messages over 100kb
  10931. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  10932. if (use_deflate) {
  10933. if (!conn->websocket_deflate_initialized) {
  10934. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  10935. return 0;
  10936. }
  10937. // Deflating the message
  10938. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  10939. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  10940. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  10941. deflated_size = (Bytef *)compressBound((uLong)dataLen);
  10942. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  10943. if (deflated == NULL) {
  10944. mg_cry_internal(
  10945. conn,
  10946. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  10947. (unsigned long)deflated_size);
  10948. mg_unlock_connection(conn);
  10949. return -1;
  10950. }
  10951. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  10952. conn->websocket_deflate_state.next_out = deflated;
  10953. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  10954. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  10955. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  10956. } else
  10957. #endif
  10958. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10959. #if defined(GCC_DIAGNOSTIC)
  10960. #pragma GCC diagnostic pop
  10961. #endif
  10962. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10963. if (dataLen < 126) {
  10964. /* inline 7-bit length field */
  10965. header[1] = (unsigned char)dataLen;
  10966. headerLen = 2;
  10967. } else if (dataLen <= 0xFFFF) {
  10968. /* 16-bit length field */
  10969. uint16_t len = htons((uint16_t)dataLen);
  10970. header[1] = 126;
  10971. memcpy(header + 2, &len, 2);
  10972. headerLen = 4;
  10973. } else {
  10974. /* 64-bit length field */
  10975. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10976. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10977. header[1] = 127;
  10978. memcpy(header + 2, &len1, 4);
  10979. memcpy(header + 6, &len2, 4);
  10980. headerLen = 10;
  10981. }
  10982. if (masking_key) {
  10983. /* add mask */
  10984. header[1] |= 0x80;
  10985. memcpy(header + headerLen, &masking_key, 4);
  10986. headerLen += 4;
  10987. }
  10988. retval = mg_write(conn, header, headerLen);
  10989. if (retval != (int)headerLen) {
  10990. /* Did not send complete header */
  10991. retval = -1;
  10992. } else {
  10993. if (dataLen > 0) {
  10994. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  10995. if (use_deflate) {
  10996. retval = mg_write(conn, deflated, dataLen);
  10997. mg_free(deflated);
  10998. } else
  10999. #endif
  11000. retval = mg_write(conn, data, dataLen);
  11001. }
  11002. /* if dataLen == 0, the header length (2) is returned */
  11003. }
  11004. /* TODO: Remove this unlock as well, when lock is removed. */
  11005. mg_unlock_connection(conn);
  11006. return retval;
  11007. }
  11008. int
  11009. mg_websocket_write(struct mg_connection *conn,
  11010. int opcode,
  11011. const char *data,
  11012. size_t dataLen)
  11013. {
  11014. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11015. }
  11016. static void
  11017. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11018. {
  11019. size_t i = 0;
  11020. i = 0;
  11021. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11022. /* Convert in 32 bit words, if data is 4 byte aligned */
  11023. while (i < (in_len - 3)) {
  11024. *(uint32_t *)(void *)(out + i) =
  11025. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11026. i += 4;
  11027. }
  11028. }
  11029. if (i != in_len) {
  11030. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11031. while (i < in_len) {
  11032. *(uint8_t *)(void *)(out + i) =
  11033. *(uint8_t *)(void *)(in + i)
  11034. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11035. i++;
  11036. }
  11037. }
  11038. }
  11039. int
  11040. mg_websocket_client_write(struct mg_connection *conn,
  11041. int opcode,
  11042. const char *data,
  11043. size_t dataLen)
  11044. {
  11045. int retval = -1;
  11046. char *masked_data =
  11047. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11048. uint32_t masking_key = 0;
  11049. if (masked_data == NULL) {
  11050. /* Return -1 in an error case */
  11051. mg_cry_internal(conn,
  11052. "%s",
  11053. "Cannot allocate buffer for masked websocket response: "
  11054. "Out of memory");
  11055. return -1;
  11056. }
  11057. do {
  11058. /* Get a masking key - but not 0 */
  11059. masking_key = (uint32_t)get_random();
  11060. } while (masking_key == 0);
  11061. mask_data(data, dataLen, masking_key, masked_data);
  11062. retval = mg_websocket_write_exec(
  11063. conn, opcode, masked_data, dataLen, masking_key);
  11064. mg_free(masked_data);
  11065. return retval;
  11066. }
  11067. static void
  11068. handle_websocket_request(struct mg_connection *conn,
  11069. const char *path,
  11070. int is_callback_resource,
  11071. struct mg_websocket_subprotocols *subprotocols,
  11072. mg_websocket_connect_handler ws_connect_handler,
  11073. mg_websocket_ready_handler ws_ready_handler,
  11074. mg_websocket_data_handler ws_data_handler,
  11075. mg_websocket_close_handler ws_close_handler,
  11076. void *cbData)
  11077. {
  11078. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11079. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11080. ptrdiff_t lua_websock = 0;
  11081. #if !defined(USE_LUA)
  11082. (void)path;
  11083. #endif
  11084. /* Step 1: Check websocket protocol version. */
  11085. /* Step 1.1: Check Sec-WebSocket-Key. */
  11086. if (!websock_key) {
  11087. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11088. * requires a Sec-WebSocket-Key header.
  11089. */
  11090. /* It could be the hixie draft version
  11091. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11092. */
  11093. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11094. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11095. char key3[8];
  11096. if ((key1 != NULL) && (key2 != NULL)) {
  11097. /* This version uses 8 byte body data in a GET request */
  11098. conn->content_len = 8;
  11099. if (8 == mg_read(conn, key3, 8)) {
  11100. /* This is the hixie version */
  11101. mg_send_http_error(conn,
  11102. 426,
  11103. "%s",
  11104. "Protocol upgrade to RFC 6455 required");
  11105. return;
  11106. }
  11107. }
  11108. /* This is an unknown version */
  11109. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11110. return;
  11111. }
  11112. /* Step 1.2: Check websocket protocol version. */
  11113. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11114. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11115. /* Reject wrong versions */
  11116. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11117. return;
  11118. }
  11119. /* Step 1.3: Could check for "Host", but we do not really nead this
  11120. * value for anything, so just ignore it. */
  11121. /* Step 2: If a callback is responsible, call it. */
  11122. if (is_callback_resource) {
  11123. /* Step 2.1 check and select subprotocol */
  11124. const char *protocols[64]; // max 64 headers
  11125. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11126. "Sec-WebSocket-Protocol",
  11127. protocols,
  11128. 64);
  11129. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11130. int cnt = 0;
  11131. int idx;
  11132. unsigned long len;
  11133. const char *sep, *curSubProtocol,
  11134. *acceptedWebSocketSubprotocol = NULL;
  11135. /* look for matching subprotocol */
  11136. do {
  11137. const char *protocol = protocols[cnt];
  11138. do {
  11139. sep = strchr(protocol, ',');
  11140. curSubProtocol = protocol;
  11141. len = sep ? (unsigned long)(sep - protocol)
  11142. : (unsigned long)strlen(protocol);
  11143. while (sep && isspace((unsigned char)*++sep))
  11144. ; // ignore leading whitespaces
  11145. protocol = sep;
  11146. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  11147. if ((strlen(subprotocols->subprotocols[idx]) == len)
  11148. && (strncmp(curSubProtocol,
  11149. subprotocols->subprotocols[idx],
  11150. len)
  11151. == 0)) {
  11152. acceptedWebSocketSubprotocol =
  11153. subprotocols->subprotocols[idx];
  11154. break;
  11155. }
  11156. }
  11157. } while (sep && !acceptedWebSocketSubprotocol);
  11158. } while (++cnt < nbSubprotocolHeader
  11159. && !acceptedWebSocketSubprotocol);
  11160. conn->request_info.acceptedWebSocketSubprotocol =
  11161. acceptedWebSocketSubprotocol;
  11162. } else if (nbSubprotocolHeader > 0) {
  11163. /* keep legacy behavior */
  11164. const char *protocol = protocols[0];
  11165. /* The protocol is a comma separated list of names. */
  11166. /* The server must only return one value from this list. */
  11167. /* First check if it is a list or just a single value. */
  11168. const char *sep = strrchr(protocol, ',');
  11169. if (sep == NULL) {
  11170. /* Just a single protocol -> accept it. */
  11171. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  11172. } else {
  11173. /* Multiple protocols -> accept the last one. */
  11174. /* This is just a quick fix if the client offers multiple
  11175. * protocols. The handler should have a list of accepted
  11176. * protocols on his own
  11177. * and use it to select one protocol among those the client
  11178. * has
  11179. * offered.
  11180. */
  11181. while (isspace((unsigned char)*++sep)) {
  11182. ; /* ignore leading whitespaces */
  11183. }
  11184. conn->request_info.acceptedWebSocketSubprotocol = sep;
  11185. }
  11186. }
  11187. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11188. websocket_deflate_negotiate(conn);
  11189. #endif
  11190. if ((ws_connect_handler != NULL)
  11191. && (ws_connect_handler(conn, cbData) != 0)) {
  11192. /* C callback has returned non-zero, do not proceed with
  11193. * handshake.
  11194. */
  11195. /* Note that C callbacks are no longer called when Lua is
  11196. * responsible, so C can no longer filter callbacks for Lua. */
  11197. return;
  11198. }
  11199. }
  11200. #if defined(USE_LUA)
  11201. /* Step 3: No callback. Check if Lua is responsible. */
  11202. else {
  11203. /* Step 3.1: Check if Lua is responsible. */
  11204. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11205. lua_websock = match_prefix_strlen(
  11206. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  11207. }
  11208. if (lua_websock) {
  11209. /* Step 3.2: Lua is responsible: call it. */
  11210. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11211. if (!conn->lua_websocket_state) {
  11212. /* Lua rejected the new client */
  11213. return;
  11214. }
  11215. }
  11216. }
  11217. #endif
  11218. /* Step 4: Check if there is a responsible websocket handler. */
  11219. if (!is_callback_resource && !lua_websock) {
  11220. /* There is no callback, and Lua is not responsible either. */
  11221. /* Reply with a 404 Not Found. We are still at a standard
  11222. * HTTP request here, before the websocket handshake, so
  11223. * we can still send standard HTTP error replies. */
  11224. mg_send_http_error(conn, 404, "%s", "Not found");
  11225. return;
  11226. }
  11227. /* Step 5: The websocket connection has been accepted */
  11228. if (!send_websocket_handshake(conn, websock_key)) {
  11229. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11230. return;
  11231. }
  11232. /* Step 6: Call the ready handler */
  11233. if (is_callback_resource) {
  11234. if (ws_ready_handler != NULL) {
  11235. ws_ready_handler(conn, cbData);
  11236. }
  11237. #if defined(USE_LUA)
  11238. } else if (lua_websock) {
  11239. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11240. /* the ready handler returned false */
  11241. return;
  11242. }
  11243. #endif
  11244. }
  11245. /* Step 7: Enter the read loop */
  11246. if (is_callback_resource) {
  11247. read_websocket(conn, ws_data_handler, cbData);
  11248. #if defined(USE_LUA)
  11249. } else if (lua_websock) {
  11250. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11251. #endif
  11252. }
  11253. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11254. /* Step 8: Close the deflate & inflate buffers */
  11255. if (conn->websocket_deflate_initialized) {
  11256. deflateEnd(&conn->websocket_deflate_state);
  11257. inflateEnd(&conn->websocket_inflate_state);
  11258. }
  11259. #endif
  11260. /* Step 9: Call the close handler */
  11261. if (ws_close_handler) {
  11262. ws_close_handler(conn, cbData);
  11263. }
  11264. }
  11265. #endif /* !USE_WEBSOCKET */
  11266. /* Is upgrade request:
  11267. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  11268. * 1 = upgrade to websocket
  11269. * 2 = upgrade to HTTP/2
  11270. * -1 = upgrade to unknown protocol
  11271. */
  11272. static int
  11273. should_switch_to_protocol(const struct mg_connection *conn)
  11274. {
  11275. const char *upgrade, *connection;
  11276. /* A websocket protocoll has the following HTTP headers:
  11277. *
  11278. * Connection: Upgrade
  11279. * Upgrade: Websocket
  11280. */
  11281. connection = mg_get_header(conn, "Connection");
  11282. if (connection == NULL) {
  11283. return PROTOCOL_TYPE_HTTP1;
  11284. }
  11285. if (!mg_strcasestr(connection, "upgrade")) {
  11286. return PROTOCOL_TYPE_HTTP1;
  11287. }
  11288. upgrade = mg_get_header(conn, "Upgrade");
  11289. if (upgrade == NULL) {
  11290. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  11291. return -1;
  11292. }
  11293. /* Upgrade to ... */
  11294. if (0 != mg_strcasestr(upgrade, "websocket")) {
  11295. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11296. * "Sec-WebSocket-Version" are also required.
  11297. * Don't check them here, since even an unsupported websocket protocol
  11298. * request still IS a websocket request (in contrast to a standard HTTP
  11299. * request). It will fail later in handle_websocket_request.
  11300. */
  11301. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  11302. }
  11303. if (0 != mg_strcasestr(upgrade, "h2")) {
  11304. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  11305. }
  11306. /* Upgrade to another protocol */
  11307. return -1;
  11308. }
  11309. static int
  11310. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  11311. {
  11312. int n;
  11313. unsigned int a, b, c, d, slash;
  11314. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n) != 5) {
  11315. slash = 32;
  11316. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n) != 4) {
  11317. n = 0;
  11318. }
  11319. }
  11320. if ((n > 0) && ((size_t)n == vec->len)) {
  11321. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  11322. /* IPv4 format */
  11323. if (sa->sa.sa_family == AF_INET) {
  11324. uint32_t ip = (uint32_t)ntohl(sa->sin.sin_addr.s_addr);
  11325. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  11326. | ((uint32_t)c << 8) | (uint32_t)d;
  11327. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  11328. return (ip & mask) == net;
  11329. }
  11330. return 0;
  11331. }
  11332. }
  11333. #if defined(USE_IPV6)
  11334. else {
  11335. char ad[50];
  11336. const char *p;
  11337. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  11338. slash = 128;
  11339. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  11340. n = 0;
  11341. }
  11342. }
  11343. if ((n <= 0) && no_strict) {
  11344. /* no square brackets? */
  11345. p = strchr(vec->ptr, '/');
  11346. if (p && (p < (vec->ptr + vec->len))) {
  11347. if (((size_t)(p - vec->ptr) < sizeof(ad))
  11348. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  11349. n += (int)(p - vec->ptr);
  11350. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  11351. } else {
  11352. n = 0;
  11353. }
  11354. } else if (vec->len < sizeof(ad)) {
  11355. n = (int)vec->len;
  11356. slash = 128;
  11357. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  11358. }
  11359. }
  11360. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  11361. p = ad;
  11362. c = 0;
  11363. /* zone indexes are unsupported, at least two colons are needed */
  11364. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  11365. if (*(p++) == ':') {
  11366. c++;
  11367. }
  11368. }
  11369. if ((*p == '\0') && (c >= 2)) {
  11370. struct sockaddr_in6 sin6;
  11371. unsigned int i;
  11372. /* for strict validation, an actual IPv6 argument is needed */
  11373. if (sa->sa.sa_family != AF_INET6) {
  11374. return 0;
  11375. }
  11376. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  11377. /* IPv6 format */
  11378. for (i = 0; i < 16; i++) {
  11379. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  11380. uint8_t net = sin6.sin6_addr.s6_addr[i];
  11381. uint8_t mask = 0;
  11382. if (8 * i + 8 < slash) {
  11383. mask = 0xFFu;
  11384. } else if (8 * i < slash) {
  11385. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  11386. }
  11387. if ((ip & mask) != net) {
  11388. return 0;
  11389. }
  11390. }
  11391. return 1;
  11392. }
  11393. }
  11394. }
  11395. }
  11396. #else
  11397. (void)no_strict;
  11398. #endif
  11399. /* malformed */
  11400. return -1;
  11401. }
  11402. static int
  11403. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  11404. {
  11405. int throttle = 0;
  11406. struct vec vec, val;
  11407. char mult;
  11408. double v;
  11409. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11410. mult = ',';
  11411. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11412. || (v < 0)
  11413. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11414. && (mult != ','))) {
  11415. continue;
  11416. }
  11417. v *= (lowercase(&mult) == 'k')
  11418. ? 1024
  11419. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11420. if (vec.len == 1 && vec.ptr[0] == '*') {
  11421. throttle = (int)v;
  11422. } else {
  11423. int matched = parse_match_net(&vec, rsa, 0);
  11424. if (matched >= 0) {
  11425. /* a valid IP subnet */
  11426. if (matched) {
  11427. throttle = (int)v;
  11428. }
  11429. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11430. throttle = (int)v;
  11431. }
  11432. }
  11433. }
  11434. return throttle;
  11435. }
  11436. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11437. #include "handle_form.inl"
  11438. static int
  11439. get_first_ssl_listener_index(const struct mg_context *ctx)
  11440. {
  11441. unsigned int i;
  11442. int idx = -1;
  11443. if (ctx) {
  11444. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11445. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11446. }
  11447. }
  11448. return idx;
  11449. }
  11450. /* Return host (without port) */
  11451. static void
  11452. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  11453. {
  11454. const char *host_header =
  11455. get_header(ri->http_headers, ri->num_headers, "Host");
  11456. host->ptr = NULL;
  11457. host->len = 0;
  11458. if (host_header != NULL) {
  11459. const char *pos;
  11460. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11461. * is found. */
  11462. if (*host_header == '[') {
  11463. pos = strchr(host_header, ']');
  11464. if (!pos) {
  11465. /* Malformed hostname starts with '[', but no ']' found */
  11466. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11467. return;
  11468. }
  11469. /* terminate after ']' */
  11470. host->ptr = host_header;
  11471. host->len = (size_t)(pos + 1 - host_header);
  11472. } else {
  11473. /* Otherwise, a ':' separates hostname and port number */
  11474. pos = strchr(host_header, ':');
  11475. if (pos != NULL) {
  11476. host->len = (size_t)(pos - host_header);
  11477. } else {
  11478. host->len = strlen(host_header);
  11479. }
  11480. host->ptr = host_header;
  11481. }
  11482. }
  11483. }
  11484. static int
  11485. switch_domain_context(struct mg_connection *conn)
  11486. {
  11487. struct vec host;
  11488. get_host_from_request_info(&host, &conn->request_info);
  11489. if (host.ptr) {
  11490. if (conn->ssl) {
  11491. /* This is a HTTPS connection, maybe we have a hostname
  11492. * from SNI (set in ssl_servername_callback). */
  11493. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11494. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11495. /* We are not using the default domain */
  11496. if ((strlen(sslhost) != host.len)
  11497. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  11498. /* Mismatch between SNI domain and HTTP domain */
  11499. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  11500. sslhost,
  11501. (int)host.len,
  11502. host.ptr);
  11503. return 0;
  11504. }
  11505. }
  11506. } else {
  11507. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11508. while (dom) {
  11509. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  11510. size_t domNameLen = strlen(domName);
  11511. if ((domNameLen == host.len)
  11512. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  11513. /* Found matching domain */
  11514. DEBUG_TRACE("HTTP domain %s found",
  11515. dom->config[AUTHENTICATION_DOMAIN]);
  11516. /* TODO: Check if this is a HTTP or HTTPS domain */
  11517. conn->dom_ctx = dom;
  11518. break;
  11519. }
  11520. mg_lock_context(conn->phys_ctx);
  11521. dom = dom->next;
  11522. mg_unlock_context(conn->phys_ctx);
  11523. }
  11524. }
  11525. DEBUG_TRACE("HTTP%s Host: %.*s",
  11526. conn->ssl ? "S" : "",
  11527. (int)host.len,
  11528. host.ptr);
  11529. } else {
  11530. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  11531. return 1;
  11532. }
  11533. return 1;
  11534. }
  11535. static int mg_construct_local_link(const struct mg_connection *conn,
  11536. char *buf,
  11537. size_t buflen,
  11538. const char *define_proto,
  11539. int define_port,
  11540. const char *define_uri);
  11541. static void
  11542. redirect_to_https_port(struct mg_connection *conn, int port)
  11543. {
  11544. char target_url[MG_BUF_LEN];
  11545. int truncated = 0;
  11546. const char *expect_proto =
  11547. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  11548. /* Use "308 Permanent Redirect" */
  11549. int redirect_code = 308;
  11550. /* In any case, close the current connection */
  11551. conn->must_close = 1;
  11552. /* Send host, port, uri and (if it exists) ?query_string */
  11553. if (mg_construct_local_link(
  11554. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  11555. < 0) {
  11556. truncated = 1;
  11557. } else if (conn->request_info.query_string != NULL) {
  11558. size_t slen1 = strlen(target_url);
  11559. size_t slen2 = strlen(conn->request_info.query_string);
  11560. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  11561. target_url[slen1] = '?';
  11562. memcpy(target_url + slen1 + 1,
  11563. conn->request_info.query_string,
  11564. slen2);
  11565. target_url[slen1 + slen2 + 1] = 0;
  11566. } else {
  11567. truncated = 1;
  11568. }
  11569. }
  11570. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11571. * is used as buffer size) */
  11572. if (truncated) {
  11573. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11574. return;
  11575. }
  11576. /* Use redirect helper function */
  11577. mg_send_http_redirect(conn, target_url, redirect_code);
  11578. }
  11579. static void
  11580. mg_set_handler_type(struct mg_context *phys_ctx,
  11581. struct mg_domain_context *dom_ctx,
  11582. const char *uri,
  11583. int handler_type,
  11584. int is_delete_request,
  11585. mg_request_handler handler,
  11586. struct mg_websocket_subprotocols *subprotocols,
  11587. mg_websocket_connect_handler connect_handler,
  11588. mg_websocket_ready_handler ready_handler,
  11589. mg_websocket_data_handler data_handler,
  11590. mg_websocket_close_handler close_handler,
  11591. mg_authorization_handler auth_handler,
  11592. void *cbdata)
  11593. {
  11594. struct mg_handler_info *tmp_rh, **lastref;
  11595. size_t urilen = strlen(uri);
  11596. if (handler_type == WEBSOCKET_HANDLER) {
  11597. DEBUG_ASSERT(handler == NULL);
  11598. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11599. || ready_handler != NULL || data_handler != NULL
  11600. || close_handler != NULL);
  11601. DEBUG_ASSERT(auth_handler == NULL);
  11602. if (handler != NULL) {
  11603. return;
  11604. }
  11605. if (!is_delete_request && (connect_handler == NULL)
  11606. && (ready_handler == NULL) && (data_handler == NULL)
  11607. && (close_handler == NULL)) {
  11608. return;
  11609. }
  11610. if (auth_handler != NULL) {
  11611. return;
  11612. }
  11613. } else if (handler_type == REQUEST_HANDLER) {
  11614. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11615. && data_handler == NULL && close_handler == NULL);
  11616. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11617. DEBUG_ASSERT(auth_handler == NULL);
  11618. if ((connect_handler != NULL) || (ready_handler != NULL)
  11619. || (data_handler != NULL) || (close_handler != NULL)) {
  11620. return;
  11621. }
  11622. if (!is_delete_request && (handler == NULL)) {
  11623. return;
  11624. }
  11625. if (auth_handler != NULL) {
  11626. return;
  11627. }
  11628. } else if (handler_type == AUTH_HANDLER) {
  11629. DEBUG_ASSERT(handler == NULL);
  11630. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11631. && data_handler == NULL && close_handler == NULL);
  11632. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  11633. if (handler != NULL) {
  11634. return;
  11635. }
  11636. if ((connect_handler != NULL) || (ready_handler != NULL)
  11637. || (data_handler != NULL) || (close_handler != NULL)) {
  11638. return;
  11639. }
  11640. if (!is_delete_request && (auth_handler == NULL)) {
  11641. return;
  11642. }
  11643. } else {
  11644. /* Unknown handler type. */
  11645. return;
  11646. }
  11647. if (!phys_ctx || !dom_ctx) {
  11648. /* no context available */
  11649. return;
  11650. }
  11651. mg_lock_context(phys_ctx);
  11652. /* first try to find an existing handler */
  11653. do {
  11654. lastref = &(dom_ctx->handlers);
  11655. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  11656. tmp_rh = tmp_rh->next) {
  11657. if (tmp_rh->handler_type == handler_type
  11658. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11659. if (!is_delete_request) {
  11660. /* update existing handler */
  11661. if (handler_type == REQUEST_HANDLER) {
  11662. /* Wait for end of use before updating */
  11663. if (tmp_rh->refcount) {
  11664. mg_unlock_context(phys_ctx);
  11665. mg_sleep(1);
  11666. mg_lock_context(phys_ctx);
  11667. /* tmp_rh might have been freed, search again. */
  11668. break;
  11669. }
  11670. /* Ok, the handler is no more use -> Update it */
  11671. tmp_rh->handler = handler;
  11672. } else if (handler_type == WEBSOCKET_HANDLER) {
  11673. tmp_rh->subprotocols = subprotocols;
  11674. tmp_rh->connect_handler = connect_handler;
  11675. tmp_rh->ready_handler = ready_handler;
  11676. tmp_rh->data_handler = data_handler;
  11677. tmp_rh->close_handler = close_handler;
  11678. } else { /* AUTH_HANDLER */
  11679. tmp_rh->auth_handler = auth_handler;
  11680. }
  11681. tmp_rh->cbdata = cbdata;
  11682. } else {
  11683. /* remove existing handler */
  11684. if (handler_type == REQUEST_HANDLER) {
  11685. /* Wait for end of use before removing */
  11686. if (tmp_rh->refcount) {
  11687. tmp_rh->removing = 1;
  11688. mg_unlock_context(phys_ctx);
  11689. mg_sleep(1);
  11690. mg_lock_context(phys_ctx);
  11691. /* tmp_rh might have been freed, search again. */
  11692. break;
  11693. }
  11694. /* Ok, the handler is no more used */
  11695. }
  11696. *lastref = tmp_rh->next;
  11697. mg_free(tmp_rh->uri);
  11698. mg_free(tmp_rh);
  11699. }
  11700. mg_unlock_context(phys_ctx);
  11701. return;
  11702. }
  11703. lastref = &(tmp_rh->next);
  11704. }
  11705. } while (tmp_rh != NULL);
  11706. if (is_delete_request) {
  11707. /* no handler to set, this was a remove request to a non-existing
  11708. * handler */
  11709. mg_unlock_context(phys_ctx);
  11710. return;
  11711. }
  11712. tmp_rh =
  11713. (struct mg_handler_info *)mg_calloc_ctx(1,
  11714. sizeof(struct mg_handler_info),
  11715. phys_ctx);
  11716. if (tmp_rh == NULL) {
  11717. mg_unlock_context(phys_ctx);
  11718. mg_cry_ctx_internal(phys_ctx,
  11719. "%s",
  11720. "Cannot create new request handler struct, OOM");
  11721. return;
  11722. }
  11723. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11724. if (!tmp_rh->uri) {
  11725. mg_unlock_context(phys_ctx);
  11726. mg_free(tmp_rh);
  11727. mg_cry_ctx_internal(phys_ctx,
  11728. "%s",
  11729. "Cannot create new request handler struct, OOM");
  11730. return;
  11731. }
  11732. tmp_rh->uri_len = urilen;
  11733. if (handler_type == REQUEST_HANDLER) {
  11734. tmp_rh->refcount = 0;
  11735. tmp_rh->removing = 0;
  11736. tmp_rh->handler = handler;
  11737. } else if (handler_type == WEBSOCKET_HANDLER) {
  11738. tmp_rh->subprotocols = subprotocols;
  11739. tmp_rh->connect_handler = connect_handler;
  11740. tmp_rh->ready_handler = ready_handler;
  11741. tmp_rh->data_handler = data_handler;
  11742. tmp_rh->close_handler = close_handler;
  11743. } else { /* AUTH_HANDLER */
  11744. tmp_rh->auth_handler = auth_handler;
  11745. }
  11746. tmp_rh->cbdata = cbdata;
  11747. tmp_rh->handler_type = handler_type;
  11748. tmp_rh->next = NULL;
  11749. *lastref = tmp_rh;
  11750. mg_unlock_context(phys_ctx);
  11751. }
  11752. void
  11753. mg_set_request_handler(struct mg_context *ctx,
  11754. const char *uri,
  11755. mg_request_handler handler,
  11756. void *cbdata)
  11757. {
  11758. mg_set_handler_type(ctx,
  11759. &(ctx->dd),
  11760. uri,
  11761. REQUEST_HANDLER,
  11762. handler == NULL,
  11763. handler,
  11764. NULL,
  11765. NULL,
  11766. NULL,
  11767. NULL,
  11768. NULL,
  11769. NULL,
  11770. cbdata);
  11771. }
  11772. void
  11773. mg_set_websocket_handler(struct mg_context *ctx,
  11774. const char *uri,
  11775. mg_websocket_connect_handler connect_handler,
  11776. mg_websocket_ready_handler ready_handler,
  11777. mg_websocket_data_handler data_handler,
  11778. mg_websocket_close_handler close_handler,
  11779. void *cbdata)
  11780. {
  11781. mg_set_websocket_handler_with_subprotocols(ctx,
  11782. uri,
  11783. NULL,
  11784. connect_handler,
  11785. ready_handler,
  11786. data_handler,
  11787. close_handler,
  11788. cbdata);
  11789. }
  11790. void
  11791. mg_set_websocket_handler_with_subprotocols(
  11792. struct mg_context *ctx,
  11793. const char *uri,
  11794. struct mg_websocket_subprotocols *subprotocols,
  11795. mg_websocket_connect_handler connect_handler,
  11796. mg_websocket_ready_handler ready_handler,
  11797. mg_websocket_data_handler data_handler,
  11798. mg_websocket_close_handler close_handler,
  11799. void *cbdata)
  11800. {
  11801. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11802. && (data_handler == NULL)
  11803. && (close_handler == NULL);
  11804. mg_set_handler_type(ctx,
  11805. &(ctx->dd),
  11806. uri,
  11807. WEBSOCKET_HANDLER,
  11808. is_delete_request,
  11809. NULL,
  11810. subprotocols,
  11811. connect_handler,
  11812. ready_handler,
  11813. data_handler,
  11814. close_handler,
  11815. NULL,
  11816. cbdata);
  11817. }
  11818. void
  11819. mg_set_auth_handler(struct mg_context *ctx,
  11820. const char *uri,
  11821. mg_authorization_handler handler,
  11822. void *cbdata)
  11823. {
  11824. mg_set_handler_type(ctx,
  11825. &(ctx->dd),
  11826. uri,
  11827. AUTH_HANDLER,
  11828. handler == NULL,
  11829. NULL,
  11830. NULL,
  11831. NULL,
  11832. NULL,
  11833. NULL,
  11834. NULL,
  11835. handler,
  11836. cbdata);
  11837. }
  11838. static int
  11839. get_request_handler(struct mg_connection *conn,
  11840. int handler_type,
  11841. mg_request_handler *handler,
  11842. struct mg_websocket_subprotocols **subprotocols,
  11843. mg_websocket_connect_handler *connect_handler,
  11844. mg_websocket_ready_handler *ready_handler,
  11845. mg_websocket_data_handler *data_handler,
  11846. mg_websocket_close_handler *close_handler,
  11847. mg_authorization_handler *auth_handler,
  11848. void **cbdata,
  11849. struct mg_handler_info **handler_info)
  11850. {
  11851. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11852. if (request_info) {
  11853. const char *uri = request_info->local_uri;
  11854. size_t urilen = strlen(uri);
  11855. struct mg_handler_info *tmp_rh;
  11856. int step, matched;
  11857. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11858. return 0;
  11859. }
  11860. mg_lock_context(conn->phys_ctx);
  11861. for (step = 0; step < 3; step++) {
  11862. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11863. tmp_rh = tmp_rh->next) {
  11864. if (tmp_rh->handler_type != handler_type) {
  11865. continue;
  11866. }
  11867. if (step == 0) {
  11868. /* first try for an exact match */
  11869. matched = (tmp_rh->uri_len == urilen)
  11870. && (strcmp(tmp_rh->uri, uri) == 0);
  11871. } else if (step == 1) {
  11872. /* next try for a partial match, we will accept
  11873. uri/something */
  11874. matched =
  11875. (tmp_rh->uri_len < urilen)
  11876. && (uri[tmp_rh->uri_len] == '/')
  11877. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  11878. } else {
  11879. /* finally try for pattern match */
  11880. matched =
  11881. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  11882. }
  11883. if (matched) {
  11884. if (handler_type == WEBSOCKET_HANDLER) {
  11885. *subprotocols = tmp_rh->subprotocols;
  11886. *connect_handler = tmp_rh->connect_handler;
  11887. *ready_handler = tmp_rh->ready_handler;
  11888. *data_handler = tmp_rh->data_handler;
  11889. *close_handler = tmp_rh->close_handler;
  11890. } else if (handler_type == REQUEST_HANDLER) {
  11891. if (tmp_rh->removing) {
  11892. /* Treat as none found */
  11893. step = 2;
  11894. break;
  11895. }
  11896. *handler = tmp_rh->handler;
  11897. /* Acquire handler and give it back */
  11898. tmp_rh->refcount++;
  11899. *handler_info = tmp_rh;
  11900. } else { /* AUTH_HANDLER */
  11901. *auth_handler = tmp_rh->auth_handler;
  11902. }
  11903. *cbdata = tmp_rh->cbdata;
  11904. mg_unlock_context(conn->phys_ctx);
  11905. return 1;
  11906. }
  11907. }
  11908. }
  11909. mg_unlock_context(conn->phys_ctx);
  11910. }
  11911. return 0; /* none found */
  11912. }
  11913. /* Check if the script file is in a path, allowed for script files.
  11914. * This can be used if uploading files is possible not only for the server
  11915. * admin, and the upload mechanism does not check the file extension.
  11916. */
  11917. static int
  11918. is_in_script_path(const struct mg_connection *conn, const char *path)
  11919. {
  11920. /* TODO (Feature): Add config value for allowed script path.
  11921. * Default: All allowed. */
  11922. (void)conn;
  11923. (void)path;
  11924. return 1;
  11925. }
  11926. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  11927. static int
  11928. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  11929. int bits,
  11930. char *data,
  11931. size_t len,
  11932. void *cbdata)
  11933. {
  11934. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11935. if (pcallbacks->websocket_data) {
  11936. return pcallbacks->websocket_data(conn, bits, data, len);
  11937. }
  11938. /* No handler set - assume "OK" */
  11939. return 1;
  11940. }
  11941. static void
  11942. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  11943. void *cbdata)
  11944. {
  11945. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11946. if (pcallbacks->connection_close) {
  11947. pcallbacks->connection_close(conn);
  11948. }
  11949. }
  11950. #endif
  11951. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  11952. */
  11953. static void
  11954. release_handler_ref(struct mg_connection *conn,
  11955. struct mg_handler_info *handler_info)
  11956. {
  11957. if (handler_info != NULL) {
  11958. /* Use context lock for ref counter */
  11959. mg_lock_context(conn->phys_ctx);
  11960. handler_info->refcount--;
  11961. mg_unlock_context(conn->phys_ctx);
  11962. }
  11963. }
  11964. /* This is the heart of the Civetweb's logic.
  11965. * This function is called when the request is read, parsed and validated,
  11966. * and Civetweb must decide what action to take: serve a file, or
  11967. * a directory, or call embedded function, etcetera. */
  11968. static void
  11969. handle_request(struct mg_connection *conn)
  11970. {
  11971. struct mg_request_info *ri = &conn->request_info;
  11972. char path[UTF8_PATH_MAX];
  11973. int uri_len, ssl_index;
  11974. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11975. is_put_or_delete_request = 0, is_callback_resource = 0,
  11976. is_template_text_file = 0;
  11977. int i;
  11978. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11979. mg_request_handler callback_handler = NULL;
  11980. struct mg_handler_info *handler_info = NULL;
  11981. struct mg_websocket_subprotocols *subprotocols;
  11982. mg_websocket_connect_handler ws_connect_handler = NULL;
  11983. mg_websocket_ready_handler ws_ready_handler = NULL;
  11984. mg_websocket_data_handler ws_data_handler = NULL;
  11985. mg_websocket_close_handler ws_close_handler = NULL;
  11986. void *callback_data = NULL;
  11987. mg_authorization_handler auth_handler = NULL;
  11988. void *auth_callback_data = NULL;
  11989. int handler_type;
  11990. time_t curtime = time(NULL);
  11991. char date[64];
  11992. char *tmp;
  11993. path[0] = 0;
  11994. /* 0. Reset internal state (required for HTTP/2 proxy) */
  11995. conn->request_state = 0;
  11996. /* 1. get the request url */
  11997. /* 1.1. split into url and query string */
  11998. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11999. != NULL) {
  12000. *((char *)conn->request_info.query_string++) = '\0';
  12001. }
  12002. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12003. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12004. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12005. if (ssl_index >= 0) {
  12006. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12007. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12008. redirect_to_https_port(conn, port);
  12009. } else {
  12010. /* A http to https forward port has been specified,
  12011. * but no https port to forward to. */
  12012. mg_send_http_error(conn,
  12013. 503,
  12014. "%s",
  12015. "Error: SSL forward not configured properly");
  12016. mg_cry_internal(conn,
  12017. "%s",
  12018. "Can not redirect to SSL, no SSL port available");
  12019. }
  12020. return;
  12021. }
  12022. uri_len = (int)strlen(ri->local_uri);
  12023. /* 1.3. decode url (if config says so) */
  12024. if (should_decode_url(conn)) {
  12025. mg_url_decode(
  12026. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  12027. if (conn->request_info.query_string) {
  12028. url_decode_in_place((char *)conn->request_info.query_string);
  12029. }
  12030. }
  12031. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12032. * possible. The fact that we cleaned the URI is stored in that the
  12033. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12034. * ri->local_uri_raw still points to memory allocated in
  12035. * worker_thread_run(). ri->local_uri is private to the request so we
  12036. * don't have to use preallocated memory here. */
  12037. tmp = mg_strdup(ri->local_uri_raw);
  12038. if (!tmp) {
  12039. /* Out of memory. We cannot do anything reasonable here. */
  12040. return;
  12041. }
  12042. remove_dot_segments(tmp);
  12043. ri->local_uri = tmp;
  12044. /* step 1. completed, the url is known now */
  12045. uri_len = (int)strlen(ri->local_uri);
  12046. DEBUG_TRACE("URL: %s", ri->local_uri);
  12047. /* 2. if this ip has limited speed, set it for this connection */
  12048. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12049. &conn->client.rsa,
  12050. ri->local_uri);
  12051. /* 3. call a "handle everything" callback, if registered */
  12052. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12053. /* Note that since V1.7 the "begin_request" function is called
  12054. * before an authorization check. If an authorization check is
  12055. * required, use a request_handler instead. */
  12056. i = conn->phys_ctx->callbacks.begin_request(conn);
  12057. if (i > 0) {
  12058. /* callback already processed the request. Store the
  12059. return value as a status code for the access log. */
  12060. conn->status_code = i;
  12061. if (!conn->must_close) {
  12062. discard_unread_request_data(conn);
  12063. }
  12064. return;
  12065. } else if (i == 0) {
  12066. /* civetweb should process the request */
  12067. } else {
  12068. /* unspecified - may change with the next version */
  12069. return;
  12070. }
  12071. }
  12072. /* request not yet handled by a handler or redirect, so the request
  12073. * is processed here */
  12074. /* 4. Check for CORS preflight requests and handle them (if configured).
  12075. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12076. */
  12077. if (!strcmp(ri->request_method, "OPTIONS")) {
  12078. /* Send a response to CORS preflights only if
  12079. * access_control_allow_methods is not NULL and not an empty string.
  12080. * In this case, scripts can still handle CORS. */
  12081. const char *cors_meth_cfg =
  12082. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12083. const char *cors_orig_cfg =
  12084. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12085. const char *cors_origin =
  12086. get_header(ri->http_headers, ri->num_headers, "Origin");
  12087. const char *cors_acrm = get_header(ri->http_headers,
  12088. ri->num_headers,
  12089. "Access-Control-Request-Method");
  12090. /* Todo: check if cors_origin is in cors_orig_cfg.
  12091. * Or, let the client check this. */
  12092. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12093. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12094. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12095. /* This is a valid CORS preflight, and the server is configured
  12096. * to handle it automatically. */
  12097. const char *cors_acrh =
  12098. get_header(ri->http_headers,
  12099. ri->num_headers,
  12100. "Access-Control-Request-Headers");
  12101. gmt_time_string(date, sizeof(date), &curtime);
  12102. mg_printf(conn,
  12103. "HTTP/1.1 200 OK\r\n"
  12104. "Date: %s\r\n"
  12105. "Access-Control-Allow-Origin: %s\r\n"
  12106. "Access-Control-Allow-Methods: %s\r\n"
  12107. "Content-Length: 0\r\n"
  12108. "Connection: %s\r\n",
  12109. date,
  12110. cors_orig_cfg,
  12111. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12112. suggest_connection_header(conn));
  12113. if (cors_acrh != NULL) {
  12114. /* CORS request is asking for additional headers */
  12115. const char *cors_hdr_cfg =
  12116. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12117. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12118. /* Allow only if access_control_allow_headers is
  12119. * not NULL and not an empty string. If this
  12120. * configuration is set to *, allow everything.
  12121. * Otherwise this configuration must be a list
  12122. * of allowed HTTP header names. */
  12123. mg_printf(conn,
  12124. "Access-Control-Allow-Headers: %s\r\n",
  12125. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12126. : cors_hdr_cfg));
  12127. }
  12128. }
  12129. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12130. mg_printf(conn, "\r\n");
  12131. return;
  12132. }
  12133. }
  12134. /* 5. interpret the url to find out how the request must be handled
  12135. */
  12136. /* 5.1. first test, if the request targets the regular http(s)://
  12137. * protocol namespace or the websocket ws(s):// protocol namespace.
  12138. */
  12139. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  12140. #if defined(USE_WEBSOCKET)
  12141. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  12142. #else
  12143. handler_type = REQUEST_HANDLER;
  12144. #endif /* defined(USE_WEBSOCKET) */
  12145. if (is_websocket_request) {
  12146. HTTP1_only;
  12147. }
  12148. /* 5.2. check if the request will be handled by a callback */
  12149. if (get_request_handler(conn,
  12150. handler_type,
  12151. &callback_handler,
  12152. &subprotocols,
  12153. &ws_connect_handler,
  12154. &ws_ready_handler,
  12155. &ws_data_handler,
  12156. &ws_close_handler,
  12157. NULL,
  12158. &callback_data,
  12159. &handler_info)) {
  12160. /* 5.2.1. A callback will handle this request. All requests
  12161. * handled by a callback have to be considered as requests
  12162. * to a script resource. */
  12163. is_callback_resource = 1;
  12164. is_script_resource = 1;
  12165. is_put_or_delete_request = is_put_or_delete_method(conn);
  12166. } else {
  12167. no_callback_resource:
  12168. /* 5.2.2. No callback is responsible for this request. The URI
  12169. * addresses a file based resource (static content or Lua/cgi
  12170. * scripts in the file system). */
  12171. is_callback_resource = 0;
  12172. interpret_uri(conn,
  12173. path,
  12174. sizeof(path),
  12175. &file.stat,
  12176. &is_found,
  12177. &is_script_resource,
  12178. &is_websocket_request,
  12179. &is_put_or_delete_request,
  12180. &is_template_text_file);
  12181. }
  12182. /* 6. authorization check */
  12183. /* 6.1. a custom authorization handler is installed */
  12184. if (get_request_handler(conn,
  12185. AUTH_HANDLER,
  12186. NULL,
  12187. NULL,
  12188. NULL,
  12189. NULL,
  12190. NULL,
  12191. NULL,
  12192. &auth_handler,
  12193. &auth_callback_data,
  12194. NULL)) {
  12195. if (!auth_handler(conn, auth_callback_data)) {
  12196. /* Callback handler will not be used anymore. Release it */
  12197. release_handler_ref(conn, handler_info);
  12198. return;
  12199. }
  12200. } else if (is_put_or_delete_request && !is_script_resource
  12201. && !is_callback_resource) {
  12202. HTTP1_only;
  12203. /* 6.2. this request is a PUT/DELETE to a real file */
  12204. /* 6.2.1. thus, the server must have real files */
  12205. #if defined(NO_FILES)
  12206. if (1) {
  12207. #else
  12208. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12209. #endif
  12210. /* This code path will not be called for request handlers */
  12211. DEBUG_ASSERT(handler_info == NULL);
  12212. /* This server does not have any real files, thus the
  12213. * PUT/DELETE methods are not valid. */
  12214. mg_send_http_error(conn,
  12215. 405,
  12216. "%s method not allowed",
  12217. conn->request_info.request_method);
  12218. return;
  12219. }
  12220. #if !defined(NO_FILES)
  12221. /* 6.2.2. Check if put authorization for static files is
  12222. * available.
  12223. */
  12224. if (!is_authorized_for_put(conn)) {
  12225. send_authorization_request(conn, NULL);
  12226. return;
  12227. }
  12228. #endif
  12229. } else {
  12230. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12231. * or it is a PUT or DELETE request to a resource that does not
  12232. * correspond to a file. Check authorization. */
  12233. if (!check_authorization(conn, path)) {
  12234. send_authorization_request(conn, NULL);
  12235. /* Callback handler will not be used anymore. Release it */
  12236. release_handler_ref(conn, handler_info);
  12237. return;
  12238. }
  12239. }
  12240. /* request is authorized or does not need authorization */
  12241. /* 7. check if there are request handlers for this uri */
  12242. if (is_callback_resource) {
  12243. HTTP1_only;
  12244. if (!is_websocket_request) {
  12245. i = callback_handler(conn, callback_data);
  12246. /* Callback handler will not be used anymore. Release it */
  12247. release_handler_ref(conn, handler_info);
  12248. if (i > 0) {
  12249. /* Do nothing, callback has served the request. Store
  12250. * then return value as status code for the log and discard
  12251. * all data from the client not used by the callback. */
  12252. conn->status_code = i;
  12253. if (!conn->must_close) {
  12254. discard_unread_request_data(conn);
  12255. }
  12256. } else {
  12257. /* The handler did NOT handle the request. */
  12258. /* Some proper reactions would be:
  12259. * a) close the connections without sending anything
  12260. * b) send a 404 not found
  12261. * c) try if there is a file matching the URI
  12262. * It would be possible to do a, b or c in the callback
  12263. * implementation, and return 1 - we cannot do anything
  12264. * here, that is not possible in the callback.
  12265. *
  12266. * TODO: What would be the best reaction here?
  12267. * (Note: The reaction may change, if there is a better
  12268. * idea.)
  12269. */
  12270. /* For the moment, use option c: We look for a proper file,
  12271. * but since a file request is not always a script resource,
  12272. * the authorization check might be different. */
  12273. interpret_uri(conn,
  12274. path,
  12275. sizeof(path),
  12276. &file.stat,
  12277. &is_found,
  12278. &is_script_resource,
  12279. &is_websocket_request,
  12280. &is_put_or_delete_request,
  12281. &is_template_text_file);
  12282. callback_handler = NULL;
  12283. /* Here we are at a dead end:
  12284. * According to URI matching, a callback should be
  12285. * responsible for handling the request,
  12286. * we called it, but the callback declared itself
  12287. * not responsible.
  12288. * We use a goto here, to get out of this dead end,
  12289. * and continue with the default handling.
  12290. * A goto here is simpler and better to understand
  12291. * than some curious loop. */
  12292. goto no_callback_resource;
  12293. }
  12294. } else {
  12295. #if defined(USE_WEBSOCKET)
  12296. handle_websocket_request(conn,
  12297. path,
  12298. is_callback_resource,
  12299. subprotocols,
  12300. ws_connect_handler,
  12301. ws_ready_handler,
  12302. ws_data_handler,
  12303. ws_close_handler,
  12304. callback_data);
  12305. #endif
  12306. }
  12307. return;
  12308. }
  12309. /* 8. handle websocket requests */
  12310. #if defined(USE_WEBSOCKET)
  12311. if (is_websocket_request) {
  12312. HTTP1_only;
  12313. if (is_script_resource) {
  12314. if (is_in_script_path(conn, path)) {
  12315. /* Websocket Lua script */
  12316. handle_websocket_request(conn,
  12317. path,
  12318. 0 /* Lua Script */,
  12319. NULL,
  12320. NULL,
  12321. NULL,
  12322. NULL,
  12323. NULL,
  12324. conn->phys_ctx->user_data);
  12325. } else {
  12326. /* Script was in an illegal path */
  12327. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12328. }
  12329. } else {
  12330. mg_send_http_error(conn, 404, "%s", "Not found");
  12331. }
  12332. return;
  12333. } else
  12334. #endif
  12335. #if defined(NO_FILES)
  12336. /* 9a. In case the server uses only callbacks, this uri is
  12337. * unknown.
  12338. * Then, all request handling ends here. */
  12339. mg_send_http_error(conn, 404, "%s", "Not Found");
  12340. #else
  12341. /* 9b. This request is either for a static file or resource handled
  12342. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12343. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12344. mg_send_http_error(conn, 404, "%s", "Not Found");
  12345. return;
  12346. }
  12347. /* 10. Request is handled by a script */
  12348. if (is_script_resource) {
  12349. HTTP1_only;
  12350. handle_file_based_request(conn, path, &file);
  12351. return;
  12352. }
  12353. /* 11. Handle put/delete/mkcol requests */
  12354. if (is_put_or_delete_request) {
  12355. HTTP1_only;
  12356. /* 11.1. PUT method */
  12357. if (!strcmp(ri->request_method, "PUT")) {
  12358. put_file(conn, path);
  12359. return;
  12360. }
  12361. /* 11.2. DELETE method */
  12362. if (!strcmp(ri->request_method, "DELETE")) {
  12363. delete_file(conn, path);
  12364. return;
  12365. }
  12366. /* 11.3. MKCOL method */
  12367. if (!strcmp(ri->request_method, "MKCOL")) {
  12368. mkcol(conn, path);
  12369. return;
  12370. }
  12371. /* 11.4. PATCH method
  12372. * This method is not supported for static resources,
  12373. * only for scripts (Lua, CGI) and callbacks. */
  12374. mg_send_http_error(conn,
  12375. 405,
  12376. "%s method not allowed",
  12377. conn->request_info.request_method);
  12378. return;
  12379. }
  12380. /* 11. File does not exist, or it was configured that it should be
  12381. * hidden */
  12382. if (!is_found || (must_hide_file(conn, path))) {
  12383. mg_send_http_error(conn, 404, "%s", "Not found");
  12384. return;
  12385. }
  12386. /* 12. Directory uris should end with a slash */
  12387. if (file.stat.is_directory && (uri_len > 0)
  12388. && (ri->local_uri[uri_len - 1] != '/')) {
  12389. size_t len = strlen(ri->request_uri);
  12390. size_t lenQS = ri->query_string ? strlen(ri->query_string) + 1 : 0;
  12391. char *new_path = (char *)mg_malloc_ctx(len + lenQS + 2, conn->phys_ctx);
  12392. if (!new_path) {
  12393. mg_send_http_error(conn, 500, "out or memory");
  12394. } else {
  12395. memcpy(new_path, ri->request_uri, len);
  12396. new_path[len] = '/';
  12397. new_path[len + 1] = 0;
  12398. if (ri->query_string) {
  12399. new_path[len + 1] = '?';
  12400. /* Copy query string including terminating zero */
  12401. memcpy(new_path + len + 2, ri->query_string, lenQS);
  12402. }
  12403. mg_send_http_redirect(conn, new_path, 301);
  12404. mg_free(new_path);
  12405. }
  12406. return;
  12407. }
  12408. /* 13. Handle other methods than GET/HEAD */
  12409. /* 13.1. Handle PROPFIND */
  12410. if (!strcmp(ri->request_method, "PROPFIND")) {
  12411. handle_propfind(conn, path, &file.stat);
  12412. return;
  12413. }
  12414. /* 13.2. Handle OPTIONS for files */
  12415. if (!strcmp(ri->request_method, "OPTIONS")) {
  12416. /* This standard handler is only used for real files.
  12417. * Scripts should support the OPTIONS method themselves, to allow a
  12418. * maximum flexibility.
  12419. * Lua and CGI scripts may fully support CORS this way (including
  12420. * preflights). */
  12421. send_options(conn);
  12422. return;
  12423. }
  12424. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12425. if ((0 != strcmp(ri->request_method, "GET"))
  12426. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12427. mg_send_http_error(conn,
  12428. 405,
  12429. "%s method not allowed",
  12430. conn->request_info.request_method);
  12431. return;
  12432. }
  12433. /* 14. directories */
  12434. if (file.stat.is_directory) {
  12435. /* Substitute files have already been handled above. */
  12436. /* Here we can either generate and send a directory listing,
  12437. * or send an "access denied" error. */
  12438. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12439. "yes")) {
  12440. handle_directory_request(conn, path);
  12441. } else {
  12442. mg_send_http_error(conn,
  12443. 403,
  12444. "%s",
  12445. "Error: Directory listing denied");
  12446. }
  12447. return;
  12448. }
  12449. /* 15. Files with search/replace patterns: LSP and SSI */
  12450. if (is_template_text_file) {
  12451. HTTP1_only;
  12452. handle_file_based_request(conn, path, &file);
  12453. return;
  12454. }
  12455. /* 16. Static file - maybe cached */
  12456. #if !defined(NO_CACHING)
  12457. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  12458. /* Send 304 "Not Modified" - this must not send any body data */
  12459. handle_not_modified_static_file_request(conn, &file);
  12460. return;
  12461. }
  12462. #endif /* !NO_CACHING */
  12463. /* 17. Static file - not cached */
  12464. handle_static_file_request(conn, path, &file, NULL, NULL);
  12465. #endif /* !defined(NO_FILES) */
  12466. }
  12467. #if !defined(NO_FILESYSTEMS)
  12468. static void
  12469. handle_file_based_request(struct mg_connection *conn,
  12470. const char *path,
  12471. struct mg_file *file)
  12472. {
  12473. #if !defined(NO_CGI)
  12474. unsigned char cgi_config_idx, inc, max;
  12475. #endif
  12476. if (!conn || !conn->dom_ctx) {
  12477. return;
  12478. }
  12479. #if defined(USE_LUA)
  12480. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12481. path)
  12482. > 0) {
  12483. if (is_in_script_path(conn, path)) {
  12484. /* Lua server page: an SSI like page containing mostly plain
  12485. * html code plus some tags with server generated contents. */
  12486. handle_lsp_request(conn, path, file, NULL);
  12487. } else {
  12488. /* Script was in an illegal path */
  12489. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12490. }
  12491. return;
  12492. }
  12493. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  12494. > 0) {
  12495. if (is_in_script_path(conn, path)) {
  12496. /* Lua in-server module script: a CGI like script used to
  12497. * generate the entire reply. */
  12498. mg_exec_lua_script(conn, path, NULL);
  12499. } else {
  12500. /* Script was in an illegal path */
  12501. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12502. }
  12503. return;
  12504. }
  12505. #endif
  12506. #if defined(USE_DUKTAPE)
  12507. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12508. path)
  12509. > 0) {
  12510. if (is_in_script_path(conn, path)) {
  12511. /* Call duktape to generate the page */
  12512. mg_exec_duktape_script(conn, path);
  12513. } else {
  12514. /* Script was in an illegal path */
  12515. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12516. }
  12517. return;
  12518. }
  12519. #endif
  12520. #if !defined(NO_CGI)
  12521. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  12522. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  12523. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  12524. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  12525. if (match_prefix_strlen(
  12526. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  12527. path)
  12528. > 0) {
  12529. if (is_in_script_path(conn, path)) {
  12530. /* CGI scripts may support all HTTP methods */
  12531. handle_cgi_request(conn, path, 0);
  12532. } else {
  12533. /* Script was in an illegal path */
  12534. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12535. }
  12536. return;
  12537. }
  12538. }
  12539. }
  12540. #endif /* !NO_CGI */
  12541. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  12542. if (is_in_script_path(conn, path)) {
  12543. handle_ssi_file_request(conn, path, file);
  12544. } else {
  12545. /* Script was in an illegal path */
  12546. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12547. }
  12548. return;
  12549. }
  12550. #if !defined(NO_CACHING)
  12551. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  12552. /* Send 304 "Not Modified" - this must not send any body data */
  12553. handle_not_modified_static_file_request(conn, file);
  12554. return;
  12555. }
  12556. #endif /* !NO_CACHING */
  12557. handle_static_file_request(conn, path, file, NULL, NULL);
  12558. }
  12559. #endif /* NO_FILESYSTEMS */
  12560. static void
  12561. close_all_listening_sockets(struct mg_context *ctx)
  12562. {
  12563. unsigned int i;
  12564. if (!ctx) {
  12565. return;
  12566. }
  12567. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12568. closesocket(ctx->listening_sockets[i].sock);
  12569. #if defined(USE_X_DOM_SOCKET)
  12570. /* For unix domain sockets, the socket name represents a file that has
  12571. * to be deleted. */
  12572. /* See
  12573. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  12574. */
  12575. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  12576. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  12577. IGNORE_UNUSED_RESULT(
  12578. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  12579. }
  12580. #endif
  12581. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12582. }
  12583. mg_free(ctx->listening_sockets);
  12584. ctx->listening_sockets = NULL;
  12585. mg_free(ctx->listening_socket_fds);
  12586. ctx->listening_socket_fds = NULL;
  12587. }
  12588. /* Valid listening port specification is: [ip_address:]port[s]
  12589. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12590. * Examples for IPv6: [::]:80, [::1]:80,
  12591. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12592. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12593. * In order to bind to both, IPv4 and IPv6, you can either add
  12594. * both ports using 8080,[::]:8080, or the short form +8080.
  12595. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12596. * one only accepting IPv4 the other only IPv6. +8080 creates
  12597. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12598. * environment, they might work differently, or might not work
  12599. * at all - it must be tested what options work best in the
  12600. * relevant network environment.
  12601. */
  12602. static int
  12603. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12604. {
  12605. unsigned int a, b, c, d;
  12606. unsigned port;
  12607. unsigned long portUL;
  12608. int ch, len;
  12609. const char *cb;
  12610. char *endptr;
  12611. #if defined(USE_IPV6)
  12612. char buf[100] = {0};
  12613. #endif
  12614. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12615. * Also, all-zeroes in the socket address means binding to all addresses
  12616. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12617. memset(so, 0, sizeof(*so));
  12618. so->lsa.sin.sin_family = AF_INET;
  12619. *ip_version = 0;
  12620. /* Initialize len as invalid. */
  12621. port = 0;
  12622. len = 0;
  12623. /* Test for different ways to format this string */
  12624. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12625. == 5) {
  12626. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12627. so->lsa.sin.sin_addr.s_addr =
  12628. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12629. so->lsa.sin.sin_port = htons((uint16_t)port);
  12630. *ip_version = 4;
  12631. #if defined(USE_IPV6)
  12632. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12633. && ((size_t)len <= vec->len)
  12634. && mg_inet_pton(
  12635. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  12636. /* IPv6 address, examples: see above */
  12637. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12638. */
  12639. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12640. *ip_version = 6;
  12641. #endif
  12642. } else if ((vec->ptr[0] == '+')
  12643. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12644. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12645. /* Add 1 to len for the + character we skipped before */
  12646. len++;
  12647. #if defined(USE_IPV6)
  12648. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12649. so->lsa.sin6.sin6_family = AF_INET6;
  12650. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12651. *ip_version = 4 + 6;
  12652. #else
  12653. /* Bind to IPv4 only, since IPv6 is not built in. */
  12654. so->lsa.sin.sin_port = htons((uint16_t)port);
  12655. *ip_version = 4;
  12656. #endif
  12657. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  12658. && (vec->ptr != endptr)) {
  12659. len = (int)(endptr - vec->ptr);
  12660. port = (uint16_t)portUL;
  12661. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12662. so->lsa.sin.sin_port = htons((uint16_t)port);
  12663. *ip_version = 4;
  12664. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12665. /* String could be a hostname. This check algotithm
  12666. * will only work for RFC 952 compliant hostnames,
  12667. * starting with a letter, containing only letters,
  12668. * digits and hyphen ('-'). Newer specs may allow
  12669. * more, but this is not guaranteed here, since it
  12670. * may interfere with rules for port option lists. */
  12671. /* According to RFC 1035, hostnames are restricted to 255 characters
  12672. * in total (63 between two dots). */
  12673. char hostname[256];
  12674. size_t hostnlen = (size_t)(cb - vec->ptr);
  12675. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  12676. /* This would be invalid in any case */
  12677. *ip_version = 0;
  12678. return 0;
  12679. }
  12680. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  12681. if (mg_inet_pton(
  12682. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  12683. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12684. *ip_version = 4;
  12685. so->lsa.sin.sin_port = htons((uint16_t)port);
  12686. len += (int)(hostnlen + 1);
  12687. } else {
  12688. len = 0;
  12689. }
  12690. #if defined(USE_IPV6)
  12691. } else if (mg_inet_pton(AF_INET6,
  12692. hostname,
  12693. &so->lsa.sin6,
  12694. sizeof(so->lsa.sin6),
  12695. 1)) {
  12696. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12697. *ip_version = 6;
  12698. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12699. len += (int)(hostnlen + 1);
  12700. } else {
  12701. len = 0;
  12702. }
  12703. #endif
  12704. } else {
  12705. len = 0;
  12706. }
  12707. #if defined(USE_X_DOM_SOCKET)
  12708. } else if (vec->ptr[0] == 'x') {
  12709. /* unix (linux) domain socket */
  12710. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  12711. len = vec->len;
  12712. so->lsa.sun.sun_family = AF_UNIX;
  12713. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  12714. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  12715. port = 0;
  12716. *ip_version = 99;
  12717. } else {
  12718. /* String too long */
  12719. len = 0;
  12720. }
  12721. #endif
  12722. } else {
  12723. /* Parsing failure. */
  12724. len = 0;
  12725. }
  12726. /* sscanf and the option splitting code ensure the following condition
  12727. * Make sure the port is valid and vector ends with the port, 's' or 'r' */
  12728. if ((len > 0) && is_valid_port(port)
  12729. && (((size_t)len == vec->len) || (((size_t)len + 1) == vec->len))) {
  12730. /* Next character after the port number */
  12731. ch = ((size_t)len < vec->len) ? vec->ptr[len] : '\0';
  12732. so->is_ssl = (ch == 's');
  12733. so->ssl_redir = (ch == 'r');
  12734. if ((ch == '\0') || (ch == 's') || (ch == 'r')) {
  12735. return 1;
  12736. }
  12737. }
  12738. /* Reset ip_version to 0 if there is an error */
  12739. *ip_version = 0;
  12740. return 0;
  12741. }
  12742. /* Is there any SSL port in use? */
  12743. static int
  12744. is_ssl_port_used(const char *ports)
  12745. {
  12746. if (ports) {
  12747. /* There are several different allowed syntax variants:
  12748. * - "80" for a single port using every network interface
  12749. * - "localhost:80" for a single port using only localhost
  12750. * - "80,localhost:8080" for two ports, one bound to localhost
  12751. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12752. * to IPv4 localhost, one to IPv6 localhost
  12753. * - "+80" use port 80 for IPv4 and IPv6
  12754. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12755. * for both: IPv4 and IPv4
  12756. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12757. * additionally port 8080 bound to localhost connections
  12758. *
  12759. * If we just look for 's' anywhere in the string, "localhost:80"
  12760. * will be detected as SSL (false positive).
  12761. * Looking for 's' after a digit may cause false positives in
  12762. * "my24service:8080".
  12763. * Looking from 's' backward if there are only ':' and numbers
  12764. * before will not work for "24service:8080" (non SSL, port 8080)
  12765. * or "24s" (SSL, port 24).
  12766. *
  12767. * Remark: Initially hostnames were not allowed to start with a
  12768. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12769. * Section 2.1).
  12770. *
  12771. * To get this correct, the entire string must be parsed as a whole,
  12772. * reading it as a list element for element and parsing with an
  12773. * algorithm equivalent to parse_port_string.
  12774. *
  12775. * In fact, we use local interface names here, not arbitrary
  12776. * hostnames, so in most cases the only name will be "localhost".
  12777. *
  12778. * So, for now, we use this simple algorithm, that may still return
  12779. * a false positive in bizarre cases.
  12780. */
  12781. int i;
  12782. int portslen = (int)strlen(ports);
  12783. char prevIsNumber = 0;
  12784. for (i = 0; i < portslen; i++) {
  12785. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12786. return 1;
  12787. }
  12788. if (ports[i] >= '0' && ports[i] <= '9') {
  12789. prevIsNumber = 1;
  12790. } else {
  12791. prevIsNumber = 0;
  12792. }
  12793. }
  12794. }
  12795. return 0;
  12796. }
  12797. static int
  12798. set_ports_option(struct mg_context *phys_ctx)
  12799. {
  12800. const char *list;
  12801. int on = 1;
  12802. #if defined(USE_IPV6)
  12803. int off = 0;
  12804. #endif
  12805. struct vec vec;
  12806. struct socket so, *ptr;
  12807. struct mg_pollfd *pfd;
  12808. union usa usa;
  12809. socklen_t len;
  12810. int ip_version;
  12811. int portsTotal = 0;
  12812. int portsOk = 0;
  12813. const char *opt_txt;
  12814. long opt_listen_backlog;
  12815. if (!phys_ctx) {
  12816. return 0;
  12817. }
  12818. memset(&so, 0, sizeof(so));
  12819. memset(&usa, 0, sizeof(usa));
  12820. len = sizeof(usa);
  12821. list = phys_ctx->dd.config[LISTENING_PORTS];
  12822. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12823. portsTotal++;
  12824. if (!parse_port_string(&vec, &so, &ip_version)) {
  12825. mg_cry_ctx_internal(
  12826. phys_ctx,
  12827. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12828. (int)vec.len,
  12829. vec.ptr,
  12830. portsTotal,
  12831. "[IP_ADDRESS:]PORT[s|r]");
  12832. continue;
  12833. }
  12834. #if !defined(NO_SSL)
  12835. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12836. mg_cry_ctx_internal(phys_ctx,
  12837. "Cannot add SSL socket (entry %i)",
  12838. portsTotal);
  12839. continue;
  12840. }
  12841. #endif
  12842. /* Create socket. */
  12843. /* For a list of protocol numbers (e.g., TCP==6) see:
  12844. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  12845. */
  12846. if ((so.sock =
  12847. socket(so.lsa.sa.sa_family,
  12848. SOCK_STREAM,
  12849. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  12850. == INVALID_SOCKET) {
  12851. mg_cry_ctx_internal(phys_ctx,
  12852. "cannot create socket (entry %i)",
  12853. portsTotal);
  12854. continue;
  12855. }
  12856. #if defined(_WIN32)
  12857. /* Windows SO_REUSEADDR lets many procs binds to a
  12858. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12859. * if someone already has the socket -- DTL */
  12860. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12861. * Windows might need a few seconds before
  12862. * the same port can be used again in the
  12863. * same process, so a short Sleep may be
  12864. * required between mg_stop and mg_start.
  12865. */
  12866. if (setsockopt(so.sock,
  12867. SOL_SOCKET,
  12868. SO_EXCLUSIVEADDRUSE,
  12869. (SOCK_OPT_TYPE)&on,
  12870. sizeof(on))
  12871. != 0) {
  12872. /* Set reuse option, but don't abort on errors. */
  12873. mg_cry_ctx_internal(
  12874. phys_ctx,
  12875. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12876. portsTotal);
  12877. }
  12878. #else
  12879. if (setsockopt(so.sock,
  12880. SOL_SOCKET,
  12881. SO_REUSEADDR,
  12882. (SOCK_OPT_TYPE)&on,
  12883. sizeof(on))
  12884. != 0) {
  12885. /* Set reuse option, but don't abort on errors. */
  12886. mg_cry_ctx_internal(
  12887. phys_ctx,
  12888. "cannot set socket option SO_REUSEADDR (entry %i)",
  12889. portsTotal);
  12890. }
  12891. #endif
  12892. #if defined(USE_X_DOM_SOCKET)
  12893. if (ip_version == 99) {
  12894. /* Unix domain socket */
  12895. } else
  12896. #endif
  12897. if (ip_version > 4) {
  12898. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12899. #if defined(USE_IPV6)
  12900. if (ip_version > 6) {
  12901. if (so.lsa.sa.sa_family == AF_INET6
  12902. && setsockopt(so.sock,
  12903. IPPROTO_IPV6,
  12904. IPV6_V6ONLY,
  12905. (void *)&off,
  12906. sizeof(off))
  12907. != 0) {
  12908. /* Set IPv6 only option, but don't abort on errors. */
  12909. mg_cry_ctx_internal(phys_ctx,
  12910. "cannot set socket option "
  12911. "IPV6_V6ONLY=off (entry %i)",
  12912. portsTotal);
  12913. }
  12914. } else {
  12915. if (so.lsa.sa.sa_family == AF_INET6
  12916. && setsockopt(so.sock,
  12917. IPPROTO_IPV6,
  12918. IPV6_V6ONLY,
  12919. (void *)&on,
  12920. sizeof(on))
  12921. != 0) {
  12922. /* Set IPv6 only option, but don't abort on errors. */
  12923. mg_cry_ctx_internal(phys_ctx,
  12924. "cannot set socket option "
  12925. "IPV6_V6ONLY=on (entry %i)",
  12926. portsTotal);
  12927. }
  12928. }
  12929. #else
  12930. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12931. closesocket(so.sock);
  12932. so.sock = INVALID_SOCKET;
  12933. continue;
  12934. #endif
  12935. }
  12936. if (so.lsa.sa.sa_family == AF_INET) {
  12937. len = sizeof(so.lsa.sin);
  12938. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12939. mg_cry_ctx_internal(phys_ctx,
  12940. "cannot bind to %.*s: %d (%s)",
  12941. (int)vec.len,
  12942. vec.ptr,
  12943. (int)ERRNO,
  12944. strerror(errno));
  12945. closesocket(so.sock);
  12946. so.sock = INVALID_SOCKET;
  12947. continue;
  12948. }
  12949. }
  12950. #if defined(USE_IPV6)
  12951. else if (so.lsa.sa.sa_family == AF_INET6) {
  12952. len = sizeof(so.lsa.sin6);
  12953. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12954. mg_cry_ctx_internal(phys_ctx,
  12955. "cannot bind to IPv6 %.*s: %d (%s)",
  12956. (int)vec.len,
  12957. vec.ptr,
  12958. (int)ERRNO,
  12959. strerror(errno));
  12960. closesocket(so.sock);
  12961. so.sock = INVALID_SOCKET;
  12962. continue;
  12963. }
  12964. }
  12965. #endif
  12966. #if defined(USE_X_DOM_SOCKET)
  12967. else if (so.lsa.sa.sa_family == AF_UNIX) {
  12968. len = sizeof(so.lsa.sun);
  12969. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12970. mg_cry_ctx_internal(phys_ctx,
  12971. "cannot bind to unix socket %s: %d (%s)",
  12972. so.lsa.sun.sun_path,
  12973. (int)ERRNO,
  12974. strerror(errno));
  12975. closesocket(so.sock);
  12976. so.sock = INVALID_SOCKET;
  12977. continue;
  12978. }
  12979. }
  12980. #endif
  12981. else {
  12982. mg_cry_ctx_internal(
  12983. phys_ctx,
  12984. "cannot bind: address family not supported (entry %i)",
  12985. portsTotal);
  12986. closesocket(so.sock);
  12987. so.sock = INVALID_SOCKET;
  12988. continue;
  12989. }
  12990. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  12991. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  12992. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  12993. mg_cry_ctx_internal(phys_ctx,
  12994. "%s value \"%s\" is invalid",
  12995. config_options[LISTEN_BACKLOG_SIZE].name,
  12996. opt_txt);
  12997. closesocket(so.sock);
  12998. so.sock = INVALID_SOCKET;
  12999. continue;
  13000. }
  13001. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  13002. mg_cry_ctx_internal(phys_ctx,
  13003. "cannot listen to %.*s: %d (%s)",
  13004. (int)vec.len,
  13005. vec.ptr,
  13006. (int)ERRNO,
  13007. strerror(errno));
  13008. closesocket(so.sock);
  13009. so.sock = INVALID_SOCKET;
  13010. continue;
  13011. }
  13012. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  13013. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  13014. int err = (int)ERRNO;
  13015. mg_cry_ctx_internal(phys_ctx,
  13016. "call to getsockname failed %.*s: %d (%s)",
  13017. (int)vec.len,
  13018. vec.ptr,
  13019. err,
  13020. strerror(errno));
  13021. closesocket(so.sock);
  13022. so.sock = INVALID_SOCKET;
  13023. continue;
  13024. }
  13025. /* Update lsa port in case of random free ports */
  13026. #if defined(USE_IPV6)
  13027. if (so.lsa.sa.sa_family == AF_INET6) {
  13028. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  13029. } else
  13030. #endif
  13031. {
  13032. so.lsa.sin.sin_port = usa.sin.sin_port;
  13033. }
  13034. if ((ptr = (struct socket *)
  13035. mg_realloc_ctx(phys_ctx->listening_sockets,
  13036. (phys_ctx->num_listening_sockets + 1)
  13037. * sizeof(phys_ctx->listening_sockets[0]),
  13038. phys_ctx))
  13039. == NULL) {
  13040. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13041. closesocket(so.sock);
  13042. so.sock = INVALID_SOCKET;
  13043. continue;
  13044. }
  13045. if ((pfd = (struct mg_pollfd *)
  13046. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  13047. (phys_ctx->num_listening_sockets + 1)
  13048. * sizeof(phys_ctx->listening_socket_fds[0]),
  13049. phys_ctx))
  13050. == NULL) {
  13051. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  13052. closesocket(so.sock);
  13053. so.sock = INVALID_SOCKET;
  13054. mg_free(ptr);
  13055. continue;
  13056. }
  13057. set_close_on_exec(so.sock, NULL, phys_ctx);
  13058. phys_ctx->listening_sockets = ptr;
  13059. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  13060. phys_ctx->listening_socket_fds = pfd;
  13061. phys_ctx->num_listening_sockets++;
  13062. portsOk++;
  13063. }
  13064. if (portsOk != portsTotal) {
  13065. close_all_listening_sockets(phys_ctx);
  13066. portsOk = 0;
  13067. }
  13068. return portsOk;
  13069. }
  13070. static const char *
  13071. header_val(const struct mg_connection *conn, const char *header)
  13072. {
  13073. const char *header_value;
  13074. if ((header_value = mg_get_header(conn, header)) == NULL) {
  13075. return "-";
  13076. } else {
  13077. return header_value;
  13078. }
  13079. }
  13080. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  13081. #include "external_log_access.inl"
  13082. #elif !defined(NO_FILESYSTEMS)
  13083. static void
  13084. log_access(const struct mg_connection *conn)
  13085. {
  13086. const struct mg_request_info *ri;
  13087. struct mg_file fi;
  13088. char date[64], src_addr[IP_ADDR_STR_LEN];
  13089. struct tm *tm;
  13090. const char *referer;
  13091. const char *user_agent;
  13092. char log_buf[4096];
  13093. if (!conn || !conn->dom_ctx) {
  13094. return;
  13095. }
  13096. /* Set log message to "empty" */
  13097. log_buf[0] = 0;
  13098. #if defined(USE_LUA)
  13099. if (conn->phys_ctx->lua_bg_log_available) {
  13100. int ret;
  13101. struct mg_context *ctx = conn->phys_ctx;
  13102. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  13103. pthread_mutex_lock(&ctx->lua_bg_mutex);
  13104. /* call "log()" in Lua */
  13105. lua_getglobal(lstate, "log");
  13106. prepare_lua_request_info_inner(conn, lstate);
  13107. push_lua_response_log_data(conn, lstate);
  13108. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  13109. if (ret == 0) {
  13110. int t = lua_type(lstate, -1);
  13111. if (t == LUA_TBOOLEAN) {
  13112. if (lua_toboolean(lstate, -1) == 0) {
  13113. /* log() returned false: do not log */
  13114. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13115. return;
  13116. }
  13117. /* log returned true: continue logging */
  13118. } else if (t == LUA_TSTRING) {
  13119. size_t len;
  13120. const char *txt = lua_tolstring(lstate, -1, &len);
  13121. if ((len == 0) || (*txt == 0)) {
  13122. /* log() returned empty string: do not log */
  13123. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13124. return;
  13125. }
  13126. /* Copy test from Lua into log_buf */
  13127. if (len >= sizeof(log_buf)) {
  13128. len = sizeof(log_buf) - 1;
  13129. }
  13130. memcpy(log_buf, txt, len);
  13131. log_buf[len] = 0;
  13132. }
  13133. } else {
  13134. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  13135. }
  13136. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  13137. }
  13138. #endif
  13139. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  13140. if (mg_fopen(conn,
  13141. conn->dom_ctx->config[ACCESS_LOG_FILE],
  13142. MG_FOPEN_MODE_APPEND,
  13143. &fi)
  13144. == 0) {
  13145. fi.access.fp = NULL;
  13146. }
  13147. } else {
  13148. fi.access.fp = NULL;
  13149. }
  13150. /* Log is written to a file and/or a callback. If both are not set,
  13151. * executing the rest of the function is pointless. */
  13152. if ((fi.access.fp == NULL)
  13153. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  13154. return;
  13155. }
  13156. /* If we did not get a log message from Lua, create it here. */
  13157. if (!log_buf[0]) {
  13158. tm = localtime(&conn->conn_birth_time);
  13159. if (tm != NULL) {
  13160. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  13161. } else {
  13162. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  13163. date[sizeof(date) - 1] = '\0';
  13164. }
  13165. ri = &conn->request_info;
  13166. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  13167. referer = header_val(conn, "Referer");
  13168. user_agent = header_val(conn, "User-Agent");
  13169. mg_snprintf(conn,
  13170. NULL, /* Ignore truncation in access log */
  13171. log_buf,
  13172. sizeof(log_buf),
  13173. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  13174. " %s %s",
  13175. src_addr,
  13176. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  13177. date,
  13178. ri->request_method ? ri->request_method : "-",
  13179. ri->request_uri ? ri->request_uri : "-",
  13180. ri->query_string ? "?" : "",
  13181. ri->query_string ? ri->query_string : "",
  13182. ri->http_version,
  13183. conn->status_code,
  13184. conn->num_bytes_sent,
  13185. referer,
  13186. user_agent);
  13187. }
  13188. /* Here we have a log message in log_buf. Call the callback */
  13189. if (conn->phys_ctx->callbacks.log_access) {
  13190. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  13191. /* do not log if callack returns non-zero */
  13192. if (fi.access.fp) {
  13193. mg_fclose(&fi.access);
  13194. }
  13195. return;
  13196. }
  13197. }
  13198. /* Store in file */
  13199. if (fi.access.fp) {
  13200. int ok = 1;
  13201. flockfile(fi.access.fp);
  13202. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  13203. ok = 0;
  13204. }
  13205. if (fflush(fi.access.fp) != 0) {
  13206. ok = 0;
  13207. }
  13208. funlockfile(fi.access.fp);
  13209. if (mg_fclose(&fi.access) != 0) {
  13210. ok = 0;
  13211. }
  13212. if (!ok) {
  13213. mg_cry_internal(conn,
  13214. "Error writing log file %s",
  13215. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  13216. }
  13217. }
  13218. }
  13219. #else
  13220. #error "Either enable filesystems or provide a custom log_access implementation"
  13221. #endif /* Externally provided function */
  13222. /* Verify given socket address against the ACL.
  13223. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  13224. */
  13225. static int
  13226. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  13227. {
  13228. int allowed, flag, matched;
  13229. struct vec vec;
  13230. if (phys_ctx) {
  13231. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  13232. /* If any ACL is set, deny by default */
  13233. allowed = (list == NULL) ? '+' : '-';
  13234. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13235. flag = vec.ptr[0];
  13236. matched = -1;
  13237. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  13238. vec.ptr++;
  13239. vec.len--;
  13240. matched = parse_match_net(&vec, sa, 1);
  13241. }
  13242. if (matched < 0) {
  13243. mg_cry_ctx_internal(phys_ctx,
  13244. "%s: subnet must be [+|-]IP-addr[/x]",
  13245. __func__);
  13246. return -1;
  13247. }
  13248. if (matched) {
  13249. allowed = flag;
  13250. }
  13251. }
  13252. return allowed == '+';
  13253. }
  13254. return -1;
  13255. }
  13256. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  13257. static int
  13258. set_uid_option(struct mg_context *phys_ctx)
  13259. {
  13260. int success = 0;
  13261. if (phys_ctx) {
  13262. /* We are currently running as curr_uid. */
  13263. const uid_t curr_uid = getuid();
  13264. /* If set, we want to run as run_as_user. */
  13265. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  13266. const struct passwd *to_pw = NULL;
  13267. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  13268. /* run_as_user does not exist on the system. We can't proceed
  13269. * further. */
  13270. mg_cry_ctx_internal(phys_ctx,
  13271. "%s: unknown user [%s]",
  13272. __func__,
  13273. run_as_user);
  13274. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  13275. /* There was either no request to change user, or we're already
  13276. * running as run_as_user. Nothing else to do.
  13277. */
  13278. success = 1;
  13279. } else {
  13280. /* Valid change request. */
  13281. if (setgid(to_pw->pw_gid) == -1) {
  13282. mg_cry_ctx_internal(phys_ctx,
  13283. "%s: setgid(%s): %s",
  13284. __func__,
  13285. run_as_user,
  13286. strerror(errno));
  13287. } else if (setgroups(0, NULL) == -1) {
  13288. mg_cry_ctx_internal(phys_ctx,
  13289. "%s: setgroups(): %s",
  13290. __func__,
  13291. strerror(errno));
  13292. } else if (setuid(to_pw->pw_uid) == -1) {
  13293. mg_cry_ctx_internal(phys_ctx,
  13294. "%s: setuid(%s): %s",
  13295. __func__,
  13296. run_as_user,
  13297. strerror(errno));
  13298. } else {
  13299. success = 1;
  13300. }
  13301. }
  13302. }
  13303. return success;
  13304. }
  13305. #endif /* !_WIN32 */
  13306. static void
  13307. tls_dtor(void *key)
  13308. {
  13309. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  13310. /* key == pthread_getspecific(sTlsKey); */
  13311. if (tls) {
  13312. if (tls->is_master == 2) {
  13313. tls->is_master = -3; /* Mark memory as dead */
  13314. mg_free(tls);
  13315. }
  13316. }
  13317. pthread_setspecific(sTlsKey, NULL);
  13318. }
  13319. #if defined(USE_MBEDTLS)
  13320. /* Check if SSL is required.
  13321. * If so, set up ctx->ssl_ctx pointer. */
  13322. static int
  13323. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13324. {
  13325. if (!phys_ctx) {
  13326. return 0;
  13327. }
  13328. if (!dom_ctx) {
  13329. dom_ctx = &(phys_ctx->dd);
  13330. }
  13331. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13332. /* No SSL port is set. No need to setup SSL. */
  13333. return 1;
  13334. }
  13335. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  13336. if (dom_ctx->ssl_ctx == NULL) {
  13337. fprintf(stderr, "ssl_ctx malloc failed\n");
  13338. return 0;
  13339. }
  13340. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  13341. == 0
  13342. ? 1
  13343. : 0;
  13344. }
  13345. #elif !defined(NO_SSL)
  13346. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13347. struct mg_domain_context *dom_ctx,
  13348. const char *pem,
  13349. const char *chain);
  13350. static const char *ssl_error(void);
  13351. static int
  13352. refresh_trust(struct mg_connection *conn)
  13353. {
  13354. struct stat cert_buf;
  13355. int64_t t = 0;
  13356. const char *pem;
  13357. const char *chain;
  13358. int should_verify_peer;
  13359. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13360. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13361. * refresh_trust still can not work. */
  13362. return 0;
  13363. }
  13364. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13365. if (chain == NULL) {
  13366. /* pem is not NULL here */
  13367. chain = pem;
  13368. }
  13369. if (*chain == 0) {
  13370. chain = NULL;
  13371. }
  13372. if (stat(pem, &cert_buf) != -1) {
  13373. t = (int64_t)cert_buf.st_mtime;
  13374. }
  13375. mg_lock_context(conn->phys_ctx);
  13376. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  13377. conn->dom_ctx->ssl_cert_last_mtime = t;
  13378. should_verify_peer = 0;
  13379. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13380. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13381. == 0) {
  13382. should_verify_peer = 1;
  13383. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13384. "optional")
  13385. == 0) {
  13386. should_verify_peer = 1;
  13387. }
  13388. }
  13389. if (should_verify_peer) {
  13390. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13391. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13392. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13393. ca_file,
  13394. ca_path)
  13395. != 1) {
  13396. mg_unlock_context(conn->phys_ctx);
  13397. mg_cry_ctx_internal(
  13398. conn->phys_ctx,
  13399. "SSL_CTX_load_verify_locations error: %s "
  13400. "ssl_verify_peer requires setting "
  13401. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13402. "present in "
  13403. "the .conf file?",
  13404. ssl_error());
  13405. return 0;
  13406. }
  13407. }
  13408. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  13409. mg_unlock_context(conn->phys_ctx);
  13410. return 0;
  13411. }
  13412. }
  13413. mg_unlock_context(conn->phys_ctx);
  13414. return 1;
  13415. }
  13416. #if defined(OPENSSL_API_1_1)
  13417. #else
  13418. static pthread_mutex_t *ssl_mutexes;
  13419. #endif /* OPENSSL_API_1_1 */
  13420. static int
  13421. sslize(struct mg_connection *conn,
  13422. int (*func)(SSL *),
  13423. const struct mg_client_options *client_options)
  13424. {
  13425. int ret, err;
  13426. int short_trust;
  13427. unsigned timeout = 1024;
  13428. unsigned i;
  13429. if (!conn) {
  13430. return 0;
  13431. }
  13432. short_trust =
  13433. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13434. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13435. if (short_trust) {
  13436. int trust_ret = refresh_trust(conn);
  13437. if (!trust_ret) {
  13438. return trust_ret;
  13439. }
  13440. }
  13441. mg_lock_context(conn->phys_ctx);
  13442. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  13443. mg_unlock_context(conn->phys_ctx);
  13444. if (conn->ssl == NULL) {
  13445. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13446. OPENSSL_REMOVE_THREAD_STATE();
  13447. return 0;
  13448. }
  13449. SSL_set_app_data(conn->ssl, (char *)conn);
  13450. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13451. if (ret != 1) {
  13452. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13453. SSL_free(conn->ssl);
  13454. conn->ssl = NULL;
  13455. OPENSSL_REMOVE_THREAD_STATE();
  13456. return 0;
  13457. }
  13458. if (client_options) {
  13459. if (client_options->host_name) {
  13460. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13461. }
  13462. }
  13463. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13464. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13465. /* NOTE: The loop below acts as a back-off, so we can end
  13466. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13467. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13468. if (to >= 0) {
  13469. timeout = (unsigned)to;
  13470. }
  13471. }
  13472. /* SSL functions may fail and require to be called again:
  13473. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13474. * Here "func" could be SSL_connect or SSL_accept. */
  13475. for (i = 0; i <= timeout; i += 50) {
  13476. ERR_clear_error();
  13477. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  13478. ret = func(conn->ssl);
  13479. if (ret != 1) {
  13480. err = SSL_get_error(conn->ssl, ret);
  13481. if ((err == SSL_ERROR_WANT_CONNECT)
  13482. || (err == SSL_ERROR_WANT_ACCEPT)
  13483. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13484. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13485. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  13486. /* Don't wait if the server is going to be stopped. */
  13487. break;
  13488. }
  13489. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13490. /* Simply retry the function call. */
  13491. mg_sleep(50);
  13492. } else {
  13493. /* Need to retry the function call "later".
  13494. * See https://linux.die.net/man/3/ssl_get_error
  13495. * This is typical for non-blocking sockets. */
  13496. struct mg_pollfd pfd;
  13497. int pollres;
  13498. pfd.fd = conn->client.sock;
  13499. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13500. || (err == SSL_ERROR_WANT_WRITE))
  13501. ? POLLOUT
  13502. : POLLIN;
  13503. pollres =
  13504. mg_poll(&pfd, 1, 50, &(conn->phys_ctx->stop_flag));
  13505. if (pollres < 0) {
  13506. /* Break if error occured (-1)
  13507. * or server shutdown (-2) */
  13508. break;
  13509. }
  13510. }
  13511. } else if (err == SSL_ERROR_SYSCALL) {
  13512. /* This is an IO error. Look at errno. */
  13513. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  13514. break;
  13515. } else {
  13516. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13517. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13518. break;
  13519. }
  13520. } else {
  13521. /* success */
  13522. break;
  13523. }
  13524. }
  13525. ERR_clear_error();
  13526. if (ret != 1) {
  13527. SSL_free(conn->ssl);
  13528. conn->ssl = NULL;
  13529. OPENSSL_REMOVE_THREAD_STATE();
  13530. return 0;
  13531. }
  13532. return 1;
  13533. }
  13534. /* Return OpenSSL error message (from CRYPTO lib) */
  13535. static const char *
  13536. ssl_error(void)
  13537. {
  13538. unsigned long err;
  13539. err = ERR_get_error();
  13540. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13541. }
  13542. static int
  13543. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13544. {
  13545. int i;
  13546. const char hexdigit[] = "0123456789abcdef";
  13547. if ((memlen <= 0) || (buflen <= 0)) {
  13548. return 0;
  13549. }
  13550. if (buflen < (3 * memlen)) {
  13551. return 0;
  13552. }
  13553. for (i = 0; i < memlen; i++) {
  13554. if (i > 0) {
  13555. buf[3 * i - 1] = ' ';
  13556. }
  13557. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13558. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13559. }
  13560. buf[3 * memlen - 1] = 0;
  13561. return 1;
  13562. }
  13563. static int
  13564. ssl_get_client_cert_info(const struct mg_connection *conn,
  13565. struct mg_client_cert *client_cert)
  13566. {
  13567. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13568. if (cert) {
  13569. char str_buf[1024];
  13570. unsigned char buf[256];
  13571. char *str_serial = NULL;
  13572. unsigned int ulen;
  13573. int ilen;
  13574. unsigned char *tmp_buf;
  13575. unsigned char *tmp_p;
  13576. /* Handle to algorithm used for fingerprint */
  13577. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13578. /* Get Subject and issuer */
  13579. X509_NAME *subj = X509_get_subject_name(cert);
  13580. X509_NAME *iss = X509_get_issuer_name(cert);
  13581. /* Get serial number */
  13582. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13583. /* Translate serial number to a hex string */
  13584. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13585. if (serial_bn) {
  13586. str_serial = BN_bn2hex(serial_bn);
  13587. BN_free(serial_bn);
  13588. }
  13589. client_cert->serial =
  13590. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  13591. /* Translate subject and issuer to a string */
  13592. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  13593. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13594. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  13595. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13596. /* Calculate SHA1 fingerprint and store as a hex string */
  13597. ulen = 0;
  13598. /* ASN1_digest is deprecated. Do the calculation manually,
  13599. * using EVP_Digest. */
  13600. ilen = i2d_X509(cert, NULL);
  13601. tmp_buf = (ilen > 0)
  13602. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13603. conn->phys_ctx)
  13604. : NULL;
  13605. if (tmp_buf) {
  13606. tmp_p = tmp_buf;
  13607. (void)i2d_X509(cert, &tmp_p);
  13608. if (!EVP_Digest(
  13609. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13610. ulen = 0;
  13611. }
  13612. mg_free(tmp_buf);
  13613. }
  13614. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  13615. *str_buf = 0;
  13616. }
  13617. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  13618. client_cert->peer_cert = (void *)cert;
  13619. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13620. * see https://linux.die.net/man/3/bn_bn2hex */
  13621. OPENSSL_free(str_serial);
  13622. return 1;
  13623. }
  13624. return 0;
  13625. }
  13626. #if defined(OPENSSL_API_1_1)
  13627. #else
  13628. static void
  13629. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13630. {
  13631. (void)line;
  13632. (void)file;
  13633. if (mode & 1) {
  13634. /* 1 is CRYPTO_LOCK */
  13635. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13636. } else {
  13637. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13638. }
  13639. }
  13640. #endif /* OPENSSL_API_1_1 */
  13641. #if !defined(NO_SSL_DL)
  13642. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  13643. static void *
  13644. load_tls_dll(char *ebuf,
  13645. size_t ebuf_len,
  13646. const char *dll_name,
  13647. struct ssl_func *sw,
  13648. int *feature_missing)
  13649. {
  13650. union {
  13651. void *p;
  13652. void (*fp)(void);
  13653. } u;
  13654. void *dll_handle;
  13655. struct ssl_func *fp;
  13656. int ok;
  13657. int truncated = 0;
  13658. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13659. mg_snprintf(NULL,
  13660. NULL, /* No truncation check for ebuf */
  13661. ebuf,
  13662. ebuf_len,
  13663. "%s: cannot load %s",
  13664. __func__,
  13665. dll_name);
  13666. return NULL;
  13667. }
  13668. ok = 1;
  13669. for (fp = sw; fp->name != NULL; fp++) {
  13670. #if defined(_WIN32)
  13671. /* GetProcAddress() returns pointer to function */
  13672. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13673. #else
  13674. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13675. * pointers to function pointers. We need to use a union to make a
  13676. * cast. */
  13677. u.p = dlsym(dll_handle, fp->name);
  13678. #endif /* _WIN32 */
  13679. /* Set pointer (might be NULL) */
  13680. fp->ptr = u.fp;
  13681. if (u.fp == NULL) {
  13682. DEBUG_TRACE("Missing function: %s\n", fp->name);
  13683. if (feature_missing) {
  13684. feature_missing[fp->required]++;
  13685. }
  13686. if (fp->required == TLS_Mandatory) {
  13687. /* Mandatory function is missing */
  13688. if (ok) {
  13689. /* This is the first missing function.
  13690. * Create a new error message. */
  13691. mg_snprintf(NULL,
  13692. &truncated,
  13693. ebuf,
  13694. ebuf_len,
  13695. "%s: %s: cannot find %s",
  13696. __func__,
  13697. dll_name,
  13698. fp->name);
  13699. ok = 0;
  13700. } else {
  13701. /* This is yet anothermissing function.
  13702. * Append existing error message. */
  13703. size_t cur_len = strlen(ebuf);
  13704. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  13705. mg_snprintf(NULL,
  13706. &truncated,
  13707. ebuf + cur_len,
  13708. ebuf_len - cur_len - 3,
  13709. ", %s",
  13710. fp->name);
  13711. if (truncated) {
  13712. /* If truncated, add "..." */
  13713. strcat(ebuf, "...");
  13714. }
  13715. }
  13716. }
  13717. }
  13718. }
  13719. }
  13720. if (!ok) {
  13721. (void)dlclose(dll_handle);
  13722. return NULL;
  13723. }
  13724. return dll_handle;
  13725. }
  13726. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13727. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13728. #endif /* NO_SSL_DL */
  13729. #if defined(SSL_ALREADY_INITIALIZED)
  13730. static volatile ptrdiff_t cryptolib_users =
  13731. 1; /* Reference counter for crypto library. */
  13732. #else
  13733. static volatile ptrdiff_t cryptolib_users =
  13734. 0; /* Reference counter for crypto library. */
  13735. #endif
  13736. static int
  13737. initialize_openssl(char *ebuf, size_t ebuf_len)
  13738. {
  13739. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13740. int i, num_locks;
  13741. size_t size;
  13742. #endif
  13743. if (ebuf_len > 0) {
  13744. ebuf[0] = 0;
  13745. }
  13746. #if !defined(NO_SSL_DL)
  13747. if (!cryptolib_dll_handle) {
  13748. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  13749. cryptolib_dll_handle = load_tls_dll(
  13750. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  13751. if (!cryptolib_dll_handle) {
  13752. mg_snprintf(NULL,
  13753. NULL, /* No truncation check for ebuf */
  13754. ebuf,
  13755. ebuf_len,
  13756. "%s: error loading library %s",
  13757. __func__,
  13758. CRYPTO_LIB);
  13759. DEBUG_TRACE("%s", ebuf);
  13760. return 0;
  13761. }
  13762. }
  13763. #endif /* NO_SSL_DL */
  13764. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13765. return 1;
  13766. }
  13767. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  13768. /* Initialize locking callbacks, needed for thread safety.
  13769. * http://www.openssl.org/support/faq.html#PROG1
  13770. */
  13771. num_locks = CRYPTO_num_locks();
  13772. if (num_locks < 0) {
  13773. num_locks = 0;
  13774. }
  13775. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13776. /* allocate mutex array, if required */
  13777. if (num_locks == 0) {
  13778. /* No mutex array required */
  13779. ssl_mutexes = NULL;
  13780. } else {
  13781. /* Mutex array required - allocate it */
  13782. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13783. /* Check OOM */
  13784. if (ssl_mutexes == NULL) {
  13785. mg_snprintf(NULL,
  13786. NULL, /* No truncation check for ebuf */
  13787. ebuf,
  13788. ebuf_len,
  13789. "%s: cannot allocate mutexes: %s",
  13790. __func__,
  13791. ssl_error());
  13792. DEBUG_TRACE("%s", ebuf);
  13793. return 0;
  13794. }
  13795. /* initialize mutex array */
  13796. for (i = 0; i < num_locks; i++) {
  13797. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13798. mg_snprintf(NULL,
  13799. NULL, /* No truncation check for ebuf */
  13800. ebuf,
  13801. ebuf_len,
  13802. "%s: error initializing mutex %i of %i",
  13803. __func__,
  13804. i,
  13805. num_locks);
  13806. DEBUG_TRACE("%s", ebuf);
  13807. mg_free(ssl_mutexes);
  13808. return 0;
  13809. }
  13810. }
  13811. }
  13812. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13813. CRYPTO_set_id_callback(&mg_current_thread_id);
  13814. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  13815. #if !defined(NO_SSL_DL)
  13816. if (!ssllib_dll_handle) {
  13817. ssllib_dll_handle =
  13818. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  13819. if (!ssllib_dll_handle) {
  13820. #if !defined(OPENSSL_API_1_1)
  13821. mg_free(ssl_mutexes);
  13822. #endif
  13823. DEBUG_TRACE("%s", ebuf);
  13824. return 0;
  13825. }
  13826. }
  13827. #endif /* NO_SSL_DL */
  13828. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  13829. /* Initialize SSL library */
  13830. OPENSSL_init_ssl(0, NULL);
  13831. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13832. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13833. NULL);
  13834. #else
  13835. /* Initialize SSL library */
  13836. SSL_library_init();
  13837. SSL_load_error_strings();
  13838. #endif
  13839. return 1;
  13840. }
  13841. static int
  13842. ssl_use_pem_file(struct mg_context *phys_ctx,
  13843. struct mg_domain_context *dom_ctx,
  13844. const char *pem,
  13845. const char *chain)
  13846. {
  13847. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13848. mg_cry_ctx_internal(phys_ctx,
  13849. "%s: cannot open certificate file %s: %s",
  13850. __func__,
  13851. pem,
  13852. ssl_error());
  13853. return 0;
  13854. }
  13855. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13856. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13857. mg_cry_ctx_internal(phys_ctx,
  13858. "%s: cannot open private key file %s: %s",
  13859. __func__,
  13860. pem,
  13861. ssl_error());
  13862. return 0;
  13863. }
  13864. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13865. mg_cry_ctx_internal(phys_ctx,
  13866. "%s: certificate and private key do not match: %s",
  13867. __func__,
  13868. pem);
  13869. return 0;
  13870. }
  13871. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13872. * chain files that contain private keys and certificates in
  13873. * SSL_CTX_use_certificate_chain_file.
  13874. * The CivetWeb-Server used pem-Files that contained both information.
  13875. * In order to make wolfSSL work, it is split in two files.
  13876. * One file that contains key and certificate used by the server and
  13877. * an optional chain file for the ssl stack.
  13878. */
  13879. if (chain) {
  13880. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13881. mg_cry_ctx_internal(phys_ctx,
  13882. "%s: cannot use certificate chain file %s: %s",
  13883. __func__,
  13884. chain,
  13885. ssl_error());
  13886. return 0;
  13887. }
  13888. }
  13889. return 1;
  13890. }
  13891. #if defined(OPENSSL_API_1_1)
  13892. static unsigned long
  13893. ssl_get_protocol(int version_id)
  13894. {
  13895. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13896. if (version_id > 0)
  13897. ret |= SSL_OP_NO_SSLv2;
  13898. if (version_id > 1)
  13899. ret |= SSL_OP_NO_SSLv3;
  13900. if (version_id > 2)
  13901. ret |= SSL_OP_NO_TLSv1;
  13902. if (version_id > 3)
  13903. ret |= SSL_OP_NO_TLSv1_1;
  13904. if (version_id > 4)
  13905. ret |= SSL_OP_NO_TLSv1_2;
  13906. #if defined(SSL_OP_NO_TLSv1_3)
  13907. if (version_id > 5)
  13908. ret |= SSL_OP_NO_TLSv1_3;
  13909. #endif
  13910. return ret;
  13911. }
  13912. #else
  13913. static long
  13914. ssl_get_protocol(int version_id)
  13915. {
  13916. unsigned long ret = (unsigned long)SSL_OP_ALL;
  13917. if (version_id > 0)
  13918. ret |= SSL_OP_NO_SSLv2;
  13919. if (version_id > 1)
  13920. ret |= SSL_OP_NO_SSLv3;
  13921. if (version_id > 2)
  13922. ret |= SSL_OP_NO_TLSv1;
  13923. if (version_id > 3)
  13924. ret |= SSL_OP_NO_TLSv1_1;
  13925. if (version_id > 4)
  13926. ret |= SSL_OP_NO_TLSv1_2;
  13927. #if defined(SSL_OP_NO_TLSv1_3)
  13928. if (version_id > 5)
  13929. ret |= SSL_OP_NO_TLSv1_3;
  13930. #endif
  13931. return (long)ret;
  13932. }
  13933. #endif /* OPENSSL_API_1_1 */
  13934. /* SSL callback documentation:
  13935. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13936. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13937. * https://linux.die.net/man/3/ssl_set_info_callback */
  13938. /* Note: There is no "const" for the first argument in the documentation
  13939. * examples, however some (maybe most, but not all) headers of OpenSSL
  13940. * versions / OpenSSL compatibility layers have it. Having a different
  13941. * definition will cause a warning in C and an error in C++. Use "const SSL
  13942. * *", while automatical conversion from "SSL *" works for all compilers,
  13943. * but not other way around */
  13944. static void
  13945. ssl_info_callback(const SSL *ssl, int what, int ret)
  13946. {
  13947. (void)ret;
  13948. if (what & SSL_CB_HANDSHAKE_START) {
  13949. SSL_get_app_data(ssl);
  13950. }
  13951. if (what & SSL_CB_HANDSHAKE_DONE) {
  13952. /* TODO: check for openSSL 1.1 */
  13953. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13954. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13955. }
  13956. }
  13957. static int
  13958. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13959. {
  13960. #if defined(GCC_DIAGNOSTIC)
  13961. #pragma GCC diagnostic push
  13962. #pragma GCC diagnostic ignored "-Wcast-align"
  13963. #endif /* defined(GCC_DIAGNOSTIC) */
  13964. /* We used an aligned pointer in SSL_set_app_data */
  13965. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13966. #if defined(GCC_DIAGNOSTIC)
  13967. #pragma GCC diagnostic pop
  13968. #endif /* defined(GCC_DIAGNOSTIC) */
  13969. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13970. (void)ad;
  13971. (void)arg;
  13972. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13973. DEBUG_ASSERT(0);
  13974. return SSL_TLSEXT_ERR_NOACK;
  13975. }
  13976. conn->dom_ctx = &(conn->phys_ctx->dd);
  13977. /* Old clients (Win XP) will not support SNI. Then, there
  13978. * is no server name available in the request - we can
  13979. * only work with the default certificate.
  13980. * Multiple HTTPS hosts on one IP+port are only possible
  13981. * with a certificate containing all alternative names.
  13982. */
  13983. if ((servername == NULL) || (*servername == 0)) {
  13984. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13985. mg_lock_context(conn->phys_ctx);
  13986. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13987. mg_unlock_context(conn->phys_ctx);
  13988. return SSL_TLSEXT_ERR_NOACK;
  13989. }
  13990. DEBUG_TRACE("TLS connection to host %s", servername);
  13991. while (conn->dom_ctx) {
  13992. if (!mg_strcasecmp(servername,
  13993. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  13994. /* Found matching domain */
  13995. DEBUG_TRACE("TLS domain %s found",
  13996. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  13997. break;
  13998. }
  13999. mg_lock_context(conn->phys_ctx);
  14000. conn->dom_ctx = conn->dom_ctx->next;
  14001. mg_unlock_context(conn->phys_ctx);
  14002. }
  14003. if (conn->dom_ctx == NULL) {
  14004. /* Default domain */
  14005. DEBUG_TRACE("TLS default domain %s used",
  14006. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  14007. conn->dom_ctx = &(conn->phys_ctx->dd);
  14008. }
  14009. mg_lock_context(conn->phys_ctx);
  14010. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  14011. mg_unlock_context(conn->phys_ctx);
  14012. return SSL_TLSEXT_ERR_OK;
  14013. }
  14014. #if defined(USE_ALPN)
  14015. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  14016. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  14017. alpn_proto_list + 3 + 8,
  14018. NULL};
  14019. #if defined(USE_HTTP2)
  14020. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  14021. alpn_proto_list + 3,
  14022. alpn_proto_list + 3 + 8,
  14023. NULL};
  14024. #endif
  14025. static int
  14026. alpn_select_cb(SSL *ssl,
  14027. const unsigned char **out,
  14028. unsigned char *outlen,
  14029. const unsigned char *in,
  14030. unsigned int inlen,
  14031. void *arg)
  14032. {
  14033. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14034. unsigned int i, j, enable_http2 = 0;
  14035. const char **alpn_proto_order = alpn_proto_order_http1;
  14036. struct mg_workerTLS *tls =
  14037. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  14038. (void)ssl;
  14039. if (tls == NULL) {
  14040. /* Need to store protocol in Thread Local Storage */
  14041. /* If there is no Thread Local Storage, don't use ALPN */
  14042. return SSL_TLSEXT_ERR_NOACK;
  14043. }
  14044. #if defined(USE_HTTP2)
  14045. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  14046. if (enable_http2) {
  14047. alpn_proto_order = alpn_proto_order_http2;
  14048. }
  14049. #endif
  14050. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  14051. /* check all accepted protocols in this order */
  14052. const char *alpn_proto = alpn_proto_order[j];
  14053. /* search input for matching protocol */
  14054. for (i = 0; i < inlen; i++) {
  14055. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  14056. *out = in + i + 1;
  14057. *outlen = in[i];
  14058. tls->alpn_proto = alpn_proto;
  14059. return SSL_TLSEXT_ERR_OK;
  14060. }
  14061. }
  14062. }
  14063. /* Nothing found */
  14064. return SSL_TLSEXT_ERR_NOACK;
  14065. }
  14066. static int
  14067. next_protos_advertised_cb(SSL *ssl,
  14068. const unsigned char **data,
  14069. unsigned int *len,
  14070. void *arg)
  14071. {
  14072. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  14073. *data = (const unsigned char *)alpn_proto_list;
  14074. *len = (unsigned int)strlen((const char *)data);
  14075. (void)ssl;
  14076. (void)dom_ctx;
  14077. return SSL_TLSEXT_ERR_OK;
  14078. }
  14079. static int
  14080. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14081. {
  14082. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  14083. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  14084. (const unsigned char *)alpn_proto_list,
  14085. alpn_len);
  14086. if (ret != 0) {
  14087. mg_cry_ctx_internal(phys_ctx,
  14088. "SSL_CTX_set_alpn_protos error: %s",
  14089. ssl_error());
  14090. }
  14091. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  14092. alpn_select_cb,
  14093. (void *)dom_ctx);
  14094. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  14095. next_protos_advertised_cb,
  14096. (void *)dom_ctx);
  14097. return ret;
  14098. }
  14099. #endif
  14100. /* Setup SSL CTX as required by CivetWeb */
  14101. static int
  14102. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  14103. struct mg_domain_context *dom_ctx,
  14104. const char *pem,
  14105. const char *chain)
  14106. {
  14107. int callback_ret;
  14108. int should_verify_peer;
  14109. int peer_certificate_optional;
  14110. const char *ca_path;
  14111. const char *ca_file;
  14112. int use_default_verify_paths;
  14113. int verify_depth;
  14114. struct timespec now_mt;
  14115. md5_byte_t ssl_context_id[16];
  14116. md5_state_t md5state;
  14117. int protocol_ver;
  14118. int ssl_cache_timeout;
  14119. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14120. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  14121. mg_cry_ctx_internal(phys_ctx,
  14122. "SSL_CTX_new (server) error: %s",
  14123. ssl_error());
  14124. return 0;
  14125. }
  14126. #else
  14127. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  14128. mg_cry_ctx_internal(phys_ctx,
  14129. "SSL_CTX_new (server) error: %s",
  14130. ssl_error());
  14131. return 0;
  14132. }
  14133. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14134. #if defined(SSL_OP_NO_TLSv1_3)
  14135. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14136. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14137. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  14138. | SSL_OP_NO_TLSv1_3);
  14139. #else
  14140. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  14141. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  14142. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  14143. #endif
  14144. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  14145. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  14146. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  14147. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  14148. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  14149. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14150. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  14151. #if defined(SSL_OP_NO_RENEGOTIATION)
  14152. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  14153. #endif
  14154. #if !defined(NO_SSL_DL)
  14155. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  14156. #endif /* NO_SSL_DL */
  14157. /* In SSL documentation examples callback defined without const
  14158. * specifier 'void (*)(SSL *, int, int)' See:
  14159. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  14160. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  14161. * But in the source code const SSL is used:
  14162. * 'void (*)(const SSL *, int, int)' See:
  14163. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  14164. * Problem about wrong documentation described, but not resolved:
  14165. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  14166. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  14167. * But when compiled with modern C++ compiler, correct const should be
  14168. * provided
  14169. */
  14170. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  14171. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  14172. ssl_servername_callback);
  14173. /* If a callback has been specified, call it. */
  14174. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  14175. ? 0
  14176. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  14177. phys_ctx->user_data));
  14178. /* If callback returns 0, civetweb sets up the SSL certificate.
  14179. * If it returns 1, civetweb assumes the calback already did this.
  14180. * If it returns -1, initializing ssl fails. */
  14181. if (callback_ret < 0) {
  14182. mg_cry_ctx_internal(phys_ctx,
  14183. "SSL callback returned error: %i",
  14184. callback_ret);
  14185. return 0;
  14186. }
  14187. if (callback_ret > 0) {
  14188. /* Callback did everything. */
  14189. return 1;
  14190. }
  14191. /* If a domain callback has been specified, call it. */
  14192. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  14193. ? 0
  14194. : (phys_ctx->callbacks.init_ssl_domain(
  14195. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14196. dom_ctx->ssl_ctx,
  14197. phys_ctx->user_data));
  14198. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  14199. * If it returns 1, civetweb assumes the calback already did this.
  14200. * If it returns -1, initializing ssl fails. */
  14201. if (callback_ret < 0) {
  14202. mg_cry_ctx_internal(phys_ctx,
  14203. "Domain SSL callback returned error: %i",
  14204. callback_ret);
  14205. return 0;
  14206. }
  14207. if (callback_ret > 0) {
  14208. /* Domain callback did everything. */
  14209. return 1;
  14210. }
  14211. /* Use some combination of start time, domain and port as a SSL
  14212. * context ID. This should be unique on the current machine. */
  14213. md5_init(&md5state);
  14214. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  14215. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  14216. md5_append(&md5state,
  14217. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  14218. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  14219. md5_append(&md5state,
  14220. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  14221. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  14222. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  14223. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  14224. md5_finish(&md5state, ssl_context_id);
  14225. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  14226. (unsigned char *)ssl_context_id,
  14227. sizeof(ssl_context_id));
  14228. if (pem != NULL) {
  14229. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  14230. return 0;
  14231. }
  14232. }
  14233. /* Should we support client certificates? */
  14234. /* Default is "no". */
  14235. should_verify_peer = 0;
  14236. peer_certificate_optional = 0;
  14237. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14238. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  14239. /* Yes, they are mandatory */
  14240. should_verify_peer = 1;
  14241. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  14242. "optional")
  14243. == 0) {
  14244. /* Yes, they are optional */
  14245. should_verify_peer = 1;
  14246. peer_certificate_optional = 1;
  14247. }
  14248. }
  14249. use_default_verify_paths =
  14250. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  14251. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  14252. == 0);
  14253. if (should_verify_peer) {
  14254. ca_path = dom_ctx->config[SSL_CA_PATH];
  14255. ca_file = dom_ctx->config[SSL_CA_FILE];
  14256. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  14257. != 1) {
  14258. mg_cry_ctx_internal(phys_ctx,
  14259. "SSL_CTX_load_verify_locations error: %s "
  14260. "ssl_verify_peer requires setting "
  14261. "either ssl_ca_path or ssl_ca_file. "
  14262. "Is any of them present in the "
  14263. ".conf file?",
  14264. ssl_error());
  14265. return 0;
  14266. }
  14267. if (peer_certificate_optional) {
  14268. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14269. } else {
  14270. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  14271. SSL_VERIFY_PEER
  14272. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  14273. NULL);
  14274. }
  14275. if (use_default_verify_paths
  14276. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  14277. mg_cry_ctx_internal(phys_ctx,
  14278. "SSL_CTX_set_default_verify_paths error: %s",
  14279. ssl_error());
  14280. return 0;
  14281. }
  14282. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  14283. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  14284. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  14285. }
  14286. }
  14287. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  14288. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  14289. dom_ctx->config[SSL_CIPHER_LIST])
  14290. != 1) {
  14291. mg_cry_ctx_internal(phys_ctx,
  14292. "SSL_CTX_set_cipher_list error: %s",
  14293. ssl_error());
  14294. }
  14295. }
  14296. /* SSL session caching */
  14297. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  14298. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  14299. : 0);
  14300. if (ssl_cache_timeout > 0) {
  14301. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  14302. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  14303. * default */
  14304. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  14305. }
  14306. #if defined(USE_ALPN)
  14307. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  14308. #if !defined(NO_SSL_DL)
  14309. if (!tls_feature_missing[TLS_ALPN])
  14310. #endif
  14311. {
  14312. init_alpn(phys_ctx, dom_ctx);
  14313. }
  14314. #endif
  14315. return 1;
  14316. }
  14317. /* Check if SSL is required.
  14318. * If so, dynamically load SSL library
  14319. * and set up ctx->ssl_ctx pointer. */
  14320. static int
  14321. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14322. {
  14323. void *ssl_ctx = 0;
  14324. int callback_ret;
  14325. const char *pem;
  14326. const char *chain;
  14327. char ebuf[128];
  14328. if (!phys_ctx) {
  14329. return 0;
  14330. }
  14331. if (!dom_ctx) {
  14332. dom_ctx = &(phys_ctx->dd);
  14333. }
  14334. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14335. /* No SSL port is set. No need to setup SSL. */
  14336. return 1;
  14337. }
  14338. /* Check for external SSL_CTX */
  14339. callback_ret =
  14340. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  14341. ? 0
  14342. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  14343. phys_ctx->user_data));
  14344. if (callback_ret < 0) {
  14345. /* Callback exists and returns <0: Initializing failed. */
  14346. mg_cry_ctx_internal(phys_ctx,
  14347. "external_ssl_ctx callback returned error: %i",
  14348. callback_ret);
  14349. return 0;
  14350. } else if (callback_ret > 0) {
  14351. /* Callback exists and returns >0: Initializing complete,
  14352. * civetweb should not modify the SSL context. */
  14353. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14354. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14355. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14356. return 0;
  14357. }
  14358. return 1;
  14359. }
  14360. /* If the callback does not exist or return 0, civetweb must initialize
  14361. * the SSL context. Handle "domain" callback next. */
  14362. /* Check for external domain SSL_CTX callback. */
  14363. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  14364. ? 0
  14365. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  14366. dom_ctx->config[AUTHENTICATION_DOMAIN],
  14367. &ssl_ctx,
  14368. phys_ctx->user_data));
  14369. if (callback_ret < 0) {
  14370. /* Callback < 0: Error. Abort init. */
  14371. mg_cry_ctx_internal(
  14372. phys_ctx,
  14373. "external_ssl_ctx_domain callback returned error: %i",
  14374. callback_ret);
  14375. return 0;
  14376. } else if (callback_ret > 0) {
  14377. /* Callback > 0: Consider init done. */
  14378. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  14379. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14380. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14381. return 0;
  14382. }
  14383. return 1;
  14384. }
  14385. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  14386. * 0, CivetWeb should continue initializing SSL */
  14387. /* If PEM file is not specified and the init_ssl callbacks
  14388. * are not specified, setup will fail. */
  14389. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  14390. && (phys_ctx->callbacks.init_ssl == NULL)
  14391. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  14392. /* No certificate and no init_ssl callbacks:
  14393. * Essential data to set up TLS is missing.
  14394. */
  14395. mg_cry_ctx_internal(phys_ctx,
  14396. "Initializing SSL failed: -%s is not set",
  14397. config_options[SSL_CERTIFICATE].name);
  14398. return 0;
  14399. }
  14400. /* If a certificate chain is configured, use it. */
  14401. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14402. if (chain == NULL) {
  14403. /* Default: certificate chain in PEM file */
  14404. chain = pem;
  14405. }
  14406. if ((chain != NULL) && (*chain == 0)) {
  14407. /* If the chain is an empty string, don't use it. */
  14408. chain = NULL;
  14409. }
  14410. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  14411. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  14412. return 0;
  14413. }
  14414. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  14415. }
  14416. static void
  14417. uninitialize_openssl(void)
  14418. {
  14419. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14420. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14421. /* Shutdown according to
  14422. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14423. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14424. */
  14425. CONF_modules_unload(1);
  14426. #else
  14427. int i;
  14428. if (mg_atomic_dec(&cryptolib_users) == 0) {
  14429. /* Shutdown according to
  14430. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  14431. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  14432. */
  14433. CRYPTO_set_locking_callback(NULL);
  14434. CRYPTO_set_id_callback(NULL);
  14435. ENGINE_cleanup();
  14436. CONF_modules_unload(1);
  14437. ERR_free_strings();
  14438. EVP_cleanup();
  14439. CRYPTO_cleanup_all_ex_data();
  14440. OPENSSL_REMOVE_THREAD_STATE();
  14441. for (i = 0; i < CRYPTO_num_locks(); i++) {
  14442. pthread_mutex_destroy(&ssl_mutexes[i]);
  14443. }
  14444. mg_free(ssl_mutexes);
  14445. ssl_mutexes = NULL;
  14446. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14447. }
  14448. }
  14449. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  14450. #if !defined(NO_FILESYSTEMS)
  14451. static int
  14452. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14453. {
  14454. if (phys_ctx) {
  14455. struct mg_file file = STRUCT_FILE_INITIALIZER;
  14456. const char *path;
  14457. struct mg_connection fc;
  14458. if (!dom_ctx) {
  14459. dom_ctx = &(phys_ctx->dd);
  14460. }
  14461. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  14462. if ((path != NULL)
  14463. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  14464. mg_cry_ctx_internal(phys_ctx,
  14465. "Cannot open %s: %s",
  14466. path,
  14467. strerror(ERRNO));
  14468. return 0;
  14469. }
  14470. return 1;
  14471. }
  14472. return 0;
  14473. }
  14474. #endif /* NO_FILESYSTEMS */
  14475. static int
  14476. set_acl_option(struct mg_context *phys_ctx)
  14477. {
  14478. union usa sa;
  14479. memset(&sa, 0, sizeof(sa));
  14480. #if defined(USE_IPV6)
  14481. sa.sin6.sin6_family = AF_INET6;
  14482. #else
  14483. sa.sin.sin_family = AF_INET;
  14484. #endif
  14485. return check_acl(phys_ctx, &sa) != -1;
  14486. }
  14487. static void
  14488. reset_per_request_attributes(struct mg_connection *conn)
  14489. {
  14490. if (!conn) {
  14491. return;
  14492. }
  14493. conn->num_bytes_sent = conn->consumed_content = 0;
  14494. conn->path_info = NULL;
  14495. conn->status_code = -1;
  14496. conn->content_len = -1;
  14497. conn->is_chunked = 0;
  14498. conn->must_close = 0;
  14499. conn->request_len = 0;
  14500. conn->request_state = 0;
  14501. conn->throttle = 0;
  14502. conn->accept_gzip = 0;
  14503. conn->response_info.content_length = conn->request_info.content_length = -1;
  14504. conn->response_info.http_version = conn->request_info.http_version = NULL;
  14505. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14506. conn->response_info.status_text = NULL;
  14507. conn->response_info.status_code = 0;
  14508. conn->request_info.remote_user = NULL;
  14509. conn->request_info.request_method = NULL;
  14510. conn->request_info.request_uri = NULL;
  14511. /* Free cleaned local URI (if any) */
  14512. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  14513. mg_free((void *)conn->request_info.local_uri);
  14514. conn->request_info.local_uri = NULL;
  14515. }
  14516. conn->request_info.local_uri = NULL;
  14517. #if defined(USE_SERVER_STATS)
  14518. conn->processing_time = 0;
  14519. #endif
  14520. #if defined(MG_LEGACY_INTERFACE)
  14521. /* Legacy before split into local_uri and request_uri */
  14522. conn->request_info.uri = NULL;
  14523. #endif
  14524. }
  14525. static int
  14526. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  14527. {
  14528. if ((so->lsa.sa.sa_family == AF_INET)
  14529. || (so->lsa.sa.sa_family == AF_INET6)) {
  14530. /* Only for TCP sockets */
  14531. if (setsockopt(so->sock,
  14532. IPPROTO_TCP,
  14533. TCP_NODELAY,
  14534. (SOCK_OPT_TYPE)&nodelay_on,
  14535. sizeof(nodelay_on))
  14536. != 0) {
  14537. /* Error */
  14538. return 1;
  14539. }
  14540. }
  14541. /* OK */
  14542. return 0;
  14543. }
  14544. #if !defined(__ZEPHYR__)
  14545. static void
  14546. close_socket_gracefully(struct mg_connection *conn)
  14547. {
  14548. #if defined(_WIN32)
  14549. char buf[MG_BUF_LEN];
  14550. int n;
  14551. #endif
  14552. struct linger linger;
  14553. int error_code = 0;
  14554. int linger_timeout = -2;
  14555. socklen_t opt_len = sizeof(error_code);
  14556. if (!conn) {
  14557. return;
  14558. }
  14559. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14560. * "Note that enabling a nonzero timeout on a nonblocking socket
  14561. * is not recommended.", so set it to blocking now */
  14562. set_blocking_mode(conn->client.sock);
  14563. /* Send FIN to the client */
  14564. shutdown(conn->client.sock, SHUTDOWN_WR);
  14565. #if defined(_WIN32)
  14566. /* Read and discard pending incoming data. If we do not do that and
  14567. * close
  14568. * the socket, the data in the send buffer may be discarded. This
  14569. * behaviour is seen on Windows, when client keeps sending data
  14570. * when server decides to close the connection; then when client
  14571. * does recv() it gets no data back. */
  14572. do {
  14573. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14574. } while (n > 0);
  14575. #endif
  14576. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14577. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14578. }
  14579. /* Set linger option according to configuration */
  14580. if (linger_timeout >= 0) {
  14581. /* Set linger option to avoid socket hanging out after close. This
  14582. * prevent ephemeral port exhaust problem under high QPS. */
  14583. linger.l_onoff = 1;
  14584. #if defined(_MSC_VER)
  14585. #pragma warning(push)
  14586. #pragma warning(disable : 4244)
  14587. #endif
  14588. #if defined(GCC_DIAGNOSTIC)
  14589. #pragma GCC diagnostic push
  14590. #pragma GCC diagnostic ignored "-Wconversion"
  14591. #endif
  14592. /* Data type of linger structure elements may differ,
  14593. * so we don't know what cast we need here.
  14594. * Disable type conversion warnings. */
  14595. linger.l_linger = (linger_timeout + 999) / 1000;
  14596. #if defined(GCC_DIAGNOSTIC)
  14597. #pragma GCC diagnostic pop
  14598. #endif
  14599. #if defined(_MSC_VER)
  14600. #pragma warning(pop)
  14601. #endif
  14602. } else {
  14603. linger.l_onoff = 0;
  14604. linger.l_linger = 0;
  14605. }
  14606. if (linger_timeout < -1) {
  14607. /* Default: don't configure any linger */
  14608. } else if (getsockopt(conn->client.sock,
  14609. SOL_SOCKET,
  14610. SO_ERROR,
  14611. #if defined(_WIN32) /* WinSock uses different data type here */
  14612. (char *)&error_code,
  14613. #else
  14614. &error_code,
  14615. #endif
  14616. &opt_len)
  14617. != 0) {
  14618. /* Cannot determine if socket is already closed. This should
  14619. * not occur and never did in a test. Log an error message
  14620. * and continue. */
  14621. mg_cry_internal(conn,
  14622. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14623. __func__,
  14624. strerror(ERRNO));
  14625. #if defined(_WIN32)
  14626. } else if (error_code == WSAECONNRESET) {
  14627. #else
  14628. } else if (error_code == ECONNRESET) {
  14629. #endif
  14630. /* Socket already closed by client/peer, close socket without linger
  14631. */
  14632. } else {
  14633. /* Set linger timeout */
  14634. if (setsockopt(conn->client.sock,
  14635. SOL_SOCKET,
  14636. SO_LINGER,
  14637. (char *)&linger,
  14638. sizeof(linger))
  14639. != 0) {
  14640. mg_cry_internal(
  14641. conn,
  14642. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14643. __func__,
  14644. linger.l_onoff,
  14645. linger.l_linger,
  14646. strerror(ERRNO));
  14647. }
  14648. }
  14649. /* Now we know that our FIN is ACK-ed, safe to close */
  14650. closesocket(conn->client.sock);
  14651. conn->client.sock = INVALID_SOCKET;
  14652. }
  14653. #endif
  14654. static void
  14655. close_connection(struct mg_connection *conn)
  14656. {
  14657. #if defined(USE_SERVER_STATS)
  14658. conn->conn_state = 6; /* to close */
  14659. #endif
  14660. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14661. if (conn->lua_websocket_state) {
  14662. lua_websocket_close(conn, conn->lua_websocket_state);
  14663. conn->lua_websocket_state = NULL;
  14664. }
  14665. #endif
  14666. mg_lock_connection(conn);
  14667. /* Set close flag, so keep-alive loops will stop */
  14668. conn->must_close = 1;
  14669. /* call the connection_close callback if assigned */
  14670. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14671. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14672. conn->phys_ctx->callbacks.connection_close(conn);
  14673. }
  14674. }
  14675. /* Reset user data, after close callback is called.
  14676. * Do not reuse it. If the user needs a destructor,
  14677. * it must be done in the connection_close callback. */
  14678. mg_set_user_connection_data(conn, NULL);
  14679. #if defined(USE_SERVER_STATS)
  14680. conn->conn_state = 7; /* closing */
  14681. #endif
  14682. #if defined(USE_MBEDTLS)
  14683. if (conn->ssl != NULL) {
  14684. mbed_ssl_close(conn->ssl);
  14685. conn->ssl = NULL;
  14686. }
  14687. #elif !defined(NO_SSL)
  14688. if (conn->ssl != NULL) {
  14689. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14690. */
  14691. SSL_shutdown(conn->ssl);
  14692. SSL_free(conn->ssl);
  14693. OPENSSL_REMOVE_THREAD_STATE();
  14694. conn->ssl = NULL;
  14695. }
  14696. #endif
  14697. if (conn->client.sock != INVALID_SOCKET) {
  14698. #if defined(__ZEPHYR__)
  14699. closesocket(conn->client.sock);
  14700. #else
  14701. close_socket_gracefully(conn);
  14702. #endif
  14703. conn->client.sock = INVALID_SOCKET;
  14704. }
  14705. /* call the connection_closed callback if assigned */
  14706. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  14707. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14708. conn->phys_ctx->callbacks.connection_closed(conn);
  14709. }
  14710. }
  14711. mg_unlock_connection(conn);
  14712. #if defined(USE_SERVER_STATS)
  14713. conn->conn_state = 8; /* closed */
  14714. #endif
  14715. }
  14716. void
  14717. mg_close_connection(struct mg_connection *conn)
  14718. {
  14719. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14720. return;
  14721. }
  14722. #if defined(USE_WEBSOCKET)
  14723. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14724. if (conn->in_websocket_handling) {
  14725. /* Set close flag, so the server thread can exit. */
  14726. conn->must_close = 1;
  14727. return;
  14728. }
  14729. }
  14730. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14731. unsigned int i;
  14732. /* client context: loops must end */
  14733. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  14734. conn->must_close = 1;
  14735. /* We need to get the client thread out of the select/recv call
  14736. * here. */
  14737. /* Since we use a sleep quantum of some seconds to check for recv
  14738. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14739. /* join worker thread */
  14740. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14741. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14742. }
  14743. }
  14744. #endif /* defined(USE_WEBSOCKET) */
  14745. close_connection(conn);
  14746. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14747. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14748. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14749. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14750. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14751. }
  14752. #endif
  14753. #if defined(USE_WEBSOCKET)
  14754. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14755. mg_free(conn->phys_ctx->worker_threadids);
  14756. (void)pthread_mutex_destroy(&conn->mutex);
  14757. mg_free(conn);
  14758. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14759. (void)pthread_mutex_destroy(&conn->mutex);
  14760. mg_free(conn);
  14761. }
  14762. #else
  14763. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14764. (void)pthread_mutex_destroy(&conn->mutex);
  14765. mg_free(conn);
  14766. }
  14767. #endif /* defined(USE_WEBSOCKET) */
  14768. }
  14769. static struct mg_connection *
  14770. mg_connect_client_impl(const struct mg_client_options *client_options,
  14771. int use_ssl,
  14772. char *ebuf,
  14773. size_t ebuf_len)
  14774. {
  14775. struct mg_connection *conn = NULL;
  14776. SOCKET sock;
  14777. union usa sa;
  14778. struct sockaddr *psa;
  14779. socklen_t len;
  14780. unsigned max_req_size =
  14781. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14782. /* Size of structures, aligned to 8 bytes */
  14783. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14784. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14785. conn =
  14786. (struct mg_connection *)mg_calloc(1,
  14787. conn_size + ctx_size + max_req_size);
  14788. if (conn == NULL) {
  14789. mg_snprintf(NULL,
  14790. NULL, /* No truncation check for ebuf */
  14791. ebuf,
  14792. ebuf_len,
  14793. "calloc(): %s",
  14794. strerror(ERRNO));
  14795. return NULL;
  14796. }
  14797. #if defined(GCC_DIAGNOSTIC)
  14798. #pragma GCC diagnostic push
  14799. #pragma GCC diagnostic ignored "-Wcast-align"
  14800. #endif /* defined(GCC_DIAGNOSTIC) */
  14801. /* conn_size is aligned to 8 bytes */
  14802. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14803. #if defined(GCC_DIAGNOSTIC)
  14804. #pragma GCC diagnostic pop
  14805. #endif /* defined(GCC_DIAGNOSTIC) */
  14806. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14807. conn->buf_size = (int)max_req_size;
  14808. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14809. conn->dom_ctx = &(conn->phys_ctx->dd);
  14810. if (!connect_socket(conn->phys_ctx,
  14811. client_options->host,
  14812. client_options->port,
  14813. use_ssl,
  14814. ebuf,
  14815. ebuf_len,
  14816. &sock,
  14817. &sa)) {
  14818. /* ebuf is set by connect_socket,
  14819. * free all memory and return NULL; */
  14820. mg_free(conn);
  14821. return NULL;
  14822. }
  14823. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14824. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  14825. if (use_ssl
  14826. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14827. == NULL) {
  14828. mg_snprintf(NULL,
  14829. NULL, /* No truncation check for ebuf */
  14830. ebuf,
  14831. ebuf_len,
  14832. "SSL_CTX_new error: %s",
  14833. ssl_error());
  14834. closesocket(sock);
  14835. mg_free(conn);
  14836. return NULL;
  14837. }
  14838. #else
  14839. if (use_ssl
  14840. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14841. == NULL) {
  14842. mg_snprintf(NULL,
  14843. NULL, /* No truncation check for ebuf */
  14844. ebuf,
  14845. ebuf_len,
  14846. "SSL_CTX_new error: %s",
  14847. ssl_error());
  14848. closesocket(sock);
  14849. mg_free(conn);
  14850. return NULL;
  14851. }
  14852. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14853. #endif /* NO_SSL */
  14854. #if defined(USE_IPV6)
  14855. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14856. : sizeof(conn->client.rsa.sin6);
  14857. psa = (sa.sa.sa_family == AF_INET)
  14858. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14859. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14860. #else
  14861. len = sizeof(conn->client.rsa.sin);
  14862. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14863. #endif
  14864. conn->client.sock = sock;
  14865. conn->client.lsa = sa;
  14866. if (getsockname(sock, psa, &len) != 0) {
  14867. mg_cry_internal(conn,
  14868. "%s: getsockname() failed: %s",
  14869. __func__,
  14870. strerror(ERRNO));
  14871. }
  14872. conn->client.is_ssl = use_ssl ? 1 : 0;
  14873. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14874. mg_snprintf(NULL,
  14875. NULL, /* No truncation check for ebuf */
  14876. ebuf,
  14877. ebuf_len,
  14878. "Can not create mutex");
  14879. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14880. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14881. #endif
  14882. closesocket(sock);
  14883. mg_free(conn);
  14884. return NULL;
  14885. }
  14886. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  14887. if (use_ssl) {
  14888. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14889. * SSL_CTX_set_verify call is needed to switch off server
  14890. * certificate checking, which is off by default in OpenSSL and
  14891. * on in yaSSL. */
  14892. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14893. * SSL_VERIFY_PEER, verify_ssl_server); */
  14894. if (client_options->client_cert) {
  14895. if (!ssl_use_pem_file(conn->phys_ctx,
  14896. conn->dom_ctx,
  14897. client_options->client_cert,
  14898. NULL)) {
  14899. mg_snprintf(NULL,
  14900. NULL, /* No truncation check for ebuf */
  14901. ebuf,
  14902. ebuf_len,
  14903. "Can not use SSL client certificate");
  14904. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14905. closesocket(sock);
  14906. mg_free(conn);
  14907. return NULL;
  14908. }
  14909. }
  14910. if (client_options->server_cert) {
  14911. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14912. client_options->server_cert,
  14913. NULL)
  14914. != 1) {
  14915. mg_cry_internal(conn,
  14916. "SSL_CTX_load_verify_locations error: %s ",
  14917. ssl_error());
  14918. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14919. closesocket(sock);
  14920. mg_free(conn);
  14921. return NULL;
  14922. }
  14923. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14924. } else {
  14925. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14926. }
  14927. if (!sslize(conn, SSL_connect, client_options)) {
  14928. mg_snprintf(NULL,
  14929. NULL, /* No truncation check for ebuf */
  14930. ebuf,
  14931. ebuf_len,
  14932. "SSL connection error");
  14933. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14934. closesocket(sock);
  14935. mg_free(conn);
  14936. return NULL;
  14937. }
  14938. }
  14939. #endif
  14940. return conn;
  14941. }
  14942. CIVETWEB_API struct mg_connection *
  14943. mg_connect_client_secure(const struct mg_client_options *client_options,
  14944. char *error_buffer,
  14945. size_t error_buffer_size)
  14946. {
  14947. return mg_connect_client_impl(client_options,
  14948. 1,
  14949. error_buffer,
  14950. error_buffer_size);
  14951. }
  14952. struct mg_connection *
  14953. mg_connect_client(const char *host,
  14954. int port,
  14955. int use_ssl,
  14956. char *error_buffer,
  14957. size_t error_buffer_size)
  14958. {
  14959. struct mg_client_options opts;
  14960. memset(&opts, 0, sizeof(opts));
  14961. opts.host = host;
  14962. opts.port = port;
  14963. return mg_connect_client_impl(&opts,
  14964. use_ssl,
  14965. error_buffer,
  14966. error_buffer_size);
  14967. }
  14968. #if defined(MG_EXPERIMENTAL_INTERFACES)
  14969. struct mg_connection *
  14970. mg_connect_client2(const char *host,
  14971. const char *protocol,
  14972. int port,
  14973. const char *path,
  14974. struct mg_init_data *init,
  14975. struct mg_error_data *error)
  14976. {
  14977. int is_ssl, is_ws;
  14978. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  14979. if (error != NULL) {
  14980. error->code = 0;
  14981. if (error->text_buffer_size > 0) {
  14982. *error->text = 0;
  14983. }
  14984. }
  14985. if ((host == NULL) || (protocol == NULL)) {
  14986. if ((error != NULL) && (error->text_buffer_size > 0)) {
  14987. mg_snprintf(NULL,
  14988. NULL, /* No truncation check for error buffers */
  14989. error->text,
  14990. error->text_buffer_size,
  14991. "%s",
  14992. "Invalid parameters");
  14993. }
  14994. return NULL;
  14995. }
  14996. /* check all known protocolls */
  14997. if (!mg_strcasecmp(protocol, "http")) {
  14998. is_ssl = 0;
  14999. is_ws = 0;
  15000. } else if (!mg_strcasecmp(protocol, "https")) {
  15001. is_ssl = 1;
  15002. is_ws = 0;
  15003. #if defined(USE_WEBSOCKET)
  15004. } else if (!mg_strcasecmp(protocol, "ws")) {
  15005. is_ssl = 0;
  15006. is_ws = 1;
  15007. } else if (!mg_strcasecmp(protocol, "wss")) {
  15008. is_ssl = 1;
  15009. is_ws = 1;
  15010. #endif
  15011. } else {
  15012. if ((error != NULL) && (error->text_buffer_size > 0)) {
  15013. mg_snprintf(NULL,
  15014. NULL, /* No truncation check for error buffers */
  15015. error->text,
  15016. error->text_buffer_size,
  15017. "Protocol %s not supported",
  15018. protocol);
  15019. }
  15020. return NULL;
  15021. }
  15022. /* TODO: The current implementation here just calls the old
  15023. * implementations, without using any new options. This is just a first
  15024. * step to test the new interfaces. */
  15025. #if defined(USE_WEBSOCKET)
  15026. if (is_ws) {
  15027. /* TODO: implement all options */
  15028. return mg_connect_websocket_client(
  15029. host,
  15030. port,
  15031. is_ssl,
  15032. ((error != NULL) ? error->text : NULL),
  15033. ((error != NULL) ? error->text_buffer_size : 0),
  15034. (path ? path : ""),
  15035. NULL /* TODO: origin */,
  15036. experimental_websocket_client_data_wrapper,
  15037. experimental_websocket_client_close_wrapper,
  15038. (void *)init->callbacks);
  15039. }
  15040. #endif
  15041. /* TODO: all additional options */
  15042. struct mg_client_options opts;
  15043. memset(&opts, 0, sizeof(opts));
  15044. opts.host = host;
  15045. opts.port = port;
  15046. return mg_connect_client_impl(&opts,
  15047. is_ssl,
  15048. ((error != NULL) ? error->text : NULL),
  15049. ((error != NULL) ? error->text_buffer_size
  15050. : 0));
  15051. }
  15052. #endif
  15053. static const struct {
  15054. const char *proto;
  15055. size_t proto_len;
  15056. unsigned default_port;
  15057. } abs_uri_protocols[] = {{"http://", 7, 80},
  15058. {"https://", 8, 443},
  15059. {"ws://", 5, 80},
  15060. {"wss://", 6, 443},
  15061. {NULL, 0, 0}};
  15062. /* Check if the uri is valid.
  15063. * return 0 for invalid uri,
  15064. * return 1 for *,
  15065. * return 2 for relative uri,
  15066. * return 3 for absolute uri without port,
  15067. * return 4 for absolute uri with port */
  15068. static int
  15069. get_uri_type(const char *uri)
  15070. {
  15071. int i;
  15072. const char *hostend, *portbegin;
  15073. char *portend;
  15074. unsigned long port;
  15075. /* According to the HTTP standard
  15076. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  15077. * URI can be an asterisk (*) or should start with slash (relative uri),
  15078. * or it should start with the protocol (absolute uri). */
  15079. if ((uri[0] == '*') && (uri[1] == '\0')) {
  15080. /* asterisk */
  15081. return 1;
  15082. }
  15083. /* Valid URIs according to RFC 3986
  15084. * (https://www.ietf.org/rfc/rfc3986.txt)
  15085. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  15086. * and unreserved characters A-Z a-z 0-9 and -._~
  15087. * and % encoded symbols.
  15088. */
  15089. for (i = 0; uri[i] != 0; i++) {
  15090. if (uri[i] < 33) {
  15091. /* control characters and spaces are invalid */
  15092. return 0;
  15093. }
  15094. /* Allow everything else here (See #894) */
  15095. }
  15096. /* A relative uri starts with a / character */
  15097. if (uri[0] == '/') {
  15098. /* relative uri */
  15099. return 2;
  15100. }
  15101. /* It could be an absolute uri: */
  15102. /* This function only checks if the uri is valid, not if it is
  15103. * addressing the current server. So civetweb can also be used
  15104. * as a proxy server. */
  15105. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15106. if (mg_strncasecmp(uri,
  15107. abs_uri_protocols[i].proto,
  15108. abs_uri_protocols[i].proto_len)
  15109. == 0) {
  15110. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  15111. if (!hostend) {
  15112. return 0;
  15113. }
  15114. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  15115. if (!portbegin) {
  15116. return 3;
  15117. }
  15118. port = strtoul(portbegin + 1, &portend, 10);
  15119. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  15120. return 0;
  15121. }
  15122. return 4;
  15123. }
  15124. }
  15125. return 0;
  15126. }
  15127. /* Return NULL or the relative uri at the current server */
  15128. static const char *
  15129. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  15130. {
  15131. const char *server_domain;
  15132. size_t server_domain_len;
  15133. size_t request_domain_len = 0;
  15134. unsigned long port = 0;
  15135. int i, auth_domain_check_enabled;
  15136. const char *hostbegin = NULL;
  15137. const char *hostend = NULL;
  15138. const char *portbegin;
  15139. char *portend;
  15140. auth_domain_check_enabled =
  15141. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  15142. /* DNS is case insensitive, so use case insensitive string compare here
  15143. */
  15144. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  15145. if (mg_strncasecmp(uri,
  15146. abs_uri_protocols[i].proto,
  15147. abs_uri_protocols[i].proto_len)
  15148. == 0) {
  15149. hostbegin = uri + abs_uri_protocols[i].proto_len;
  15150. hostend = strchr(hostbegin, '/');
  15151. if (!hostend) {
  15152. return 0;
  15153. }
  15154. portbegin = strchr(hostbegin, ':');
  15155. if ((!portbegin) || (portbegin > hostend)) {
  15156. port = abs_uri_protocols[i].default_port;
  15157. request_domain_len = (size_t)(hostend - hostbegin);
  15158. } else {
  15159. port = strtoul(portbegin + 1, &portend, 10);
  15160. if ((portend != hostend) || (port <= 0)
  15161. || !is_valid_port(port)) {
  15162. return 0;
  15163. }
  15164. request_domain_len = (size_t)(portbegin - hostbegin);
  15165. }
  15166. /* protocol found, port set */
  15167. break;
  15168. }
  15169. }
  15170. if (!port) {
  15171. /* port remains 0 if the protocol is not found */
  15172. return 0;
  15173. }
  15174. /* Check if the request is directed to a different server. */
  15175. /* First check if the port is the same. */
  15176. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  15177. /* Request is directed to a different port */
  15178. return 0;
  15179. }
  15180. /* Finally check if the server corresponds to the authentication
  15181. * domain of the server (the server domain).
  15182. * Allow full matches (like http://mydomain.com/path/file.ext), and
  15183. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  15184. * but do not allow substrings (like
  15185. * http://notmydomain.com/path/file.ext
  15186. * or http://mydomain.com.fake/path/file.ext).
  15187. */
  15188. if (auth_domain_check_enabled) {
  15189. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  15190. server_domain_len = strlen(server_domain);
  15191. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  15192. return 0;
  15193. }
  15194. if ((request_domain_len == server_domain_len)
  15195. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  15196. /* Request is directed to this server - full name match. */
  15197. } else {
  15198. if (request_domain_len < (server_domain_len + 2)) {
  15199. /* Request is directed to another server: The server name
  15200. * is longer than the request name.
  15201. * Drop this case here to avoid overflows in the
  15202. * following checks. */
  15203. return 0;
  15204. }
  15205. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  15206. /* Request is directed to another server: It could be a
  15207. * substring
  15208. * like notmyserver.com */
  15209. return 0;
  15210. }
  15211. if (0
  15212. != memcmp(server_domain,
  15213. hostbegin + request_domain_len - server_domain_len,
  15214. server_domain_len)) {
  15215. /* Request is directed to another server:
  15216. * The server name is different. */
  15217. return 0;
  15218. }
  15219. }
  15220. }
  15221. return hostend;
  15222. }
  15223. static int
  15224. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15225. {
  15226. if (ebuf_len > 0) {
  15227. ebuf[0] = '\0';
  15228. }
  15229. *err = 0;
  15230. reset_per_request_attributes(conn);
  15231. if (!conn) {
  15232. mg_snprintf(conn,
  15233. NULL, /* No truncation check for ebuf */
  15234. ebuf,
  15235. ebuf_len,
  15236. "%s",
  15237. "Internal error");
  15238. *err = 500;
  15239. return 0;
  15240. }
  15241. /* Set the time the request was received. This value should be used for
  15242. * timeouts. */
  15243. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  15244. conn->request_len =
  15245. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  15246. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  15247. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  15248. mg_snprintf(conn,
  15249. NULL, /* No truncation check for ebuf */
  15250. ebuf,
  15251. ebuf_len,
  15252. "%s",
  15253. "Invalid message size");
  15254. *err = 500;
  15255. return 0;
  15256. }
  15257. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  15258. mg_snprintf(conn,
  15259. NULL, /* No truncation check for ebuf */
  15260. ebuf,
  15261. ebuf_len,
  15262. "%s",
  15263. "Message too large");
  15264. *err = 413;
  15265. return 0;
  15266. }
  15267. if (conn->request_len <= 0) {
  15268. if (conn->data_len > 0) {
  15269. mg_snprintf(conn,
  15270. NULL, /* No truncation check for ebuf */
  15271. ebuf,
  15272. ebuf_len,
  15273. "%s",
  15274. "Malformed message");
  15275. *err = 400;
  15276. } else {
  15277. /* Server did not recv anything -> just close the connection */
  15278. conn->must_close = 1;
  15279. mg_snprintf(conn,
  15280. NULL, /* No truncation check for ebuf */
  15281. ebuf,
  15282. ebuf_len,
  15283. "%s",
  15284. "No data received");
  15285. *err = 0;
  15286. }
  15287. return 0;
  15288. }
  15289. return 1;
  15290. }
  15291. static int
  15292. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15293. {
  15294. const char *cl;
  15295. conn->connection_type =
  15296. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  15297. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15298. return 0;
  15299. }
  15300. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  15301. <= 0) {
  15302. mg_snprintf(conn,
  15303. NULL, /* No truncation check for ebuf */
  15304. ebuf,
  15305. ebuf_len,
  15306. "%s",
  15307. "Bad request");
  15308. *err = 400;
  15309. return 0;
  15310. }
  15311. /* Message is a valid request */
  15312. if (!switch_domain_context(conn)) {
  15313. mg_snprintf(conn,
  15314. NULL, /* No truncation check for ebuf */
  15315. ebuf,
  15316. ebuf_len,
  15317. "%s",
  15318. "Bad request: Host mismatch");
  15319. *err = 400;
  15320. return 0;
  15321. }
  15322. #if USE_ZLIB
  15323. if (((cl = get_header(conn->request_info.http_headers,
  15324. conn->request_info.num_headers,
  15325. "Accept-Encoding"))
  15326. != NULL)
  15327. && strstr(cl, "gzip")) {
  15328. conn->accept_gzip = 1;
  15329. }
  15330. #endif
  15331. if (((cl = get_header(conn->request_info.http_headers,
  15332. conn->request_info.num_headers,
  15333. "Transfer-Encoding"))
  15334. != NULL)
  15335. && mg_strcasecmp(cl, "identity")) {
  15336. if (mg_strcasecmp(cl, "chunked")) {
  15337. mg_snprintf(conn,
  15338. NULL, /* No truncation check for ebuf */
  15339. ebuf,
  15340. ebuf_len,
  15341. "%s",
  15342. "Bad request");
  15343. *err = 400;
  15344. return 0;
  15345. }
  15346. conn->is_chunked = 1;
  15347. conn->content_len = 0; /* not yet read */
  15348. } else if ((cl = get_header(conn->request_info.http_headers,
  15349. conn->request_info.num_headers,
  15350. "Content-Length"))
  15351. != NULL) {
  15352. /* Request has content length set */
  15353. char *endptr = NULL;
  15354. conn->content_len = strtoll(cl, &endptr, 10);
  15355. if ((endptr == cl) || (conn->content_len < 0)) {
  15356. mg_snprintf(conn,
  15357. NULL, /* No truncation check for ebuf */
  15358. ebuf,
  15359. ebuf_len,
  15360. "%s",
  15361. "Bad request");
  15362. *err = 411;
  15363. return 0;
  15364. }
  15365. /* Publish the content length back to the request info. */
  15366. conn->request_info.content_length = conn->content_len;
  15367. } else {
  15368. /* There is no exception, see RFC7230. */
  15369. conn->content_len = 0;
  15370. }
  15371. return 1;
  15372. }
  15373. /* conn is assumed to be valid in this internal function */
  15374. static int
  15375. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  15376. {
  15377. const char *cl;
  15378. conn->connection_type =
  15379. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  15380. if (!get_message(conn, ebuf, ebuf_len, err)) {
  15381. return 0;
  15382. }
  15383. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  15384. <= 0) {
  15385. mg_snprintf(conn,
  15386. NULL, /* No truncation check for ebuf */
  15387. ebuf,
  15388. ebuf_len,
  15389. "%s",
  15390. "Bad response");
  15391. *err = 400;
  15392. return 0;
  15393. }
  15394. /* Message is a valid response */
  15395. if (((cl = get_header(conn->response_info.http_headers,
  15396. conn->response_info.num_headers,
  15397. "Transfer-Encoding"))
  15398. != NULL)
  15399. && mg_strcasecmp(cl, "identity")) {
  15400. if (mg_strcasecmp(cl, "chunked")) {
  15401. mg_snprintf(conn,
  15402. NULL, /* No truncation check for ebuf */
  15403. ebuf,
  15404. ebuf_len,
  15405. "%s",
  15406. "Bad request");
  15407. *err = 400;
  15408. return 0;
  15409. }
  15410. conn->is_chunked = 1;
  15411. conn->content_len = 0; /* not yet read */
  15412. } else if ((cl = get_header(conn->response_info.http_headers,
  15413. conn->response_info.num_headers,
  15414. "Content-Length"))
  15415. != NULL) {
  15416. char *endptr = NULL;
  15417. conn->content_len = strtoll(cl, &endptr, 10);
  15418. if ((endptr == cl) || (conn->content_len < 0)) {
  15419. mg_snprintf(conn,
  15420. NULL, /* No truncation check for ebuf */
  15421. ebuf,
  15422. ebuf_len,
  15423. "%s",
  15424. "Bad request");
  15425. *err = 411;
  15426. return 0;
  15427. }
  15428. /* Publish the content length back to the response info. */
  15429. conn->response_info.content_length = conn->content_len;
  15430. /* TODO: check if it is still used in response_info */
  15431. conn->request_info.content_length = conn->content_len;
  15432. /* TODO: we should also consider HEAD method */
  15433. if (conn->response_info.status_code == 304) {
  15434. conn->content_len = 0;
  15435. }
  15436. } else {
  15437. /* TODO: we should also consider HEAD method */
  15438. if (((conn->response_info.status_code >= 100)
  15439. && (conn->response_info.status_code <= 199))
  15440. || (conn->response_info.status_code == 204)
  15441. || (conn->response_info.status_code == 304)) {
  15442. conn->content_len = 0;
  15443. } else {
  15444. conn->content_len = -1; /* unknown content length */
  15445. }
  15446. }
  15447. return 1;
  15448. }
  15449. int
  15450. mg_get_response(struct mg_connection *conn,
  15451. char *ebuf,
  15452. size_t ebuf_len,
  15453. int timeout)
  15454. {
  15455. int err, ret;
  15456. char txt[32]; /* will not overflow */
  15457. char *save_timeout;
  15458. char *new_timeout;
  15459. if (ebuf_len > 0) {
  15460. ebuf[0] = '\0';
  15461. }
  15462. if (!conn) {
  15463. mg_snprintf(conn,
  15464. NULL, /* No truncation check for ebuf */
  15465. ebuf,
  15466. ebuf_len,
  15467. "%s",
  15468. "Parameter error");
  15469. return -1;
  15470. }
  15471. /* Reset the previous responses */
  15472. conn->data_len = 0;
  15473. /* Implementation of API function for HTTP clients */
  15474. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  15475. if (timeout >= 0) {
  15476. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  15477. new_timeout = txt;
  15478. } else {
  15479. new_timeout = NULL;
  15480. }
  15481. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  15482. ret = get_response(conn, ebuf, ebuf_len, &err);
  15483. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  15484. #if defined(MG_LEGACY_INTERFACE)
  15485. /* TODO: 1) uri is deprecated;
  15486. * 2) here, ri.uri is the http response code */
  15487. conn->request_info.uri = conn->request_info.request_uri;
  15488. #endif
  15489. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15490. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15491. /* TODO (mid): Define proper return values - maybe return length?
  15492. * For the first test use <0 for error and >0 for OK */
  15493. return (ret == 0) ? -1 : +1;
  15494. }
  15495. struct mg_connection *
  15496. mg_download(const char *host,
  15497. int port,
  15498. int use_ssl,
  15499. char *ebuf,
  15500. size_t ebuf_len,
  15501. const char *fmt,
  15502. ...)
  15503. {
  15504. struct mg_connection *conn;
  15505. va_list ap;
  15506. int i;
  15507. int reqerr;
  15508. if (ebuf_len > 0) {
  15509. ebuf[0] = '\0';
  15510. }
  15511. va_start(ap, fmt);
  15512. /* open a connection */
  15513. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  15514. if (conn != NULL) {
  15515. i = mg_vprintf(conn, fmt, ap);
  15516. if (i <= 0) {
  15517. mg_snprintf(conn,
  15518. NULL, /* No truncation check for ebuf */
  15519. ebuf,
  15520. ebuf_len,
  15521. "%s",
  15522. "Error sending request");
  15523. } else {
  15524. /* make sure the buffer is clear */
  15525. conn->data_len = 0;
  15526. get_response(conn, ebuf, ebuf_len, &reqerr);
  15527. #if defined(MG_LEGACY_INTERFACE)
  15528. /* TODO: 1) uri is deprecated;
  15529. * 2) here, ri.uri is the http response code */
  15530. conn->request_info.uri = conn->request_info.request_uri;
  15531. #endif
  15532. conn->request_info.local_uri = conn->request_info.request_uri;
  15533. }
  15534. }
  15535. /* if an error occurred, close the connection */
  15536. if ((ebuf[0] != '\0') && (conn != NULL)) {
  15537. mg_close_connection(conn);
  15538. conn = NULL;
  15539. }
  15540. va_end(ap);
  15541. return conn;
  15542. }
  15543. struct websocket_client_thread_data {
  15544. struct mg_connection *conn;
  15545. mg_websocket_data_handler data_handler;
  15546. mg_websocket_close_handler close_handler;
  15547. void *callback_data;
  15548. };
  15549. #if defined(USE_WEBSOCKET)
  15550. #if defined(_WIN32)
  15551. static unsigned __stdcall websocket_client_thread(void *data)
  15552. #else
  15553. static void *
  15554. websocket_client_thread(void *data)
  15555. #endif
  15556. {
  15557. struct websocket_client_thread_data *cdata =
  15558. (struct websocket_client_thread_data *)data;
  15559. void *user_thread_ptr = NULL;
  15560. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  15561. struct sigaction sa;
  15562. /* Ignore SIGPIPE */
  15563. memset(&sa, 0, sizeof(sa));
  15564. sa.sa_handler = SIG_IGN;
  15565. sigaction(SIGPIPE, &sa, NULL);
  15566. #endif
  15567. mg_set_thread_name("ws-clnt");
  15568. if (cdata->conn->phys_ctx) {
  15569. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  15570. /* 3 indicates a websocket client thread */
  15571. /* TODO: check if conn->phys_ctx can be set */
  15572. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  15573. cdata->conn->phys_ctx, 3);
  15574. }
  15575. }
  15576. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  15577. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  15578. if (cdata->close_handler != NULL) {
  15579. cdata->close_handler(cdata->conn, cdata->callback_data);
  15580. }
  15581. /* The websocket_client context has only this thread. If it runs out,
  15582. set the stop_flag to 2 (= "stopped"). */
  15583. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  15584. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  15585. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15586. 3,
  15587. user_thread_ptr);
  15588. }
  15589. mg_free((void *)cdata);
  15590. #if defined(_WIN32)
  15591. return 0;
  15592. #else
  15593. return NULL;
  15594. #endif
  15595. }
  15596. #endif
  15597. static struct mg_connection *
  15598. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  15599. int use_ssl,
  15600. char *error_buffer,
  15601. size_t error_buffer_size,
  15602. const char *path,
  15603. const char *origin,
  15604. const char *extensions,
  15605. mg_websocket_data_handler data_func,
  15606. mg_websocket_close_handler close_func,
  15607. void *user_data)
  15608. {
  15609. struct mg_connection *conn = NULL;
  15610. #if defined(USE_WEBSOCKET)
  15611. struct websocket_client_thread_data *thread_data;
  15612. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15613. const char *host = client_options->host;
  15614. int i;
  15615. #if defined(__clang__)
  15616. #pragma clang diagnostic push
  15617. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15618. #endif
  15619. /* Establish the client connection and request upgrade */
  15620. conn = mg_connect_client_impl(client_options,
  15621. use_ssl,
  15622. error_buffer,
  15623. error_buffer_size);
  15624. /* Connection object will be null if something goes wrong */
  15625. if (conn == NULL) {
  15626. /* error_buffer should be already filled ... */
  15627. if (!error_buffer[0]) {
  15628. /* ... if not add an error message */
  15629. mg_snprintf(conn,
  15630. NULL, /* No truncation check for ebuf */
  15631. error_buffer,
  15632. error_buffer_size,
  15633. "Unexpected error");
  15634. }
  15635. return NULL;
  15636. }
  15637. if (origin != NULL) {
  15638. if (extensions != NULL) {
  15639. i = mg_printf(conn,
  15640. "GET %s HTTP/1.1\r\n"
  15641. "Host: %s\r\n"
  15642. "Upgrade: websocket\r\n"
  15643. "Connection: Upgrade\r\n"
  15644. "Sec-WebSocket-Key: %s\r\n"
  15645. "Sec-WebSocket-Version: 13\r\n"
  15646. "Sec-WebSocket-Extensions: %s\r\n"
  15647. "Origin: %s\r\n"
  15648. "\r\n",
  15649. path,
  15650. host,
  15651. magic,
  15652. extensions,
  15653. origin);
  15654. } else {
  15655. i = mg_printf(conn,
  15656. "GET %s HTTP/1.1\r\n"
  15657. "Host: %s\r\n"
  15658. "Upgrade: websocket\r\n"
  15659. "Connection: Upgrade\r\n"
  15660. "Sec-WebSocket-Key: %s\r\n"
  15661. "Sec-WebSocket-Version: 13\r\n"
  15662. "Origin: %s\r\n"
  15663. "\r\n",
  15664. path,
  15665. host,
  15666. magic,
  15667. origin);
  15668. }
  15669. } else {
  15670. if (extensions != NULL) {
  15671. i = mg_printf(conn,
  15672. "GET %s HTTP/1.1\r\n"
  15673. "Host: %s\r\n"
  15674. "Upgrade: websocket\r\n"
  15675. "Connection: Upgrade\r\n"
  15676. "Sec-WebSocket-Key: %s\r\n"
  15677. "Sec-WebSocket-Version: 13\r\n"
  15678. "Sec-WebSocket-Extensions: %s\r\n"
  15679. "\r\n",
  15680. path,
  15681. host,
  15682. magic,
  15683. extensions);
  15684. } else {
  15685. i = mg_printf(conn,
  15686. "GET %s HTTP/1.1\r\n"
  15687. "Host: %s\r\n"
  15688. "Upgrade: websocket\r\n"
  15689. "Connection: Upgrade\r\n"
  15690. "Sec-WebSocket-Key: %s\r\n"
  15691. "Sec-WebSocket-Version: 13\r\n"
  15692. "\r\n",
  15693. path,
  15694. host,
  15695. magic);
  15696. }
  15697. }
  15698. if (i <= 0) {
  15699. mg_snprintf(conn,
  15700. NULL, /* No truncation check for ebuf */
  15701. error_buffer,
  15702. error_buffer_size,
  15703. "%s",
  15704. "Error sending request");
  15705. mg_close_connection(conn);
  15706. return NULL;
  15707. }
  15708. conn->data_len = 0;
  15709. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  15710. mg_close_connection(conn);
  15711. return NULL;
  15712. }
  15713. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  15714. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  15715. #if defined(__clang__)
  15716. #pragma clang diagnostic pop
  15717. #endif
  15718. if (conn->response_info.status_code != 101) {
  15719. /* We sent an "upgrade" request. For a correct websocket
  15720. * protocol handshake, we expect a "101 Continue" response.
  15721. * Otherwise it is a protocol violation. Maybe the HTTP
  15722. * Server does not know websockets. */
  15723. if (!*error_buffer) {
  15724. /* set an error, if not yet set */
  15725. mg_snprintf(conn,
  15726. NULL, /* No truncation check for ebuf */
  15727. error_buffer,
  15728. error_buffer_size,
  15729. "Unexpected server reply");
  15730. }
  15731. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15732. mg_close_connection(conn);
  15733. return NULL;
  15734. }
  15735. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15736. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15737. if (!thread_data) {
  15738. DEBUG_TRACE("%s\r\n", "Out of memory");
  15739. mg_close_connection(conn);
  15740. return NULL;
  15741. }
  15742. thread_data->conn = conn;
  15743. thread_data->data_handler = data_func;
  15744. thread_data->close_handler = close_func;
  15745. thread_data->callback_data = user_data;
  15746. conn->phys_ctx->worker_threadids =
  15747. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15748. if (!conn->phys_ctx->worker_threadids) {
  15749. DEBUG_TRACE("%s\r\n", "Out of memory");
  15750. mg_free(thread_data);
  15751. mg_close_connection(conn);
  15752. return NULL;
  15753. }
  15754. /* Now upgrade to ws/wss client context */
  15755. conn->phys_ctx->user_data = user_data;
  15756. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15757. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15758. /* Start a thread to read the websocket client connection
  15759. * This thread will automatically stop when mg_disconnect is
  15760. * called on the client connection */
  15761. if (mg_start_thread_with_id(websocket_client_thread,
  15762. thread_data,
  15763. conn->phys_ctx->worker_threadids)
  15764. != 0) {
  15765. conn->phys_ctx->cfg_worker_threads = 0;
  15766. mg_free(thread_data);
  15767. mg_close_connection(conn);
  15768. conn = NULL;
  15769. DEBUG_TRACE("%s",
  15770. "Websocket client connect thread could not be started\r\n");
  15771. }
  15772. #else
  15773. /* Appease "unused parameter" warnings */
  15774. (void)client_options;
  15775. (void)use_ssl;
  15776. (void)error_buffer;
  15777. (void)error_buffer_size;
  15778. (void)path;
  15779. (void)origin;
  15780. (void)extensions;
  15781. (void)user_data;
  15782. (void)data_func;
  15783. (void)close_func;
  15784. #endif
  15785. return conn;
  15786. }
  15787. struct mg_connection *
  15788. mg_connect_websocket_client(const char *host,
  15789. int port,
  15790. int use_ssl,
  15791. char *error_buffer,
  15792. size_t error_buffer_size,
  15793. const char *path,
  15794. const char *origin,
  15795. mg_websocket_data_handler data_func,
  15796. mg_websocket_close_handler close_func,
  15797. void *user_data)
  15798. {
  15799. struct mg_client_options client_options;
  15800. memset(&client_options, 0, sizeof(client_options));
  15801. client_options.host = host;
  15802. client_options.port = port;
  15803. return mg_connect_websocket_client_impl(&client_options,
  15804. use_ssl,
  15805. error_buffer,
  15806. error_buffer_size,
  15807. path,
  15808. origin,
  15809. NULL,
  15810. data_func,
  15811. close_func,
  15812. user_data);
  15813. }
  15814. struct mg_connection *
  15815. mg_connect_websocket_client_secure(
  15816. const struct mg_client_options *client_options,
  15817. char *error_buffer,
  15818. size_t error_buffer_size,
  15819. const char *path,
  15820. const char *origin,
  15821. mg_websocket_data_handler data_func,
  15822. mg_websocket_close_handler close_func,
  15823. void *user_data)
  15824. {
  15825. if (!client_options) {
  15826. return NULL;
  15827. }
  15828. return mg_connect_websocket_client_impl(client_options,
  15829. 1,
  15830. error_buffer,
  15831. error_buffer_size,
  15832. path,
  15833. origin,
  15834. NULL,
  15835. data_func,
  15836. close_func,
  15837. user_data);
  15838. }
  15839. struct mg_connection *
  15840. mg_connect_websocket_client_extensions(const char *host,
  15841. int port,
  15842. int use_ssl,
  15843. char *error_buffer,
  15844. size_t error_buffer_size,
  15845. const char *path,
  15846. const char *origin,
  15847. const char *extensions,
  15848. mg_websocket_data_handler data_func,
  15849. mg_websocket_close_handler close_func,
  15850. void *user_data)
  15851. {
  15852. struct mg_client_options client_options;
  15853. memset(&client_options, 0, sizeof(client_options));
  15854. client_options.host = host;
  15855. client_options.port = port;
  15856. return mg_connect_websocket_client_impl(&client_options,
  15857. use_ssl,
  15858. error_buffer,
  15859. error_buffer_size,
  15860. path,
  15861. origin,
  15862. extensions,
  15863. data_func,
  15864. close_func,
  15865. user_data);
  15866. }
  15867. struct mg_connection *
  15868. mg_connect_websocket_client_secure_extensions(
  15869. const struct mg_client_options *client_options,
  15870. char *error_buffer,
  15871. size_t error_buffer_size,
  15872. const char *path,
  15873. const char *origin,
  15874. const char *extensions,
  15875. mg_websocket_data_handler data_func,
  15876. mg_websocket_close_handler close_func,
  15877. void *user_data)
  15878. {
  15879. if (!client_options) {
  15880. return NULL;
  15881. }
  15882. return mg_connect_websocket_client_impl(client_options,
  15883. 1,
  15884. error_buffer,
  15885. error_buffer_size,
  15886. path,
  15887. origin,
  15888. extensions,
  15889. data_func,
  15890. close_func,
  15891. user_data);
  15892. }
  15893. /* Prepare connection data structure */
  15894. static void
  15895. init_connection(struct mg_connection *conn)
  15896. {
  15897. /* Is keep alive allowed by the server */
  15898. int keep_alive_enabled =
  15899. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15900. if (!keep_alive_enabled) {
  15901. conn->must_close = 1;
  15902. }
  15903. /* Important: on new connection, reset the receiving buffer. Credit
  15904. * goes to crule42. */
  15905. conn->data_len = 0;
  15906. conn->handled_requests = 0;
  15907. conn->connection_type = CONNECTION_TYPE_INVALID;
  15908. mg_set_user_connection_data(conn, NULL);
  15909. #if defined(USE_SERVER_STATS)
  15910. conn->conn_state = 2; /* init */
  15911. #endif
  15912. /* call the init_connection callback if assigned */
  15913. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15914. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15915. void *conn_data = NULL;
  15916. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15917. mg_set_user_connection_data(conn, conn_data);
  15918. }
  15919. }
  15920. }
  15921. /* Process a connection - may handle multiple requests
  15922. * using the same connection.
  15923. * Must be called with a valid connection (conn and
  15924. * conn->phys_ctx must be valid).
  15925. */
  15926. static void
  15927. process_new_connection(struct mg_connection *conn)
  15928. {
  15929. struct mg_request_info *ri = &conn->request_info;
  15930. int keep_alive, discard_len;
  15931. char ebuf[100];
  15932. const char *hostend;
  15933. int reqerr, uri_type;
  15934. #if defined(USE_SERVER_STATS)
  15935. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15936. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15937. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  15938. #endif
  15939. DEBUG_TRACE("Start processing connection from %s",
  15940. conn->request_info.remote_addr);
  15941. /* Loop over multiple requests sent using the same connection
  15942. * (while "keep alive"). */
  15943. do {
  15944. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15945. conn->handled_requests + 1);
  15946. #if defined(USE_SERVER_STATS)
  15947. conn->conn_state = 3; /* ready */
  15948. #endif
  15949. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15950. /* The request sent by the client could not be understood by
  15951. * the server, or it was incomplete or a timeout. Send an
  15952. * error message and close the connection. */
  15953. if (reqerr > 0) {
  15954. DEBUG_ASSERT(ebuf[0] != '\0');
  15955. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15956. }
  15957. } else if (strcmp(ri->http_version, "1.0")
  15958. && strcmp(ri->http_version, "1.1")) {
  15959. /* HTTP/2 is not allowed here */
  15960. mg_snprintf(conn,
  15961. NULL, /* No truncation check for ebuf */
  15962. ebuf,
  15963. sizeof(ebuf),
  15964. "Bad HTTP version: [%s]",
  15965. ri->http_version);
  15966. mg_send_http_error(conn, 505, "%s", ebuf);
  15967. }
  15968. if (ebuf[0] == '\0') {
  15969. uri_type = get_uri_type(conn->request_info.request_uri);
  15970. switch (uri_type) {
  15971. case 1:
  15972. /* Asterisk */
  15973. conn->request_info.local_uri_raw = 0;
  15974. /* TODO: Deal with '*'. */
  15975. break;
  15976. case 2:
  15977. /* relative uri */
  15978. conn->request_info.local_uri_raw =
  15979. conn->request_info.request_uri;
  15980. break;
  15981. case 3:
  15982. case 4:
  15983. /* absolute uri (with/without port) */
  15984. hostend = get_rel_url_at_current_server(
  15985. conn->request_info.request_uri, conn);
  15986. if (hostend) {
  15987. conn->request_info.local_uri_raw = hostend;
  15988. } else {
  15989. conn->request_info.local_uri_raw = NULL;
  15990. }
  15991. break;
  15992. default:
  15993. mg_snprintf(conn,
  15994. NULL, /* No truncation check for ebuf */
  15995. ebuf,
  15996. sizeof(ebuf),
  15997. "Invalid URI");
  15998. mg_send_http_error(conn, 400, "%s", ebuf);
  15999. conn->request_info.local_uri_raw = NULL;
  16000. break;
  16001. }
  16002. conn->request_info.local_uri =
  16003. (char *)conn->request_info.local_uri_raw;
  16004. #if defined(MG_LEGACY_INTERFACE)
  16005. /* Legacy before split into local_uri and request_uri */
  16006. conn->request_info.uri = conn->request_info.local_uri;
  16007. #endif
  16008. }
  16009. if (ebuf[0] != '\0') {
  16010. conn->protocol_type = -1;
  16011. } else {
  16012. /* HTTP/1 allows protocol upgrade */
  16013. conn->protocol_type = should_switch_to_protocol(conn);
  16014. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  16015. /* This will occur, if a HTTP/1.1 request should be upgraded
  16016. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  16017. * Since most (all?) major browsers only support HTTP/2 using
  16018. * ALPN, this is hard to test and very low priority.
  16019. * Deactivate it (at least for now).
  16020. */
  16021. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16022. }
  16023. }
  16024. DEBUG_TRACE("http: %s, error: %s",
  16025. (ri->http_version ? ri->http_version : "none"),
  16026. (ebuf[0] ? ebuf : "none"));
  16027. if (ebuf[0] == '\0') {
  16028. if (conn->request_info.local_uri) {
  16029. /* handle request to local server */
  16030. handle_request_stat_log(conn);
  16031. } else {
  16032. /* TODO: handle non-local request (PROXY) */
  16033. conn->must_close = 1;
  16034. }
  16035. } else {
  16036. conn->must_close = 1;
  16037. }
  16038. /* Response complete. Free header buffer */
  16039. free_buffered_response_header_list(conn);
  16040. if (ri->remote_user != NULL) {
  16041. mg_free((void *)ri->remote_user);
  16042. /* Important! When having connections with and without auth
  16043. * would cause double free and then crash */
  16044. ri->remote_user = NULL;
  16045. }
  16046. /* NOTE(lsm): order is important here. should_keep_alive() call
  16047. * is using parsed request, which will be invalid after
  16048. * memmove's below.
  16049. * Therefore, memorize should_keep_alive() result now for later
  16050. * use in loop exit condition. */
  16051. /* Enable it only if this request is completely discardable. */
  16052. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  16053. && should_keep_alive(conn) && (conn->content_len >= 0)
  16054. && (conn->request_len > 0)
  16055. && ((conn->is_chunked == 4)
  16056. || (!conn->is_chunked
  16057. && ((conn->consumed_content == conn->content_len)
  16058. || ((conn->request_len + conn->content_len)
  16059. <= conn->data_len))))
  16060. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  16061. if (keep_alive) {
  16062. /* Discard all buffered data for this request */
  16063. discard_len =
  16064. ((conn->request_len + conn->content_len) < conn->data_len)
  16065. ? (int)(conn->request_len + conn->content_len)
  16066. : conn->data_len;
  16067. conn->data_len -= discard_len;
  16068. if (conn->data_len > 0) {
  16069. DEBUG_TRACE("discard_len = %d", discard_len);
  16070. memmove(conn->buf,
  16071. conn->buf + discard_len,
  16072. (size_t)conn->data_len);
  16073. }
  16074. }
  16075. DEBUG_ASSERT(conn->data_len >= 0);
  16076. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  16077. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  16078. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  16079. (long int)conn->data_len,
  16080. (long int)conn->buf_size);
  16081. break;
  16082. }
  16083. conn->handled_requests++;
  16084. } while (keep_alive);
  16085. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  16086. conn->request_info.remote_addr,
  16087. difftime(time(NULL), conn->conn_birth_time));
  16088. close_connection(conn);
  16089. #if defined(USE_SERVER_STATS)
  16090. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  16091. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  16092. #endif
  16093. }
  16094. #if defined(ALTERNATIVE_QUEUE)
  16095. static void
  16096. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16097. {
  16098. unsigned int i;
  16099. while (!ctx->stop_flag) {
  16100. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16101. /* find a free worker slot and signal it */
  16102. if (ctx->client_socks[i].in_use == 2) {
  16103. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16104. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  16105. ctx->client_socks[i] = *sp;
  16106. ctx->client_socks[i].in_use = 1;
  16107. /* socket has been moved to the consumer */
  16108. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16109. (void)event_signal(ctx->client_wait_events[i]);
  16110. return;
  16111. }
  16112. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16113. }
  16114. }
  16115. /* queue is full */
  16116. mg_sleep(1);
  16117. }
  16118. /* must consume */
  16119. set_blocking_mode(sp->sock);
  16120. closesocket(sp->sock);
  16121. }
  16122. static int
  16123. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16124. {
  16125. DEBUG_TRACE("%s", "going idle");
  16126. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16127. ctx->client_socks[thread_index].in_use = 2;
  16128. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16129. event_wait(ctx->client_wait_events[thread_index]);
  16130. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16131. *sp = ctx->client_socks[thread_index];
  16132. if (ctx->stop_flag) {
  16133. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16134. if (sp->in_use == 1) {
  16135. /* must consume */
  16136. set_blocking_mode(sp->sock);
  16137. closesocket(sp->sock);
  16138. }
  16139. return 0;
  16140. }
  16141. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16142. if (sp->in_use == 1) {
  16143. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  16144. return 1;
  16145. }
  16146. /* must not reach here */
  16147. DEBUG_ASSERT(0);
  16148. return 0;
  16149. }
  16150. #else /* ALTERNATIVE_QUEUE */
  16151. /* Worker threads take accepted socket from the queue */
  16152. static int
  16153. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  16154. {
  16155. (void)thread_index;
  16156. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16157. DEBUG_TRACE("%s", "going idle");
  16158. /* If the queue is empty, wait. We're idle at this point. */
  16159. while ((ctx->sq_head == ctx->sq_tail)
  16160. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  16161. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  16162. }
  16163. /* If we're stopping, sq_head may be equal to sq_tail. */
  16164. if (ctx->sq_head > ctx->sq_tail) {
  16165. /* Copy socket from the queue and increment tail */
  16166. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  16167. ctx->sq_tail++;
  16168. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  16169. /* Wrap pointers if needed */
  16170. while (ctx->sq_tail > ctx->sq_size) {
  16171. ctx->sq_tail -= ctx->sq_size;
  16172. ctx->sq_head -= ctx->sq_size;
  16173. }
  16174. }
  16175. (void)pthread_cond_signal(&ctx->sq_empty);
  16176. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16177. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  16178. }
  16179. /* Master thread adds accepted socket to a queue */
  16180. static void
  16181. produce_socket(struct mg_context *ctx, const struct socket *sp)
  16182. {
  16183. int queue_filled;
  16184. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16185. queue_filled = ctx->sq_head - ctx->sq_tail;
  16186. /* If the queue is full, wait */
  16187. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16188. && (queue_filled >= ctx->sq_size)) {
  16189. ctx->sq_blocked = 1; /* Status information: All threads busy */
  16190. #if defined(USE_SERVER_STATS)
  16191. if (queue_filled > ctx->sq_max_fill) {
  16192. ctx->sq_max_fill = queue_filled;
  16193. }
  16194. #endif
  16195. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  16196. ctx->sq_blocked = 0; /* Not blocked now */
  16197. queue_filled = ctx->sq_head - ctx->sq_tail;
  16198. }
  16199. if (queue_filled < ctx->sq_size) {
  16200. /* Copy socket to the queue and increment head */
  16201. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  16202. ctx->sq_head++;
  16203. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  16204. }
  16205. queue_filled = ctx->sq_head - ctx->sq_tail;
  16206. #if defined(USE_SERVER_STATS)
  16207. if (queue_filled > ctx->sq_max_fill) {
  16208. ctx->sq_max_fill = queue_filled;
  16209. }
  16210. #endif
  16211. (void)pthread_cond_signal(&ctx->sq_full);
  16212. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16213. }
  16214. #endif /* ALTERNATIVE_QUEUE */
  16215. static void
  16216. worker_thread_run(struct mg_connection *conn)
  16217. {
  16218. struct mg_context *ctx = conn->phys_ctx;
  16219. int thread_index;
  16220. struct mg_workerTLS tls;
  16221. mg_set_thread_name("worker");
  16222. tls.is_master = 0;
  16223. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16224. #if defined(_WIN32)
  16225. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16226. #endif
  16227. /* Initialize thread local storage before calling any callback */
  16228. pthread_setspecific(sTlsKey, &tls);
  16229. /* Check if there is a user callback */
  16230. if (ctx->callbacks.init_thread) {
  16231. /* call init_thread for a worker thread (type 1), and store the
  16232. * return value */
  16233. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  16234. } else {
  16235. /* No callback: set user pointer to NULL */
  16236. tls.user_ptr = NULL;
  16237. }
  16238. /* Connection structure has been pre-allocated */
  16239. thread_index = (int)(conn - ctx->worker_connections);
  16240. if ((thread_index < 0)
  16241. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  16242. mg_cry_ctx_internal(ctx,
  16243. "Internal error: Invalid worker index %i",
  16244. thread_index);
  16245. return;
  16246. }
  16247. /* Request buffers are not pre-allocated. They are private to the
  16248. * request and do not contain any state information that might be
  16249. * of interest to anyone observing a server status. */
  16250. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  16251. if (conn->buf == NULL) {
  16252. mg_cry_ctx_internal(
  16253. ctx,
  16254. "Out of memory: Cannot allocate buffer for worker %i",
  16255. thread_index);
  16256. return;
  16257. }
  16258. conn->buf_size = (int)ctx->max_request_size;
  16259. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  16260. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  16261. conn->request_info.user_data = ctx->user_data;
  16262. /* Allocate a mutex for this connection to allow communication both
  16263. * within the request handler and from elsewhere in the application
  16264. */
  16265. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  16266. mg_free(conn->buf);
  16267. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  16268. return;
  16269. }
  16270. #if defined(USE_SERVER_STATS)
  16271. conn->conn_state = 1; /* not consumed */
  16272. #endif
  16273. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  16274. * signal sq_empty condvar to wake up the master waiting in
  16275. * produce_socket() */
  16276. while (consume_socket(ctx, &conn->client, thread_index)) {
  16277. /* New connections must start with new protocol negotiation */
  16278. tls.alpn_proto = NULL;
  16279. #if defined(USE_SERVER_STATS)
  16280. conn->conn_close_time = 0;
  16281. #endif
  16282. conn->conn_birth_time = time(NULL);
  16283. /* Fill in IP, port info early so even if SSL setup below fails,
  16284. * error handler would have the corresponding info.
  16285. * Thanks to Johannes Winkelmann for the patch.
  16286. */
  16287. conn->request_info.remote_port =
  16288. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  16289. conn->request_info.server_port =
  16290. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  16291. sockaddr_to_string(conn->request_info.remote_addr,
  16292. sizeof(conn->request_info.remote_addr),
  16293. &conn->client.rsa);
  16294. DEBUG_TRACE("Incomming %sconnection from %s",
  16295. (conn->client.is_ssl ? "SSL " : ""),
  16296. conn->request_info.remote_addr);
  16297. conn->request_info.is_ssl = conn->client.is_ssl;
  16298. if (conn->client.is_ssl) {
  16299. #if defined(USE_MBEDTLS)
  16300. /* HTTPS connection */
  16301. if (mbed_ssl_accept(&(conn->ssl),
  16302. conn->dom_ctx->ssl_ctx,
  16303. (int *)&(conn->client.sock),
  16304. conn->phys_ctx)
  16305. == 0) {
  16306. /* conn->dom_ctx is set in get_request */
  16307. /* process HTTPS connection */
  16308. init_connection(conn);
  16309. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16310. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16311. process_new_connection(conn);
  16312. } else {
  16313. /* make sure the connection is cleaned up on SSL failure */
  16314. close_connection(conn);
  16315. }
  16316. #elif !defined(NO_SSL)
  16317. /* HTTPS connection */
  16318. if (sslize(conn, SSL_accept, NULL)) {
  16319. /* conn->dom_ctx is set in get_request */
  16320. /* Get SSL client certificate information (if set) */
  16321. struct mg_client_cert client_cert;
  16322. if (ssl_get_client_cert_info(conn, &client_cert)) {
  16323. conn->request_info.client_cert = &client_cert;
  16324. }
  16325. /* process HTTPS connection */
  16326. #if defined(USE_HTTP2)
  16327. if ((tls.alpn_proto != NULL)
  16328. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  16329. /* process HTTPS/2 connection */
  16330. init_connection(conn);
  16331. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16332. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  16333. conn->content_len =
  16334. -1; /* content length is not predefined */
  16335. conn->is_chunked = 0; /* HTTP2 is never chunked */
  16336. process_new_http2_connection(conn);
  16337. } else
  16338. #endif
  16339. {
  16340. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  16341. init_connection(conn);
  16342. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16343. /* Start with HTTP, WS will be an "upgrade" request later */
  16344. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16345. process_new_connection(conn);
  16346. }
  16347. /* Free client certificate info */
  16348. if (conn->request_info.client_cert) {
  16349. mg_free((void *)(conn->request_info.client_cert->subject));
  16350. mg_free((void *)(conn->request_info.client_cert->issuer));
  16351. mg_free((void *)(conn->request_info.client_cert->serial));
  16352. mg_free((void *)(conn->request_info.client_cert->finger));
  16353. /* Free certificate memory */
  16354. X509_free(
  16355. (X509 *)conn->request_info.client_cert->peer_cert);
  16356. conn->request_info.client_cert->peer_cert = 0;
  16357. conn->request_info.client_cert->subject = 0;
  16358. conn->request_info.client_cert->issuer = 0;
  16359. conn->request_info.client_cert->serial = 0;
  16360. conn->request_info.client_cert->finger = 0;
  16361. conn->request_info.client_cert = 0;
  16362. }
  16363. } else {
  16364. /* make sure the connection is cleaned up on SSL failure */
  16365. close_connection(conn);
  16366. }
  16367. #endif
  16368. } else {
  16369. /* process HTTP connection */
  16370. init_connection(conn);
  16371. conn->connection_type = CONNECTION_TYPE_REQUEST;
  16372. /* Start with HTTP, WS will be an "upgrade" request later */
  16373. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  16374. process_new_connection(conn);
  16375. }
  16376. DEBUG_TRACE("%s", "Connection closed");
  16377. #if defined(USE_SERVER_STATS)
  16378. conn->conn_close_time = time(NULL);
  16379. #endif
  16380. }
  16381. /* Call exit thread user callback */
  16382. if (ctx->callbacks.exit_thread) {
  16383. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  16384. }
  16385. /* delete thread local storage objects */
  16386. pthread_setspecific(sTlsKey, NULL);
  16387. #if defined(_WIN32)
  16388. CloseHandle(tls.pthread_cond_helper_mutex);
  16389. #endif
  16390. pthread_mutex_destroy(&conn->mutex);
  16391. /* Free the request buffer. */
  16392. conn->buf_size = 0;
  16393. mg_free(conn->buf);
  16394. conn->buf = NULL;
  16395. /* Free cleaned URI (if any) */
  16396. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  16397. mg_free((void *)conn->request_info.local_uri);
  16398. conn->request_info.local_uri = NULL;
  16399. }
  16400. #if defined(USE_SERVER_STATS)
  16401. conn->conn_state = 9; /* done */
  16402. #endif
  16403. DEBUG_TRACE("%s", "exiting");
  16404. }
  16405. /* Threads have different return types on Windows and Unix. */
  16406. #if defined(_WIN32)
  16407. static unsigned __stdcall worker_thread(void *thread_func_param)
  16408. {
  16409. worker_thread_run((struct mg_connection *)thread_func_param);
  16410. return 0;
  16411. }
  16412. #else
  16413. static void *
  16414. worker_thread(void *thread_func_param)
  16415. {
  16416. #if !defined(__ZEPHYR__)
  16417. struct sigaction sa;
  16418. /* Ignore SIGPIPE */
  16419. memset(&sa, 0, sizeof(sa));
  16420. sa.sa_handler = SIG_IGN;
  16421. sigaction(SIGPIPE, &sa, NULL);
  16422. #endif
  16423. worker_thread_run((struct mg_connection *)thread_func_param);
  16424. return NULL;
  16425. }
  16426. #endif /* _WIN32 */
  16427. /* This is an internal function, thus all arguments are expected to be
  16428. * valid - a NULL check is not required. */
  16429. static void
  16430. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  16431. {
  16432. struct socket so;
  16433. char src_addr[IP_ADDR_STR_LEN];
  16434. socklen_t len = sizeof(so.rsa);
  16435. #if !defined(__ZEPHYR__)
  16436. int on = 1;
  16437. #endif
  16438. memset(&so, 0, sizeof(so));
  16439. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  16440. == INVALID_SOCKET) {
  16441. } else if (check_acl(ctx, &so.rsa) != 1) {
  16442. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  16443. mg_cry_ctx_internal(ctx,
  16444. "%s: %s is not allowed to connect",
  16445. __func__,
  16446. src_addr);
  16447. closesocket(so.sock);
  16448. } else {
  16449. /* Put so socket structure into the queue */
  16450. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  16451. set_close_on_exec(so.sock, NULL, ctx);
  16452. so.is_ssl = listener->is_ssl;
  16453. so.ssl_redir = listener->ssl_redir;
  16454. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  16455. mg_cry_ctx_internal(ctx,
  16456. "%s: getsockname() failed: %s",
  16457. __func__,
  16458. strerror(ERRNO));
  16459. }
  16460. #if !defined(__ZEPHYR__)
  16461. if ((so.lsa.sa.sa_family == AF_INET)
  16462. || (so.lsa.sa.sa_family == AF_INET6)) {
  16463. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  16464. * This is needed because if HTTP-level keep-alive
  16465. * is enabled, and client resets the connection, server won't get
  16466. * TCP FIN or RST and will keep the connection open forever. With
  16467. * TCP keep-alive, next keep-alive handshake will figure out that
  16468. * the client is down and will close the server end.
  16469. * Thanks to Igor Klopov who suggested the patch. */
  16470. if (setsockopt(so.sock,
  16471. SOL_SOCKET,
  16472. SO_KEEPALIVE,
  16473. (SOCK_OPT_TYPE)&on,
  16474. sizeof(on))
  16475. != 0) {
  16476. mg_cry_ctx_internal(
  16477. ctx,
  16478. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  16479. __func__,
  16480. strerror(ERRNO));
  16481. }
  16482. }
  16483. #endif
  16484. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  16485. * to effectively fill up the underlying IP packet payload and
  16486. * reduce the overhead of sending lots of small buffers. However
  16487. * this hurts the server's throughput (ie. operations per second)
  16488. * when HTTP 1.1 persistent connections are used and the responses
  16489. * are relatively small (eg. less than 1400 bytes).
  16490. */
  16491. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  16492. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  16493. if (set_tcp_nodelay(&so, 1) != 0) {
  16494. mg_cry_ctx_internal(
  16495. ctx,
  16496. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  16497. __func__,
  16498. strerror(ERRNO));
  16499. }
  16500. }
  16501. /* The "non blocking" property should already be
  16502. * inherited from the parent socket. Set it for
  16503. * non-compliant socket implementations. */
  16504. set_non_blocking_mode(so.sock);
  16505. so.in_use = 0;
  16506. produce_socket(ctx, &so);
  16507. }
  16508. }
  16509. static void
  16510. master_thread_run(struct mg_context *ctx)
  16511. {
  16512. struct mg_workerTLS tls;
  16513. struct mg_pollfd *pfd;
  16514. unsigned int i;
  16515. unsigned int workerthreadcount;
  16516. if (!ctx) {
  16517. return;
  16518. }
  16519. mg_set_thread_name("master");
  16520. /* Increase priority of the master thread */
  16521. #if defined(_WIN32)
  16522. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  16523. #elif defined(USE_MASTER_THREAD_PRIORITY)
  16524. int min_prio = sched_get_priority_min(SCHED_RR);
  16525. int max_prio = sched_get_priority_max(SCHED_RR);
  16526. if ((min_prio >= 0) && (max_prio >= 0)
  16527. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  16528. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  16529. struct sched_param sched_param = {0};
  16530. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  16531. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  16532. }
  16533. #endif
  16534. /* Initialize thread local storage */
  16535. #if defined(_WIN32)
  16536. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  16537. #endif
  16538. tls.is_master = 1;
  16539. pthread_setspecific(sTlsKey, &tls);
  16540. if (ctx->callbacks.init_thread) {
  16541. /* Callback for the master thread (type 0) */
  16542. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  16543. } else {
  16544. tls.user_ptr = NULL;
  16545. }
  16546. /* Lua background script "start" event */
  16547. #if defined(USE_LUA)
  16548. if (ctx->lua_background_state) {
  16549. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16550. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16551. /* call "start()" in Lua */
  16552. lua_getglobal(lstate, "start");
  16553. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16554. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16555. if (ret != 0) {
  16556. struct mg_connection fc;
  16557. lua_cry(fake_connection(&fc, ctx),
  16558. ret,
  16559. lstate,
  16560. "lua_background_script",
  16561. "start");
  16562. }
  16563. } else {
  16564. lua_pop(lstate, 1);
  16565. }
  16566. /* determine if there is a "log()" function in Lua background script */
  16567. lua_getglobal(lstate, "log");
  16568. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16569. ctx->lua_bg_log_available = 1;
  16570. }
  16571. lua_pop(lstate, 1);
  16572. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16573. }
  16574. #endif
  16575. /* Server starts *now* */
  16576. ctx->start_time = time(NULL);
  16577. /* Server accept loop */
  16578. pfd = ctx->listening_socket_fds;
  16579. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  16580. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16581. pfd[i].fd = ctx->listening_sockets[i].sock;
  16582. pfd[i].events = POLLIN;
  16583. }
  16584. if (mg_poll(pfd,
  16585. ctx->num_listening_sockets,
  16586. SOCKET_TIMEOUT_QUANTUM,
  16587. &(ctx->stop_flag))
  16588. > 0) {
  16589. for (i = 0; i < ctx->num_listening_sockets; i++) {
  16590. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  16591. * successful poll, and POLLIN is defined as
  16592. * (POLLRDNORM | POLLRDBAND)
  16593. * Therefore, we're checking pfd[i].revents & POLLIN, not
  16594. * pfd[i].revents == POLLIN. */
  16595. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  16596. && (pfd[i].revents & POLLIN)) {
  16597. accept_new_connection(&ctx->listening_sockets[i], ctx);
  16598. }
  16599. }
  16600. }
  16601. }
  16602. /* Here stop_flag is 1 - Initiate shutdown. */
  16603. DEBUG_TRACE("%s", "stopping workers");
  16604. /* Stop signal received: somebody called mg_stop. Quit. */
  16605. close_all_listening_sockets(ctx);
  16606. /* Wakeup workers that are waiting for connections to handle. */
  16607. #if defined(ALTERNATIVE_QUEUE)
  16608. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16609. event_signal(ctx->client_wait_events[i]);
  16610. }
  16611. #else
  16612. (void)pthread_mutex_lock(&ctx->thread_mutex);
  16613. pthread_cond_broadcast(&ctx->sq_full);
  16614. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  16615. #endif
  16616. /* Join all worker threads to avoid leaking threads. */
  16617. workerthreadcount = ctx->cfg_worker_threads;
  16618. for (i = 0; i < workerthreadcount; i++) {
  16619. if (ctx->worker_threadids[i] != 0) {
  16620. mg_join_thread(ctx->worker_threadids[i]);
  16621. }
  16622. }
  16623. #if defined(USE_LUA)
  16624. /* Free Lua state of lua background task */
  16625. if (ctx->lua_background_state) {
  16626. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  16627. ctx->lua_bg_log_available = 0;
  16628. /* call "stop()" in Lua */
  16629. pthread_mutex_lock(&ctx->lua_bg_mutex);
  16630. lua_getglobal(lstate, "stop");
  16631. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  16632. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  16633. if (ret != 0) {
  16634. struct mg_connection fc;
  16635. lua_cry(fake_connection(&fc, ctx),
  16636. ret,
  16637. lstate,
  16638. "lua_background_script",
  16639. "stop");
  16640. }
  16641. }
  16642. lua_close(lstate);
  16643. ctx->lua_background_state = 0;
  16644. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  16645. }
  16646. #endif
  16647. DEBUG_TRACE("%s", "exiting");
  16648. /* call exit thread callback */
  16649. if (ctx->callbacks.exit_thread) {
  16650. /* Callback for the master thread (type 0) */
  16651. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  16652. }
  16653. #if defined(_WIN32)
  16654. CloseHandle(tls.pthread_cond_helper_mutex);
  16655. #endif
  16656. pthread_setspecific(sTlsKey, NULL);
  16657. /* Signal mg_stop() that we're done.
  16658. * WARNING: This must be the very last thing this
  16659. * thread does, as ctx becomes invalid after this line. */
  16660. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  16661. }
  16662. /* Threads have different return types on Windows and Unix. */
  16663. #if defined(_WIN32)
  16664. static unsigned __stdcall master_thread(void *thread_func_param)
  16665. {
  16666. master_thread_run((struct mg_context *)thread_func_param);
  16667. return 0;
  16668. }
  16669. #else
  16670. static void *
  16671. master_thread(void *thread_func_param)
  16672. {
  16673. #if !defined(__ZEPHYR__)
  16674. struct sigaction sa;
  16675. /* Ignore SIGPIPE */
  16676. memset(&sa, 0, sizeof(sa));
  16677. sa.sa_handler = SIG_IGN;
  16678. sigaction(SIGPIPE, &sa, NULL);
  16679. #endif
  16680. master_thread_run((struct mg_context *)thread_func_param);
  16681. return NULL;
  16682. }
  16683. #endif /* _WIN32 */
  16684. static void
  16685. free_context(struct mg_context *ctx)
  16686. {
  16687. int i;
  16688. struct mg_handler_info *tmp_rh;
  16689. if (ctx == NULL) {
  16690. return;
  16691. }
  16692. /* Call user callback */
  16693. if (ctx->callbacks.exit_context) {
  16694. ctx->callbacks.exit_context(ctx);
  16695. }
  16696. /* All threads exited, no sync is needed. Destroy thread mutex and
  16697. * condvars
  16698. */
  16699. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  16700. #if defined(ALTERNATIVE_QUEUE)
  16701. mg_free(ctx->client_socks);
  16702. if (ctx->client_wait_events != NULL) {
  16703. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16704. event_destroy(ctx->client_wait_events[i]);
  16705. }
  16706. mg_free(ctx->client_wait_events);
  16707. }
  16708. #else
  16709. (void)pthread_cond_destroy(&ctx->sq_empty);
  16710. (void)pthread_cond_destroy(&ctx->sq_full);
  16711. mg_free(ctx->squeue);
  16712. #endif
  16713. /* Destroy other context global data structures mutex */
  16714. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  16715. #if defined(USE_LUA)
  16716. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  16717. #endif
  16718. /* Deallocate config parameters */
  16719. for (i = 0; i < NUM_OPTIONS; i++) {
  16720. if (ctx->dd.config[i] != NULL) {
  16721. #if defined(_MSC_VER)
  16722. #pragma warning(suppress : 6001)
  16723. #endif
  16724. mg_free(ctx->dd.config[i]);
  16725. }
  16726. }
  16727. /* Deallocate request handlers */
  16728. while (ctx->dd.handlers) {
  16729. tmp_rh = ctx->dd.handlers;
  16730. ctx->dd.handlers = tmp_rh->next;
  16731. mg_free(tmp_rh->uri);
  16732. mg_free(tmp_rh);
  16733. }
  16734. #if defined(USE_MBEDTLS)
  16735. if (ctx->dd.ssl_ctx != NULL) {
  16736. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  16737. mg_free(ctx->dd.ssl_ctx);
  16738. ctx->dd.ssl_ctx = NULL;
  16739. }
  16740. #elif !defined(NO_SSL)
  16741. /* Deallocate SSL context */
  16742. if (ctx->dd.ssl_ctx != NULL) {
  16743. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  16744. int callback_ret =
  16745. (ctx->callbacks.external_ssl_ctx == NULL)
  16746. ? 0
  16747. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  16748. if (callback_ret == 0) {
  16749. SSL_CTX_free(ctx->dd.ssl_ctx);
  16750. }
  16751. /* else: ignore error and ommit SSL_CTX_free in case
  16752. * callback_ret is 1 */
  16753. }
  16754. #endif /* !NO_SSL */
  16755. /* Deallocate worker thread ID array */
  16756. mg_free(ctx->worker_threadids);
  16757. /* Deallocate worker thread ID array */
  16758. mg_free(ctx->worker_connections);
  16759. /* deallocate system name string */
  16760. mg_free(ctx->systemName);
  16761. /* Deallocate context itself */
  16762. mg_free(ctx);
  16763. }
  16764. void
  16765. mg_stop(struct mg_context *ctx)
  16766. {
  16767. pthread_t mt;
  16768. if (!ctx) {
  16769. return;
  16770. }
  16771. /* We don't use a lock here. Calling mg_stop with the same ctx from
  16772. * two threads is not allowed. */
  16773. mt = ctx->masterthreadid;
  16774. if (mt == 0) {
  16775. return;
  16776. }
  16777. ctx->masterthreadid = 0;
  16778. /* Set stop flag, so all threads know they have to exit. */
  16779. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  16780. /* Join timer thread */
  16781. #if defined(USE_TIMERS)
  16782. timers_exit(ctx);
  16783. #endif
  16784. /* Wait until everything has stopped. */
  16785. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  16786. (void)mg_sleep(10);
  16787. }
  16788. /* Wait to stop master thread */
  16789. mg_join_thread(mt);
  16790. /* Close remaining Lua states */
  16791. #if defined(USE_LUA)
  16792. lua_ctx_exit(ctx);
  16793. #endif
  16794. /* Free memory */
  16795. free_context(ctx);
  16796. }
  16797. static void
  16798. get_system_name(char **sysName)
  16799. {
  16800. #if defined(_WIN32)
  16801. char name[128];
  16802. DWORD dwVersion = 0;
  16803. DWORD dwMajorVersion = 0;
  16804. DWORD dwMinorVersion = 0;
  16805. DWORD dwBuild = 0;
  16806. BOOL wowRet, isWoW = FALSE;
  16807. #if defined(_MSC_VER)
  16808. #pragma warning(push)
  16809. /* GetVersion was declared deprecated */
  16810. #pragma warning(disable : 4996)
  16811. #endif
  16812. dwVersion = GetVersion();
  16813. #if defined(_MSC_VER)
  16814. #pragma warning(pop)
  16815. #endif
  16816. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16817. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16818. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  16819. (void)dwBuild;
  16820. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  16821. sprintf(name,
  16822. "Windows %u.%u%s",
  16823. (unsigned)dwMajorVersion,
  16824. (unsigned)dwMinorVersion,
  16825. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  16826. *sysName = mg_strdup(name);
  16827. #elif defined(__ZEPHYR__)
  16828. *sysName = mg_strdup("Zephyr OS");
  16829. #else
  16830. struct utsname name;
  16831. memset(&name, 0, sizeof(name));
  16832. uname(&name);
  16833. *sysName = mg_strdup(name.sysname);
  16834. #endif
  16835. }
  16836. static void
  16837. legacy_init(const char **options)
  16838. {
  16839. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  16840. if (options) {
  16841. const char **run_options = options;
  16842. const char *optname = config_options[LISTENING_PORTS].name;
  16843. /* Try to find the "listening_ports" option */
  16844. while (*run_options) {
  16845. if (!strcmp(*run_options, optname)) {
  16846. ports_option = run_options[1];
  16847. }
  16848. run_options += 2;
  16849. }
  16850. }
  16851. if (is_ssl_port_used(ports_option)) {
  16852. /* Initialize with SSL support */
  16853. mg_init_library(MG_FEATURES_TLS);
  16854. } else {
  16855. /* Initialize without SSL support */
  16856. mg_init_library(MG_FEATURES_DEFAULT);
  16857. }
  16858. }
  16859. #if !defined(MG_EXPERIMENTAL_INTERFACES)
  16860. static
  16861. #endif
  16862. struct mg_context *
  16863. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  16864. {
  16865. struct mg_context *ctx;
  16866. const char *name, *value, *default_value;
  16867. int idx, ok, workerthreadcount;
  16868. unsigned int i;
  16869. int itmp;
  16870. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16871. const char **options =
  16872. ((init != NULL) ? (init->configuration_options) : (NULL));
  16873. struct mg_workerTLS tls;
  16874. if (error != NULL) {
  16875. error->code = 0;
  16876. if (error->text_buffer_size > 0) {
  16877. *error->text = 0;
  16878. }
  16879. }
  16880. if (mg_init_library_called == 0) {
  16881. /* Legacy INIT, if mg_start is called without mg_init_library.
  16882. * Note: This will cause a memory leak when unloading the library.
  16883. */
  16884. legacy_init(options);
  16885. }
  16886. if (mg_init_library_called == 0) {
  16887. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16888. mg_snprintf(NULL,
  16889. NULL, /* No truncation check for error buffers */
  16890. error->text,
  16891. error->text_buffer_size,
  16892. "%s",
  16893. "Library uninitialized");
  16894. }
  16895. return NULL;
  16896. }
  16897. /* Allocate context and initialize reasonable general case defaults. */
  16898. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16899. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16900. mg_snprintf(NULL,
  16901. NULL, /* No truncation check for error buffers */
  16902. error->text,
  16903. error->text_buffer_size,
  16904. "%s",
  16905. "Out of memory");
  16906. }
  16907. return NULL;
  16908. }
  16909. /* Random number generator will initialize at the first call */
  16910. ctx->dd.auth_nonce_mask =
  16911. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16912. /* Save started thread index to reuse in other external API calls
  16913. * For the sake of thread synchronization all non-civetweb threads
  16914. * can be considered as single external thread */
  16915. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16916. tls.is_master = -1; /* Thread calling mg_start */
  16917. tls.thread_idx = ctx->starter_thread_idx;
  16918. #if defined(_WIN32)
  16919. tls.pthread_cond_helper_mutex = NULL;
  16920. #endif
  16921. pthread_setspecific(sTlsKey, &tls);
  16922. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16923. #if !defined(ALTERNATIVE_QUEUE)
  16924. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16925. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16926. ctx->sq_blocked = 0;
  16927. #endif
  16928. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16929. #if defined(USE_LUA)
  16930. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  16931. #endif
  16932. if (!ok) {
  16933. const char *err_msg =
  16934. "Cannot initialize thread synchronization objects";
  16935. /* Fatal error - abort start. However, this situation should never
  16936. * occur in practice. */
  16937. mg_cry_ctx_internal(ctx, "%s", err_msg);
  16938. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16939. mg_snprintf(NULL,
  16940. NULL, /* No truncation check for error buffers */
  16941. error->text,
  16942. error->text_buffer_size,
  16943. "%s",
  16944. err_msg);
  16945. }
  16946. mg_free(ctx);
  16947. pthread_setspecific(sTlsKey, NULL);
  16948. return NULL;
  16949. }
  16950. if ((init != NULL) && (init->callbacks != NULL)) {
  16951. /* Set all callbacks except exit_context. */
  16952. ctx->callbacks = *init->callbacks;
  16953. exit_callback = init->callbacks->exit_context;
  16954. /* The exit callback is activated once the context is successfully
  16955. * created. It should not be called, if an incomplete context object
  16956. * is deleted during a failed initialization. */
  16957. ctx->callbacks.exit_context = 0;
  16958. }
  16959. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  16960. ctx->dd.handlers = NULL;
  16961. ctx->dd.next = NULL;
  16962. #if defined(USE_LUA)
  16963. lua_ctx_init(ctx);
  16964. #endif
  16965. /* Store options */
  16966. while (options && (name = *options++) != NULL) {
  16967. if ((idx = get_option_index(name)) == -1) {
  16968. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16969. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16970. mg_snprintf(NULL,
  16971. NULL, /* No truncation check for error buffers */
  16972. error->text,
  16973. error->text_buffer_size,
  16974. "Invalid configuration option: %s",
  16975. name);
  16976. }
  16977. free_context(ctx);
  16978. pthread_setspecific(sTlsKey, NULL);
  16979. return NULL;
  16980. } else if ((value = *options++) == NULL) {
  16981. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16982. if ((error != NULL) && (error->text_buffer_size > 0)) {
  16983. mg_snprintf(NULL,
  16984. NULL, /* No truncation check for error buffers */
  16985. error->text,
  16986. error->text_buffer_size,
  16987. "Invalid configuration option value: %s",
  16988. name);
  16989. }
  16990. free_context(ctx);
  16991. pthread_setspecific(sTlsKey, NULL);
  16992. return NULL;
  16993. }
  16994. if (ctx->dd.config[idx] != NULL) {
  16995. /* A duplicate configuration option is not an error - the last
  16996. * option value will be used. */
  16997. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16998. mg_free(ctx->dd.config[idx]);
  16999. }
  17000. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  17001. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17002. }
  17003. /* Set default value if needed */
  17004. for (i = 0; config_options[i].name != NULL; i++) {
  17005. default_value = config_options[i].default_value;
  17006. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  17007. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  17008. }
  17009. }
  17010. /* Request size option */
  17011. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  17012. if (itmp < 1024) {
  17013. mg_cry_ctx_internal(ctx,
  17014. "%s too small",
  17015. config_options[MAX_REQUEST_SIZE].name);
  17016. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17017. mg_snprintf(NULL,
  17018. NULL, /* No truncation check for error buffers */
  17019. error->text,
  17020. error->text_buffer_size,
  17021. "Invalid configuration option value: %s",
  17022. config_options[MAX_REQUEST_SIZE].name);
  17023. }
  17024. free_context(ctx);
  17025. pthread_setspecific(sTlsKey, NULL);
  17026. return NULL;
  17027. }
  17028. ctx->max_request_size = (unsigned)itmp;
  17029. /* Queue length */
  17030. #if !defined(ALTERNATIVE_QUEUE)
  17031. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  17032. if (itmp < 1) {
  17033. mg_cry_ctx_internal(ctx,
  17034. "%s too small",
  17035. config_options[CONNECTION_QUEUE_SIZE].name);
  17036. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17037. mg_snprintf(NULL,
  17038. NULL, /* No truncation check for error buffers */
  17039. error->text,
  17040. error->text_buffer_size,
  17041. "Invalid configuration option value: %s",
  17042. config_options[CONNECTION_QUEUE_SIZE].name);
  17043. }
  17044. free_context(ctx);
  17045. pthread_setspecific(sTlsKey, NULL);
  17046. return NULL;
  17047. }
  17048. ctx->squeue =
  17049. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  17050. if (ctx->squeue == NULL) {
  17051. mg_cry_ctx_internal(ctx,
  17052. "Out of memory: Cannot allocate %s",
  17053. config_options[CONNECTION_QUEUE_SIZE].name);
  17054. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17055. mg_snprintf(NULL,
  17056. NULL, /* No truncation check for error buffers */
  17057. error->text,
  17058. error->text_buffer_size,
  17059. "Out of memory: Cannot allocate %s",
  17060. config_options[CONNECTION_QUEUE_SIZE].name);
  17061. }
  17062. free_context(ctx);
  17063. pthread_setspecific(sTlsKey, NULL);
  17064. return NULL;
  17065. }
  17066. ctx->sq_size = itmp;
  17067. #endif
  17068. /* Worker thread count option */
  17069. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  17070. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  17071. if (workerthreadcount <= 0) {
  17072. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  17073. } else {
  17074. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  17075. }
  17076. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17077. mg_snprintf(NULL,
  17078. NULL, /* No truncation check for error buffers */
  17079. error->text,
  17080. error->text_buffer_size,
  17081. "Invalid configuration option value: %s",
  17082. config_options[NUM_THREADS].name);
  17083. }
  17084. free_context(ctx);
  17085. pthread_setspecific(sTlsKey, NULL);
  17086. return NULL;
  17087. }
  17088. /* Document root */
  17089. #if defined(NO_FILES)
  17090. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  17091. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  17092. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17093. mg_snprintf(NULL,
  17094. NULL, /* No truncation check for error buffers */
  17095. error->text,
  17096. error->text_buffer_size,
  17097. "Invalid configuration option value: %s",
  17098. config_options[DOCUMENT_ROOT].name);
  17099. }
  17100. free_context(ctx);
  17101. pthread_setspecific(sTlsKey, NULL);
  17102. return NULL;
  17103. }
  17104. #endif
  17105. get_system_name(&ctx->systemName);
  17106. #if defined(USE_LUA)
  17107. /* If a Lua background script has been configured, start it. */
  17108. ctx->lua_bg_log_available = 0;
  17109. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  17110. char ebuf[256];
  17111. struct vec opt_vec;
  17112. struct vec eq_vec;
  17113. const char *sparams;
  17114. memset(ebuf, 0, sizeof(ebuf));
  17115. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17116. /* Create a Lua state, load all standard libraries and the mg table */
  17117. lua_State *state = mg_lua_context_script_prepare(
  17118. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  17119. if (!state) {
  17120. mg_cry_ctx_internal(ctx,
  17121. "lua_background_script load error: %s",
  17122. ebuf);
  17123. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17124. mg_snprintf(NULL,
  17125. NULL, /* No truncation check for error buffers */
  17126. error->text,
  17127. error->text_buffer_size,
  17128. "Error in script %s: %s",
  17129. config_options[LUA_BACKGROUND_SCRIPT].name,
  17130. ebuf);
  17131. }
  17132. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17133. free_context(ctx);
  17134. pthread_setspecific(sTlsKey, NULL);
  17135. return NULL;
  17136. }
  17137. /* Add a table with parameters into mg.params */
  17138. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  17139. if (sparams && sparams[0]) {
  17140. lua_getglobal(state, "mg");
  17141. lua_pushstring(state, "params");
  17142. lua_newtable(state);
  17143. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  17144. != NULL) {
  17145. reg_llstring(
  17146. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  17147. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  17148. break;
  17149. }
  17150. lua_rawset(state, -3);
  17151. lua_pop(state, 1);
  17152. }
  17153. /* Call script */
  17154. state = mg_lua_context_script_run(state,
  17155. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  17156. ctx,
  17157. ebuf,
  17158. sizeof(ebuf));
  17159. if (!state) {
  17160. mg_cry_ctx_internal(ctx,
  17161. "lua_background_script start error: %s",
  17162. ebuf);
  17163. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17164. mg_snprintf(NULL,
  17165. NULL, /* No truncation check for error buffers */
  17166. error->text,
  17167. error->text_buffer_size,
  17168. "Error in script %s: %s",
  17169. config_options[DOCUMENT_ROOT].name,
  17170. ebuf);
  17171. }
  17172. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17173. free_context(ctx);
  17174. pthread_setspecific(sTlsKey, NULL);
  17175. return NULL;
  17176. }
  17177. /* state remains valid */
  17178. ctx->lua_background_state = (void *)state;
  17179. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17180. } else {
  17181. ctx->lua_background_state = 0;
  17182. }
  17183. #endif
  17184. /* Step by step initialization of ctx - depending on build options */
  17185. #if !defined(NO_FILESYSTEMS)
  17186. if (!set_gpass_option(ctx, NULL)) {
  17187. const char *err_msg = "Invalid global password file";
  17188. /* Fatal error - abort start. */
  17189. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17190. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17191. mg_snprintf(NULL,
  17192. NULL, /* No truncation check for error buffers */
  17193. error->text,
  17194. error->text_buffer_size,
  17195. "%s",
  17196. err_msg);
  17197. }
  17198. free_context(ctx);
  17199. pthread_setspecific(sTlsKey, NULL);
  17200. return NULL;
  17201. }
  17202. #endif
  17203. #if defined(USE_MBEDTLS)
  17204. if (!mg_sslctx_init(ctx, NULL)) {
  17205. const char *err_msg = "Error initializing SSL context";
  17206. /* Fatal error - abort start. */
  17207. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17208. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17209. mg_snprintf(NULL,
  17210. NULL, /* No truncation check for error buffers */
  17211. error->text,
  17212. error->text_buffer_size,
  17213. "%s",
  17214. err_msg);
  17215. }
  17216. free_context(ctx);
  17217. pthread_setspecific(sTlsKey, NULL);
  17218. return NULL;
  17219. }
  17220. #elif !defined(NO_SSL)
  17221. if (!init_ssl_ctx(ctx, NULL)) {
  17222. const char *err_msg = "Error initializing SSL context";
  17223. /* Fatal error - abort start. */
  17224. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17225. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17226. mg_snprintf(NULL,
  17227. NULL, /* No truncation check for error buffers */
  17228. error->text,
  17229. error->text_buffer_size,
  17230. "%s",
  17231. err_msg);
  17232. }
  17233. free_context(ctx);
  17234. pthread_setspecific(sTlsKey, NULL);
  17235. return NULL;
  17236. }
  17237. #endif
  17238. if (!set_ports_option(ctx)) {
  17239. const char *err_msg = "Failed to setup server ports";
  17240. /* Fatal error - abort start. */
  17241. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17242. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17243. mg_snprintf(NULL,
  17244. NULL, /* No truncation check for error buffers */
  17245. error->text,
  17246. error->text_buffer_size,
  17247. "%s",
  17248. err_msg);
  17249. }
  17250. free_context(ctx);
  17251. pthread_setspecific(sTlsKey, NULL);
  17252. return NULL;
  17253. }
  17254. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  17255. if (!set_uid_option(ctx)) {
  17256. const char *err_msg = "Failed to run as configured user";
  17257. /* Fatal error - abort start. */
  17258. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17259. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17260. mg_snprintf(NULL,
  17261. NULL, /* No truncation check for error buffers */
  17262. error->text,
  17263. error->text_buffer_size,
  17264. "%s",
  17265. err_msg);
  17266. }
  17267. free_context(ctx);
  17268. pthread_setspecific(sTlsKey, NULL);
  17269. return NULL;
  17270. }
  17271. #endif
  17272. if (!set_acl_option(ctx)) {
  17273. const char *err_msg = "Failed to setup access control list";
  17274. /* Fatal error - abort start. */
  17275. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17276. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17277. mg_snprintf(NULL,
  17278. NULL, /* No truncation check for error buffers */
  17279. error->text,
  17280. error->text_buffer_size,
  17281. "%s",
  17282. err_msg);
  17283. }
  17284. free_context(ctx);
  17285. pthread_setspecific(sTlsKey, NULL);
  17286. return NULL;
  17287. }
  17288. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  17289. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17290. sizeof(pthread_t),
  17291. ctx);
  17292. if (ctx->worker_threadids == NULL) {
  17293. const char *err_msg = "Not enough memory for worker thread ID array";
  17294. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17295. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17296. mg_snprintf(NULL,
  17297. NULL, /* No truncation check for error buffers */
  17298. error->text,
  17299. error->text_buffer_size,
  17300. "%s",
  17301. err_msg);
  17302. }
  17303. free_context(ctx);
  17304. pthread_setspecific(sTlsKey, NULL);
  17305. return NULL;
  17306. }
  17307. ctx->worker_connections =
  17308. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17309. sizeof(struct mg_connection),
  17310. ctx);
  17311. if (ctx->worker_connections == NULL) {
  17312. const char *err_msg =
  17313. "Not enough memory for worker thread connection array";
  17314. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17315. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17316. mg_snprintf(NULL,
  17317. NULL, /* No truncation check for error buffers */
  17318. error->text,
  17319. error->text_buffer_size,
  17320. "%s",
  17321. err_msg);
  17322. }
  17323. free_context(ctx);
  17324. pthread_setspecific(sTlsKey, NULL);
  17325. return NULL;
  17326. }
  17327. #if defined(ALTERNATIVE_QUEUE)
  17328. ctx->client_wait_events =
  17329. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  17330. sizeof(ctx->client_wait_events[0]),
  17331. ctx);
  17332. if (ctx->client_wait_events == NULL) {
  17333. const char *err_msg = "Not enough memory for worker event array";
  17334. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17335. mg_free(ctx->worker_threadids);
  17336. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17337. mg_snprintf(NULL,
  17338. NULL, /* No truncation check for error buffers */
  17339. error->text,
  17340. error->text_buffer_size,
  17341. "%s",
  17342. err_msg);
  17343. }
  17344. free_context(ctx);
  17345. pthread_setspecific(sTlsKey, NULL);
  17346. return NULL;
  17347. }
  17348. ctx->client_socks =
  17349. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  17350. sizeof(ctx->client_socks[0]),
  17351. ctx);
  17352. if (ctx->client_socks == NULL) {
  17353. const char *err_msg = "Not enough memory for worker socket array";
  17354. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17355. mg_free(ctx->client_wait_events);
  17356. mg_free(ctx->worker_threadids);
  17357. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17358. mg_snprintf(NULL,
  17359. NULL, /* No truncation check for error buffers */
  17360. error->text,
  17361. error->text_buffer_size,
  17362. "%s",
  17363. err_msg);
  17364. }
  17365. free_context(ctx);
  17366. pthread_setspecific(sTlsKey, NULL);
  17367. return NULL;
  17368. }
  17369. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  17370. ctx->client_wait_events[i] = event_create();
  17371. if (ctx->client_wait_events[i] == 0) {
  17372. const char *err_msg = "Error creating worker event %i";
  17373. mg_cry_ctx_internal(ctx, err_msg, i);
  17374. while (i > 0) {
  17375. i--;
  17376. event_destroy(ctx->client_wait_events[i]);
  17377. }
  17378. mg_free(ctx->client_socks);
  17379. mg_free(ctx->client_wait_events);
  17380. mg_free(ctx->worker_threadids);
  17381. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17382. mg_snprintf(NULL,
  17383. NULL, /* No truncation check for error buffers */
  17384. error->text,
  17385. error->text_buffer_size,
  17386. err_msg,
  17387. i);
  17388. }
  17389. free_context(ctx);
  17390. pthread_setspecific(sTlsKey, NULL);
  17391. return NULL;
  17392. }
  17393. }
  17394. #endif
  17395. #if defined(USE_TIMERS)
  17396. if (timers_init(ctx) != 0) {
  17397. const char *err_msg = "Error creating timers";
  17398. mg_cry_ctx_internal(ctx, "%s", err_msg);
  17399. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17400. mg_snprintf(NULL,
  17401. NULL, /* No truncation check for error buffers */
  17402. error->text,
  17403. error->text_buffer_size,
  17404. "%s",
  17405. err_msg);
  17406. }
  17407. free_context(ctx);
  17408. pthread_setspecific(sTlsKey, NULL);
  17409. return NULL;
  17410. }
  17411. #endif
  17412. /* Context has been created - init user libraries */
  17413. if (ctx->callbacks.init_context) {
  17414. ctx->callbacks.init_context(ctx);
  17415. }
  17416. /* From now, the context is successfully created.
  17417. * When it is destroyed, the exit callback should be called. */
  17418. ctx->callbacks.exit_context = exit_callback;
  17419. ctx->context_type = CONTEXT_SERVER; /* server context */
  17420. /* Start worker threads */
  17421. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  17422. /* worker_thread sets up the other fields */
  17423. ctx->worker_connections[i].phys_ctx = ctx;
  17424. if (mg_start_thread_with_id(worker_thread,
  17425. &ctx->worker_connections[i],
  17426. &ctx->worker_threadids[i])
  17427. != 0) {
  17428. long error_no = (long)ERRNO;
  17429. /* thread was not created */
  17430. if (i > 0) {
  17431. /* If the second, third, ... thread cannot be created, set a
  17432. * warning, but keep running. */
  17433. mg_cry_ctx_internal(ctx,
  17434. "Cannot start worker thread %i: error %ld",
  17435. i + 1,
  17436. error_no);
  17437. /* If the server initialization should stop here, all
  17438. * threads that have already been created must be stopped
  17439. * first, before any free_context(ctx) call.
  17440. */
  17441. } else {
  17442. /* If the first worker thread cannot be created, stop
  17443. * initialization and free the entire server context. */
  17444. mg_cry_ctx_internal(ctx,
  17445. "Cannot create threads: error %ld",
  17446. error_no);
  17447. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17448. mg_snprintf(
  17449. NULL,
  17450. NULL, /* No truncation check for error buffers */
  17451. error->text,
  17452. error->text_buffer_size,
  17453. "Cannot create first worker thread: error %ld",
  17454. error_no);
  17455. }
  17456. free_context(ctx);
  17457. pthread_setspecific(sTlsKey, NULL);
  17458. return NULL;
  17459. }
  17460. break;
  17461. }
  17462. }
  17463. /* Start master (listening) thread */
  17464. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  17465. pthread_setspecific(sTlsKey, NULL);
  17466. return ctx;
  17467. }
  17468. struct mg_context *
  17469. mg_start(const struct mg_callbacks *callbacks,
  17470. void *user_data,
  17471. const char **options)
  17472. {
  17473. struct mg_init_data init = {0};
  17474. init.callbacks = callbacks;
  17475. init.user_data = user_data;
  17476. init.configuration_options = options;
  17477. return mg_start2(&init, NULL);
  17478. }
  17479. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17480. /* Add an additional domain to an already running web server. */
  17481. int
  17482. mg_start_domain2(struct mg_context *ctx,
  17483. const char **options,
  17484. struct mg_error_data *error)
  17485. {
  17486. const char *name;
  17487. const char *value;
  17488. const char *default_value;
  17489. struct mg_domain_context *new_dom;
  17490. struct mg_domain_context *dom;
  17491. int idx, i;
  17492. if (error != NULL) {
  17493. error->code = 0;
  17494. if (error->text_buffer_size > 0) {
  17495. *error->text = 0;
  17496. }
  17497. }
  17498. if ((ctx == NULL) || (options == NULL)) {
  17499. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17500. mg_snprintf(NULL,
  17501. NULL, /* No truncation check for error buffers */
  17502. error->text,
  17503. error->text_buffer_size,
  17504. "%s",
  17505. "Invalid parameters");
  17506. }
  17507. return -1;
  17508. }
  17509. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17510. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17511. mg_snprintf(NULL,
  17512. NULL, /* No truncation check for error buffers */
  17513. error->text,
  17514. error->text_buffer_size,
  17515. "%s",
  17516. "Server already stopped");
  17517. }
  17518. return -1;
  17519. }
  17520. new_dom = (struct mg_domain_context *)
  17521. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  17522. if (!new_dom) {
  17523. /* Out of memory */
  17524. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17525. mg_snprintf(NULL,
  17526. NULL, /* No truncation check for error buffers */
  17527. error->text,
  17528. error->text_buffer_size,
  17529. "%s",
  17530. "Out or memory");
  17531. }
  17532. return -6;
  17533. }
  17534. /* Store options - TODO: unite duplicate code */
  17535. while (options && (name = *options++) != NULL) {
  17536. if ((idx = get_option_index(name)) == -1) {
  17537. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  17538. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17539. mg_snprintf(NULL,
  17540. NULL, /* No truncation check for error buffers */
  17541. error->text,
  17542. error->text_buffer_size,
  17543. "Invalid option: %s",
  17544. name);
  17545. }
  17546. mg_free(new_dom);
  17547. return -2;
  17548. } else if ((value = *options++) == NULL) {
  17549. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  17550. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17551. mg_snprintf(NULL,
  17552. NULL, /* No truncation check for error buffers */
  17553. error->text,
  17554. error->text_buffer_size,
  17555. "Invalid option value: %s",
  17556. name);
  17557. }
  17558. mg_free(new_dom);
  17559. return -2;
  17560. }
  17561. if (new_dom->config[idx] != NULL) {
  17562. /* Duplicate option: Later values overwrite earlier ones. */
  17563. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  17564. mg_free(new_dom->config[idx]);
  17565. }
  17566. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  17567. DEBUG_TRACE("[%s] -> [%s]", name, value);
  17568. }
  17569. /* Authentication domain is mandatory */
  17570. /* TODO: Maybe use a new option hostname? */
  17571. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  17572. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  17573. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17574. mg_snprintf(NULL,
  17575. NULL, /* No truncation check for error buffers */
  17576. error->text,
  17577. error->text_buffer_size,
  17578. "Mandatory option %s missing",
  17579. config_options[AUTHENTICATION_DOMAIN].name);
  17580. }
  17581. mg_free(new_dom);
  17582. return -4;
  17583. }
  17584. /* Set default value if needed. Take the config value from
  17585. * ctx as a default value. */
  17586. for (i = 0; config_options[i].name != NULL; i++) {
  17587. default_value = ctx->dd.config[i];
  17588. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  17589. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  17590. }
  17591. }
  17592. new_dom->handlers = NULL;
  17593. new_dom->next = NULL;
  17594. new_dom->nonce_count = 0;
  17595. new_dom->auth_nonce_mask =
  17596. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  17597. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  17598. new_dom->shared_lua_websockets = NULL;
  17599. #endif
  17600. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  17601. if (!init_ssl_ctx(ctx, new_dom)) {
  17602. /* Init SSL failed */
  17603. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17604. mg_snprintf(NULL,
  17605. NULL, /* No truncation check for error buffers */
  17606. error->text,
  17607. error->text_buffer_size,
  17608. "%s",
  17609. "Initializing SSL context failed");
  17610. }
  17611. mg_free(new_dom);
  17612. return -3;
  17613. }
  17614. #endif
  17615. /* Add element to linked list. */
  17616. mg_lock_context(ctx);
  17617. idx = 0;
  17618. dom = &(ctx->dd);
  17619. for (;;) {
  17620. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  17621. dom->config[AUTHENTICATION_DOMAIN])) {
  17622. /* Domain collision */
  17623. mg_cry_ctx_internal(ctx,
  17624. "domain %s already in use",
  17625. new_dom->config[AUTHENTICATION_DOMAIN]);
  17626. if ((error != NULL) && (error->text_buffer_size > 0)) {
  17627. mg_snprintf(NULL,
  17628. NULL, /* No truncation check for error buffers */
  17629. error->text,
  17630. error->text_buffer_size,
  17631. "Domain %s specified by %s is already in use",
  17632. new_dom->config[AUTHENTICATION_DOMAIN],
  17633. config_options[AUTHENTICATION_DOMAIN].name);
  17634. }
  17635. mg_free(new_dom);
  17636. mg_unlock_context(ctx);
  17637. return -5;
  17638. }
  17639. /* Count number of domains */
  17640. idx++;
  17641. if (dom->next == NULL) {
  17642. dom->next = new_dom;
  17643. break;
  17644. }
  17645. dom = dom->next;
  17646. }
  17647. mg_unlock_context(ctx);
  17648. /* Return domain number */
  17649. return idx;
  17650. }
  17651. int
  17652. mg_start_domain(struct mg_context *ctx, const char **options)
  17653. {
  17654. return mg_start_domain2(ctx, options, NULL);
  17655. }
  17656. #endif
  17657. /* Feature check API function */
  17658. unsigned
  17659. mg_check_feature(unsigned feature)
  17660. {
  17661. static const unsigned feature_set = 0
  17662. /* Set bits for available features according to API documentation.
  17663. * This bit mask is created at compile time, according to the active
  17664. * preprocessor defines. It is a single const value at runtime. */
  17665. #if !defined(NO_FILES)
  17666. | MG_FEATURES_FILES
  17667. #endif
  17668. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  17669. | MG_FEATURES_SSL
  17670. #endif
  17671. #if !defined(NO_CGI)
  17672. | MG_FEATURES_CGI
  17673. #endif
  17674. #if defined(USE_IPV6)
  17675. | MG_FEATURES_IPV6
  17676. #endif
  17677. #if defined(USE_WEBSOCKET)
  17678. | MG_FEATURES_WEBSOCKET
  17679. #endif
  17680. #if defined(USE_LUA)
  17681. | MG_FEATURES_LUA
  17682. #endif
  17683. #if defined(USE_DUKTAPE)
  17684. | MG_FEATURES_SSJS
  17685. #endif
  17686. #if !defined(NO_CACHING)
  17687. | MG_FEATURES_CACHE
  17688. #endif
  17689. #if defined(USE_SERVER_STATS)
  17690. | MG_FEATURES_STATS
  17691. #endif
  17692. #if defined(USE_ZLIB)
  17693. | MG_FEATURES_COMPRESSION
  17694. #endif
  17695. #if defined(USE_HTTP2)
  17696. | MG_FEATURES_HTTP2
  17697. #endif
  17698. #if defined(USE_X_DOM_SOCKET)
  17699. | MG_FEATURES_X_DOMAIN_SOCKET
  17700. #endif
  17701. /* Set some extra bits not defined in the API documentation.
  17702. * These bits may change without further notice. */
  17703. #if defined(MG_LEGACY_INTERFACE)
  17704. | 0x80000000u
  17705. #endif
  17706. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17707. | 0x40000000u
  17708. #endif
  17709. #if !defined(NO_RESPONSE_BUFFERING)
  17710. | 0x20000000u
  17711. #endif
  17712. #if defined(MEMORY_DEBUGGING)
  17713. | 0x10000000u
  17714. #endif
  17715. ;
  17716. return (feature & feature_set);
  17717. }
  17718. static size_t
  17719. mg_str_append(char **dst, char *end, const char *src)
  17720. {
  17721. size_t len = strlen(src);
  17722. if (*dst != end) {
  17723. /* Append src if enough space, or close dst. */
  17724. if ((size_t)(end - *dst) > len) {
  17725. strcpy(*dst, src);
  17726. *dst += len;
  17727. } else {
  17728. *dst = end;
  17729. }
  17730. }
  17731. return len;
  17732. }
  17733. /* Get system information. It can be printed or stored by the caller.
  17734. * Return the size of available information. */
  17735. int
  17736. mg_get_system_info(char *buffer, int buflen)
  17737. {
  17738. char *end, *append_eoobj = NULL, block[256];
  17739. size_t system_info_length = 0;
  17740. #if defined(_WIN32)
  17741. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  17742. #else
  17743. static const char eol[] = "\n", eoobj[] = "\n}\n";
  17744. #endif
  17745. if ((buffer == NULL) || (buflen < 1)) {
  17746. buflen = 0;
  17747. end = buffer;
  17748. } else {
  17749. *buffer = 0;
  17750. end = buffer + buflen;
  17751. }
  17752. if (buflen > (int)(sizeof(eoobj) - 1)) {
  17753. /* has enough space to append eoobj */
  17754. append_eoobj = buffer;
  17755. if (end) {
  17756. end -= sizeof(eoobj) - 1;
  17757. }
  17758. }
  17759. system_info_length += mg_str_append(&buffer, end, "{");
  17760. /* Server version */
  17761. {
  17762. const char *version = mg_version();
  17763. mg_snprintf(NULL,
  17764. NULL,
  17765. block,
  17766. sizeof(block),
  17767. "%s\"version\" : \"%s\"",
  17768. eol,
  17769. version);
  17770. system_info_length += mg_str_append(&buffer, end, block);
  17771. }
  17772. /* System info */
  17773. {
  17774. #if defined(_WIN32)
  17775. DWORD dwVersion = 0;
  17776. DWORD dwMajorVersion = 0;
  17777. DWORD dwMinorVersion = 0;
  17778. SYSTEM_INFO si;
  17779. GetSystemInfo(&si);
  17780. #if defined(_MSC_VER)
  17781. #pragma warning(push)
  17782. /* GetVersion was declared deprecated */
  17783. #pragma warning(disable : 4996)
  17784. #endif
  17785. dwVersion = GetVersion();
  17786. #if defined(_MSC_VER)
  17787. #pragma warning(pop)
  17788. #endif
  17789. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17790. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17791. mg_snprintf(NULL,
  17792. NULL,
  17793. block,
  17794. sizeof(block),
  17795. ",%s\"os\" : \"Windows %u.%u\"",
  17796. eol,
  17797. (unsigned)dwMajorVersion,
  17798. (unsigned)dwMinorVersion);
  17799. system_info_length += mg_str_append(&buffer, end, block);
  17800. mg_snprintf(NULL,
  17801. NULL,
  17802. block,
  17803. sizeof(block),
  17804. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  17805. eol,
  17806. (unsigned)si.wProcessorArchitecture,
  17807. (unsigned)si.dwNumberOfProcessors,
  17808. (unsigned)si.dwActiveProcessorMask);
  17809. system_info_length += mg_str_append(&buffer, end, block);
  17810. #elif defined(__ZEPHYR__)
  17811. mg_snprintf(NULL,
  17812. NULL,
  17813. block,
  17814. sizeof(block),
  17815. ",%s\"os\" : \"%s %s\"",
  17816. eol,
  17817. "Zephyr OS",
  17818. ZEPHYR_VERSION);
  17819. system_info_length += mg_str_append(&buffer, end, block);
  17820. #else
  17821. struct utsname name;
  17822. memset(&name, 0, sizeof(name));
  17823. uname(&name);
  17824. mg_snprintf(NULL,
  17825. NULL,
  17826. block,
  17827. sizeof(block),
  17828. ",%s\"os\" : \"%s %s (%s) - %s\"",
  17829. eol,
  17830. name.sysname,
  17831. name.version,
  17832. name.release,
  17833. name.machine);
  17834. system_info_length += mg_str_append(&buffer, end, block);
  17835. #endif
  17836. }
  17837. /* Features */
  17838. {
  17839. mg_snprintf(NULL,
  17840. NULL,
  17841. block,
  17842. sizeof(block),
  17843. ",%s\"features\" : %lu"
  17844. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  17845. eol,
  17846. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  17847. eol,
  17848. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  17849. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  17850. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  17851. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  17852. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  17853. : "",
  17854. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  17855. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  17856. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  17857. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  17858. system_info_length += mg_str_append(&buffer, end, block);
  17859. #if defined(USE_LUA)
  17860. mg_snprintf(NULL,
  17861. NULL,
  17862. block,
  17863. sizeof(block),
  17864. ",%s\"lua_version\" : \"%u (%s)\"",
  17865. eol,
  17866. (unsigned)LUA_VERSION_NUM,
  17867. LUA_RELEASE);
  17868. system_info_length += mg_str_append(&buffer, end, block);
  17869. #endif
  17870. #if defined(USE_DUKTAPE)
  17871. mg_snprintf(NULL,
  17872. NULL,
  17873. block,
  17874. sizeof(block),
  17875. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  17876. eol,
  17877. (unsigned)DUK_VERSION / 10000,
  17878. ((unsigned)DUK_VERSION / 100) % 100,
  17879. (unsigned)DUK_VERSION % 100);
  17880. system_info_length += mg_str_append(&buffer, end, block);
  17881. #endif
  17882. }
  17883. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  17884. {
  17885. #if defined(BUILD_DATE)
  17886. const char *bd = BUILD_DATE;
  17887. #else
  17888. #if defined(GCC_DIAGNOSTIC)
  17889. #if GCC_VERSION >= 40900
  17890. #pragma GCC diagnostic push
  17891. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  17892. * does not work in some versions. If "BUILD_DATE" is defined to some
  17893. * string, it is used instead of __DATE__. */
  17894. #pragma GCC diagnostic ignored "-Wdate-time"
  17895. #endif
  17896. #endif
  17897. const char *bd = __DATE__;
  17898. #if defined(GCC_DIAGNOSTIC)
  17899. #if GCC_VERSION >= 40900
  17900. #pragma GCC diagnostic pop
  17901. #endif
  17902. #endif
  17903. #endif
  17904. mg_snprintf(
  17905. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  17906. system_info_length += mg_str_append(&buffer, end, block);
  17907. }
  17908. /* Compiler information */
  17909. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  17910. {
  17911. #if defined(_MSC_VER)
  17912. mg_snprintf(NULL,
  17913. NULL,
  17914. block,
  17915. sizeof(block),
  17916. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  17917. eol,
  17918. (unsigned)_MSC_VER,
  17919. (unsigned)_MSC_FULL_VER);
  17920. system_info_length += mg_str_append(&buffer, end, block);
  17921. #elif defined(__MINGW64__)
  17922. mg_snprintf(NULL,
  17923. NULL,
  17924. block,
  17925. sizeof(block),
  17926. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  17927. eol,
  17928. (unsigned)__MINGW64_VERSION_MAJOR,
  17929. (unsigned)__MINGW64_VERSION_MINOR);
  17930. system_info_length += mg_str_append(&buffer, end, block);
  17931. mg_snprintf(NULL,
  17932. NULL,
  17933. block,
  17934. sizeof(block),
  17935. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17936. eol,
  17937. (unsigned)__MINGW32_MAJOR_VERSION,
  17938. (unsigned)__MINGW32_MINOR_VERSION);
  17939. system_info_length += mg_str_append(&buffer, end, block);
  17940. #elif defined(__MINGW32__)
  17941. mg_snprintf(NULL,
  17942. NULL,
  17943. block,
  17944. sizeof(block),
  17945. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  17946. eol,
  17947. (unsigned)__MINGW32_MAJOR_VERSION,
  17948. (unsigned)__MINGW32_MINOR_VERSION);
  17949. system_info_length += mg_str_append(&buffer, end, block);
  17950. #elif defined(__clang__)
  17951. mg_snprintf(NULL,
  17952. NULL,
  17953. block,
  17954. sizeof(block),
  17955. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  17956. eol,
  17957. __clang_major__,
  17958. __clang_minor__,
  17959. __clang_patchlevel__,
  17960. __clang_version__);
  17961. system_info_length += mg_str_append(&buffer, end, block);
  17962. #elif defined(__GNUC__)
  17963. mg_snprintf(NULL,
  17964. NULL,
  17965. block,
  17966. sizeof(block),
  17967. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  17968. eol,
  17969. (unsigned)__GNUC__,
  17970. (unsigned)__GNUC_MINOR__,
  17971. (unsigned)__GNUC_PATCHLEVEL__);
  17972. system_info_length += mg_str_append(&buffer, end, block);
  17973. #elif defined(__INTEL_COMPILER)
  17974. mg_snprintf(NULL,
  17975. NULL,
  17976. block,
  17977. sizeof(block),
  17978. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  17979. eol,
  17980. (unsigned)__INTEL_COMPILER);
  17981. system_info_length += mg_str_append(&buffer, end, block);
  17982. #elif defined(__BORLANDC__)
  17983. mg_snprintf(NULL,
  17984. NULL,
  17985. block,
  17986. sizeof(block),
  17987. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  17988. eol,
  17989. (unsigned)__BORLANDC__);
  17990. system_info_length += mg_str_append(&buffer, end, block);
  17991. #elif defined(__SUNPRO_C)
  17992. mg_snprintf(NULL,
  17993. NULL,
  17994. block,
  17995. sizeof(block),
  17996. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  17997. eol,
  17998. (unsigned)__SUNPRO_C);
  17999. system_info_length += mg_str_append(&buffer, end, block);
  18000. #else
  18001. mg_snprintf(NULL,
  18002. NULL,
  18003. block,
  18004. sizeof(block),
  18005. ",%s\"compiler\" : \"other\"",
  18006. eol);
  18007. system_info_length += mg_str_append(&buffer, end, block);
  18008. #endif
  18009. }
  18010. /* Determine 32/64 bit data mode.
  18011. * see https://en.wikipedia.org/wiki/64-bit_computing */
  18012. {
  18013. mg_snprintf(NULL,
  18014. NULL,
  18015. block,
  18016. sizeof(block),
  18017. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  18018. "char:%u/%u, "
  18019. "ptr:%u, size:%u, time:%u\"",
  18020. eol,
  18021. (unsigned)sizeof(short),
  18022. (unsigned)sizeof(int),
  18023. (unsigned)sizeof(long),
  18024. (unsigned)sizeof(long long),
  18025. (unsigned)sizeof(float),
  18026. (unsigned)sizeof(double),
  18027. (unsigned)sizeof(long double),
  18028. (unsigned)sizeof(char),
  18029. (unsigned)sizeof(wchar_t),
  18030. (unsigned)sizeof(void *),
  18031. (unsigned)sizeof(size_t),
  18032. (unsigned)sizeof(time_t));
  18033. system_info_length += mg_str_append(&buffer, end, block);
  18034. }
  18035. /* Terminate string */
  18036. if (append_eoobj) {
  18037. strcat(append_eoobj, eoobj);
  18038. }
  18039. system_info_length += sizeof(eoobj) - 1;
  18040. return (int)system_info_length;
  18041. }
  18042. /* Get context information. It can be printed or stored by the caller.
  18043. * Return the size of available information. */
  18044. int
  18045. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  18046. {
  18047. #if defined(USE_SERVER_STATS)
  18048. char *end, *append_eoobj = NULL, block[256];
  18049. size_t context_info_length = 0;
  18050. #if defined(_WIN32)
  18051. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18052. #else
  18053. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18054. #endif
  18055. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  18056. if ((buffer == NULL) || (buflen < 1)) {
  18057. buflen = 0;
  18058. end = buffer;
  18059. } else {
  18060. *buffer = 0;
  18061. end = buffer + buflen;
  18062. }
  18063. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18064. /* has enough space to append eoobj */
  18065. append_eoobj = buffer;
  18066. end -= sizeof(eoobj) - 1;
  18067. }
  18068. context_info_length += mg_str_append(&buffer, end, "{");
  18069. if (ms) { /* <-- should be always true */
  18070. /* Memory information */
  18071. int blockCount = (int)ms->blockCount;
  18072. int64_t totalMemUsed = ms->totalMemUsed;
  18073. int64_t maxMemUsed = ms->maxMemUsed;
  18074. if (totalMemUsed > maxMemUsed) {
  18075. maxMemUsed = totalMemUsed;
  18076. }
  18077. mg_snprintf(NULL,
  18078. NULL,
  18079. block,
  18080. sizeof(block),
  18081. "%s\"memory\" : {%s"
  18082. "\"blocks\" : %i,%s"
  18083. "\"used\" : %" INT64_FMT ",%s"
  18084. "\"maxUsed\" : %" INT64_FMT "%s"
  18085. "}",
  18086. eol,
  18087. eol,
  18088. blockCount,
  18089. eol,
  18090. totalMemUsed,
  18091. eol,
  18092. maxMemUsed,
  18093. eol);
  18094. context_info_length += mg_str_append(&buffer, end, block);
  18095. }
  18096. if (ctx) {
  18097. /* Declare all variables at begin of the block, to comply
  18098. * with old C standards. */
  18099. char start_time_str[64] = {0};
  18100. char now_str[64] = {0};
  18101. time_t start_time = ctx->start_time;
  18102. time_t now = time(NULL);
  18103. int64_t total_data_read, total_data_written;
  18104. int active_connections = (int)ctx->active_connections;
  18105. int max_active_connections = (int)ctx->max_active_connections;
  18106. int total_connections = (int)ctx->total_connections;
  18107. if (active_connections > max_active_connections) {
  18108. max_active_connections = active_connections;
  18109. }
  18110. if (active_connections > total_connections) {
  18111. total_connections = active_connections;
  18112. }
  18113. /* Connections information */
  18114. mg_snprintf(NULL,
  18115. NULL,
  18116. block,
  18117. sizeof(block),
  18118. ",%s\"connections\" : {%s"
  18119. "\"active\" : %i,%s"
  18120. "\"maxActive\" : %i,%s"
  18121. "\"total\" : %i%s"
  18122. "}",
  18123. eol,
  18124. eol,
  18125. active_connections,
  18126. eol,
  18127. max_active_connections,
  18128. eol,
  18129. total_connections,
  18130. eol);
  18131. context_info_length += mg_str_append(&buffer, end, block);
  18132. /* Queue information */
  18133. #if !defined(ALTERNATIVE_QUEUE)
  18134. mg_snprintf(NULL,
  18135. NULL,
  18136. block,
  18137. sizeof(block),
  18138. ",%s\"queue\" : {%s"
  18139. "\"length\" : %i,%s"
  18140. "\"filled\" : %i,%s"
  18141. "\"maxFilled\" : %i,%s"
  18142. "\"full\" : %s%s"
  18143. "}",
  18144. eol,
  18145. eol,
  18146. ctx->sq_size,
  18147. eol,
  18148. ctx->sq_head - ctx->sq_tail,
  18149. eol,
  18150. ctx->sq_max_fill,
  18151. eol,
  18152. (ctx->sq_blocked ? "true" : "false"),
  18153. eol);
  18154. context_info_length += mg_str_append(&buffer, end, block);
  18155. #endif
  18156. /* Requests information */
  18157. mg_snprintf(NULL,
  18158. NULL,
  18159. block,
  18160. sizeof(block),
  18161. ",%s\"requests\" : {%s"
  18162. "\"total\" : %lu%s"
  18163. "}",
  18164. eol,
  18165. eol,
  18166. (unsigned long)ctx->total_requests,
  18167. eol);
  18168. context_info_length += mg_str_append(&buffer, end, block);
  18169. /* Data information */
  18170. total_data_read =
  18171. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  18172. total_data_written =
  18173. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  18174. mg_snprintf(NULL,
  18175. NULL,
  18176. block,
  18177. sizeof(block),
  18178. ",%s\"data\" : {%s"
  18179. "\"read\" : %" INT64_FMT ",%s"
  18180. "\"written\" : %" INT64_FMT "%s"
  18181. "}",
  18182. eol,
  18183. eol,
  18184. total_data_read,
  18185. eol,
  18186. total_data_written,
  18187. eol);
  18188. context_info_length += mg_str_append(&buffer, end, block);
  18189. /* Execution time information */
  18190. gmt_time_string(start_time_str,
  18191. sizeof(start_time_str) - 1,
  18192. &start_time);
  18193. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  18194. mg_snprintf(NULL,
  18195. NULL,
  18196. block,
  18197. sizeof(block),
  18198. ",%s\"time\" : {%s"
  18199. "\"uptime\" : %.0f,%s"
  18200. "\"start\" : \"%s\",%s"
  18201. "\"now\" : \"%s\"%s"
  18202. "}",
  18203. eol,
  18204. eol,
  18205. difftime(now, start_time),
  18206. eol,
  18207. start_time_str,
  18208. eol,
  18209. now_str,
  18210. eol);
  18211. context_info_length += mg_str_append(&buffer, end, block);
  18212. }
  18213. /* Terminate string */
  18214. if (append_eoobj) {
  18215. strcat(append_eoobj, eoobj);
  18216. }
  18217. context_info_length += sizeof(eoobj) - 1;
  18218. return (int)context_info_length;
  18219. #else
  18220. (void)ctx;
  18221. if ((buffer != NULL) && (buflen > 0)) {
  18222. *buffer = 0;
  18223. }
  18224. return 0;
  18225. #endif
  18226. }
  18227. void
  18228. mg_disable_connection_keep_alive(struct mg_connection *conn)
  18229. {
  18230. /* https://github.com/civetweb/civetweb/issues/727 */
  18231. if (conn != NULL) {
  18232. conn->must_close = 1;
  18233. }
  18234. }
  18235. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18236. /* Get connection information. It can be printed or stored by the caller.
  18237. * Return the size of available information. */
  18238. int
  18239. mg_get_connection_info(const struct mg_context *ctx,
  18240. int idx,
  18241. char *buffer,
  18242. int buflen)
  18243. {
  18244. const struct mg_connection *conn;
  18245. const struct mg_request_info *ri;
  18246. char *end, *append_eoobj = NULL, block[256];
  18247. size_t connection_info_length = 0;
  18248. int state = 0;
  18249. const char *state_str = "unknown";
  18250. #if defined(_WIN32)
  18251. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  18252. #else
  18253. static const char eol[] = "\n", eoobj[] = "\n}\n";
  18254. #endif
  18255. if ((buffer == NULL) || (buflen < 1)) {
  18256. buflen = 0;
  18257. end = buffer;
  18258. } else {
  18259. *buffer = 0;
  18260. end = buffer + buflen;
  18261. }
  18262. if (buflen > (int)(sizeof(eoobj) - 1)) {
  18263. /* has enough space to append eoobj */
  18264. append_eoobj = buffer;
  18265. end -= sizeof(eoobj) - 1;
  18266. }
  18267. if ((ctx == NULL) || (idx < 0)) {
  18268. /* Parameter error */
  18269. return 0;
  18270. }
  18271. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  18272. /* Out of range */
  18273. return 0;
  18274. }
  18275. /* Take connection [idx]. This connection is not locked in
  18276. * any way, so some other thread might use it. */
  18277. conn = (ctx->worker_connections) + idx;
  18278. /* Initialize output string */
  18279. connection_info_length += mg_str_append(&buffer, end, "{");
  18280. /* Init variables */
  18281. ri = &(conn->request_info);
  18282. #if defined(USE_SERVER_STATS)
  18283. state = conn->conn_state;
  18284. /* State as string */
  18285. switch (state) {
  18286. case 0:
  18287. state_str = "undefined";
  18288. break;
  18289. case 1:
  18290. state_str = "not used";
  18291. break;
  18292. case 2:
  18293. state_str = "init";
  18294. break;
  18295. case 3:
  18296. state_str = "ready";
  18297. break;
  18298. case 4:
  18299. state_str = "processing";
  18300. break;
  18301. case 5:
  18302. state_str = "processed";
  18303. break;
  18304. case 6:
  18305. state_str = "to close";
  18306. break;
  18307. case 7:
  18308. state_str = "closing";
  18309. break;
  18310. case 8:
  18311. state_str = "closed";
  18312. break;
  18313. case 9:
  18314. state_str = "done";
  18315. break;
  18316. }
  18317. #endif
  18318. /* Connection info */
  18319. if ((state >= 3) && (state < 9)) {
  18320. mg_snprintf(NULL,
  18321. NULL,
  18322. block,
  18323. sizeof(block),
  18324. "%s\"connection\" : {%s"
  18325. "\"remote\" : {%s"
  18326. "\"protocol\" : \"%s\",%s"
  18327. "\"addr\" : \"%s\",%s"
  18328. "\"port\" : %u%s"
  18329. "},%s"
  18330. "\"handled_requests\" : %u%s"
  18331. "}",
  18332. eol,
  18333. eol,
  18334. eol,
  18335. get_proto_name(conn),
  18336. eol,
  18337. ri->remote_addr,
  18338. eol,
  18339. ri->remote_port,
  18340. eol,
  18341. eol,
  18342. conn->handled_requests,
  18343. eol);
  18344. connection_info_length += mg_str_append(&buffer, end, block);
  18345. }
  18346. /* Request info */
  18347. if ((state >= 4) && (state < 6)) {
  18348. mg_snprintf(NULL,
  18349. NULL,
  18350. block,
  18351. sizeof(block),
  18352. "%s%s\"request_info\" : {%s"
  18353. "\"method\" : \"%s\",%s"
  18354. "\"uri\" : \"%s\",%s"
  18355. "\"query\" : %s%s%s%s"
  18356. "}",
  18357. (connection_info_length > 1 ? "," : ""),
  18358. eol,
  18359. eol,
  18360. ri->request_method,
  18361. eol,
  18362. ri->request_uri,
  18363. eol,
  18364. ri->query_string ? "\"" : "",
  18365. ri->query_string ? ri->query_string : "null",
  18366. ri->query_string ? "\"" : "",
  18367. eol);
  18368. connection_info_length += mg_str_append(&buffer, end, block);
  18369. }
  18370. /* Execution time information */
  18371. if ((state >= 2) && (state < 9)) {
  18372. char start_time_str[64] = {0};
  18373. char close_time_str[64] = {0};
  18374. time_t start_time = conn->conn_birth_time;
  18375. time_t close_time = 0;
  18376. double time_diff;
  18377. gmt_time_string(start_time_str,
  18378. sizeof(start_time_str) - 1,
  18379. &start_time);
  18380. #if defined(USE_SERVER_STATS)
  18381. close_time = conn->conn_close_time;
  18382. #endif
  18383. if (close_time != 0) {
  18384. time_diff = difftime(close_time, start_time);
  18385. gmt_time_string(close_time_str,
  18386. sizeof(close_time_str) - 1,
  18387. &close_time);
  18388. } else {
  18389. time_t now = time(NULL);
  18390. time_diff = difftime(now, start_time);
  18391. close_time_str[0] = 0; /* or use "now" ? */
  18392. }
  18393. mg_snprintf(NULL,
  18394. NULL,
  18395. block,
  18396. sizeof(block),
  18397. "%s%s\"time\" : {%s"
  18398. "\"uptime\" : %.0f,%s"
  18399. "\"start\" : \"%s\",%s"
  18400. "\"closed\" : \"%s\"%s"
  18401. "}",
  18402. (connection_info_length > 1 ? "," : ""),
  18403. eol,
  18404. eol,
  18405. time_diff,
  18406. eol,
  18407. start_time_str,
  18408. eol,
  18409. close_time_str,
  18410. eol);
  18411. connection_info_length += mg_str_append(&buffer, end, block);
  18412. }
  18413. /* Remote user name */
  18414. if ((ri->remote_user) && (state < 9)) {
  18415. mg_snprintf(NULL,
  18416. NULL,
  18417. block,
  18418. sizeof(block),
  18419. "%s%s\"user\" : {%s"
  18420. "\"name\" : \"%s\",%s"
  18421. "}",
  18422. (connection_info_length > 1 ? "," : ""),
  18423. eol,
  18424. eol,
  18425. ri->remote_user,
  18426. eol);
  18427. connection_info_length += mg_str_append(&buffer, end, block);
  18428. }
  18429. /* Data block */
  18430. if (state >= 3) {
  18431. mg_snprintf(NULL,
  18432. NULL,
  18433. block,
  18434. sizeof(block),
  18435. "%s%s\"data\" : {%s"
  18436. "\"read\" : %" INT64_FMT ",%s"
  18437. "\"written\" : %" INT64_FMT "%s"
  18438. "}",
  18439. (connection_info_length > 1 ? "," : ""),
  18440. eol,
  18441. eol,
  18442. conn->consumed_content,
  18443. eol,
  18444. conn->num_bytes_sent,
  18445. eol);
  18446. connection_info_length += mg_str_append(&buffer, end, block);
  18447. }
  18448. /* State */
  18449. mg_snprintf(NULL,
  18450. NULL,
  18451. block,
  18452. sizeof(block),
  18453. "%s%s\"state\" : \"%s\"",
  18454. (connection_info_length > 1 ? "," : ""),
  18455. eol,
  18456. state_str);
  18457. connection_info_length += mg_str_append(&buffer, end, block);
  18458. /* Terminate string */
  18459. if (append_eoobj) {
  18460. strcat(append_eoobj, eoobj);
  18461. }
  18462. connection_info_length += sizeof(eoobj) - 1;
  18463. return (int)connection_info_length;
  18464. }
  18465. #endif
  18466. /* Initialize this library. This function does not need to be thread safe.
  18467. */
  18468. unsigned
  18469. mg_init_library(unsigned features)
  18470. {
  18471. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  18472. unsigned features_inited = features_to_init;
  18473. if (mg_init_library_called <= 0) {
  18474. /* Not initialized yet */
  18475. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  18476. return 0;
  18477. }
  18478. }
  18479. mg_global_lock();
  18480. if (mg_init_library_called <= 0) {
  18481. #if defined(_WIN32)
  18482. int file_mutex_init = 1;
  18483. int wsa = 1;
  18484. #else
  18485. int mutexattr_init = 1;
  18486. #endif
  18487. int failed = 1;
  18488. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  18489. if (key_create == 0) {
  18490. #if defined(_WIN32)
  18491. file_mutex_init =
  18492. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  18493. if (file_mutex_init == 0) {
  18494. /* Start WinSock */
  18495. WSADATA data;
  18496. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  18497. }
  18498. #else
  18499. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  18500. if (mutexattr_init == 0) {
  18501. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  18502. PTHREAD_MUTEX_RECURSIVE);
  18503. }
  18504. #endif
  18505. }
  18506. if (failed) {
  18507. #if defined(_WIN32)
  18508. if (wsa == 0) {
  18509. (void)WSACleanup();
  18510. }
  18511. if (file_mutex_init == 0) {
  18512. (void)pthread_mutex_destroy(&global_log_file_lock);
  18513. }
  18514. #else
  18515. if (mutexattr_init == 0) {
  18516. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18517. }
  18518. #endif
  18519. if (key_create == 0) {
  18520. (void)pthread_key_delete(sTlsKey);
  18521. }
  18522. mg_global_unlock();
  18523. (void)pthread_mutex_destroy(&global_lock_mutex);
  18524. return 0;
  18525. }
  18526. #if defined(USE_LUA)
  18527. lua_init_optional_libraries();
  18528. #endif
  18529. }
  18530. mg_global_unlock();
  18531. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  18532. || defined(OPENSSL_API_3_0)) \
  18533. && !defined(NO_SSL)
  18534. if (features_to_init & MG_FEATURES_SSL) {
  18535. if (!mg_openssl_initialized) {
  18536. char ebuf[128];
  18537. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  18538. mg_openssl_initialized = 1;
  18539. } else {
  18540. (void)ebuf;
  18541. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  18542. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  18543. }
  18544. } else {
  18545. /* ssl already initialized */
  18546. }
  18547. }
  18548. #endif
  18549. mg_global_lock();
  18550. if (mg_init_library_called <= 0) {
  18551. mg_init_library_called = 1;
  18552. } else {
  18553. mg_init_library_called++;
  18554. }
  18555. mg_global_unlock();
  18556. return features_inited;
  18557. }
  18558. /* Un-initialize this library. */
  18559. unsigned
  18560. mg_exit_library(void)
  18561. {
  18562. if (mg_init_library_called <= 0) {
  18563. return 0;
  18564. }
  18565. mg_global_lock();
  18566. mg_init_library_called--;
  18567. if (mg_init_library_called == 0) {
  18568. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  18569. if (mg_openssl_initialized) {
  18570. uninitialize_openssl();
  18571. mg_openssl_initialized = 0;
  18572. }
  18573. #endif
  18574. #if defined(_WIN32)
  18575. (void)WSACleanup();
  18576. (void)pthread_mutex_destroy(&global_log_file_lock);
  18577. #else
  18578. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  18579. #endif
  18580. (void)pthread_key_delete(sTlsKey);
  18581. #if defined(USE_LUA)
  18582. lua_exit_optional_libraries();
  18583. #endif
  18584. mg_global_unlock();
  18585. (void)pthread_mutex_destroy(&global_lock_mutex);
  18586. return 1;
  18587. }
  18588. mg_global_unlock();
  18589. return 1;
  18590. }
  18591. /* End of civetweb.c */