civetweb.c 613 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948
  1. /* Copyright (c) 2013-2023 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #ifndef GCC_VERSION
  24. #define GCC_VERSION \
  25. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  26. #endif
  27. #if GCC_VERSION >= 40500
  28. /* gcc diagnostic pragmas available */
  29. #define GCC_DIAGNOSTIC
  30. #endif
  31. #endif
  32. #if defined(GCC_DIAGNOSTIC)
  33. /* Disable unused macros warnings - not all defines are required
  34. * for all systems and all compilers. */
  35. #pragma GCC diagnostic ignored "-Wunused-macros"
  36. /* A padding warning is just plain useless */
  37. #pragma GCC diagnostic ignored "-Wpadded"
  38. #endif
  39. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  40. /* We must set some flags for the headers we include. These flags
  41. * are reserved ids according to C99, so we need to disable a
  42. * warning for that. */
  43. #pragma GCC diagnostic push
  44. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  45. #endif
  46. #if defined(_WIN32)
  47. #if !defined(_CRT_SECURE_NO_WARNINGS)
  48. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  49. #endif
  50. #if !defined(_WIN32_WINNT) /* Minimum API version */
  51. #define _WIN32_WINNT 0x0601
  52. #endif
  53. #else
  54. #if !defined(_GNU_SOURCE)
  55. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  56. #endif
  57. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  58. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  59. #endif
  60. #if defined(__LSB_VERSION__) || defined(__sun)
  61. #define NEED_TIMEGM
  62. #define NO_THREAD_NAME
  63. #endif
  64. #if !defined(_LARGEFILE_SOURCE)
  65. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  66. #endif
  67. #if !defined(_FILE_OFFSET_BITS)
  68. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  69. #endif
  70. #if !defined(__STDC_FORMAT_MACROS)
  71. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  72. #endif
  73. #if !defined(__STDC_LIMIT_MACROS)
  74. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  75. #endif
  76. #if !defined(_DARWIN_UNLIMITED_SELECT)
  77. #define _DARWIN_UNLIMITED_SELECT
  78. #endif
  79. #if defined(__sun)
  80. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  81. #define __inline inline /* not recognized on older compiler versions */
  82. #endif
  83. #endif
  84. #if defined(__clang__)
  85. /* Enable reserved-id-macro warning again. */
  86. #pragma GCC diagnostic pop
  87. #endif
  88. #if defined(USE_LUA)
  89. #define USE_TIMERS
  90. #endif
  91. #if defined(_MSC_VER)
  92. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  93. #pragma warning(disable : 4306)
  94. /* conditional expression is constant: introduced by FD_SET(..) */
  95. #pragma warning(disable : 4127)
  96. /* non-constant aggregate initializer: issued due to missing C99 support */
  97. #pragma warning(disable : 4204)
  98. /* padding added after data member */
  99. #pragma warning(disable : 4820)
  100. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  101. #pragma warning(disable : 4668)
  102. /* no function prototype given: converting '()' to '(void)' */
  103. #pragma warning(disable : 4255)
  104. /* function has been selected for automatic inline expansion */
  105. #pragma warning(disable : 4711)
  106. #endif
  107. /* This code uses static_assert to check some conditions.
  108. * Unfortunately some compilers still do not support it, so we have a
  109. * replacement function here. */
  110. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  111. #define mg_static_assert _Static_assert
  112. #elif defined(__cplusplus) && __cplusplus >= 201103L
  113. #define mg_static_assert static_assert
  114. #else
  115. char static_assert_replacement[1];
  116. #define mg_static_assert(cond, txt) \
  117. extern char static_assert_replacement[(cond) ? 1 : -1]
  118. #endif
  119. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  120. "int data type size check");
  121. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  122. "pointer data type size check");
  123. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  124. /* Select queue implementation. Diagnosis features originally only implemented
  125. * for the "ALTERNATIVE_QUEUE" have been ported to the previous queue
  126. * implementation (NO_ALTERNATIVE_QUEUE) as well. The new configuration value
  127. * "CONNECTION_QUEUE_SIZE" is only available for the previous queue
  128. * implementation, since the queue length is independent from the number of
  129. * worker threads there, while the new queue is one element per worker thread.
  130. *
  131. */
  132. #if defined(NO_ALTERNATIVE_QUEUE) && defined(ALTERNATIVE_QUEUE)
  133. /* The queues are exclusive or - only one can be used. */
  134. #error \
  135. "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE (or none of them), but not both"
  136. #endif
  137. #if !defined(NO_ALTERNATIVE_QUEUE) && !defined(ALTERNATIVE_QUEUE)
  138. /* Use a default implementation */
  139. #define NO_ALTERNATIVE_QUEUE
  140. #endif
  141. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  142. /* File system access:
  143. * NO_FILES = do not serve any files from the file system automatically.
  144. * However, with NO_FILES CivetWeb may still write log files, read access
  145. * control files, default error page files or use API functions like
  146. * mg_send_file in callbacks to send files from the server local
  147. * file system.
  148. * NO_FILES only disables the automatic mapping between URLs and local
  149. * file names.
  150. * NO_FILESYSTEM = do not access any file at all. Useful for embedded
  151. * devices without file system. Logging to files in not available
  152. * (use callbacks instead) and API functions like mg_send_file are not
  153. * available.
  154. * If NO_FILESYSTEM is set, NO_FILES must be set as well.
  155. */
  156. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  157. #endif
  158. /* DTL -- including winsock2.h works better if lean and mean */
  159. #if !defined(WIN32_LEAN_AND_MEAN)
  160. #define WIN32_LEAN_AND_MEAN
  161. #endif
  162. #if defined(__SYMBIAN32__)
  163. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  164. * Symbian is no longer maintained since 2014-01-01.
  165. * Support for Symbian has been removed from CivetWeb
  166. */
  167. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  168. #endif /* __SYMBIAN32__ */
  169. #if defined(__ZEPHYR__)
  170. #include <ctype.h>
  171. #include <fcntl.h>
  172. #include <netdb.h>
  173. #include <poll.h>
  174. #include <pthread.h>
  175. #include <stdio.h>
  176. #include <stdlib.h>
  177. #include <string.h>
  178. #include <sys/socket.h>
  179. #include <time.h>
  180. #include <zephyr/kernel.h>
  181. /* Max worker threads is the max of pthreads minus the main application thread
  182. * and minus the main civetweb thread, thus -2
  183. */
  184. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  186. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  187. #else
  188. #define ZEPHYR_STACK_SIZE (1024 * 16)
  189. #endif
  190. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  191. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  192. MAX_WORKER_THREADS,
  193. ZEPHYR_STACK_SIZE);
  194. static int zephyr_worker_stack_index;
  195. #endif
  196. #if !defined(CIVETWEB_HEADER_INCLUDED)
  197. /* Include the header file here, so the CivetWeb interface is defined for the
  198. * entire implementation, including the following forward definitions. */
  199. #include "civetweb.h"
  200. #endif
  201. #if !defined(DEBUG_TRACE)
  202. #if defined(DEBUG)
  203. static void DEBUG_TRACE_FUNC(const char *func,
  204. unsigned line,
  205. PRINTF_FORMAT_STRING(const char *fmt),
  206. ...) PRINTF_ARGS(3, 4);
  207. #define DEBUG_TRACE(fmt, ...) \
  208. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  209. #define NEED_DEBUG_TRACE_FUNC
  210. #if !defined(DEBUG_TRACE_STREAM)
  211. #define DEBUG_TRACE_STREAM stdout
  212. #endif
  213. #else
  214. #define DEBUG_TRACE(fmt, ...) \
  215. do { \
  216. } while (0)
  217. #endif /* DEBUG */
  218. #endif /* DEBUG_TRACE */
  219. #if !defined(DEBUG_ASSERT)
  220. #if defined(DEBUG)
  221. #include <stdlib.h>
  222. #define DEBUG_ASSERT(cond) \
  223. do { \
  224. if (!(cond)) { \
  225. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  226. exit(2); /* Exit with error */ \
  227. } \
  228. } while (0)
  229. #else
  230. #define DEBUG_ASSERT(cond)
  231. #endif /* DEBUG */
  232. #endif
  233. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  234. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  235. __attribute__((no_instrument_function));
  236. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  237. __attribute__((no_instrument_function));
  238. void
  239. __cyg_profile_func_enter(void *this_fn, void *call_site)
  240. {
  241. if ((void *)this_fn != (void *)printf) {
  242. printf("E %p %p\n", this_fn, call_site);
  243. }
  244. }
  245. void
  246. __cyg_profile_func_exit(void *this_fn, void *call_site)
  247. {
  248. if ((void *)this_fn != (void *)printf) {
  249. printf("X %p %p\n", this_fn, call_site);
  250. }
  251. }
  252. #endif
  253. #if !defined(IGNORE_UNUSED_RESULT)
  254. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  255. #endif
  256. #if defined(__GNUC__) || defined(__MINGW32__)
  257. /* GCC unused function attribute seems fundamentally broken.
  258. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  259. * OR UNUSED" for individual functions failed.
  260. * Either the compiler creates an "unused-function" warning if a
  261. * function is not marked with __attribute__((unused)).
  262. * On the other hand, if the function is marked with this attribute,
  263. * but is used, the compiler raises a completely idiotic
  264. * "used-but-marked-unused" warning - and
  265. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  266. * raises error: unknown option after "#pragma GCC diagnostic".
  267. * Disable this warning completely, until the GCC guys sober up
  268. * again.
  269. */
  270. #pragma GCC diagnostic ignored "-Wunused-function"
  271. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  272. #else
  273. #define FUNCTION_MAY_BE_UNUSED
  274. #endif
  275. /* Some ANSI #includes are not available on Windows CE and Zephyr */
  276. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  277. #include <errno.h>
  278. #include <fcntl.h>
  279. #include <signal.h>
  280. #include <stdlib.h>
  281. #include <sys/stat.h>
  282. #include <sys/types.h>
  283. #endif /* !_WIN32_WCE */
  284. #if defined(__clang__)
  285. /* When using -Weverything, clang does not accept it's own headers
  286. * in a release build configuration. Disable what is too much in
  287. * -Weverything. */
  288. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  289. #endif
  290. #if defined(__GNUC__) || defined(__MINGW32__)
  291. /* Who on earth came to the conclusion, using __DATE__ should rise
  292. * an "expansion of date or time macro is not reproducible"
  293. * warning. That's exactly what was intended by using this macro.
  294. * Just disable this nonsense warning. */
  295. /* And disabling them does not work either:
  296. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  297. * #pragma clang diagnostic ignored "-Wdate-time"
  298. * So we just have to disable ALL warnings for some lines
  299. * of code.
  300. * This seems to be a known GCC bug, not resolved since 2012:
  301. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  302. */
  303. #endif
  304. #if defined(__MACH__) && defined(__APPLE__) /* Apple OSX section */
  305. #if defined(__clang__)
  306. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  307. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  308. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  309. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  310. #endif
  311. #endif
  312. #ifndef CLOCK_MONOTONIC
  313. #define CLOCK_MONOTONIC (1)
  314. #endif
  315. #ifndef CLOCK_REALTIME
  316. #define CLOCK_REALTIME (2)
  317. #endif
  318. #include <mach/clock.h>
  319. #include <mach/mach.h>
  320. #include <mach/mach_time.h>
  321. #include <sys/errno.h>
  322. #include <sys/time.h>
  323. /* clock_gettime is not implemented on OSX prior to 10.12 */
  324. static int
  325. _civet_clock_gettime(int clk_id, struct timespec *t)
  326. {
  327. memset(t, 0, sizeof(*t));
  328. if (clk_id == CLOCK_REALTIME) {
  329. struct timeval now;
  330. int rv = gettimeofday(&now, NULL);
  331. if (rv) {
  332. return rv;
  333. }
  334. t->tv_sec = now.tv_sec;
  335. t->tv_nsec = now.tv_usec * 1000;
  336. return 0;
  337. } else if (clk_id == CLOCK_MONOTONIC) {
  338. static uint64_t clock_start_time = 0;
  339. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  340. uint64_t now = mach_absolute_time();
  341. if (clock_start_time == 0) {
  342. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  343. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  344. /* appease "unused variable" warning for release builds */
  345. (void)mach_status;
  346. clock_start_time = now;
  347. }
  348. now = (uint64_t)((double)(now - clock_start_time)
  349. * (double)timebase_ifo.numer
  350. / (double)timebase_ifo.denom);
  351. t->tv_sec = now / 1000000000;
  352. t->tv_nsec = now % 1000000000;
  353. return 0;
  354. }
  355. return -1; /* EINVAL - Clock ID is unknown */
  356. }
  357. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  358. #if defined(__CLOCK_AVAILABILITY)
  359. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  360. * declared but it may be NULL at runtime. So we need to check before using
  361. * it. */
  362. static int
  363. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  364. {
  365. if (clock_gettime) {
  366. return clock_gettime(clk_id, t);
  367. }
  368. return _civet_clock_gettime(clk_id, t);
  369. }
  370. #define clock_gettime _civet_safe_clock_gettime
  371. #else
  372. #define clock_gettime _civet_clock_gettime
  373. #endif
  374. #endif
  375. #if defined(_WIN32)
  376. #define ERROR_TRY_AGAIN(err) ((err) == WSAEWOULDBLOCK)
  377. #else
  378. /* Unix might return different error codes indicating to try again.
  379. * For Linux EAGAIN==EWOULDBLOCK, maybe EAGAIN!=EWOULDBLOCK is history from
  380. * decades ago, but better check both and let the compiler optimize it. */
  381. #define ERROR_TRY_AGAIN(err) \
  382. (((err) == EAGAIN) || ((err) == EWOULDBLOCK) || ((err) == EINTR))
  383. #endif
  384. #if defined(USE_ZLIB)
  385. #include "zconf.h"
  386. #include "zlib.h"
  387. #endif
  388. /********************************************************************/
  389. /* CivetWeb configuration defines */
  390. /********************************************************************/
  391. /* Maximum number of threads that can be configured.
  392. * The number of threads actually created depends on the "num_threads"
  393. * configuration parameter, but this is the upper limit. */
  394. #if !defined(MAX_WORKER_THREADS)
  395. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  396. #endif
  397. /* Timeout interval for select/poll calls.
  398. * The timeouts depend on "*_timeout_ms" configuration values, but long
  399. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  400. * This reduces the time required to stop the server. */
  401. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  402. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  403. #endif
  404. /* Do not try to compress files smaller than this limit. */
  405. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  406. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  407. #endif
  408. #if !defined(PASSWORDS_FILE_NAME)
  409. #define PASSWORDS_FILE_NAME ".htpasswd"
  410. #endif
  411. /* Initial buffer size for all CGI environment variables. In case there is
  412. * not enough space, another block is allocated. */
  413. #if !defined(CGI_ENVIRONMENT_SIZE)
  414. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  415. #endif
  416. /* Maximum number of environment variables. */
  417. #if !defined(MAX_CGI_ENVIR_VARS)
  418. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  419. #endif
  420. /* General purpose buffer size. */
  421. #if !defined(MG_BUF_LEN) /* in bytes */
  422. #define MG_BUF_LEN (1024 * 8)
  423. #endif
  424. /********************************************************************/
  425. /* Helper macros */
  426. #if !defined(ARRAY_SIZE)
  427. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  428. #endif
  429. #include <stdint.h>
  430. /* Standard defines */
  431. #if !defined(INT64_MAX)
  432. #define INT64_MAX (9223372036854775807)
  433. #endif
  434. #define SHUTDOWN_RD (0)
  435. #define SHUTDOWN_WR (1)
  436. #define SHUTDOWN_BOTH (2)
  437. mg_static_assert(MAX_WORKER_THREADS >= 1,
  438. "worker threads must be a positive number");
  439. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  440. "size_t data type size check");
  441. #if defined(_WIN32) /* WINDOWS include block */
  442. #include <malloc.h> /* *alloc( */
  443. #include <stdlib.h> /* *alloc( */
  444. #include <time.h> /* struct timespec */
  445. #include <windows.h>
  446. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  447. #include <ws2tcpip.h>
  448. typedef const char *SOCK_OPT_TYPE;
  449. /* For a detailed description of these *_PATH_MAX defines, see
  450. * https://github.com/civetweb/civetweb/issues/937. */
  451. /* UTF8_PATH_MAX is a char buffer size for 259 BMP characters in UTF-8 plus
  452. * null termination, rounded up to the next 4 bytes boundary */
  453. #define UTF8_PATH_MAX (3 * 260)
  454. /* UTF16_PATH_MAX is the 16-bit wchar_t buffer size required for 259 BMP
  455. * characters plus termination. (Note: wchar_t is 16 bit on Windows) */
  456. #define UTF16_PATH_MAX (260)
  457. #if !defined(_IN_PORT_T)
  458. #if !defined(in_port_t)
  459. #define in_port_t u_short
  460. #endif
  461. #endif
  462. #if defined(_WIN32_WCE)
  463. #error "WinCE support has ended"
  464. #endif
  465. #include <direct.h>
  466. #include <io.h>
  467. #include <process.h>
  468. #define MAKEUQUAD(lo, hi) \
  469. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  470. #define RATE_DIFF (10000000) /* 100 nsecs */
  471. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  472. #define SYS2UNIX_TIME(lo, hi) \
  473. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  474. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  475. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  476. * Also use _strtoui64 on modern M$ compilers */
  477. #if defined(_MSC_VER)
  478. #if (_MSC_VER < 1300)
  479. #define STRX(x) #x
  480. #define STR(x) STRX(x)
  481. #define __func__ __FILE__ ":" STR(__LINE__)
  482. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  483. #define strtoll(x, y, z) (_atoi64(x))
  484. #else
  485. #define __func__ __FUNCTION__
  486. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  487. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  488. #endif
  489. #endif /* _MSC_VER */
  490. #define ERRNO ((int)(GetLastError()))
  491. #define NO_SOCKLEN_T
  492. #if defined(_WIN64) || defined(__MINGW64__)
  493. #if !defined(SSL_LIB)
  494. #if defined(OPENSSL_API_3_0)
  495. #define SSL_LIB "libssl-3-x64.dll"
  496. #define CRYPTO_LIB "libcrypto-3-x64.dll"
  497. #endif
  498. #if defined(OPENSSL_API_1_1)
  499. #define SSL_LIB "libssl-1_1-x64.dll"
  500. #define CRYPTO_LIB "libcrypto-1_1-x64.dll"
  501. #endif /* OPENSSL_API_1_1 */
  502. #if defined(OPENSSL_API_1_0)
  503. #define SSL_LIB "ssleay64.dll"
  504. #define CRYPTO_LIB "libeay64.dll"
  505. #endif /* OPENSSL_API_1_0 */
  506. #endif
  507. #else /* defined(_WIN64) || defined(__MINGW64__) */
  508. #if !defined(SSL_LIB)
  509. #if defined(OPENSSL_API_3_0)
  510. #define SSL_LIB "libssl-3.dll"
  511. #define CRYPTO_LIB "libcrypto-3.dll"
  512. #endif
  513. #if defined(OPENSSL_API_1_1)
  514. #define SSL_LIB "libssl-1_1.dll"
  515. #define CRYPTO_LIB "libcrypto-1_1.dll"
  516. #endif /* OPENSSL_API_1_1 */
  517. #if defined(OPENSSL_API_1_0)
  518. #define SSL_LIB "ssleay32.dll"
  519. #define CRYPTO_LIB "libeay32.dll"
  520. #endif /* OPENSSL_API_1_0 */
  521. #endif /* SSL_LIB */
  522. #endif /* defined(_WIN64) || defined(__MINGW64__) */
  523. #define O_NONBLOCK (0)
  524. #if !defined(W_OK)
  525. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  526. #endif
  527. #define _POSIX_
  528. #define INT64_FMT "I64d"
  529. #define UINT64_FMT "I64u"
  530. #define WINCDECL __cdecl
  531. #define vsnprintf_impl _vsnprintf
  532. #define access _access
  533. #define mg_sleep(x) (Sleep(x))
  534. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  535. #if !defined(popen)
  536. #define popen(x, y) (_popen(x, y))
  537. #endif
  538. #if !defined(pclose)
  539. #define pclose(x) (_pclose(x))
  540. #endif
  541. #define close(x) (_close(x))
  542. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  543. #define RTLD_LAZY (0)
  544. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  545. #define fdopen(x, y) (_fdopen((x), (y)))
  546. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  547. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  548. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  549. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  550. #define sleep(x) (Sleep((x)*1000))
  551. #define rmdir(x) (_rmdir(x))
  552. #if defined(_WIN64) || !defined(__MINGW32__)
  553. /* Only MinGW 32 bit is missing this function */
  554. #define timegm(x) (_mkgmtime(x))
  555. #else
  556. time_t timegm(struct tm *tm);
  557. #define NEED_TIMEGM
  558. #endif
  559. #if !defined(fileno)
  560. #define fileno(x) (_fileno(x))
  561. #endif /* !fileno MINGW #defines fileno */
  562. typedef struct {
  563. CRITICAL_SECTION sec; /* Immovable */
  564. } pthread_mutex_t;
  565. typedef DWORD pthread_key_t;
  566. typedef HANDLE pthread_t;
  567. typedef struct {
  568. pthread_mutex_t threadIdSec;
  569. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  570. } pthread_cond_t;
  571. #if !defined(__clockid_t_defined)
  572. typedef DWORD clockid_t;
  573. #endif
  574. #if !defined(CLOCK_MONOTONIC)
  575. #define CLOCK_MONOTONIC (1)
  576. #endif
  577. #if !defined(CLOCK_REALTIME)
  578. #define CLOCK_REALTIME (2)
  579. #endif
  580. #if !defined(CLOCK_THREAD)
  581. #define CLOCK_THREAD (3)
  582. #endif
  583. #if !defined(CLOCK_PROCESS)
  584. #define CLOCK_PROCESS (4)
  585. #endif
  586. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  587. #define _TIMESPEC_DEFINED
  588. #endif
  589. #if !defined(_TIMESPEC_DEFINED)
  590. struct timespec {
  591. time_t tv_sec; /* seconds */
  592. long tv_nsec; /* nanoseconds */
  593. };
  594. #endif
  595. #if !defined(WIN_PTHREADS_TIME_H)
  596. #define MUST_IMPLEMENT_CLOCK_GETTIME
  597. #endif
  598. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  599. #define clock_gettime mg_clock_gettime
  600. static int
  601. clock_gettime(clockid_t clk_id, struct timespec *tp)
  602. {
  603. FILETIME ft;
  604. ULARGE_INTEGER li, li2;
  605. BOOL ok = FALSE;
  606. double d;
  607. static double perfcnt_per_sec = 0.0;
  608. static BOOL initialized = FALSE;
  609. if (!initialized) {
  610. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  611. perfcnt_per_sec = 1.0 / li.QuadPart;
  612. initialized = TRUE;
  613. }
  614. if (tp) {
  615. memset(tp, 0, sizeof(*tp));
  616. if (clk_id == CLOCK_REALTIME) {
  617. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  618. GetSystemTimeAsFileTime(&ft);
  619. li.LowPart = ft.dwLowDateTime;
  620. li.HighPart = ft.dwHighDateTime;
  621. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  622. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  623. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  624. ok = TRUE;
  625. /* END: CLOCK_REALTIME */
  626. } else if (clk_id == CLOCK_MONOTONIC) {
  627. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  628. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  629. d = li.QuadPart * perfcnt_per_sec;
  630. tp->tv_sec = (time_t)d;
  631. d -= (double)tp->tv_sec;
  632. tp->tv_nsec = (long)(d * 1.0E9);
  633. ok = TRUE;
  634. /* END: CLOCK_MONOTONIC */
  635. } else if (clk_id == CLOCK_THREAD) {
  636. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  637. FILETIME t_create, t_exit, t_kernel, t_user;
  638. if (GetThreadTimes(GetCurrentThread(),
  639. &t_create,
  640. &t_exit,
  641. &t_kernel,
  642. &t_user)) {
  643. li.LowPart = t_user.dwLowDateTime;
  644. li.HighPart = t_user.dwHighDateTime;
  645. li2.LowPart = t_kernel.dwLowDateTime;
  646. li2.HighPart = t_kernel.dwHighDateTime;
  647. li.QuadPart += li2.QuadPart;
  648. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  649. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  650. ok = TRUE;
  651. }
  652. /* END: CLOCK_THREAD */
  653. } else if (clk_id == CLOCK_PROCESS) {
  654. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  655. FILETIME t_create, t_exit, t_kernel, t_user;
  656. if (GetProcessTimes(GetCurrentProcess(),
  657. &t_create,
  658. &t_exit,
  659. &t_kernel,
  660. &t_user)) {
  661. li.LowPart = t_user.dwLowDateTime;
  662. li.HighPart = t_user.dwHighDateTime;
  663. li2.LowPart = t_kernel.dwLowDateTime;
  664. li2.HighPart = t_kernel.dwHighDateTime;
  665. li.QuadPart += li2.QuadPart;
  666. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  667. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  668. ok = TRUE;
  669. }
  670. /* END: CLOCK_PROCESS */
  671. } else {
  672. /* BEGIN: unknown clock */
  673. /* ok = FALSE; already set by init */
  674. /* END: unknown clock */
  675. }
  676. }
  677. return ok ? 0 : -1;
  678. }
  679. #endif
  680. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  681. static int pthread_mutex_lock(pthread_mutex_t *);
  682. static int pthread_mutex_unlock(pthread_mutex_t *);
  683. static void path_to_unicode(const struct mg_connection *conn,
  684. const char *path,
  685. wchar_t *wbuf,
  686. size_t wbuf_len);
  687. /* All file operations need to be rewritten to solve #246. */
  688. struct mg_file;
  689. static const char *mg_fgets(char *buf, size_t size, struct mg_file *filep);
  690. /* POSIX dirent interface */
  691. struct dirent {
  692. char d_name[UTF8_PATH_MAX];
  693. };
  694. typedef struct DIR {
  695. HANDLE handle;
  696. WIN32_FIND_DATAW info;
  697. struct dirent result;
  698. } DIR;
  699. #if defined(HAVE_POLL)
  700. #define mg_pollfd pollfd
  701. #else
  702. struct mg_pollfd {
  703. SOCKET fd;
  704. short events;
  705. short revents;
  706. };
  707. #endif
  708. /* Mark required libraries */
  709. #if defined(_MSC_VER)
  710. #pragma comment(lib, "Ws2_32.lib")
  711. #endif
  712. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  713. #include <inttypes.h>
  714. /* Linux & co. internally use UTF8 */
  715. #define UTF8_PATH_MAX (PATH_MAX)
  716. typedef const void *SOCK_OPT_TYPE;
  717. #if defined(ANDROID)
  718. typedef unsigned short int in_port_t;
  719. #endif
  720. #if !defined(__ZEPHYR__)
  721. #include <arpa/inet.h>
  722. #include <ctype.h>
  723. #include <dirent.h>
  724. #include <grp.h>
  725. #include <limits.h>
  726. #include <netdb.h>
  727. #include <netinet/in.h>
  728. #include <netinet/tcp.h>
  729. #include <poll.h>
  730. #include <pthread.h>
  731. #include <pwd.h>
  732. #include <stdarg.h>
  733. #include <stddef.h>
  734. #include <stdio.h>
  735. #include <stdlib.h>
  736. #include <string.h>
  737. #include <sys/socket.h>
  738. #include <sys/time.h>
  739. #include <sys/utsname.h>
  740. #include <sys/wait.h>
  741. #include <time.h>
  742. #include <unistd.h>
  743. #if defined(USE_X_DOM_SOCKET)
  744. #include <sys/un.h>
  745. #endif
  746. #endif
  747. #define vsnprintf_impl vsnprintf
  748. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  749. #include <dlfcn.h>
  750. #endif
  751. #if defined(__MACH__) && defined(__APPLE__)
  752. #define SSL_LIB "libssl.dylib"
  753. #define CRYPTO_LIB "libcrypto.dylib"
  754. #else
  755. #if !defined(SSL_LIB)
  756. #define SSL_LIB "libssl.so"
  757. #endif
  758. #if !defined(CRYPTO_LIB)
  759. #define CRYPTO_LIB "libcrypto.so"
  760. #endif
  761. #endif
  762. #if !defined(O_BINARY)
  763. #define O_BINARY (0)
  764. #endif /* O_BINARY */
  765. #define closesocket(a) (close(a))
  766. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  767. #define mg_remove(conn, x) (remove(x))
  768. #define mg_sleep(x) (usleep((x)*1000))
  769. #define mg_opendir(conn, x) (opendir(x))
  770. #define mg_closedir(x) (closedir(x))
  771. #define mg_readdir(x) (readdir(x))
  772. #define ERRNO (errno)
  773. #define INVALID_SOCKET (-1)
  774. #define INT64_FMT PRId64
  775. #define UINT64_FMT PRIu64
  776. typedef int SOCKET;
  777. #define WINCDECL
  778. #if defined(__hpux)
  779. /* HPUX 11 does not have monotonic, fall back to realtime */
  780. #if !defined(CLOCK_MONOTONIC)
  781. #define CLOCK_MONOTONIC CLOCK_REALTIME
  782. #endif
  783. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  784. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  785. * the prototypes use int* rather than socklen_t* which matches the
  786. * actual library expectation. When called with the wrong size arg
  787. * accept() returns a zero client inet addr and check_acl() always
  788. * fails. Since socklen_t is widely used below, just force replace
  789. * their typedef with int. - DTL
  790. */
  791. #define socklen_t int
  792. #endif /* hpux */
  793. #define mg_pollfd pollfd
  794. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  795. /* In case our C library is missing "timegm", provide an implementation */
  796. #if defined(NEED_TIMEGM)
  797. static inline int
  798. is_leap(int y)
  799. {
  800. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  801. }
  802. static inline int
  803. count_leap(int y)
  804. {
  805. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  806. }
  807. time_t
  808. timegm(struct tm *tm)
  809. {
  810. static const unsigned short ydays[] = {
  811. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  812. int year = tm->tm_year + 1900;
  813. int mon = tm->tm_mon;
  814. int mday = tm->tm_mday - 1;
  815. int hour = tm->tm_hour;
  816. int min = tm->tm_min;
  817. int sec = tm->tm_sec;
  818. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  819. || (mday >= ydays[mon + 1] - ydays[mon]
  820. + (mon == 1 && is_leap(year) ? 1 : 0))
  821. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  822. return -1;
  823. time_t res = year - 1970;
  824. res *= 365;
  825. res += mday;
  826. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  827. res += count_leap(year);
  828. res *= 24;
  829. res += hour;
  830. res *= 60;
  831. res += min;
  832. res *= 60;
  833. res += sec;
  834. return res;
  835. }
  836. #endif /* NEED_TIMEGM */
  837. /* va_copy should always be a macro, C99 and C++11 - DTL */
  838. #if !defined(va_copy)
  839. #define va_copy(x, y) ((x) = (y))
  840. #endif
  841. #if defined(_WIN32)
  842. /* Create substitutes for POSIX functions in Win32. */
  843. #if defined(GCC_DIAGNOSTIC)
  844. /* Show no warning in case system functions are not used. */
  845. #pragma GCC diagnostic push
  846. #pragma GCC diagnostic ignored "-Wunused-function"
  847. #endif
  848. static pthread_mutex_t global_log_file_lock;
  849. FUNCTION_MAY_BE_UNUSED
  850. static DWORD
  851. pthread_self(void)
  852. {
  853. return GetCurrentThreadId();
  854. }
  855. FUNCTION_MAY_BE_UNUSED
  856. static int
  857. pthread_key_create(
  858. pthread_key_t *key,
  859. void (*_ignored)(void *) /* destructor not supported for Windows */
  860. )
  861. {
  862. (void)_ignored;
  863. if ((key != 0)) {
  864. *key = TlsAlloc();
  865. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  866. }
  867. return -2;
  868. }
  869. FUNCTION_MAY_BE_UNUSED
  870. static int
  871. pthread_key_delete(pthread_key_t key)
  872. {
  873. return TlsFree(key) ? 0 : 1;
  874. }
  875. FUNCTION_MAY_BE_UNUSED
  876. static int
  877. pthread_setspecific(pthread_key_t key, void *value)
  878. {
  879. return TlsSetValue(key, value) ? 0 : 1;
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static void *
  883. pthread_getspecific(pthread_key_t key)
  884. {
  885. return TlsGetValue(key);
  886. }
  887. #if defined(GCC_DIAGNOSTIC)
  888. /* Enable unused function warning again */
  889. #pragma GCC diagnostic pop
  890. #endif
  891. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  892. #else
  893. static pthread_mutexattr_t pthread_mutex_attr;
  894. #endif /* _WIN32 */
  895. #if defined(GCC_DIAGNOSTIC)
  896. /* Show no warning in case system functions are not used. */
  897. #pragma GCC diagnostic push
  898. #pragma GCC diagnostic ignored "-Wunused-function"
  899. #endif /* defined(GCC_DIAGNOSTIC) */
  900. #if defined(__clang__)
  901. /* Show no warning in case system functions are not used. */
  902. #pragma clang diagnostic push
  903. #pragma clang diagnostic ignored "-Wunused-function"
  904. #endif
  905. static pthread_mutex_t global_lock_mutex;
  906. FUNCTION_MAY_BE_UNUSED
  907. static void
  908. mg_global_lock(void)
  909. {
  910. (void)pthread_mutex_lock(&global_lock_mutex);
  911. }
  912. FUNCTION_MAY_BE_UNUSED
  913. static void
  914. mg_global_unlock(void)
  915. {
  916. (void)pthread_mutex_unlock(&global_lock_mutex);
  917. }
  918. #if defined(_WIN64)
  919. mg_static_assert(SIZE_MAX == 0xFFFFFFFFFFFFFFFFu, "Mismatch for atomic types");
  920. #elif defined(_WIN32)
  921. mg_static_assert(SIZE_MAX == 0xFFFFFFFFu, "Mismatch for atomic types");
  922. #endif
  923. /* Atomic functions working on ptrdiff_t ("signed size_t").
  924. * Operations: Increment, Decrement, Add, Maximum.
  925. * Up to size_t, they do not an atomic "load" operation.
  926. */
  927. FUNCTION_MAY_BE_UNUSED
  928. static ptrdiff_t
  929. mg_atomic_inc(volatile ptrdiff_t *addr)
  930. {
  931. ptrdiff_t ret;
  932. #if defined(_WIN64) && !defined(NO_ATOMICS)
  933. ret = InterlockedIncrement64(addr);
  934. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  935. #ifdef __cplusplus
  936. /* For C++ the Microsoft Visual Studio compiler can not decide what
  937. * overloaded function prototpye in the SDC corresponds to "ptrdiff_t". */
  938. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  939. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  940. ret = InterlockedIncrement((LONG *)addr);
  941. #else
  942. ret = InterlockedIncrement(addr);
  943. #endif
  944. #elif defined(__GNUC__) \
  945. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  946. && !defined(NO_ATOMICS)
  947. ret = __sync_add_and_fetch(addr, 1);
  948. #else
  949. mg_global_lock();
  950. ret = (++(*addr));
  951. mg_global_unlock();
  952. #endif
  953. return ret;
  954. }
  955. FUNCTION_MAY_BE_UNUSED
  956. static ptrdiff_t
  957. mg_atomic_dec(volatile ptrdiff_t *addr)
  958. {
  959. ptrdiff_t ret;
  960. #if defined(_WIN64) && !defined(NO_ATOMICS)
  961. ret = InterlockedDecrement64(addr);
  962. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  963. #ifdef __cplusplus
  964. /* see mg_atomic_inc */
  965. static_assert(sizeof(ptrdiff_t) == sizeof(LONG), "Size mismatch");
  966. static_assert(sizeof(ptrdiff_t) == sizeof(int32_t), "Size mismatch");
  967. ret = InterlockedDecrement((LONG *)addr);
  968. #else
  969. ret = InterlockedDecrement(addr);
  970. #endif
  971. #elif defined(__GNUC__) \
  972. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  973. && !defined(NO_ATOMICS)
  974. ret = __sync_sub_and_fetch(addr, 1);
  975. #else
  976. mg_global_lock();
  977. ret = (--(*addr));
  978. mg_global_unlock();
  979. #endif
  980. return ret;
  981. }
  982. #if defined(USE_SERVER_STATS) || defined(STOP_FLAG_NEEDS_LOCK)
  983. static ptrdiff_t
  984. mg_atomic_add(volatile ptrdiff_t *addr, ptrdiff_t value)
  985. {
  986. ptrdiff_t ret;
  987. #if defined(_WIN64) && !defined(NO_ATOMICS)
  988. ret = InterlockedAdd64(addr, value);
  989. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  990. ret = InterlockedExchangeAdd(addr, value) + value;
  991. #elif defined(__GNUC__) \
  992. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  993. && !defined(NO_ATOMICS)
  994. ret = __sync_add_and_fetch(addr, value);
  995. #else
  996. mg_global_lock();
  997. *addr += value;
  998. ret = (*addr);
  999. mg_global_unlock();
  1000. #endif
  1001. return ret;
  1002. }
  1003. FUNCTION_MAY_BE_UNUSED
  1004. static ptrdiff_t
  1005. mg_atomic_compare_and_swap(volatile ptrdiff_t *addr,
  1006. ptrdiff_t oldval,
  1007. ptrdiff_t newval)
  1008. {
  1009. ptrdiff_t ret;
  1010. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1011. ret = InterlockedCompareExchange64(addr, newval, oldval);
  1012. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1013. ret = InterlockedCompareExchange(addr, newval, oldval);
  1014. #elif defined(__GNUC__) \
  1015. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1016. && !defined(NO_ATOMICS)
  1017. ret = __sync_val_compare_and_swap(addr, oldval, newval);
  1018. #else
  1019. mg_global_lock();
  1020. ret = *addr;
  1021. if ((ret != newval) && (ret == oldval)) {
  1022. *addr = newval;
  1023. }
  1024. mg_global_unlock();
  1025. #endif
  1026. return ret;
  1027. }
  1028. static void
  1029. mg_atomic_max(volatile ptrdiff_t *addr, ptrdiff_t value)
  1030. {
  1031. register ptrdiff_t tmp = *addr;
  1032. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1033. while (tmp < value) {
  1034. tmp = InterlockedCompareExchange64(addr, value, tmp);
  1035. }
  1036. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1037. while (tmp < value) {
  1038. tmp = InterlockedCompareExchange(addr, value, tmp);
  1039. }
  1040. #elif defined(__GNUC__) \
  1041. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1042. && !defined(NO_ATOMICS)
  1043. while (tmp < value) {
  1044. tmp = __sync_val_compare_and_swap(addr, tmp, value);
  1045. }
  1046. #else
  1047. mg_global_lock();
  1048. if (*addr < value) {
  1049. *addr = value;
  1050. }
  1051. mg_global_unlock();
  1052. #endif
  1053. }
  1054. static int64_t
  1055. mg_atomic_add64(volatile int64_t *addr, int64_t value)
  1056. {
  1057. int64_t ret;
  1058. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1059. ret = InterlockedAdd64(addr, value);
  1060. #elif defined(_WIN32) && !defined(NO_ATOMICS)
  1061. ret = InterlockedExchangeAdd64(addr, value) + value;
  1062. #elif defined(__GNUC__) \
  1063. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1064. && !defined(NO_ATOMICS)
  1065. ret = __sync_add_and_fetch(addr, value);
  1066. #else
  1067. mg_global_lock();
  1068. *addr += value;
  1069. ret = (*addr);
  1070. mg_global_unlock();
  1071. #endif
  1072. return ret;
  1073. }
  1074. #endif
  1075. #if defined(GCC_DIAGNOSTIC)
  1076. /* Show no warning in case system functions are not used. */
  1077. #pragma GCC diagnostic pop
  1078. #endif /* defined(GCC_DIAGNOSTIC) */
  1079. #if defined(__clang__)
  1080. /* Show no warning in case system functions are not used. */
  1081. #pragma clang diagnostic pop
  1082. #endif
  1083. #if defined(USE_SERVER_STATS)
  1084. struct mg_memory_stat {
  1085. volatile ptrdiff_t totalMemUsed;
  1086. volatile ptrdiff_t maxMemUsed;
  1087. volatile ptrdiff_t blockCount;
  1088. };
  1089. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1090. static void *
  1091. mg_malloc_ex(size_t size,
  1092. struct mg_context *ctx,
  1093. const char *file,
  1094. unsigned line)
  1095. {
  1096. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1097. void *memory = 0;
  1098. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1099. #if defined(MEMORY_DEBUGGING)
  1100. char mallocStr[256];
  1101. #else
  1102. (void)file;
  1103. (void)line;
  1104. #endif
  1105. if (data) {
  1106. uintptr_t *tmp = (uintptr_t *)data;
  1107. ptrdiff_t mmem = mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)size);
  1108. mg_atomic_max(&mstat->maxMemUsed, mmem);
  1109. mg_atomic_inc(&mstat->blockCount);
  1110. tmp[0] = size;
  1111. tmp[1] = (uintptr_t)mstat;
  1112. memory = (void *)&tmp[2];
  1113. }
  1114. #if defined(MEMORY_DEBUGGING)
  1115. sprintf(mallocStr,
  1116. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1117. memory,
  1118. (unsigned long)size,
  1119. (unsigned long)mstat->totalMemUsed,
  1120. (unsigned long)mstat->blockCount,
  1121. file,
  1122. line);
  1123. DEBUG_TRACE("%s", mallocStr);
  1124. #endif
  1125. return memory;
  1126. }
  1127. static void *
  1128. mg_calloc_ex(size_t count,
  1129. size_t size,
  1130. struct mg_context *ctx,
  1131. const char *file,
  1132. unsigned line)
  1133. {
  1134. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1135. if (data) {
  1136. memset(data, 0, size * count);
  1137. }
  1138. return data;
  1139. }
  1140. static void
  1141. mg_free_ex(void *memory, const char *file, unsigned line)
  1142. {
  1143. #if defined(MEMORY_DEBUGGING)
  1144. char mallocStr[256];
  1145. #else
  1146. (void)file;
  1147. (void)line;
  1148. #endif
  1149. if (memory) {
  1150. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1151. uintptr_t size = ((uintptr_t *)data)[0];
  1152. struct mg_memory_stat *mstat =
  1153. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1154. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)size);
  1155. mg_atomic_dec(&mstat->blockCount);
  1156. #if defined(MEMORY_DEBUGGING)
  1157. sprintf(mallocStr,
  1158. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1159. memory,
  1160. (unsigned long)size,
  1161. (unsigned long)mstat->totalMemUsed,
  1162. (unsigned long)mstat->blockCount,
  1163. file,
  1164. line);
  1165. DEBUG_TRACE("%s", mallocStr);
  1166. #endif
  1167. free(data);
  1168. }
  1169. }
  1170. static void *
  1171. mg_realloc_ex(void *memory,
  1172. size_t newsize,
  1173. struct mg_context *ctx,
  1174. const char *file,
  1175. unsigned line)
  1176. {
  1177. void *data;
  1178. void *_realloc;
  1179. uintptr_t oldsize;
  1180. #if defined(MEMORY_DEBUGGING)
  1181. char mallocStr[256];
  1182. #else
  1183. (void)file;
  1184. (void)line;
  1185. #endif
  1186. if (newsize) {
  1187. if (memory) {
  1188. /* Reallocate existing block */
  1189. struct mg_memory_stat *mstat;
  1190. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1191. oldsize = ((uintptr_t *)data)[0];
  1192. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1193. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1194. if (_realloc) {
  1195. data = _realloc;
  1196. mg_atomic_add(&mstat->totalMemUsed, -(ptrdiff_t)oldsize);
  1197. #if defined(MEMORY_DEBUGGING)
  1198. sprintf(mallocStr,
  1199. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1200. memory,
  1201. (unsigned long)oldsize,
  1202. (unsigned long)mstat->totalMemUsed,
  1203. (unsigned long)mstat->blockCount,
  1204. file,
  1205. line);
  1206. DEBUG_TRACE("%s", mallocStr);
  1207. #endif
  1208. mg_atomic_add(&mstat->totalMemUsed, (ptrdiff_t)newsize);
  1209. #if defined(MEMORY_DEBUGGING)
  1210. sprintf(mallocStr,
  1211. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1212. memory,
  1213. (unsigned long)newsize,
  1214. (unsigned long)mstat->totalMemUsed,
  1215. (unsigned long)mstat->blockCount,
  1216. file,
  1217. line);
  1218. DEBUG_TRACE("%s", mallocStr);
  1219. #endif
  1220. *(uintptr_t *)data = newsize;
  1221. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1222. } else {
  1223. #if defined(MEMORY_DEBUGGING)
  1224. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1225. #endif
  1226. return _realloc;
  1227. }
  1228. } else {
  1229. /* Allocate new block */
  1230. data = mg_malloc_ex(newsize, ctx, file, line);
  1231. }
  1232. } else {
  1233. /* Free existing block */
  1234. data = 0;
  1235. mg_free_ex(memory, file, line);
  1236. }
  1237. return data;
  1238. }
  1239. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1240. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1241. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1242. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1243. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1246. #else /* USE_SERVER_STATS */
  1247. static __inline void *
  1248. mg_malloc(size_t a)
  1249. {
  1250. return malloc(a);
  1251. }
  1252. static __inline void *
  1253. mg_calloc(size_t a, size_t b)
  1254. {
  1255. return calloc(a, b);
  1256. }
  1257. static __inline void *
  1258. mg_realloc(void *a, size_t b)
  1259. {
  1260. return realloc(a, b);
  1261. }
  1262. static __inline void
  1263. mg_free(void *a)
  1264. {
  1265. free(a);
  1266. }
  1267. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1268. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1269. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1270. #define mg_free_ctx(a, c) mg_free(a)
  1271. #endif /* USE_SERVER_STATS */
  1272. static void mg_vsnprintf(const struct mg_connection *conn,
  1273. int *truncated,
  1274. char *buf,
  1275. size_t buflen,
  1276. const char *fmt,
  1277. va_list ap);
  1278. static void mg_snprintf(const struct mg_connection *conn,
  1279. int *truncated,
  1280. char *buf,
  1281. size_t buflen,
  1282. PRINTF_FORMAT_STRING(const char *fmt),
  1283. ...) PRINTF_ARGS(5, 6);
  1284. /* This following lines are just meant as a reminder to use the mg-functions
  1285. * for memory management */
  1286. #if defined(malloc)
  1287. #undef malloc
  1288. #endif
  1289. #if defined(calloc)
  1290. #undef calloc
  1291. #endif
  1292. #if defined(realloc)
  1293. #undef realloc
  1294. #endif
  1295. #if defined(free)
  1296. #undef free
  1297. #endif
  1298. #if defined(snprintf)
  1299. #undef snprintf
  1300. #endif
  1301. #if defined(vsnprintf)
  1302. #undef vsnprintf
  1303. #endif
  1304. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1305. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1306. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1307. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1308. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1309. #if defined(_WIN32)
  1310. /* vsnprintf must not be used in any system,
  1311. * but this define only works well for Windows. */
  1312. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1313. #endif
  1314. /* mg_init_library counter */
  1315. static int mg_init_library_called = 0;
  1316. #if !defined(NO_SSL)
  1317. #if defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1318. || defined(OPENSSL_API_3_0)
  1319. static int mg_openssl_initialized = 0;
  1320. #endif
  1321. #if !defined(OPENSSL_API_1_0) && !defined(OPENSSL_API_1_1) \
  1322. && !defined(OPENSSL_API_3_0) && !defined(USE_MBEDTLS)
  1323. #error "Please define OPENSSL_API_#_# or USE_MBEDTLS"
  1324. #endif
  1325. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_1_1)
  1326. #error "Multiple OPENSSL_API versions defined"
  1327. #endif
  1328. #if defined(OPENSSL_API_1_1) && defined(OPENSSL_API_3_0)
  1329. #error "Multiple OPENSSL_API versions defined"
  1330. #endif
  1331. #if defined(OPENSSL_API_1_0) && defined(OPENSSL_API_3_0)
  1332. #error "Multiple OPENSSL_API versions defined"
  1333. #endif
  1334. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  1335. || defined(OPENSSL_API_3_0)) \
  1336. && defined(USE_MBEDTLS)
  1337. #error "Multiple SSL libraries defined"
  1338. #endif
  1339. #endif
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static volatile ptrdiff_t thread_idx_max = 0;
  1342. #if defined(MG_LEGACY_INTERFACE)
  1343. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1344. #endif
  1345. struct mg_workerTLS {
  1346. int is_master;
  1347. unsigned long thread_idx;
  1348. void *user_ptr;
  1349. #if defined(_WIN32)
  1350. HANDLE pthread_cond_helper_mutex;
  1351. struct mg_workerTLS *next_waiting_thread;
  1352. #endif
  1353. const char *alpn_proto;
  1354. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1355. char txtbuf[4];
  1356. #endif
  1357. };
  1358. #if defined(GCC_DIAGNOSTIC)
  1359. /* Show no warning in case system functions are not used. */
  1360. #pragma GCC diagnostic push
  1361. #pragma GCC diagnostic ignored "-Wunused-function"
  1362. #endif /* defined(GCC_DIAGNOSTIC) */
  1363. #if defined(__clang__)
  1364. /* Show no warning in case system functions are not used. */
  1365. #pragma clang diagnostic push
  1366. #pragma clang diagnostic ignored "-Wunused-function"
  1367. #endif
  1368. /* Get a unique thread ID as unsigned long, independent from the data type
  1369. * of thread IDs defined by the operating system API.
  1370. * If two calls to mg_current_thread_id return the same value, they calls
  1371. * are done from the same thread. If they return different values, they are
  1372. * done from different threads. (Provided this function is used in the same
  1373. * process context and threads are not repeatedly created and deleted, but
  1374. * CivetWeb does not do that).
  1375. * This function must match the signature required for SSL id callbacks:
  1376. * CRYPTO_set_id_callback
  1377. */
  1378. FUNCTION_MAY_BE_UNUSED
  1379. static unsigned long
  1380. mg_current_thread_id(void)
  1381. {
  1382. #if defined(_WIN32)
  1383. return GetCurrentThreadId();
  1384. #else
  1385. #if defined(__clang__)
  1386. #pragma clang diagnostic push
  1387. #pragma clang diagnostic ignored "-Wunreachable-code"
  1388. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1389. * or not, so one of the two conditions will be unreachable by construction.
  1390. * Unfortunately the C standard does not define a way to check this at
  1391. * compile time, since the #if preprocessor conditions can not use the
  1392. * sizeof operator as an argument. */
  1393. #endif
  1394. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1395. /* This is the problematic case for CRYPTO_set_id_callback:
  1396. * The OS pthread_t can not be cast to unsigned long. */
  1397. struct mg_workerTLS *tls =
  1398. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1399. if (tls == NULL) {
  1400. /* SSL called from an unknown thread: Create some thread index.
  1401. */
  1402. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1403. tls->is_master = -2; /* -2 means "3rd party thread" */
  1404. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1405. pthread_setspecific(sTlsKey, tls);
  1406. }
  1407. return tls->thread_idx;
  1408. } else {
  1409. /* pthread_t may be any data type, so a simple cast to unsigned long
  1410. * can rise a warning/error, depending on the platform.
  1411. * Here memcpy is used as an anything-to-anything cast. */
  1412. unsigned long ret = 0;
  1413. pthread_t t = pthread_self();
  1414. memcpy(&ret, &t, sizeof(pthread_t));
  1415. return ret;
  1416. }
  1417. #if defined(__clang__)
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #endif
  1421. }
  1422. FUNCTION_MAY_BE_UNUSED
  1423. static uint64_t
  1424. mg_get_current_time_ns(void)
  1425. {
  1426. struct timespec tsnow;
  1427. clock_gettime(CLOCK_REALTIME, &tsnow);
  1428. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1429. }
  1430. #if defined(GCC_DIAGNOSTIC)
  1431. /* Show no warning in case system functions are not used. */
  1432. #pragma GCC diagnostic pop
  1433. #endif /* defined(GCC_DIAGNOSTIC) */
  1434. #if defined(__clang__)
  1435. /* Show no warning in case system functions are not used. */
  1436. #pragma clang diagnostic pop
  1437. #endif
  1438. #if defined(NEED_DEBUG_TRACE_FUNC)
  1439. static void
  1440. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1441. {
  1442. va_list args;
  1443. struct timespec tsnow;
  1444. /* Get some operating system independent thread id */
  1445. unsigned long thread_id = mg_current_thread_id();
  1446. clock_gettime(CLOCK_REALTIME, &tsnow);
  1447. flockfile(DEBUG_TRACE_STREAM);
  1448. fprintf(DEBUG_TRACE_STREAM,
  1449. "*** %lu.%09lu %lu %s:%u: ",
  1450. (unsigned long)tsnow.tv_sec,
  1451. (unsigned long)tsnow.tv_nsec,
  1452. thread_id,
  1453. func,
  1454. line);
  1455. va_start(args, fmt);
  1456. vfprintf(DEBUG_TRACE_STREAM, fmt, args);
  1457. va_end(args);
  1458. putc('\n', DEBUG_TRACE_STREAM);
  1459. fflush(DEBUG_TRACE_STREAM);
  1460. funlockfile(DEBUG_TRACE_STREAM);
  1461. }
  1462. #endif /* NEED_DEBUG_TRACE_FUNC */
  1463. #define MD5_STATIC static
  1464. #include "md5.inl"
  1465. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1466. #if defined(NO_SOCKLEN_T)
  1467. typedef int socklen_t;
  1468. #endif /* NO_SOCKLEN_T */
  1469. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1470. #if !defined(MSG_NOSIGNAL)
  1471. #define MSG_NOSIGNAL (0)
  1472. #endif
  1473. /* SSL: mbedTLS vs. no-ssl vs. OpenSSL */
  1474. #if defined(USE_MBEDTLS)
  1475. /* mbedTLS */
  1476. #include "mod_mbedtls.inl"
  1477. #elif defined(NO_SSL)
  1478. /* no SSL */
  1479. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1480. typedef struct SSL_CTX SSL_CTX;
  1481. #elif defined(NO_SSL_DL)
  1482. /* OpenSSL without dynamic loading */
  1483. #include <openssl/bn.h>
  1484. #include <openssl/conf.h>
  1485. #include <openssl/crypto.h>
  1486. #include <openssl/dh.h>
  1487. #include <openssl/engine.h>
  1488. #include <openssl/err.h>
  1489. #include <openssl/opensslv.h>
  1490. #include <openssl/pem.h>
  1491. #include <openssl/ssl.h>
  1492. #include <openssl/tls1.h>
  1493. #include <openssl/x509.h>
  1494. #if defined(WOLFSSL_VERSION)
  1495. /* Additional defines for WolfSSL, see
  1496. * https://github.com/civetweb/civetweb/issues/583 */
  1497. #include "wolfssl_extras.inl"
  1498. #endif
  1499. #if defined(OPENSSL_IS_BORINGSSL)
  1500. /* From boringssl/src/include/openssl/mem.h:
  1501. *
  1502. * OpenSSL has, historically, had a complex set of malloc debugging options.
  1503. * However, that was written in a time before Valgrind and ASAN. Since we now
  1504. * have those tools, the OpenSSL allocation functions are simply macros around
  1505. * the standard memory functions.
  1506. *
  1507. * #define OPENSSL_free free */
  1508. #define free free
  1509. // disable for boringssl
  1510. #define CONF_modules_unload(a) ((void)0)
  1511. #define ENGINE_cleanup() ((void)0)
  1512. #endif
  1513. /* If OpenSSL headers are included, automatically select the API version */
  1514. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  1515. #if !defined(OPENSSL_API_3_0)
  1516. #define OPENSSL_API_3_0
  1517. #endif
  1518. #define OPENSSL_REMOVE_THREAD_STATE()
  1519. #else
  1520. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1521. #if !defined(OPENSSL_API_1_1)
  1522. #define OPENSSL_API_1_1
  1523. #endif
  1524. #define OPENSSL_REMOVE_THREAD_STATE()
  1525. #else
  1526. #if !defined(OPENSSL_API_1_0)
  1527. #define OPENSSL_API_1_0
  1528. #endif
  1529. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1530. #endif
  1531. #endif
  1532. #else
  1533. /* SSL loaded dynamically from DLL / shared object */
  1534. /* Add all prototypes here, to be independent from OpenSSL source
  1535. * installation. */
  1536. #include "openssl_dl.inl"
  1537. #endif /* Various SSL bindings */
  1538. #if !defined(NO_CACHING)
  1539. static const char month_names[][4] = {"Jan",
  1540. "Feb",
  1541. "Mar",
  1542. "Apr",
  1543. "May",
  1544. "Jun",
  1545. "Jul",
  1546. "Aug",
  1547. "Sep",
  1548. "Oct",
  1549. "Nov",
  1550. "Dec"};
  1551. #endif /* !NO_CACHING */
  1552. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1553. * the union u. */
  1554. union usa {
  1555. struct sockaddr sa;
  1556. struct sockaddr_in sin;
  1557. #if defined(USE_IPV6)
  1558. struct sockaddr_in6 sin6;
  1559. #endif
  1560. #if defined(USE_X_DOM_SOCKET)
  1561. struct sockaddr_un sun;
  1562. #endif
  1563. };
  1564. #if defined(USE_X_DOM_SOCKET)
  1565. static unsigned short
  1566. USA_IN_PORT_UNSAFE(union usa *s)
  1567. {
  1568. if (s->sa.sa_family == AF_INET)
  1569. return s->sin.sin_port;
  1570. #if defined(USE_IPV6)
  1571. if (s->sa.sa_family == AF_INET6)
  1572. return s->sin6.sin6_port;
  1573. #endif
  1574. return 0;
  1575. }
  1576. #endif
  1577. #if defined(USE_IPV6)
  1578. #define USA_IN_PORT_UNSAFE(s) \
  1579. (((s)->sa.sa_family == AF_INET6) ? (s)->sin6.sin6_port : (s)->sin.sin_port)
  1580. #else
  1581. #define USA_IN_PORT_UNSAFE(s) ((s)->sin.sin_port)
  1582. #endif
  1583. /* Describes a string (chunk of memory). */
  1584. struct vec {
  1585. const char *ptr;
  1586. size_t len;
  1587. };
  1588. struct mg_file_stat {
  1589. /* File properties filled by mg_stat: */
  1590. uint64_t size;
  1591. time_t last_modified;
  1592. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1593. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1594. * case we need a "Content-Eencoding: gzip" header */
  1595. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1596. };
  1597. struct mg_file_access {
  1598. /* File properties filled by mg_fopen: */
  1599. FILE *fp;
  1600. };
  1601. struct mg_file {
  1602. struct mg_file_stat stat;
  1603. struct mg_file_access access;
  1604. };
  1605. #define STRUCT_FILE_INITIALIZER \
  1606. { \
  1607. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1608. { \
  1609. (FILE *)NULL \
  1610. } \
  1611. }
  1612. /* Describes listening socket, or socket which was accept()-ed by the master
  1613. * thread and queued for future handling by the worker thread. */
  1614. struct socket {
  1615. SOCKET sock; /* Listening socket */
  1616. union usa lsa; /* Local socket address */
  1617. union usa rsa; /* Remote socket address */
  1618. unsigned char is_ssl; /* Is port SSL-ed */
  1619. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1620. * port */
  1621. unsigned char
  1622. is_optional; /* Shouldn't cause us to exit if we can't bind to it */
  1623. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1624. };
  1625. /* Enum const for all options must be in sync with
  1626. * static struct mg_option config_options[]
  1627. * This is tested in the unit test (test/private.c)
  1628. * "Private Config Options"
  1629. */
  1630. enum {
  1631. /* Once for each server */
  1632. LISTENING_PORTS,
  1633. NUM_THREADS,
  1634. PRESPAWN_THREADS,
  1635. RUN_AS_USER,
  1636. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1637. * socket option typedef TCP_NODELAY. */
  1638. MAX_REQUEST_SIZE,
  1639. LINGER_TIMEOUT,
  1640. CONNECTION_QUEUE_SIZE,
  1641. LISTEN_BACKLOG_SIZE,
  1642. #if defined(__linux__)
  1643. ALLOW_SENDFILE_CALL,
  1644. #endif
  1645. #if defined(_WIN32)
  1646. CASE_SENSITIVE_FILES,
  1647. #endif
  1648. THROTTLE,
  1649. ENABLE_KEEP_ALIVE,
  1650. REQUEST_TIMEOUT,
  1651. KEEP_ALIVE_TIMEOUT,
  1652. #if defined(USE_WEBSOCKET)
  1653. WEBSOCKET_TIMEOUT,
  1654. ENABLE_WEBSOCKET_PING_PONG,
  1655. #endif
  1656. DECODE_URL,
  1657. DECODE_QUERY_STRING,
  1658. #if defined(USE_LUA)
  1659. LUA_BACKGROUND_SCRIPT,
  1660. LUA_BACKGROUND_SCRIPT_PARAMS,
  1661. #endif
  1662. #if defined(USE_HTTP2)
  1663. ENABLE_HTTP2,
  1664. #endif
  1665. /* Once for each domain */
  1666. DOCUMENT_ROOT,
  1667. FALLBACK_DOCUMENT_ROOT,
  1668. ACCESS_LOG_FILE,
  1669. ERROR_LOG_FILE,
  1670. CGI_EXTENSIONS,
  1671. CGI_ENVIRONMENT,
  1672. CGI_INTERPRETER,
  1673. CGI_INTERPRETER_ARGS,
  1674. #if defined(USE_TIMERS)
  1675. CGI_TIMEOUT,
  1676. #endif
  1677. CGI_BUFFERING,
  1678. CGI2_EXTENSIONS,
  1679. CGI2_ENVIRONMENT,
  1680. CGI2_INTERPRETER,
  1681. CGI2_INTERPRETER_ARGS,
  1682. #if defined(USE_TIMERS)
  1683. CGI2_TIMEOUT,
  1684. #endif
  1685. CGI2_BUFFERING,
  1686. #if defined(USE_4_CGI)
  1687. CGI3_EXTENSIONS,
  1688. CGI3_ENVIRONMENT,
  1689. CGI3_INTERPRETER,
  1690. CGI3_INTERPRETER_ARGS,
  1691. #if defined(USE_TIMERS)
  1692. CGI3_TIMEOUT,
  1693. #endif
  1694. CGI3_BUFFERING,
  1695. CGI4_EXTENSIONS,
  1696. CGI4_ENVIRONMENT,
  1697. CGI4_INTERPRETER,
  1698. CGI4_INTERPRETER_ARGS,
  1699. #if defined(USE_TIMERS)
  1700. CGI4_TIMEOUT,
  1701. #endif
  1702. CGI4_BUFFERING,
  1703. #endif
  1704. PUT_DELETE_PASSWORDS_FILE, /* must follow CGI_* */
  1705. PROTECT_URI,
  1706. AUTHENTICATION_DOMAIN,
  1707. ENABLE_AUTH_DOMAIN_CHECK,
  1708. SSI_EXTENSIONS,
  1709. ENABLE_DIRECTORY_LISTING,
  1710. ENABLE_WEBDAV,
  1711. GLOBAL_PASSWORDS_FILE,
  1712. INDEX_FILES,
  1713. ACCESS_CONTROL_LIST,
  1714. EXTRA_MIME_TYPES,
  1715. SSL_CERTIFICATE,
  1716. SSL_CERTIFICATE_CHAIN,
  1717. URL_REWRITE_PATTERN,
  1718. HIDE_FILES,
  1719. SSL_DO_VERIFY_PEER,
  1720. SSL_CACHE_TIMEOUT,
  1721. SSL_CA_PATH,
  1722. SSL_CA_FILE,
  1723. SSL_VERIFY_DEPTH,
  1724. SSL_DEFAULT_VERIFY_PATHS,
  1725. SSL_CIPHER_LIST,
  1726. SSL_PROTOCOL_VERSION,
  1727. SSL_SHORT_TRUST,
  1728. #if defined(USE_LUA)
  1729. LUA_PRELOAD_FILE,
  1730. LUA_SCRIPT_EXTENSIONS,
  1731. LUA_SERVER_PAGE_EXTENSIONS,
  1732. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1733. LUA_DEBUG_PARAMS,
  1734. #endif
  1735. #endif
  1736. #if defined(USE_DUKTAPE)
  1737. DUKTAPE_SCRIPT_EXTENSIONS,
  1738. #endif
  1739. #if defined(USE_WEBSOCKET)
  1740. WEBSOCKET_ROOT,
  1741. FALLBACK_WEBSOCKET_ROOT,
  1742. #endif
  1743. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1744. LUA_WEBSOCKET_EXTENSIONS,
  1745. #endif
  1746. ACCESS_CONTROL_ALLOW_ORIGIN,
  1747. ACCESS_CONTROL_ALLOW_METHODS,
  1748. ACCESS_CONTROL_ALLOW_HEADERS,
  1749. ACCESS_CONTROL_EXPOSE_HEADERS,
  1750. ACCESS_CONTROL_ALLOW_CREDENTIALS,
  1751. ERROR_PAGES,
  1752. #if !defined(NO_CACHING)
  1753. STATIC_FILE_MAX_AGE,
  1754. STATIC_FILE_CACHE_CONTROL,
  1755. #endif
  1756. #if !defined(NO_SSL)
  1757. STRICT_HTTPS_MAX_AGE,
  1758. #endif
  1759. ADDITIONAL_HEADER,
  1760. ALLOW_INDEX_SCRIPT_SUB_RES,
  1761. NUM_OPTIONS
  1762. };
  1763. /* Config option name, config types, default value.
  1764. * Must be in the same order as the enum const above.
  1765. */
  1766. static const struct mg_option config_options[] = {
  1767. /* Once for each server */
  1768. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1769. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1770. {"prespawn_threads", MG_CONFIG_TYPE_NUMBER, "0"},
  1771. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1772. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1773. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1774. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1775. {"connection_queue", MG_CONFIG_TYPE_NUMBER, "20"},
  1776. {"listen_backlog", MG_CONFIG_TYPE_NUMBER, "200"},
  1777. #if defined(__linux__)
  1778. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1779. #endif
  1780. #if defined(_WIN32)
  1781. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1782. #endif
  1783. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1784. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1785. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1786. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1787. #if defined(USE_WEBSOCKET)
  1788. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1789. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1790. #endif
  1791. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1792. {"decode_query_string", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1793. #if defined(USE_LUA)
  1794. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1795. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1796. #endif
  1797. #if defined(USE_HTTP2)
  1798. {"enable_http2", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1799. #endif
  1800. /* Once for each domain */
  1801. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1802. {"fallback_document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1803. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1804. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1805. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1806. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1807. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1808. {"cgi_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1809. #if defined(USE_TIMERS)
  1810. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1811. #endif
  1812. {"cgi_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1813. {"cgi2_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1814. {"cgi2_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1815. {"cgi2_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1816. {"cgi2_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1817. #if defined(USE_TIMERS)
  1818. {"cgi2_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1819. #endif
  1820. {"cgi2_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1821. #if defined(USE_4_CGI)
  1822. {"cgi3_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1823. {"cgi3_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1824. {"cgi3_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1825. {"cgi3_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1826. #if defined(USE_TIMERS)
  1827. {"cgi3_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1828. #endif
  1829. {"cgi3_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1830. {"cgi4_pattern", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1831. {"cgi4_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1832. {"cgi4_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1833. {"cgi4_interpreter_args", MG_CONFIG_TYPE_STRING, NULL},
  1834. #if defined(USE_TIMERS)
  1835. {"cgi4_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1836. #endif
  1837. {"cgi4_buffering", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1838. #endif
  1839. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1840. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1841. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1842. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1843. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1844. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1845. {"enable_webdav", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1846. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1847. {"index_files",
  1848. MG_CONFIG_TYPE_STRING_LIST,
  1849. #if defined(USE_LUA)
  1850. "index.xhtml,index.html,index.htm,"
  1851. "index.lp,index.lsp,index.lua,index.cgi,"
  1852. "index.shtml,index.php"},
  1853. #else
  1854. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1855. #endif
  1856. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1857. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1858. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1859. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1860. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1861. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1862. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1863. {"ssl_cache_timeout", MG_CONFIG_TYPE_NUMBER, "-1"},
  1864. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1865. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1866. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1867. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1868. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1869. /* HTTP2 requires ALPN, and anyway TLS1.2 should be considered
  1870. * as a minimum in 2020 */
  1871. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "4"},
  1872. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1873. #if defined(USE_LUA)
  1874. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1875. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1876. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1877. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1878. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  1879. #endif
  1880. #endif
  1881. #if defined(USE_DUKTAPE)
  1882. /* The support for duktape is still in alpha version state.
  1883. * The name of this config option might change. */
  1884. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1885. #endif
  1886. #if defined(USE_WEBSOCKET)
  1887. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1888. {"fallback_websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1889. #endif
  1890. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1891. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1892. #endif
  1893. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1894. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1895. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1896. {"access_control_expose_headers", MG_CONFIG_TYPE_STRING, ""},
  1897. {"access_control_allow_credentials", MG_CONFIG_TYPE_STRING, ""},
  1898. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1899. #if !defined(NO_CACHING)
  1900. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1901. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  1902. #endif
  1903. #if !defined(NO_SSL)
  1904. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1905. #endif
  1906. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1907. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1908. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1909. /* Check if the config_options and the corresponding enum have compatible
  1910. * sizes. */
  1911. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1912. == (NUM_OPTIONS + 1),
  1913. "config_options and enum not sync");
  1914. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1915. struct mg_handler_info {
  1916. /* Name/Pattern of the URI. */
  1917. char *uri;
  1918. size_t uri_len;
  1919. /* handler type */
  1920. int handler_type;
  1921. /* Handler for http/https or requests. */
  1922. mg_request_handler handler;
  1923. unsigned int refcount;
  1924. int removing;
  1925. /* Handler for ws/wss (websocket) requests. */
  1926. mg_websocket_connect_handler connect_handler;
  1927. mg_websocket_ready_handler ready_handler;
  1928. mg_websocket_data_handler data_handler;
  1929. mg_websocket_close_handler close_handler;
  1930. /* accepted subprotocols for ws/wss requests. */
  1931. struct mg_websocket_subprotocols *subprotocols;
  1932. /* Handler for authorization requests */
  1933. mg_authorization_handler auth_handler;
  1934. /* User supplied argument for the handler function. */
  1935. void *cbdata;
  1936. /* next handler in a linked list */
  1937. struct mg_handler_info *next;
  1938. };
  1939. enum {
  1940. CONTEXT_INVALID,
  1941. CONTEXT_SERVER,
  1942. CONTEXT_HTTP_CLIENT,
  1943. CONTEXT_WS_CLIENT
  1944. };
  1945. struct mg_domain_context {
  1946. SSL_CTX *ssl_ctx; /* SSL context */
  1947. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1948. struct mg_handler_info *handlers; /* linked list of uri handlers */
  1949. int64_t ssl_cert_last_mtime;
  1950. /* Server nonce */
  1951. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1952. unsigned long nonce_count; /* Used nonces, used for authentication */
  1953. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1954. /* linked list of shared lua websockets */
  1955. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1956. #endif
  1957. /* Linked list of domains */
  1958. struct mg_domain_context *next;
  1959. };
  1960. /* Stop flag can be "volatile" or require a lock.
  1961. * MSDN uses volatile for "Interlocked" operations, but also explicitly
  1962. * states a read operation for int is always atomic. */
  1963. #if defined(STOP_FLAG_NEEDS_LOCK)
  1964. typedef ptrdiff_t volatile stop_flag_t;
  1965. static int
  1966. STOP_FLAG_IS_ZERO(const stop_flag_t *f)
  1967. {
  1968. stop_flag_t sf = mg_atomic_add((stop_flag_t *)f, 0);
  1969. return (sf == 0);
  1970. }
  1971. static int
  1972. STOP_FLAG_IS_TWO(stop_flag_t *f)
  1973. {
  1974. stop_flag_t sf = mg_atomic_add(f, 0);
  1975. return (sf == 2);
  1976. }
  1977. static void
  1978. STOP_FLAG_ASSIGN(stop_flag_t *f, stop_flag_t v)
  1979. {
  1980. stop_flag_t sf = 0;
  1981. do {
  1982. sf = mg_atomic_compare_and_swap(f, *f, v);
  1983. } while (sf != v);
  1984. }
  1985. #else /* STOP_FLAG_NEEDS_LOCK */
  1986. typedef int volatile stop_flag_t;
  1987. #define STOP_FLAG_IS_ZERO(f) ((*(f)) == 0)
  1988. #define STOP_FLAG_IS_TWO(f) ((*(f)) == 2)
  1989. #define STOP_FLAG_ASSIGN(f, v) ((*(f)) = (v))
  1990. #endif /* STOP_FLAG_NEEDS_LOCK */
  1991. #if !defined(NUM_WEBDAV_LOCKS)
  1992. #define NUM_WEBDAV_LOCKS 10
  1993. #endif
  1994. #if !defined(LOCK_DURATION_S)
  1995. #define LOCK_DURATION_S 60
  1996. #endif
  1997. struct twebdav_lock {
  1998. uint64_t locktime;
  1999. char token[33];
  2000. char path[UTF8_PATH_MAX * 2];
  2001. char user[UTF8_PATH_MAX * 2];
  2002. };
  2003. struct mg_context {
  2004. /* Part 1 - Physical context:
  2005. * This holds threads, ports, timeouts, ...
  2006. * set for the entire server, independent from the
  2007. * addressed hostname.
  2008. */
  2009. /* Connection related */
  2010. int context_type; /* See CONTEXT_* above */
  2011. struct socket *listening_sockets;
  2012. struct mg_pollfd *listening_socket_fds;
  2013. unsigned int num_listening_sockets;
  2014. struct mg_connection *worker_connections; /* The connection struct, pre-
  2015. * allocated for each worker */
  2016. #if defined(USE_SERVER_STATS)
  2017. volatile ptrdiff_t active_connections;
  2018. volatile ptrdiff_t max_active_connections;
  2019. volatile ptrdiff_t total_connections;
  2020. volatile ptrdiff_t total_requests;
  2021. volatile int64_t total_data_read;
  2022. volatile int64_t total_data_written;
  2023. #endif
  2024. /* Thread related */
  2025. stop_flag_t stop_flag; /* Should we stop event loop */
  2026. pthread_mutex_t thread_mutex; /* Protects client_socks or queue */
  2027. pthread_t masterthreadid; /* The master thread ID */
  2028. unsigned int cfg_max_worker_threads; /* How many worker-threads we are
  2029. allowed to create, total */
  2030. unsigned int spawned_worker_threads; /* How many worker-threads currently
  2031. exist (modified by master thread) */
  2032. unsigned int
  2033. idle_worker_thread_count; /* How many worker-threads are currently
  2034. sitting around with nothing to do */
  2035. /* Access to this value MUST be synchronized by thread_mutex */
  2036. pthread_t *worker_threadids; /* The worker thread IDs */
  2037. unsigned long starter_thread_idx; /* thread index which called mg_start */
  2038. /* Connection to thread dispatching */
  2039. #if defined(ALTERNATIVE_QUEUE)
  2040. struct socket *client_socks;
  2041. void **client_wait_events;
  2042. #else
  2043. struct socket *squeue; /* Socket queue (sq) : accepted sockets waiting for a
  2044. worker thread */
  2045. volatile int sq_head; /* Head of the socket queue */
  2046. volatile int sq_tail; /* Tail of the socket queue */
  2047. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2048. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2049. volatile int sq_blocked; /* Status information: sq is full */
  2050. int sq_size; /* No of elements in socket queue */
  2051. #if defined(USE_SERVER_STATS)
  2052. int sq_max_fill;
  2053. #endif /* USE_SERVER_STATS */
  2054. #endif /* ALTERNATIVE_QUEUE */
  2055. /* Memory related */
  2056. unsigned int max_request_size; /* The max request size */
  2057. #if defined(USE_SERVER_STATS)
  2058. struct mg_memory_stat ctx_memory;
  2059. #endif
  2060. /* WebDAV lock structures */
  2061. struct twebdav_lock webdav_lock[NUM_WEBDAV_LOCKS];
  2062. /* Operating system related */
  2063. char *systemName; /* What operating system is running */
  2064. time_t start_time; /* Server start time, used for authentication
  2065. * and for diagnstics. */
  2066. #if defined(USE_TIMERS)
  2067. struct ttimers *timers;
  2068. #endif
  2069. /* Lua specific: Background operations and shared websockets */
  2070. #if defined(USE_LUA)
  2071. void *lua_background_state; /* lua_State (here as void *) */
  2072. pthread_mutex_t lua_bg_mutex; /* Protect background state */
  2073. int lua_bg_log_available; /* Use Lua background state for access log */
  2074. #endif
  2075. int user_shutdown_notification_socket; /* mg_stop() will close this
  2076. socket... */
  2077. int thread_shutdown_notification_socket; /* to cause poll() in all threads
  2078. to return immediately */
  2079. /* Server nonce */
  2080. pthread_mutex_t nonce_mutex; /* Protects ssl_ctx, handlers,
  2081. * ssl_cert_last_mtime, nonce_count, and
  2082. * next (linked list) */
  2083. /* Server callbacks */
  2084. struct mg_callbacks callbacks; /* User-defined callback function */
  2085. void *user_data; /* User-defined data */
  2086. /* Part 2 - Logical domain:
  2087. * This holds hostname, TLS certificate, document root, ...
  2088. * set for a domain hosted at the server.
  2089. * There may be multiple domains hosted at one physical server.
  2090. * The default domain "dd" is the first element of a list of
  2091. * domains.
  2092. */
  2093. struct mg_domain_context dd; /* default domain */
  2094. };
  2095. #if defined(USE_SERVER_STATS)
  2096. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2097. static struct mg_memory_stat *
  2098. get_memory_stat(struct mg_context *ctx)
  2099. {
  2100. if (ctx) {
  2101. return &(ctx->ctx_memory);
  2102. }
  2103. return &mg_common_memory;
  2104. }
  2105. #endif
  2106. enum {
  2107. CONNECTION_TYPE_INVALID = 0,
  2108. CONNECTION_TYPE_REQUEST = 1,
  2109. CONNECTION_TYPE_RESPONSE = 2
  2110. };
  2111. enum {
  2112. PROTOCOL_TYPE_HTTP1 = 0,
  2113. PROTOCOL_TYPE_WEBSOCKET = 1,
  2114. PROTOCOL_TYPE_HTTP2 = 2
  2115. };
  2116. #if defined(USE_HTTP2)
  2117. #if !defined(HTTP2_DYN_TABLE_SIZE)
  2118. #define HTTP2_DYN_TABLE_SIZE (256)
  2119. #endif
  2120. struct mg_http2_connection {
  2121. uint32_t stream_id;
  2122. uint32_t dyn_table_size;
  2123. struct mg_header dyn_table[HTTP2_DYN_TABLE_SIZE];
  2124. };
  2125. #endif
  2126. struct mg_connection {
  2127. int connection_type; /* see CONNECTION_TYPE_* above */
  2128. int protocol_type; /* see PROTOCOL_TYPE_*: 0=http/1.x, 1=ws, 2=http/2 */
  2129. int request_state; /* 0: nothing sent, 1: header partially sent, 2: header
  2130. fully sent */
  2131. #if defined(USE_HTTP2)
  2132. struct mg_http2_connection http2;
  2133. #endif
  2134. struct mg_request_info request_info;
  2135. struct mg_response_info response_info;
  2136. struct mg_context *phys_ctx;
  2137. struct mg_domain_context *dom_ctx;
  2138. #if defined(USE_SERVER_STATS)
  2139. int conn_state; /* 0 = undef, numerical value may change in different
  2140. * versions. For the current definition, see
  2141. * mg_get_connection_info_impl */
  2142. #endif
  2143. SSL *ssl; /* SSL descriptor */
  2144. struct socket client; /* Connected client */
  2145. time_t conn_birth_time; /* Time (wall clock) when connection was
  2146. * established */
  2147. #if defined(USE_SERVER_STATS)
  2148. time_t conn_close_time; /* Time (wall clock) when connection was
  2149. * closed (or 0 if still open) */
  2150. double processing_time; /* Processing time for one request. */
  2151. #endif
  2152. struct timespec req_time; /* Time (since system start) when the request
  2153. * was received */
  2154. int64_t num_bytes_sent; /* Total bytes sent to client */
  2155. int64_t content_len; /* How many bytes of content can be read
  2156. * !is_chunked: Content-Length header value
  2157. * or -1 (until connection closed,
  2158. * not allowed for a request)
  2159. * is_chunked: >= 0, appended gradually
  2160. */
  2161. int64_t consumed_content; /* How many bytes of content have been read */
  2162. int is_chunked; /* Transfer-Encoding is chunked:
  2163. * 0 = not chunked,
  2164. * 1 = chunked, not yet, or some data read,
  2165. * 2 = chunked, has error,
  2166. * 3 = chunked, all data read except trailer,
  2167. * 4 = chunked, all data read
  2168. */
  2169. char *buf; /* Buffer for received data */
  2170. char *path_info; /* PATH_INFO part of the URL */
  2171. int must_close; /* 1 if connection must be closed */
  2172. int accept_gzip; /* 1 if gzip encoding is accepted */
  2173. int in_error_handler; /* 1 if in handler for user defined error
  2174. * pages */
  2175. #if defined(USE_WEBSOCKET)
  2176. int in_websocket_handling; /* 1 if in read_websocket */
  2177. #endif
  2178. #if defined(USE_ZLIB) && defined(USE_WEBSOCKET) \
  2179. && defined(MG_EXPERIMENTAL_INTERFACES)
  2180. /* Parameters for websocket data compression according to rfc7692 */
  2181. int websocket_deflate_server_max_windows_bits;
  2182. int websocket_deflate_client_max_windows_bits;
  2183. int websocket_deflate_server_no_context_takeover;
  2184. int websocket_deflate_client_no_context_takeover;
  2185. int websocket_deflate_initialized;
  2186. int websocket_deflate_flush;
  2187. z_stream websocket_deflate_state;
  2188. z_stream websocket_inflate_state;
  2189. #endif
  2190. int handled_requests; /* Number of requests handled by this connection
  2191. */
  2192. int buf_size; /* Buffer size */
  2193. int request_len; /* Size of the request + headers in a buffer */
  2194. int data_len; /* Total size of data in a buffer */
  2195. int status_code; /* HTTP reply status code, e.g. 200 */
  2196. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2197. * throttle */
  2198. time_t last_throttle_time; /* Last time throttled data was sent */
  2199. int last_throttle_bytes; /* Bytes sent this second */
  2200. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2201. * atomic transmissions for websockets */
  2202. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2203. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2204. #endif
  2205. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2206. * for quick access */
  2207. };
  2208. /* Directory entry */
  2209. struct de {
  2210. char *file_name;
  2211. struct mg_file_stat file;
  2212. };
  2213. #define mg_cry_internal(conn, fmt, ...) \
  2214. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2215. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2216. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2217. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2218. struct mg_context *ctx,
  2219. const char *func,
  2220. unsigned line,
  2221. const char *fmt,
  2222. ...) PRINTF_ARGS(5, 6);
  2223. #if !defined(NO_THREAD_NAME)
  2224. #if defined(_WIN32) && defined(_MSC_VER)
  2225. /* Set the thread name for debugging purposes in Visual Studio
  2226. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2227. */
  2228. #pragma pack(push, 8)
  2229. typedef struct tagTHREADNAME_INFO {
  2230. DWORD dwType; /* Must be 0x1000. */
  2231. LPCSTR szName; /* Pointer to name (in user addr space). */
  2232. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2233. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2234. } THREADNAME_INFO;
  2235. #pragma pack(pop)
  2236. #elif defined(__linux__)
  2237. #include <sys/prctl.h>
  2238. #include <sys/sendfile.h>
  2239. #if defined(ALTERNATIVE_QUEUE)
  2240. #include <sys/eventfd.h>
  2241. #endif /* ALTERNATIVE_QUEUE */
  2242. #if defined(ALTERNATIVE_QUEUE)
  2243. static void *
  2244. event_create(void)
  2245. {
  2246. int evhdl = eventfd(0, EFD_CLOEXEC);
  2247. int *ret;
  2248. if (evhdl == -1) {
  2249. /* Linux uses -1 on error, Windows NULL. */
  2250. /* However, Linux does not return 0 on success either. */
  2251. return 0;
  2252. }
  2253. ret = (int *)mg_malloc(sizeof(int));
  2254. if (ret) {
  2255. *ret = evhdl;
  2256. } else {
  2257. (void)close(evhdl);
  2258. }
  2259. return (void *)ret;
  2260. }
  2261. static int
  2262. event_wait(void *eventhdl)
  2263. {
  2264. uint64_t u;
  2265. int evhdl, s;
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return 0;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. s = (int)read(evhdl, &u, sizeof(u));
  2272. if (s != sizeof(u)) {
  2273. /* error */
  2274. return 0;
  2275. }
  2276. (void)u; /* the value is not required */
  2277. return 1;
  2278. }
  2279. static int
  2280. event_signal(void *eventhdl)
  2281. {
  2282. uint64_t u = 1;
  2283. int evhdl, s;
  2284. if (!eventhdl) {
  2285. /* error */
  2286. return 0;
  2287. }
  2288. evhdl = *(int *)eventhdl;
  2289. s = (int)write(evhdl, &u, sizeof(u));
  2290. if (s != sizeof(u)) {
  2291. /* error */
  2292. return 0;
  2293. }
  2294. return 1;
  2295. }
  2296. static void
  2297. event_destroy(void *eventhdl)
  2298. {
  2299. int evhdl;
  2300. if (!eventhdl) {
  2301. /* error */
  2302. return;
  2303. }
  2304. evhdl = *(int *)eventhdl;
  2305. close(evhdl);
  2306. mg_free(eventhdl);
  2307. }
  2308. #endif
  2309. #endif
  2310. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2311. struct posix_event {
  2312. pthread_mutex_t mutex;
  2313. pthread_cond_t cond;
  2314. int signaled;
  2315. };
  2316. static void *
  2317. event_create(void)
  2318. {
  2319. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2320. if (ret == 0) {
  2321. /* out of memory */
  2322. return 0;
  2323. }
  2324. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2325. /* pthread mutex not available */
  2326. mg_free(ret);
  2327. return 0;
  2328. }
  2329. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2330. /* pthread cond not available */
  2331. pthread_mutex_destroy(&(ret->mutex));
  2332. mg_free(ret);
  2333. return 0;
  2334. }
  2335. ret->signaled = 0;
  2336. return (void *)ret;
  2337. }
  2338. static int
  2339. event_wait(void *eventhdl)
  2340. {
  2341. struct posix_event *ev = (struct posix_event *)eventhdl;
  2342. pthread_mutex_lock(&(ev->mutex));
  2343. while (!ev->signaled) {
  2344. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2345. }
  2346. ev->signaled = 0;
  2347. pthread_mutex_unlock(&(ev->mutex));
  2348. return 1;
  2349. }
  2350. static int
  2351. event_signal(void *eventhdl)
  2352. {
  2353. struct posix_event *ev = (struct posix_event *)eventhdl;
  2354. pthread_mutex_lock(&(ev->mutex));
  2355. pthread_cond_signal(&(ev->cond));
  2356. ev->signaled = 1;
  2357. pthread_mutex_unlock(&(ev->mutex));
  2358. return 1;
  2359. }
  2360. static void
  2361. event_destroy(void *eventhdl)
  2362. {
  2363. struct posix_event *ev = (struct posix_event *)eventhdl;
  2364. pthread_cond_destroy(&(ev->cond));
  2365. pthread_mutex_destroy(&(ev->mutex));
  2366. mg_free(ev);
  2367. }
  2368. #endif
  2369. static void
  2370. mg_set_thread_name(const char *name)
  2371. {
  2372. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2373. mg_snprintf(
  2374. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2375. #if defined(_WIN32)
  2376. #if defined(_MSC_VER)
  2377. /* Windows and Visual Studio Compiler */
  2378. __try {
  2379. THREADNAME_INFO info;
  2380. info.dwType = 0x1000;
  2381. info.szName = threadName;
  2382. info.dwThreadID = ~0U;
  2383. info.dwFlags = 0;
  2384. RaiseException(0x406D1388,
  2385. 0,
  2386. sizeof(info) / sizeof(ULONG_PTR),
  2387. (ULONG_PTR *)&info);
  2388. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2389. }
  2390. #elif defined(__MINGW32__)
  2391. /* No option known to set thread name for MinGW known */
  2392. #endif
  2393. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2394. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2395. /* pthread_setname_np first appeared in glibc in version 2.12 */
  2396. #if defined(__MACH__) && defined(__APPLE__)
  2397. /* OS X only current thread name can be changed */
  2398. (void)pthread_setname_np(threadName);
  2399. #else
  2400. (void)pthread_setname_np(pthread_self(), threadName);
  2401. #endif
  2402. #elif defined(__linux__)
  2403. /* On Linux we can use the prctl function.
  2404. * When building for Linux Standard Base (LSB) use
  2405. * NO_THREAD_NAME. However, thread names are a big
  2406. * help for debugging, so the stadard is to set them.
  2407. */
  2408. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2409. #endif
  2410. }
  2411. #else /* !defined(NO_THREAD_NAME) */
  2412. static void
  2413. mg_set_thread_name(const char *threadName)
  2414. {
  2415. }
  2416. #endif
  2417. CIVETWEB_API const struct mg_option *
  2418. mg_get_valid_options(void)
  2419. {
  2420. return config_options;
  2421. }
  2422. /* Do not open file (unused) */
  2423. #define MG_FOPEN_MODE_NONE (0)
  2424. /* Open file for read only access */
  2425. #define MG_FOPEN_MODE_READ (1)
  2426. /* Open file for writing, create and overwrite */
  2427. #define MG_FOPEN_MODE_WRITE (2)
  2428. /* Open file for writing, create and append */
  2429. #define MG_FOPEN_MODE_APPEND (4)
  2430. static int
  2431. is_file_opened(const struct mg_file_access *fileacc)
  2432. {
  2433. if (!fileacc) {
  2434. return 0;
  2435. }
  2436. return (fileacc->fp != NULL);
  2437. }
  2438. #if !defined(NO_FILESYSTEMS)
  2439. static int mg_stat(const struct mg_connection *conn,
  2440. const char *path,
  2441. struct mg_file_stat *filep);
  2442. /* Reject files with special characters (for Windows) */
  2443. static int
  2444. mg_path_suspicious(const struct mg_connection *conn, const char *path)
  2445. {
  2446. const uint8_t *c = (const uint8_t *)path;
  2447. (void)conn; /* not used */
  2448. if ((c == NULL) || (c[0] == 0)) {
  2449. /* Null pointer or empty path --> suspicious */
  2450. return 1;
  2451. }
  2452. #if defined(_WIN32)
  2453. while (*c) {
  2454. if (*c < 32) {
  2455. /* Control character */
  2456. return 1;
  2457. }
  2458. if ((*c == '>') || (*c == '<') || (*c == '|')) {
  2459. /* stdin/stdout redirection character */
  2460. return 1;
  2461. }
  2462. if ((*c == '*') || (*c == '?')) {
  2463. /* Wildcard character */
  2464. return 1;
  2465. }
  2466. if (*c == '"') {
  2467. /* Windows quotation */
  2468. return 1;
  2469. }
  2470. c++;
  2471. }
  2472. #endif
  2473. /* Nothing suspicious found */
  2474. return 0;
  2475. }
  2476. /* mg_fopen will open a file either in memory or on the disk.
  2477. * The input parameter path is a string in UTF-8 encoding.
  2478. * The input parameter mode is MG_FOPEN_MODE_*
  2479. * On success, fp will be set in the output struct mg_file.
  2480. * All status members will also be set.
  2481. * The function returns 1 on success, 0 on error. */
  2482. static int
  2483. mg_fopen(const struct mg_connection *conn,
  2484. const char *path,
  2485. int mode,
  2486. struct mg_file *filep)
  2487. {
  2488. int found;
  2489. if (!filep) {
  2490. return 0;
  2491. }
  2492. filep->access.fp = NULL;
  2493. if (mg_path_suspicious(conn, path)) {
  2494. return 0;
  2495. }
  2496. /* filep is initialized in mg_stat: all fields with memset to,
  2497. * some fields like size and modification date with values */
  2498. found = mg_stat(conn, path, &(filep->stat));
  2499. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2500. /* file does not exist and will not be created */
  2501. return 0;
  2502. }
  2503. #if defined(_WIN32)
  2504. {
  2505. wchar_t wbuf[UTF16_PATH_MAX];
  2506. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2507. switch (mode) {
  2508. case MG_FOPEN_MODE_READ:
  2509. filep->access.fp = _wfopen(wbuf, L"rb");
  2510. break;
  2511. case MG_FOPEN_MODE_WRITE:
  2512. filep->access.fp = _wfopen(wbuf, L"wb");
  2513. break;
  2514. case MG_FOPEN_MODE_APPEND:
  2515. filep->access.fp = _wfopen(wbuf, L"ab");
  2516. break;
  2517. }
  2518. }
  2519. #else
  2520. /* Linux et al already use unicode. No need to convert. */
  2521. switch (mode) {
  2522. case MG_FOPEN_MODE_READ:
  2523. filep->access.fp = fopen(path, "r");
  2524. break;
  2525. case MG_FOPEN_MODE_WRITE:
  2526. filep->access.fp = fopen(path, "w");
  2527. break;
  2528. case MG_FOPEN_MODE_APPEND:
  2529. filep->access.fp = fopen(path, "a");
  2530. break;
  2531. }
  2532. #endif
  2533. if (!found) {
  2534. /* File did not exist before fopen was called.
  2535. * Maybe it has been created now. Get stat info
  2536. * like creation time now. */
  2537. found = mg_stat(conn, path, &(filep->stat));
  2538. (void)found;
  2539. }
  2540. /* return OK if file is opened */
  2541. return (filep->access.fp != NULL);
  2542. }
  2543. /* return 0 on success, just like fclose */
  2544. static int
  2545. mg_fclose(struct mg_file_access *fileacc)
  2546. {
  2547. int ret = -1;
  2548. if (fileacc != NULL) {
  2549. if (fileacc->fp != NULL) {
  2550. ret = fclose(fileacc->fp);
  2551. }
  2552. /* reset all members of fileacc */
  2553. memset(fileacc, 0, sizeof(*fileacc));
  2554. }
  2555. return ret;
  2556. }
  2557. #endif /* NO_FILESYSTEMS */
  2558. static void
  2559. mg_strlcpy(char *dst, const char *src, size_t n)
  2560. {
  2561. for (; *src != '\0' && n > 1; n--) {
  2562. *dst++ = *src++;
  2563. }
  2564. *dst = '\0';
  2565. }
  2566. static int
  2567. lowercase(const char *s)
  2568. {
  2569. return tolower((unsigned char)*s);
  2570. }
  2571. CIVETWEB_API int
  2572. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2573. {
  2574. int diff = 0;
  2575. if (len > 0) {
  2576. do {
  2577. diff = lowercase(s1++) - lowercase(s2++);
  2578. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2579. }
  2580. return diff;
  2581. }
  2582. CIVETWEB_API int
  2583. mg_strcasecmp(const char *s1, const char *s2)
  2584. {
  2585. int diff;
  2586. do {
  2587. diff = lowercase(s1++) - lowercase(s2++);
  2588. } while (diff == 0 && s1[-1] != '\0');
  2589. return diff;
  2590. }
  2591. static char *
  2592. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2593. {
  2594. char *p;
  2595. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2596. * defined */
  2597. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2598. mg_strlcpy(p, ptr, len + 1);
  2599. }
  2600. return p;
  2601. }
  2602. static char *
  2603. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2604. {
  2605. return mg_strndup_ctx(str, strlen(str), ctx);
  2606. }
  2607. static char *
  2608. mg_strdup(const char *str)
  2609. {
  2610. return mg_strndup_ctx(str, strlen(str), NULL);
  2611. }
  2612. static const char *
  2613. mg_strcasestr(const char *big_str, const char *small_str)
  2614. {
  2615. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2616. if (big_len >= small_len) {
  2617. for (i = 0; i <= (big_len - small_len); i++) {
  2618. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2619. return big_str + i;
  2620. }
  2621. }
  2622. }
  2623. return NULL;
  2624. }
  2625. /* Return null terminated string of given maximum length.
  2626. * Report errors if length is exceeded. */
  2627. static void
  2628. mg_vsnprintf(const struct mg_connection *conn,
  2629. int *truncated,
  2630. char *buf,
  2631. size_t buflen,
  2632. const char *fmt,
  2633. va_list ap)
  2634. {
  2635. int n, ok;
  2636. if (buflen == 0) {
  2637. if (truncated) {
  2638. *truncated = 1;
  2639. }
  2640. return;
  2641. }
  2642. #if defined(__clang__)
  2643. #pragma clang diagnostic push
  2644. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2645. /* Using fmt as a non-literal is intended here, since it is mostly called
  2646. * indirectly by mg_snprintf */
  2647. #endif
  2648. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2649. ok = (n >= 0) && ((size_t)n < buflen);
  2650. #if defined(__clang__)
  2651. #pragma clang diagnostic pop
  2652. #endif
  2653. if (ok) {
  2654. if (truncated) {
  2655. *truncated = 0;
  2656. }
  2657. } else {
  2658. if (truncated) {
  2659. *truncated = 1;
  2660. }
  2661. mg_cry_internal(conn,
  2662. "truncating vsnprintf buffer: [%.*s]",
  2663. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2664. buf);
  2665. n = (int)buflen - 1;
  2666. }
  2667. buf[n] = '\0';
  2668. }
  2669. static void
  2670. mg_snprintf(const struct mg_connection *conn,
  2671. int *truncated,
  2672. char *buf,
  2673. size_t buflen,
  2674. const char *fmt,
  2675. ...)
  2676. {
  2677. va_list ap;
  2678. va_start(ap, fmt);
  2679. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2680. va_end(ap);
  2681. }
  2682. static int
  2683. get_option_index(const char *name)
  2684. {
  2685. int i;
  2686. for (i = 0; config_options[i].name != NULL; i++) {
  2687. if (strcmp(config_options[i].name, name) == 0) {
  2688. return i;
  2689. }
  2690. }
  2691. return -1;
  2692. }
  2693. CIVETWEB_API const char *
  2694. mg_get_option(const struct mg_context *ctx, const char *name)
  2695. {
  2696. int i;
  2697. if ((i = get_option_index(name)) == -1) {
  2698. return NULL;
  2699. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2700. return "";
  2701. } else {
  2702. return ctx->dd.config[i];
  2703. }
  2704. }
  2705. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2706. CIVETWEB_API struct mg_context *
  2707. mg_get_context(const struct mg_connection *conn)
  2708. {
  2709. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2710. }
  2711. CIVETWEB_API void *
  2712. mg_get_user_data(const struct mg_context *ctx)
  2713. {
  2714. return (ctx == NULL) ? NULL : ctx->user_data;
  2715. }
  2716. CIVETWEB_API void *
  2717. mg_get_user_context_data(const struct mg_connection *conn)
  2718. {
  2719. return mg_get_user_data(mg_get_context(conn));
  2720. }
  2721. CIVETWEB_API void *
  2722. mg_get_thread_pointer(const struct mg_connection *conn)
  2723. {
  2724. /* both methods should return the same pointer */
  2725. if (conn) {
  2726. /* quick access, in case conn is known */
  2727. return conn->tls_user_ptr;
  2728. } else {
  2729. /* otherwise get pointer from thread local storage (TLS) */
  2730. struct mg_workerTLS *tls =
  2731. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2732. return tls->user_ptr;
  2733. }
  2734. }
  2735. CIVETWEB_API void
  2736. mg_set_user_connection_data(const struct mg_connection *const_conn, void *data)
  2737. {
  2738. if (const_conn != NULL) {
  2739. /* Const cast, since "const struct mg_connection *" does not mean
  2740. * the connection object is not modified. Here "const" is used,
  2741. * to indicate mg_read/mg_write/mg_send/.. must not be called. */
  2742. struct mg_connection *conn = (struct mg_connection *)const_conn;
  2743. conn->request_info.conn_data = data;
  2744. }
  2745. }
  2746. CIVETWEB_API void *
  2747. mg_get_user_connection_data(const struct mg_connection *conn)
  2748. {
  2749. if (conn != NULL) {
  2750. return conn->request_info.conn_data;
  2751. }
  2752. return NULL;
  2753. }
  2754. CIVETWEB_API int
  2755. mg_get_server_ports(const struct mg_context *ctx,
  2756. int size,
  2757. struct mg_server_port *ports)
  2758. {
  2759. int i, cnt = 0;
  2760. if (size <= 0) {
  2761. return -1;
  2762. }
  2763. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2764. if (!ctx) {
  2765. return -1;
  2766. }
  2767. if (!ctx->listening_sockets) {
  2768. return -1;
  2769. }
  2770. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2771. ports[cnt].port =
  2772. ntohs(USA_IN_PORT_UNSAFE(&(ctx->listening_sockets[i].lsa)));
  2773. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2774. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2775. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2776. /* IPv4 */
  2777. ports[cnt].protocol = 1;
  2778. cnt++;
  2779. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2780. /* IPv6 */
  2781. ports[cnt].protocol = 3;
  2782. cnt++;
  2783. }
  2784. }
  2785. return cnt;
  2786. }
  2787. #if defined(USE_X_DOM_SOCKET) && !defined(UNIX_DOMAIN_SOCKET_SERVER_NAME)
  2788. #define UNIX_DOMAIN_SOCKET_SERVER_NAME "*"
  2789. #endif
  2790. static void
  2791. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2792. {
  2793. buf[0] = '\0';
  2794. if (!usa) {
  2795. return;
  2796. }
  2797. if (usa->sa.sa_family == AF_INET) {
  2798. getnameinfo(&usa->sa,
  2799. sizeof(usa->sin),
  2800. buf,
  2801. (unsigned)len,
  2802. NULL,
  2803. 0,
  2804. NI_NUMERICHOST);
  2805. }
  2806. #if defined(USE_IPV6)
  2807. else if (usa->sa.sa_family == AF_INET6) {
  2808. getnameinfo(&usa->sa,
  2809. sizeof(usa->sin6),
  2810. buf,
  2811. (unsigned)len,
  2812. NULL,
  2813. 0,
  2814. NI_NUMERICHOST);
  2815. }
  2816. #endif
  2817. #if defined(USE_X_DOM_SOCKET)
  2818. else if (usa->sa.sa_family == AF_UNIX) {
  2819. /* TODO: Define a remote address for unix domain sockets.
  2820. * This code will always return "localhost", identical to http+tcp:
  2821. getnameinfo(&usa->sa,
  2822. sizeof(usa->sun),
  2823. buf,
  2824. (unsigned)len,
  2825. NULL,
  2826. 0,
  2827. NI_NUMERICHOST);
  2828. */
  2829. mg_strlcpy(buf, UNIX_DOMAIN_SOCKET_SERVER_NAME, len);
  2830. }
  2831. #endif
  2832. }
  2833. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2834. * included in all responses other than 100, 101, 5xx. */
  2835. static void
  2836. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2837. {
  2838. #if !defined(REENTRANT_TIME)
  2839. struct tm *tm;
  2840. tm = ((t != NULL) ? gmtime(t) : NULL);
  2841. if (tm != NULL) {
  2842. #else
  2843. struct tm _tm;
  2844. struct tm *tm = &_tm;
  2845. if (t != NULL) {
  2846. gmtime_r(t, tm);
  2847. #endif
  2848. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2849. } else {
  2850. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2851. }
  2852. }
  2853. /* difftime for struct timespec. Return value is in seconds. */
  2854. static double
  2855. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2856. {
  2857. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2858. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2859. }
  2860. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2861. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2862. const char *func,
  2863. unsigned line,
  2864. const char *fmt,
  2865. va_list ap);
  2866. #include "external_mg_cry_internal_impl.inl"
  2867. #elif !defined(NO_FILESYSTEMS)
  2868. /* Print error message to the opened error log stream. */
  2869. static void
  2870. mg_cry_internal_impl(const struct mg_connection *conn,
  2871. const char *func,
  2872. unsigned line,
  2873. const char *fmt,
  2874. va_list ap)
  2875. {
  2876. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2877. struct mg_file fi;
  2878. time_t timestamp;
  2879. /* Unused, in the RELEASE build */
  2880. (void)func;
  2881. (void)line;
  2882. #if defined(GCC_DIAGNOSTIC)
  2883. #pragma GCC diagnostic push
  2884. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2885. #endif
  2886. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2887. #if defined(GCC_DIAGNOSTIC)
  2888. #pragma GCC diagnostic pop
  2889. #endif
  2890. buf[sizeof(buf) - 1] = 0;
  2891. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2892. if (!conn) {
  2893. puts(buf);
  2894. return;
  2895. }
  2896. /* Do not lock when getting the callback value, here and below.
  2897. * I suppose this is fine, since function cannot disappear in the
  2898. * same way string option can. */
  2899. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2900. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2901. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2902. if (mg_fopen(conn,
  2903. conn->dom_ctx->config[ERROR_LOG_FILE],
  2904. MG_FOPEN_MODE_APPEND,
  2905. &fi)
  2906. == 0) {
  2907. fi.access.fp = NULL;
  2908. }
  2909. } else {
  2910. fi.access.fp = NULL;
  2911. }
  2912. if (fi.access.fp != NULL) {
  2913. flockfile(fi.access.fp);
  2914. timestamp = time(NULL);
  2915. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2916. fprintf(fi.access.fp,
  2917. "[%010lu] [error] [client %s] ",
  2918. (unsigned long)timestamp,
  2919. src_addr);
  2920. if (conn->request_info.request_method != NULL) {
  2921. fprintf(fi.access.fp,
  2922. "%s %s: ",
  2923. conn->request_info.request_method,
  2924. conn->request_info.request_uri
  2925. ? conn->request_info.request_uri
  2926. : "");
  2927. }
  2928. fprintf(fi.access.fp, "%s", buf);
  2929. fputc('\n', fi.access.fp);
  2930. fflush(fi.access.fp);
  2931. funlockfile(fi.access.fp);
  2932. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2933. * mg_cry here anyway ;-) */
  2934. }
  2935. }
  2936. }
  2937. #else
  2938. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  2939. #endif /* Externally provided function */
  2940. /* Construct fake connection structure. Used for logging, if connection
  2941. * is not applicable at the moment of logging. */
  2942. static struct mg_connection *
  2943. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  2944. {
  2945. static const struct mg_connection conn_zero = {0};
  2946. *fc = conn_zero;
  2947. fc->phys_ctx = ctx;
  2948. fc->dom_ctx = &(ctx->dd);
  2949. return fc;
  2950. }
  2951. static void
  2952. mg_cry_internal_wrap(const struct mg_connection *conn,
  2953. struct mg_context *ctx,
  2954. const char *func,
  2955. unsigned line,
  2956. const char *fmt,
  2957. ...)
  2958. {
  2959. va_list ap;
  2960. va_start(ap, fmt);
  2961. if (!conn && ctx) {
  2962. struct mg_connection fc;
  2963. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  2964. } else {
  2965. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2966. }
  2967. va_end(ap);
  2968. }
  2969. CIVETWEB_API void
  2970. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2971. {
  2972. va_list ap;
  2973. va_start(ap, fmt);
  2974. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2975. va_end(ap);
  2976. }
  2977. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2978. CIVETWEB_API const char *
  2979. mg_version(void)
  2980. {
  2981. return CIVETWEB_VERSION;
  2982. }
  2983. CIVETWEB_API const struct mg_request_info *
  2984. mg_get_request_info(const struct mg_connection *conn)
  2985. {
  2986. if (!conn) {
  2987. return NULL;
  2988. }
  2989. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  2990. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2991. char txt[16];
  2992. struct mg_workerTLS *tls =
  2993. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2994. sprintf(txt, "%03i", conn->response_info.status_code);
  2995. if (strlen(txt) == 3) {
  2996. memcpy(tls->txtbuf, txt, 4);
  2997. } else {
  2998. strcpy(tls->txtbuf, "ERR");
  2999. }
  3000. ((struct mg_connection *)conn)->request_info.local_uri =
  3001. tls->txtbuf; /* use thread safe buffer */
  3002. ((struct mg_connection *)conn)->request_info.local_uri_raw =
  3003. tls->txtbuf; /* use the same thread safe buffer */
  3004. ((struct mg_connection *)conn)->request_info.request_uri =
  3005. tls->txtbuf; /* use the same thread safe buffer */
  3006. ((struct mg_connection *)conn)->request_info.num_headers =
  3007. conn->response_info.num_headers;
  3008. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3009. conn->response_info.http_headers,
  3010. sizeof(conn->response_info.http_headers));
  3011. } else
  3012. #endif
  3013. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3014. return NULL;
  3015. }
  3016. return &conn->request_info;
  3017. }
  3018. CIVETWEB_API const struct mg_response_info *
  3019. mg_get_response_info(const struct mg_connection *conn)
  3020. {
  3021. if (!conn) {
  3022. return NULL;
  3023. }
  3024. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3025. return NULL;
  3026. }
  3027. return &conn->response_info;
  3028. }
  3029. static const char *
  3030. get_proto_name(const struct mg_connection *conn)
  3031. {
  3032. #if defined(__clang__)
  3033. #pragma clang diagnostic push
  3034. #pragma clang diagnostic ignored "-Wunreachable-code"
  3035. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3036. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3037. * unreachable, but splitting into four different #ifdef clauses here is
  3038. * more complicated.
  3039. */
  3040. #endif
  3041. const struct mg_request_info *ri = &conn->request_info;
  3042. const char *proto = ((conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET)
  3043. ? (ri->is_ssl ? "wss" : "ws")
  3044. : (ri->is_ssl ? "https" : "http"));
  3045. return proto;
  3046. #if defined(__clang__)
  3047. #pragma clang diagnostic pop
  3048. #endif
  3049. }
  3050. static int
  3051. mg_construct_local_link(const struct mg_connection *conn,
  3052. char *buf,
  3053. size_t buflen,
  3054. const char *define_proto,
  3055. int define_port,
  3056. const char *define_uri)
  3057. {
  3058. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3059. return -1;
  3060. } else {
  3061. int i, j;
  3062. int truncated = 0;
  3063. const struct mg_request_info *ri = &conn->request_info;
  3064. const char *proto =
  3065. (define_proto != NULL) ? define_proto : get_proto_name(conn);
  3066. const char *uri =
  3067. (define_uri != NULL)
  3068. ? define_uri
  3069. : ((ri->request_uri != NULL) ? ri->request_uri : ri->local_uri);
  3070. int port = (define_port > 0) ? define_port : ri->server_port;
  3071. int default_port = 80;
  3072. char *uri_encoded;
  3073. size_t uri_encoded_len;
  3074. if (uri == NULL) {
  3075. return -1;
  3076. }
  3077. uri_encoded_len = strlen(uri) * 3 + 1;
  3078. uri_encoded = (char *)mg_malloc_ctx(uri_encoded_len, conn->phys_ctx);
  3079. if (uri_encoded == NULL) {
  3080. return -1;
  3081. }
  3082. mg_url_encode(uri, uri_encoded, uri_encoded_len);
  3083. /* Directory separator should be preserved. */
  3084. for (i = j = 0; uri_encoded[i]; j++) {
  3085. if (!strncmp(uri_encoded + i, "%2f", 3)) {
  3086. uri_encoded[j] = '/';
  3087. i += 3;
  3088. } else {
  3089. uri_encoded[j] = uri_encoded[i++];
  3090. }
  3091. }
  3092. uri_encoded[j] = '\0';
  3093. #if defined(USE_X_DOM_SOCKET)
  3094. if (conn->client.lsa.sa.sa_family == AF_UNIX) {
  3095. /* TODO: Define and document a link for UNIX domain sockets. */
  3096. /* There seems to be no official standard for this.
  3097. * Common uses seem to be "httpunix://", "http.unix://" or
  3098. * "http+unix://" as a protocol definition string, followed by
  3099. * "localhost" or "127.0.0.1" or "/tmp/unix/path" or
  3100. * "%2Ftmp%2Funix%2Fpath" (url % encoded) or
  3101. * "localhost:%2Ftmp%2Funix%2Fpath" (domain socket path as port) or
  3102. * "" (completely skipping the server name part). In any case, the
  3103. * last part is the server local path. */
  3104. const char *server_name = UNIX_DOMAIN_SOCKET_SERVER_NAME;
  3105. mg_snprintf(conn,
  3106. &truncated,
  3107. buf,
  3108. buflen,
  3109. "%s.unix://%s%s",
  3110. proto,
  3111. server_name,
  3112. ri->local_uri);
  3113. default_port = 0;
  3114. mg_free(uri_encoded);
  3115. return 0;
  3116. }
  3117. #endif
  3118. if (define_proto) {
  3119. /* If we got a protocol name, use the default port accordingly. */
  3120. if ((0 == strcmp(define_proto, "https"))
  3121. || (0 == strcmp(define_proto, "wss"))) {
  3122. default_port = 443;
  3123. }
  3124. } else if (ri->is_ssl) {
  3125. /* If we did not get a protocol name, use TLS as default if it is
  3126. * already used. */
  3127. default_port = 443;
  3128. }
  3129. {
  3130. #if defined(USE_IPV6)
  3131. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3132. #endif
  3133. int auth_domain_check_enabled =
  3134. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3135. && (!mg_strcasecmp(
  3136. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3137. const char *server_domain =
  3138. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3139. char portstr[16];
  3140. char server_ip[48];
  3141. if (port != default_port) {
  3142. sprintf(portstr, ":%u", (unsigned)port);
  3143. } else {
  3144. portstr[0] = 0;
  3145. }
  3146. if (!auth_domain_check_enabled || !server_domain) {
  3147. sockaddr_to_string(server_ip,
  3148. sizeof(server_ip),
  3149. &conn->client.lsa);
  3150. server_domain = server_ip;
  3151. }
  3152. mg_snprintf(conn,
  3153. &truncated,
  3154. buf,
  3155. buflen,
  3156. #if defined(USE_IPV6)
  3157. "%s://%s%s%s%s%s",
  3158. proto,
  3159. (is_ipv6 && (server_domain == server_ip)) ? "[" : "",
  3160. server_domain,
  3161. (is_ipv6 && (server_domain == server_ip)) ? "]" : "",
  3162. #else
  3163. "%s://%s%s%s",
  3164. proto,
  3165. server_domain,
  3166. #endif
  3167. portstr,
  3168. uri_encoded);
  3169. mg_free(uri_encoded);
  3170. if (truncated) {
  3171. return -1;
  3172. }
  3173. return 0;
  3174. }
  3175. }
  3176. }
  3177. CIVETWEB_API int
  3178. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3179. {
  3180. return mg_construct_local_link(conn, buf, buflen, NULL, -1, NULL);
  3181. }
  3182. /* Skip the characters until one of the delimiters characters found.
  3183. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3184. * Advance pointer to buffer to the next word. Return found 0-terminated
  3185. * word.
  3186. * Delimiters can be quoted with quotechar. */
  3187. static char *
  3188. skip_quoted(char **buf,
  3189. const char *delimiters,
  3190. const char *whitespace,
  3191. char quotechar)
  3192. {
  3193. char *p, *begin_word, *end_word, *end_whitespace;
  3194. begin_word = *buf;
  3195. end_word = begin_word + strcspn(begin_word, delimiters);
  3196. /* Check for quotechar */
  3197. if (end_word > begin_word) {
  3198. p = end_word - 1;
  3199. while (*p == quotechar) {
  3200. /* While the delimiter is quoted, look for the next delimiter. */
  3201. /* This happens, e.g., in calls from parse_auth_header,
  3202. * if the user name contains a " character. */
  3203. /* If there is anything beyond end_word, copy it. */
  3204. if (*end_word != '\0') {
  3205. size_t end_off = strcspn(end_word + 1, delimiters);
  3206. memmove(p, end_word, end_off + 1);
  3207. p += end_off; /* p must correspond to end_word - 1 */
  3208. end_word += end_off + 1;
  3209. } else {
  3210. *p = '\0';
  3211. break;
  3212. }
  3213. }
  3214. for (p++; p < end_word; p++) {
  3215. *p = '\0';
  3216. }
  3217. }
  3218. if (*end_word == '\0') {
  3219. *buf = end_word;
  3220. } else {
  3221. #if defined(GCC_DIAGNOSTIC)
  3222. /* Disable spurious conversion warning for GCC */
  3223. #pragma GCC diagnostic push
  3224. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3225. #endif /* defined(GCC_DIAGNOSTIC) */
  3226. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3227. #if defined(GCC_DIAGNOSTIC)
  3228. #pragma GCC diagnostic pop
  3229. #endif /* defined(GCC_DIAGNOSTIC) */
  3230. for (p = end_word; p < end_whitespace; p++) {
  3231. *p = '\0';
  3232. }
  3233. *buf = end_whitespace;
  3234. }
  3235. return begin_word;
  3236. }
  3237. /* Return HTTP header value, or NULL if not found. */
  3238. static const char *
  3239. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3240. {
  3241. int i;
  3242. for (i = 0; i < num_hdr; i++) {
  3243. if (!mg_strcasecmp(name, hdr[i].name)) {
  3244. return hdr[i].value;
  3245. }
  3246. }
  3247. return NULL;
  3248. }
  3249. /* Retrieve requested HTTP header multiple values, and return the number of
  3250. * found occurrences */
  3251. static int
  3252. get_req_headers(const struct mg_request_info *ri,
  3253. const char *name,
  3254. const char **output,
  3255. int output_max_size)
  3256. {
  3257. int i;
  3258. int cnt = 0;
  3259. if (ri) {
  3260. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3261. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3262. output[cnt++] = ri->http_headers[i].value;
  3263. }
  3264. }
  3265. }
  3266. return cnt;
  3267. }
  3268. CIVETWEB_API const char *
  3269. mg_get_header(const struct mg_connection *conn, const char *name)
  3270. {
  3271. if (!conn) {
  3272. return NULL;
  3273. }
  3274. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3275. return get_header(conn->request_info.http_headers,
  3276. conn->request_info.num_headers,
  3277. name);
  3278. }
  3279. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3280. return get_header(conn->response_info.http_headers,
  3281. conn->response_info.num_headers,
  3282. name);
  3283. }
  3284. return NULL;
  3285. }
  3286. static const char *
  3287. get_http_version(const struct mg_connection *conn)
  3288. {
  3289. if (!conn) {
  3290. return NULL;
  3291. }
  3292. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3293. return conn->request_info.http_version;
  3294. }
  3295. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3296. return conn->response_info.http_version;
  3297. }
  3298. return NULL;
  3299. }
  3300. /* A helper function for traversing a comma separated list of values.
  3301. * It returns a list pointer shifted to the next value, or NULL if the end
  3302. * of the list found.
  3303. * Value is stored in val vector. If value has form "x=y", then eq_val
  3304. * vector is initialized to point to the "y" part, and val vector length
  3305. * is adjusted to point only to "x". */
  3306. static const char *
  3307. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3308. {
  3309. int end;
  3310. reparse:
  3311. if (val == NULL || list == NULL || *list == '\0') {
  3312. /* End of the list */
  3313. return NULL;
  3314. }
  3315. /* Skip over leading LWS */
  3316. while (*list == ' ' || *list == '\t')
  3317. list++;
  3318. val->ptr = list;
  3319. if ((list = strchr(val->ptr, ',')) != NULL) {
  3320. /* Comma found. Store length and shift the list ptr */
  3321. val->len = ((size_t)(list - val->ptr));
  3322. list++;
  3323. } else {
  3324. /* This value is the last one */
  3325. list = val->ptr + strlen(val->ptr);
  3326. val->len = ((size_t)(list - val->ptr));
  3327. }
  3328. /* Adjust length for trailing LWS */
  3329. end = (int)val->len - 1;
  3330. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3331. end--;
  3332. val->len = (size_t)(end) + (size_t)(1);
  3333. if (val->len == 0) {
  3334. /* Ignore any empty entries. */
  3335. goto reparse;
  3336. }
  3337. if (eq_val != NULL) {
  3338. /* Value has form "x=y", adjust pointers and lengths
  3339. * so that val points to "x", and eq_val points to "y". */
  3340. eq_val->len = 0;
  3341. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3342. if (eq_val->ptr != NULL) {
  3343. eq_val->ptr++; /* Skip over '=' character */
  3344. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3345. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3346. }
  3347. }
  3348. return list;
  3349. }
  3350. /* A helper function for checking if a comma separated list of values
  3351. * contains
  3352. * the given option (case insensitvely).
  3353. * 'header' can be NULL, in which case false is returned. */
  3354. static int
  3355. header_has_option(const char *header, const char *option)
  3356. {
  3357. struct vec opt_vec;
  3358. struct vec eq_vec;
  3359. DEBUG_ASSERT(option != NULL);
  3360. DEBUG_ASSERT(option[0] != '\0');
  3361. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3362. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3363. return 1;
  3364. }
  3365. return 0;
  3366. }
  3367. /* Sorting function implemented in a separate file */
  3368. #include "sort.inl"
  3369. /* Pattern matching has been reimplemented in a new file */
  3370. #include "match.inl"
  3371. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3372. * This function must tolerate situations when connection info is not
  3373. * set up, for example if request parsing failed. */
  3374. static int
  3375. should_keep_alive(const struct mg_connection *conn)
  3376. {
  3377. const char *http_version;
  3378. const char *header;
  3379. /* First satisfy needs of the server */
  3380. if ((conn == NULL) || conn->must_close) {
  3381. /* Close, if civetweb framework needs to close */
  3382. return 0;
  3383. }
  3384. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3385. /* Close, if keep alive is not enabled */
  3386. return 0;
  3387. }
  3388. /* Check explicit wish of the client */
  3389. header = mg_get_header(conn, "Connection");
  3390. if (header) {
  3391. /* If there is a connection header from the client, obey */
  3392. if (header_has_option(header, "keep-alive")) {
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Use default of the standard */
  3398. http_version = get_http_version(conn);
  3399. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3400. /* HTTP 1.1 default is keep alive */
  3401. return 1;
  3402. }
  3403. /* HTTP 1.0 (and earlier) default is to close the connection */
  3404. return 0;
  3405. }
  3406. static int
  3407. should_decode_url(const struct mg_connection *conn)
  3408. {
  3409. if (!conn || !conn->dom_ctx) {
  3410. return 0;
  3411. }
  3412. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3413. }
  3414. static int
  3415. should_decode_query_string(const struct mg_connection *conn)
  3416. {
  3417. if (!conn || !conn->dom_ctx) {
  3418. return 0;
  3419. }
  3420. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_QUERY_STRING], "yes")
  3421. == 0);
  3422. }
  3423. static const char *
  3424. suggest_connection_header(const struct mg_connection *conn)
  3425. {
  3426. return should_keep_alive(conn) ? "keep-alive" : "close";
  3427. }
  3428. #include "response.inl"
  3429. static void
  3430. send_no_cache_header(struct mg_connection *conn)
  3431. {
  3432. /* Send all current and obsolete cache opt-out directives. */
  3433. mg_response_header_add(conn,
  3434. "Cache-Control",
  3435. "no-cache, no-store, "
  3436. "must-revalidate, private, max-age=0",
  3437. -1);
  3438. mg_response_header_add(conn, "Expires", "0", -1);
  3439. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3440. /* Obsolete, but still send it for HTTP/1.0 */
  3441. mg_response_header_add(conn, "Pragma", "no-cache", -1);
  3442. }
  3443. }
  3444. static void
  3445. send_static_cache_header(struct mg_connection *conn)
  3446. {
  3447. #if !defined(NO_CACHING)
  3448. int max_age;
  3449. char val[64];
  3450. const char *cache_control =
  3451. conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3452. /* If there is a full cache-control option configured,0 use it */
  3453. if (cache_control != NULL) {
  3454. mg_response_header_add(conn, "Cache-Control", cache_control, -1);
  3455. return;
  3456. }
  3457. /* Read the server config to check how long a file may be cached.
  3458. * The configuration is in seconds. */
  3459. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3460. if (max_age <= 0) {
  3461. /* 0 means "do not cache". All values <0 are reserved
  3462. * and may be used differently in the future. */
  3463. /* If a file should not be cached, do not only send
  3464. * max-age=0, but also pragmas and Expires headers. */
  3465. send_no_cache_header(conn);
  3466. return;
  3467. }
  3468. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3469. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3470. /* See also https://www.mnot.net/cache_docs/ */
  3471. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3472. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3473. * leap
  3474. * year to 31622400 seconds. For the moment, we just send whatever has
  3475. * been configured, still the behavior for >1 year should be considered
  3476. * as undefined. */
  3477. mg_snprintf(
  3478. conn, NULL, val, sizeof(val), "max-age=%lu", (unsigned long)max_age);
  3479. mg_response_header_add(conn, "Cache-Control", val, -1);
  3480. #else /* NO_CACHING */
  3481. send_no_cache_header(conn);
  3482. #endif /* !NO_CACHING */
  3483. }
  3484. static void
  3485. send_additional_header(struct mg_connection *conn)
  3486. {
  3487. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3488. #if !defined(NO_SSL)
  3489. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3490. long max_age = atol(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3491. if (max_age >= 0) {
  3492. char val[64];
  3493. mg_snprintf(conn,
  3494. NULL,
  3495. val,
  3496. sizeof(val),
  3497. "max-age=%lu",
  3498. (unsigned long)max_age);
  3499. mg_response_header_add(conn, "Strict-Transport-Security", val, -1);
  3500. }
  3501. }
  3502. #endif
  3503. // Content-Security-Policy
  3504. if (header && header[0]) {
  3505. mg_response_header_add_lines(conn, header);
  3506. }
  3507. }
  3508. static void
  3509. send_cors_header(struct mg_connection *conn)
  3510. {
  3511. const char *origin_hdr = mg_get_header(conn, "Origin");
  3512. const char *cors_orig_cfg =
  3513. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  3514. const char *cors_cred_cfg =
  3515. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  3516. const char *cors_hdr_cfg =
  3517. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  3518. const char *cors_exphdr_cfg =
  3519. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  3520. const char *cors_meth_cfg =
  3521. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  3522. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr && *origin_hdr) {
  3523. /* Cross-origin resource sharing (CORS), see
  3524. * http://www.html5rocks.com/en/tutorials/cors/,
  3525. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  3526. * CORS preflight is not supported for files. */
  3527. mg_response_header_add(conn,
  3528. "Access-Control-Allow-Origin",
  3529. cors_orig_cfg,
  3530. -1);
  3531. }
  3532. if (cors_cred_cfg && *cors_cred_cfg && origin_hdr && *origin_hdr) {
  3533. /* Cross-origin resource sharing (CORS), see
  3534. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
  3535. */
  3536. mg_response_header_add(conn,
  3537. "Access-Control-Allow-Credentials",
  3538. cors_cred_cfg,
  3539. -1);
  3540. }
  3541. if (cors_hdr_cfg && *cors_hdr_cfg) {
  3542. mg_response_header_add(conn,
  3543. "Access-Control-Allow-Headers",
  3544. cors_hdr_cfg,
  3545. -1);
  3546. }
  3547. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  3548. mg_response_header_add(conn,
  3549. "Access-Control-Expose-Headers",
  3550. cors_exphdr_cfg,
  3551. -1);
  3552. }
  3553. if (cors_meth_cfg && *cors_meth_cfg) {
  3554. mg_response_header_add(conn,
  3555. "Access-Control-Allow-Methods",
  3556. cors_meth_cfg,
  3557. -1);
  3558. }
  3559. }
  3560. #if !defined(NO_FILESYSTEMS)
  3561. static void handle_file_based_request(struct mg_connection *conn,
  3562. const char *path,
  3563. struct mg_file *filep);
  3564. #endif /* NO_FILESYSTEMS */
  3565. CIVETWEB_API const char *
  3566. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3567. {
  3568. /* See IANA HTTP status code assignment:
  3569. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3570. */
  3571. switch (response_code) {
  3572. /* RFC2616 Section 10.1 - Informational 1xx */
  3573. case 100:
  3574. return "Continue"; /* RFC2616 Section 10.1.1 */
  3575. case 101:
  3576. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3577. case 102:
  3578. return "Processing"; /* RFC2518 Section 10.1 */
  3579. /* RFC2616 Section 10.2 - Successful 2xx */
  3580. case 200:
  3581. return "OK"; /* RFC2616 Section 10.2.1 */
  3582. case 201:
  3583. return "Created"; /* RFC2616 Section 10.2.2 */
  3584. case 202:
  3585. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3586. case 203:
  3587. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3588. case 204:
  3589. return "No Content"; /* RFC2616 Section 10.2.5 */
  3590. case 205:
  3591. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3592. case 206:
  3593. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3594. case 207:
  3595. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3596. */
  3597. case 208:
  3598. return "Already Reported"; /* RFC5842 Section 7.1 */
  3599. case 226:
  3600. return "IM used"; /* RFC3229 Section 10.4.1 */
  3601. /* RFC2616 Section 10.3 - Redirection 3xx */
  3602. case 300:
  3603. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3604. case 301:
  3605. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3606. case 302:
  3607. return "Found"; /* RFC2616 Section 10.3.3 */
  3608. case 303:
  3609. return "See Other"; /* RFC2616 Section 10.3.4 */
  3610. case 304:
  3611. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3612. case 305:
  3613. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3614. case 307:
  3615. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3616. case 308:
  3617. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3618. /* RFC2616 Section 10.4 - Client Error 4xx */
  3619. case 400:
  3620. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3621. case 401:
  3622. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3623. case 402:
  3624. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3625. case 403:
  3626. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3627. case 404:
  3628. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3629. case 405:
  3630. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3631. case 406:
  3632. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3633. case 407:
  3634. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3635. case 408:
  3636. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3637. case 409:
  3638. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3639. case 410:
  3640. return "Gone"; /* RFC2616 Section 10.4.11 */
  3641. case 411:
  3642. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3643. case 412:
  3644. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3645. case 413:
  3646. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3647. case 414:
  3648. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3649. case 415:
  3650. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3651. case 416:
  3652. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3653. */
  3654. case 417:
  3655. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3656. case 421:
  3657. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3658. case 422:
  3659. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3660. * Section 11.2 */
  3661. case 423:
  3662. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3663. case 424:
  3664. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3665. * Section 11.4 */
  3666. case 426:
  3667. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3668. case 428:
  3669. return "Precondition Required"; /* RFC 6585, Section 3 */
  3670. case 429:
  3671. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3672. case 431:
  3673. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3674. case 451:
  3675. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3676. * Section 3 */
  3677. /* RFC2616 Section 10.5 - Server Error 5xx */
  3678. case 500:
  3679. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3680. case 501:
  3681. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3682. case 502:
  3683. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3684. case 503:
  3685. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3686. case 504:
  3687. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3688. case 505:
  3689. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3690. case 506:
  3691. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3692. case 507:
  3693. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3694. * Section 11.5 */
  3695. case 508:
  3696. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3697. case 510:
  3698. return "Not Extended"; /* RFC 2774, Section 7 */
  3699. case 511:
  3700. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3701. /* Other status codes, not shown in the IANA HTTP status code
  3702. * assignment.
  3703. * E.g., "de facto" standards due to common use, ... */
  3704. case 418:
  3705. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3706. case 419:
  3707. return "Authentication Timeout"; /* common use */
  3708. case 420:
  3709. return "Enhance Your Calm"; /* common use */
  3710. case 440:
  3711. return "Login Timeout"; /* common use */
  3712. case 509:
  3713. return "Bandwidth Limit Exceeded"; /* common use */
  3714. default:
  3715. /* This error code is unknown. This should not happen. */
  3716. if (conn) {
  3717. mg_cry_internal(conn,
  3718. "Unknown HTTP response code: %u",
  3719. response_code);
  3720. }
  3721. /* Return at least a category according to RFC 2616 Section 10. */
  3722. if (response_code >= 100 && response_code < 200) {
  3723. /* Unknown informational status code */
  3724. return "Information";
  3725. }
  3726. if (response_code >= 200 && response_code < 300) {
  3727. /* Unknown success code */
  3728. return "Success";
  3729. }
  3730. if (response_code >= 300 && response_code < 400) {
  3731. /* Unknown redirection code */
  3732. return "Redirection";
  3733. }
  3734. if (response_code >= 400 && response_code < 500) {
  3735. /* Unknown request error code */
  3736. return "Client Error";
  3737. }
  3738. if (response_code >= 500 && response_code < 600) {
  3739. /* Unknown server error code */
  3740. return "Server Error";
  3741. }
  3742. /* Response code not even within reasonable range */
  3743. return "";
  3744. }
  3745. }
  3746. static int
  3747. mg_send_http_error_impl(struct mg_connection *conn,
  3748. int status,
  3749. const char *fmt,
  3750. va_list args)
  3751. {
  3752. char errmsg_buf[MG_BUF_LEN];
  3753. va_list ap;
  3754. int has_body;
  3755. #if !defined(NO_FILESYSTEMS)
  3756. char path_buf[UTF8_PATH_MAX];
  3757. int len, i, page_handler_found, scope, truncated;
  3758. const char *error_handler = NULL;
  3759. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3760. const char *error_page_file_ext, *tstr;
  3761. #endif /* NO_FILESYSTEMS */
  3762. int handled_by_callback = 0;
  3763. if ((conn == NULL) || (fmt == NULL)) {
  3764. return -2;
  3765. }
  3766. /* Set status (for log) */
  3767. conn->status_code = status;
  3768. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3769. has_body = ((status > 199) && (status != 204) && (status != 304));
  3770. /* Prepare message in buf, if required */
  3771. if (has_body
  3772. || (!conn->in_error_handler
  3773. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3774. /* Store error message in errmsg_buf */
  3775. va_copy(ap, args);
  3776. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3777. va_end(ap);
  3778. /* In a debug build, print all html errors */
  3779. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3780. }
  3781. /* If there is a http_error callback, call it.
  3782. * But don't do it recursively, if callback calls mg_send_http_error again.
  3783. */
  3784. if (!conn->in_error_handler
  3785. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3786. /* Mark in_error_handler to avoid recursion and call user callback. */
  3787. conn->in_error_handler = 1;
  3788. handled_by_callback =
  3789. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3790. == 0);
  3791. conn->in_error_handler = 0;
  3792. }
  3793. if (!handled_by_callback) {
  3794. /* Check for recursion */
  3795. if (conn->in_error_handler) {
  3796. DEBUG_TRACE(
  3797. "Recursion when handling error %u - fall back to default",
  3798. status);
  3799. #if !defined(NO_FILESYSTEMS)
  3800. } else {
  3801. /* Send user defined error pages, if defined */
  3802. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3803. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3804. page_handler_found = 0;
  3805. if (error_handler != NULL) {
  3806. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3807. switch (scope) {
  3808. case 1: /* Handler for specific error, e.g. 404 error */
  3809. mg_snprintf(conn,
  3810. &truncated,
  3811. path_buf,
  3812. sizeof(path_buf) - 32,
  3813. "%serror%03u.",
  3814. error_handler,
  3815. status);
  3816. break;
  3817. case 2: /* Handler for error group, e.g., 5xx error
  3818. * handler
  3819. * for all server errors (500-599) */
  3820. mg_snprintf(conn,
  3821. &truncated,
  3822. path_buf,
  3823. sizeof(path_buf) - 32,
  3824. "%serror%01uxx.",
  3825. error_handler,
  3826. status / 100);
  3827. break;
  3828. default: /* Handler for all errors */
  3829. mg_snprintf(conn,
  3830. &truncated,
  3831. path_buf,
  3832. sizeof(path_buf) - 32,
  3833. "%serror.",
  3834. error_handler);
  3835. break;
  3836. }
  3837. /* String truncation in buf may only occur if
  3838. * error_handler is too long. This string is
  3839. * from the config, not from a client. */
  3840. (void)truncated;
  3841. /* The following code is redundant, but it should avoid
  3842. * false positives in static source code analyzers and
  3843. * vulnerability scanners.
  3844. */
  3845. path_buf[sizeof(path_buf) - 32] = 0;
  3846. len = (int)strlen(path_buf);
  3847. if (len > (int)sizeof(path_buf) - 32) {
  3848. len = (int)sizeof(path_buf) - 32;
  3849. }
  3850. /* Start with the file extension from the configuration. */
  3851. tstr = strchr(error_page_file_ext, '.');
  3852. while (tstr) {
  3853. for (i = 1;
  3854. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3855. i++) {
  3856. /* buffer overrun is not possible here, since
  3857. * (i < 32) && (len < sizeof(path_buf) - 32)
  3858. * ==> (i + len) < sizeof(path_buf) */
  3859. path_buf[len + i - 1] = tstr[i];
  3860. }
  3861. /* buffer overrun is not possible here, since
  3862. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3863. * ==> (i + len) <= sizeof(path_buf) */
  3864. path_buf[len + i - 1] = 0;
  3865. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3866. DEBUG_TRACE("Check error page %s - found",
  3867. path_buf);
  3868. page_handler_found = 1;
  3869. break;
  3870. }
  3871. DEBUG_TRACE("Check error page %s - not found",
  3872. path_buf);
  3873. /* Continue with the next file extension from the
  3874. * configuration (if there is a next one). */
  3875. tstr = strchr(tstr + i, '.');
  3876. }
  3877. }
  3878. }
  3879. if (page_handler_found) {
  3880. conn->in_error_handler = 1;
  3881. handle_file_based_request(conn, path_buf, &error_page_file);
  3882. conn->in_error_handler = 0;
  3883. return 0;
  3884. }
  3885. #endif /* NO_FILESYSTEMS */
  3886. }
  3887. /* No custom error page. Send default error page. */
  3888. conn->must_close = 1;
  3889. mg_response_header_start(conn, status);
  3890. send_no_cache_header(conn);
  3891. send_additional_header(conn);
  3892. send_cors_header(conn);
  3893. if (has_body) {
  3894. mg_response_header_add(conn,
  3895. "Content-Type",
  3896. "text/plain; charset=utf-8",
  3897. -1);
  3898. }
  3899. mg_response_header_send(conn);
  3900. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3901. if (has_body) {
  3902. /* For other errors, send a generic error message. */
  3903. const char *status_text = mg_get_response_code_text(conn, status);
  3904. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3905. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3906. } else {
  3907. /* No body allowed. Close the connection. */
  3908. DEBUG_TRACE("Error %i", status);
  3909. }
  3910. }
  3911. return 0;
  3912. }
  3913. CIVETWEB_API int
  3914. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3915. {
  3916. va_list ap;
  3917. int ret;
  3918. va_start(ap, fmt);
  3919. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3920. va_end(ap);
  3921. return ret;
  3922. }
  3923. CIVETWEB_API int
  3924. mg_send_http_ok(struct mg_connection *conn,
  3925. const char *mime_type,
  3926. long long content_length)
  3927. {
  3928. if ((mime_type == NULL) || (*mime_type == 0)) {
  3929. /* No content type defined: default to text/html */
  3930. mime_type = "text/html";
  3931. }
  3932. mg_response_header_start(conn, 200);
  3933. send_no_cache_header(conn);
  3934. send_additional_header(conn);
  3935. send_cors_header(conn);
  3936. mg_response_header_add(conn, "Content-Type", mime_type, -1);
  3937. if (content_length < 0) {
  3938. /* Size not known. Use chunked encoding (HTTP/1.x) */
  3939. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  3940. /* Only HTTP/1.x defines "chunked" encoding, HTTP/2 does not*/
  3941. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  3942. }
  3943. } else {
  3944. char len[32];
  3945. int trunc = 0;
  3946. mg_snprintf(conn,
  3947. &trunc,
  3948. len,
  3949. sizeof(len),
  3950. "%" UINT64_FMT,
  3951. (uint64_t)content_length);
  3952. if (!trunc) {
  3953. /* Since 32 bytes is enough to hold any 64 bit decimal number,
  3954. * !trunc is always true */
  3955. mg_response_header_add(conn, "Content-Length", len, -1);
  3956. }
  3957. }
  3958. mg_response_header_send(conn);
  3959. return 0;
  3960. }
  3961. CIVETWEB_API int
  3962. mg_send_http_redirect(struct mg_connection *conn,
  3963. const char *target_url,
  3964. int redirect_code)
  3965. {
  3966. /* Send a 30x redirect response.
  3967. *
  3968. * Redirect types (status codes):
  3969. *
  3970. * Status | Perm/Temp | Method | Version
  3971. * 301 | permanent | POST->GET undefined | HTTP/1.0
  3972. * 302 | temporary | POST->GET undefined | HTTP/1.0
  3973. * 303 | temporary | always use GET | HTTP/1.1
  3974. * 307 | temporary | always keep method | HTTP/1.1
  3975. * 308 | permanent | always keep method | HTTP/1.1
  3976. */
  3977. #if defined(MG_SEND_REDIRECT_BODY)
  3978. char redirect_body[MG_BUF_LEN];
  3979. size_t content_len = 0;
  3980. char content_len_text[32];
  3981. #endif
  3982. /* In case redirect_code=0, use 307. */
  3983. if (redirect_code == 0) {
  3984. redirect_code = 307;
  3985. }
  3986. /* In case redirect_code is none of the above, return error. */
  3987. if ((redirect_code != 301) && (redirect_code != 302)
  3988. && (redirect_code != 303) && (redirect_code != 307)
  3989. && (redirect_code != 308)) {
  3990. /* Parameter error */
  3991. return -2;
  3992. }
  3993. /* If target_url is not defined, redirect to "/". */
  3994. if ((target_url == NULL) || (*target_url == 0)) {
  3995. target_url = "/";
  3996. }
  3997. #if defined(MG_SEND_REDIRECT_BODY)
  3998. /* TODO: condition name? */
  3999. /* Prepare a response body with a hyperlink.
  4000. *
  4001. * According to RFC2616 (and RFC1945 before):
  4002. * Unless the request method was HEAD, the entity of the
  4003. * response SHOULD contain a short hypertext note with a hyperlink to
  4004. * the new URI(s).
  4005. *
  4006. * However, this response body is not useful in M2M communication.
  4007. * Probably the original reason in the RFC was, clients not supporting
  4008. * a 30x HTTP redirect could still show the HTML page and let the user
  4009. * press the link. Since current browsers support 30x HTTP, the additional
  4010. * HTML body does not seem to make sense anymore.
  4011. *
  4012. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4013. * but it only notes:
  4014. * The server's response payload usually contains a short
  4015. * hypertext note with a hyperlink to the new URI(s).
  4016. *
  4017. * Deactivated by default. If you need the 30x body, set the define.
  4018. */
  4019. mg_snprintf(
  4020. conn,
  4021. NULL /* ignore truncation */,
  4022. redirect_body,
  4023. sizeof(redirect_body),
  4024. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4025. redirect_text,
  4026. target_url,
  4027. target_url);
  4028. content_len = strlen(reply);
  4029. sprintf(content_len_text, "%lu", (unsigned long)content_len);
  4030. #endif
  4031. /* Send all required headers */
  4032. mg_response_header_start(conn, redirect_code);
  4033. mg_response_header_add(conn, "Location", target_url, -1);
  4034. if ((redirect_code == 301) || (redirect_code == 308)) {
  4035. /* Permanent redirect */
  4036. send_static_cache_header(conn);
  4037. } else {
  4038. /* Temporary redirect */
  4039. send_no_cache_header(conn);
  4040. }
  4041. send_additional_header(conn);
  4042. send_cors_header(conn);
  4043. #if defined(MG_SEND_REDIRECT_BODY)
  4044. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  4045. mg_response_header_add(conn, "Content-Length", content_len_text, -1);
  4046. #else
  4047. mg_response_header_add(conn, "Content-Length", "0", 1);
  4048. #endif
  4049. mg_response_header_send(conn);
  4050. #if defined(MG_SEND_REDIRECT_BODY)
  4051. /* Send response body */
  4052. /* ... unless it is a HEAD request */
  4053. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4054. ret = mg_write(conn, redirect_body, content_len);
  4055. }
  4056. #endif
  4057. return 1;
  4058. }
  4059. #if defined(_WIN32)
  4060. /* Create substitutes for POSIX functions in Win32. */
  4061. #if defined(GCC_DIAGNOSTIC)
  4062. /* Show no warning in case system functions are not used. */
  4063. #pragma GCC diagnostic push
  4064. #pragma GCC diagnostic ignored "-Wunused-function"
  4065. #endif
  4066. static int
  4067. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4068. {
  4069. (void)unused;
  4070. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4071. InitializeCriticalSection(&mutex->sec);
  4072. return 0;
  4073. }
  4074. static int
  4075. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4076. {
  4077. DeleteCriticalSection(&mutex->sec);
  4078. return 0;
  4079. }
  4080. static int
  4081. pthread_mutex_lock(pthread_mutex_t *mutex)
  4082. {
  4083. EnterCriticalSection(&mutex->sec);
  4084. return 0;
  4085. }
  4086. static int
  4087. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4088. {
  4089. LeaveCriticalSection(&mutex->sec);
  4090. return 0;
  4091. }
  4092. FUNCTION_MAY_BE_UNUSED
  4093. static int
  4094. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4095. {
  4096. (void)unused;
  4097. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4098. cv->waiting_thread = NULL;
  4099. return 0;
  4100. }
  4101. FUNCTION_MAY_BE_UNUSED
  4102. static int
  4103. pthread_cond_timedwait(pthread_cond_t *cv,
  4104. pthread_mutex_t *mutex,
  4105. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4106. {
  4107. struct mg_workerTLS **ptls,
  4108. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4109. int ok;
  4110. uint64_t nsnow, nswaitabs;
  4111. int64_t nswaitrel;
  4112. DWORD mswaitrel;
  4113. pthread_mutex_lock(&cv->threadIdSec);
  4114. /* Add this thread to cv's waiting list */
  4115. ptls = &cv->waiting_thread;
  4116. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4117. ;
  4118. tls->next_waiting_thread = NULL;
  4119. *ptls = tls;
  4120. pthread_mutex_unlock(&cv->threadIdSec);
  4121. if (abstime) {
  4122. nsnow = mg_get_current_time_ns();
  4123. nswaitabs =
  4124. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4125. nswaitrel = nswaitabs - nsnow;
  4126. if (nswaitrel < 0) {
  4127. nswaitrel = 0;
  4128. }
  4129. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4130. } else {
  4131. mswaitrel = (DWORD)INFINITE;
  4132. }
  4133. pthread_mutex_unlock(mutex);
  4134. ok = (WAIT_OBJECT_0
  4135. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4136. if (!ok) {
  4137. ok = 1;
  4138. pthread_mutex_lock(&cv->threadIdSec);
  4139. ptls = &cv->waiting_thread;
  4140. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4141. if (*ptls == tls) {
  4142. *ptls = tls->next_waiting_thread;
  4143. ok = 0;
  4144. break;
  4145. }
  4146. }
  4147. pthread_mutex_unlock(&cv->threadIdSec);
  4148. if (ok) {
  4149. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4150. (DWORD)INFINITE);
  4151. }
  4152. }
  4153. /* This thread has been removed from cv's waiting list */
  4154. pthread_mutex_lock(mutex);
  4155. return ok ? 0 : -1;
  4156. }
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static int
  4159. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4160. {
  4161. return pthread_cond_timedwait(cv, mutex, NULL);
  4162. }
  4163. FUNCTION_MAY_BE_UNUSED
  4164. static int
  4165. pthread_cond_signal(pthread_cond_t *cv)
  4166. {
  4167. HANDLE wkup = NULL;
  4168. BOOL ok = FALSE;
  4169. pthread_mutex_lock(&cv->threadIdSec);
  4170. if (cv->waiting_thread) {
  4171. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4172. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4173. ok = SetEvent(wkup);
  4174. DEBUG_ASSERT(ok);
  4175. }
  4176. pthread_mutex_unlock(&cv->threadIdSec);
  4177. return ok ? 0 : 1;
  4178. }
  4179. FUNCTION_MAY_BE_UNUSED
  4180. static int
  4181. pthread_cond_broadcast(pthread_cond_t *cv)
  4182. {
  4183. pthread_mutex_lock(&cv->threadIdSec);
  4184. while (cv->waiting_thread) {
  4185. pthread_cond_signal(cv);
  4186. }
  4187. pthread_mutex_unlock(&cv->threadIdSec);
  4188. return 0;
  4189. }
  4190. FUNCTION_MAY_BE_UNUSED
  4191. static int
  4192. pthread_cond_destroy(pthread_cond_t *cv)
  4193. {
  4194. pthread_mutex_lock(&cv->threadIdSec);
  4195. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4196. pthread_mutex_unlock(&cv->threadIdSec);
  4197. pthread_mutex_destroy(&cv->threadIdSec);
  4198. return 0;
  4199. }
  4200. #if defined(ALTERNATIVE_QUEUE)
  4201. FUNCTION_MAY_BE_UNUSED
  4202. static void *
  4203. event_create(void)
  4204. {
  4205. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4206. }
  4207. FUNCTION_MAY_BE_UNUSED
  4208. static int
  4209. event_wait(void *eventhdl)
  4210. {
  4211. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4212. return (res == WAIT_OBJECT_0);
  4213. }
  4214. FUNCTION_MAY_BE_UNUSED
  4215. static int
  4216. event_signal(void *eventhdl)
  4217. {
  4218. return (int)SetEvent((HANDLE)eventhdl);
  4219. }
  4220. FUNCTION_MAY_BE_UNUSED
  4221. static void
  4222. event_destroy(void *eventhdl)
  4223. {
  4224. CloseHandle((HANDLE)eventhdl);
  4225. }
  4226. #endif
  4227. #if defined(GCC_DIAGNOSTIC)
  4228. /* Enable unused function warning again */
  4229. #pragma GCC diagnostic pop
  4230. #endif
  4231. /* For Windows, change all slashes to backslashes in path names. */
  4232. static void
  4233. change_slashes_to_backslashes(char *path)
  4234. {
  4235. int i;
  4236. for (i = 0; path[i] != '\0'; i++) {
  4237. if (path[i] == '/') {
  4238. path[i] = '\\';
  4239. }
  4240. /* remove double backslash (check i > 0 to preserve UNC paths,
  4241. * like \\server\file.txt) */
  4242. if ((i > 0) && (path[i] == '\\')) {
  4243. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4244. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4245. }
  4246. }
  4247. }
  4248. }
  4249. static int
  4250. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4251. {
  4252. int diff;
  4253. do {
  4254. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4255. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4256. s1++;
  4257. s2++;
  4258. } while ((diff == 0) && (s1[-1] != L'\0'));
  4259. return diff;
  4260. }
  4261. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4262. * wbuf and wbuf_len is a target buffer and its length. */
  4263. static void
  4264. path_to_unicode(const struct mg_connection *conn,
  4265. const char *path,
  4266. wchar_t *wbuf,
  4267. size_t wbuf_len)
  4268. {
  4269. char buf[UTF8_PATH_MAX], buf2[UTF8_PATH_MAX];
  4270. wchar_t wbuf2[UTF16_PATH_MAX + 1];
  4271. DWORD long_len, err;
  4272. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4273. mg_strlcpy(buf, path, sizeof(buf));
  4274. change_slashes_to_backslashes(buf);
  4275. /* Convert to Unicode and back. If doubly-converted string does not
  4276. * match the original, something is fishy, reject. */
  4277. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4278. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4279. WideCharToMultiByte(
  4280. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4281. if (strcmp(buf, buf2) != 0) {
  4282. wbuf[0] = L'\0';
  4283. }
  4284. /* Windows file systems are not case sensitive, but you can still use
  4285. * uppercase and lowercase letters (on all modern file systems).
  4286. * The server can check if the URI uses the same upper/lowercase
  4287. * letters an the file system, effectively making Windows servers
  4288. * case sensitive (like Linux servers are). It is still not possible
  4289. * to use two files with the same name in different cases on Windows
  4290. * (like /a and /A) - this would be possible in Linux.
  4291. * As a default, Windows is not case sensitive, but the case sensitive
  4292. * file name check can be activated by an additional configuration. */
  4293. if (conn) {
  4294. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4295. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4296. "yes")) {
  4297. /* Use case sensitive compare function */
  4298. fcompare = wcscmp;
  4299. }
  4300. }
  4301. (void)conn; /* conn is currently unused */
  4302. /* Only accept a full file path, not a Windows short (8.3) path. */
  4303. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4304. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4305. if (long_len == 0) {
  4306. err = GetLastError();
  4307. if (err == ERROR_FILE_NOT_FOUND) {
  4308. /* File does not exist. This is not always a problem here. */
  4309. return;
  4310. }
  4311. }
  4312. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4313. /* Short name is used. */
  4314. wbuf[0] = L'\0';
  4315. }
  4316. }
  4317. #if !defined(NO_FILESYSTEMS)
  4318. /* Get file information, return 1 if file exists, 0 if not */
  4319. static int
  4320. mg_stat(const struct mg_connection *conn,
  4321. const char *path,
  4322. struct mg_file_stat *filep)
  4323. {
  4324. wchar_t wbuf[UTF16_PATH_MAX];
  4325. WIN32_FILE_ATTRIBUTE_DATA info;
  4326. time_t creation_time;
  4327. size_t len;
  4328. if (!filep) {
  4329. return 0;
  4330. }
  4331. memset(filep, 0, sizeof(*filep));
  4332. if (mg_path_suspicious(conn, path)) {
  4333. return 0;
  4334. }
  4335. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4336. /* Windows happily opens files with some garbage at the end of file name.
  4337. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4338. * "a.cgi", despite one would expect an error back. */
  4339. len = strlen(path);
  4340. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4341. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4342. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4343. filep->last_modified =
  4344. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4345. info.ftLastWriteTime.dwHighDateTime);
  4346. /* On Windows, the file creation time can be higher than the
  4347. * modification time, e.g. when a file is copied.
  4348. * Since the Last-Modified timestamp is used for caching
  4349. * it should be based on the most recent timestamp. */
  4350. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4351. info.ftCreationTime.dwHighDateTime);
  4352. if (creation_time > filep->last_modified) {
  4353. filep->last_modified = creation_time;
  4354. }
  4355. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4356. return 1;
  4357. }
  4358. return 0;
  4359. }
  4360. #endif
  4361. static int
  4362. mg_remove(const struct mg_connection *conn, const char *path)
  4363. {
  4364. wchar_t wbuf[UTF16_PATH_MAX];
  4365. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4366. return DeleteFileW(wbuf) ? 0 : -1;
  4367. }
  4368. static int
  4369. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4370. {
  4371. wchar_t wbuf[UTF16_PATH_MAX];
  4372. (void)mode;
  4373. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4374. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4375. }
  4376. /* Create substitutes for POSIX functions in Win32. */
  4377. #if defined(GCC_DIAGNOSTIC)
  4378. /* Show no warning in case system functions are not used. */
  4379. #pragma GCC diagnostic push
  4380. #pragma GCC diagnostic ignored "-Wunused-function"
  4381. #endif
  4382. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4383. FUNCTION_MAY_BE_UNUSED
  4384. static DIR *
  4385. mg_opendir(const struct mg_connection *conn, const char *name)
  4386. {
  4387. DIR *dir = NULL;
  4388. wchar_t wpath[UTF16_PATH_MAX];
  4389. DWORD attrs;
  4390. if (name == NULL) {
  4391. SetLastError(ERROR_BAD_ARGUMENTS);
  4392. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4393. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4394. } else {
  4395. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4396. attrs = GetFileAttributesW(wpath);
  4397. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4398. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4399. (void)wcscat(wpath, L"\\*");
  4400. dir->handle = FindFirstFileW(wpath, &dir->info);
  4401. dir->result.d_name[0] = '\0';
  4402. } else {
  4403. mg_free(dir);
  4404. dir = NULL;
  4405. }
  4406. }
  4407. return dir;
  4408. }
  4409. FUNCTION_MAY_BE_UNUSED
  4410. static int
  4411. mg_closedir(DIR *dir)
  4412. {
  4413. int result = 0;
  4414. if (dir != NULL) {
  4415. if (dir->handle != INVALID_HANDLE_VALUE)
  4416. result = FindClose(dir->handle) ? 0 : -1;
  4417. mg_free(dir);
  4418. } else {
  4419. result = -1;
  4420. SetLastError(ERROR_BAD_ARGUMENTS);
  4421. }
  4422. return result;
  4423. }
  4424. FUNCTION_MAY_BE_UNUSED
  4425. static struct dirent *
  4426. mg_readdir(DIR *dir)
  4427. {
  4428. struct dirent *result = 0;
  4429. if (dir) {
  4430. if (dir->handle != INVALID_HANDLE_VALUE) {
  4431. result = &dir->result;
  4432. (void)WideCharToMultiByte(CP_UTF8,
  4433. 0,
  4434. dir->info.cFileName,
  4435. -1,
  4436. result->d_name,
  4437. sizeof(result->d_name),
  4438. NULL,
  4439. NULL);
  4440. if (!FindNextFileW(dir->handle, &dir->info)) {
  4441. (void)FindClose(dir->handle);
  4442. dir->handle = INVALID_HANDLE_VALUE;
  4443. }
  4444. } else {
  4445. SetLastError(ERROR_FILE_NOT_FOUND);
  4446. }
  4447. } else {
  4448. SetLastError(ERROR_BAD_ARGUMENTS);
  4449. }
  4450. return result;
  4451. }
  4452. #if !defined(HAVE_POLL)
  4453. #undef POLLIN
  4454. #undef POLLPRI
  4455. #undef POLLOUT
  4456. #undef POLLERR
  4457. #define POLLIN (1) /* Data ready - read will not block. */
  4458. #define POLLPRI (2) /* Priority data ready. */
  4459. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4460. #define POLLERR (8) /* Error event */
  4461. FUNCTION_MAY_BE_UNUSED
  4462. static int
  4463. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4464. {
  4465. struct timeval tv;
  4466. fd_set rset;
  4467. fd_set wset;
  4468. fd_set eset;
  4469. unsigned int i;
  4470. int result;
  4471. SOCKET maxfd = 0;
  4472. memset(&tv, 0, sizeof(tv));
  4473. tv.tv_sec = milliseconds / 1000;
  4474. tv.tv_usec = (milliseconds % 1000) * 1000;
  4475. FD_ZERO(&rset);
  4476. FD_ZERO(&wset);
  4477. FD_ZERO(&eset);
  4478. for (i = 0; i < n; i++) {
  4479. if (pfd[i].events & (POLLIN | POLLOUT | POLLERR)) {
  4480. if (pfd[i].events & POLLIN) {
  4481. FD_SET(pfd[i].fd, &rset);
  4482. }
  4483. if (pfd[i].events & POLLOUT) {
  4484. FD_SET(pfd[i].fd, &wset);
  4485. }
  4486. /* Check for errors for any FD in the set */
  4487. FD_SET(pfd[i].fd, &eset);
  4488. }
  4489. pfd[i].revents = 0;
  4490. if (pfd[i].fd > maxfd) {
  4491. maxfd = pfd[i].fd;
  4492. }
  4493. }
  4494. if ((result = select((int)maxfd + 1, &rset, &wset, &eset, &tv)) > 0) {
  4495. for (i = 0; i < n; i++) {
  4496. if (FD_ISSET(pfd[i].fd, &rset)) {
  4497. pfd[i].revents |= POLLIN;
  4498. }
  4499. if (FD_ISSET(pfd[i].fd, &wset)) {
  4500. pfd[i].revents |= POLLOUT;
  4501. }
  4502. if (FD_ISSET(pfd[i].fd, &eset)) {
  4503. pfd[i].revents |= POLLERR;
  4504. }
  4505. }
  4506. }
  4507. /* We should subtract the time used in select from remaining
  4508. * "milliseconds", in particular if called from mg_poll with a
  4509. * timeout quantum.
  4510. * Unfortunately, the remaining time is not stored in "tv" in all
  4511. * implementations, so the result in "tv" must be considered undefined.
  4512. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4513. return result;
  4514. }
  4515. #endif /* HAVE_POLL */
  4516. #if defined(GCC_DIAGNOSTIC)
  4517. /* Enable unused function warning again */
  4518. #pragma GCC diagnostic pop
  4519. #endif
  4520. static void
  4521. set_close_on_exec(SOCKET sock,
  4522. const struct mg_connection *conn /* may be null */,
  4523. struct mg_context *ctx /* may be null */)
  4524. {
  4525. (void)conn; /* Unused. */
  4526. (void)ctx;
  4527. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4528. }
  4529. CIVETWEB_API int
  4530. mg_start_thread(mg_thread_func_t f, void *p)
  4531. {
  4532. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4533. /* Compile-time option to control stack size, e.g.
  4534. * -DUSE_STACK_SIZE=16384
  4535. */
  4536. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4537. == ((uintptr_t)(-1L)))
  4538. ? -1
  4539. : 0);
  4540. #else
  4541. return (
  4542. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4543. ? -1
  4544. : 0);
  4545. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4546. }
  4547. /* Start a thread storing the thread context. */
  4548. static int
  4549. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4550. void *p,
  4551. pthread_t *threadidptr)
  4552. {
  4553. uintptr_t uip;
  4554. HANDLE threadhandle;
  4555. int result = -1;
  4556. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4557. threadhandle = (HANDLE)uip;
  4558. if ((uip != 0) && (threadidptr != NULL)) {
  4559. *threadidptr = threadhandle;
  4560. result = 0;
  4561. }
  4562. return result;
  4563. }
  4564. /* Wait for a thread to finish. */
  4565. static int
  4566. mg_join_thread(pthread_t threadid)
  4567. {
  4568. int result;
  4569. DWORD dwevent;
  4570. result = -1;
  4571. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4572. if (dwevent == WAIT_FAILED) {
  4573. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4574. } else {
  4575. if (dwevent == WAIT_OBJECT_0) {
  4576. CloseHandle(threadid);
  4577. result = 0;
  4578. }
  4579. }
  4580. return result;
  4581. }
  4582. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4583. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4584. /* Create substitutes for POSIX functions in Win32. */
  4585. #if defined(GCC_DIAGNOSTIC)
  4586. /* Show no warning in case system functions are not used. */
  4587. #pragma GCC diagnostic push
  4588. #pragma GCC diagnostic ignored "-Wunused-function"
  4589. #endif
  4590. FUNCTION_MAY_BE_UNUSED
  4591. static HANDLE
  4592. dlopen(const char *dll_name, int flags)
  4593. {
  4594. wchar_t wbuf[UTF16_PATH_MAX];
  4595. (void)flags;
  4596. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4597. return LoadLibraryW(wbuf);
  4598. }
  4599. FUNCTION_MAY_BE_UNUSED
  4600. static int
  4601. dlclose(void *handle)
  4602. {
  4603. int result;
  4604. if (FreeLibrary((HMODULE)handle) != 0) {
  4605. result = 0;
  4606. } else {
  4607. result = -1;
  4608. }
  4609. return result;
  4610. }
  4611. #if defined(GCC_DIAGNOSTIC)
  4612. /* Enable unused function warning again */
  4613. #pragma GCC diagnostic pop
  4614. #endif
  4615. #endif
  4616. #if !defined(NO_CGI)
  4617. #define SIGKILL (0)
  4618. static int
  4619. kill(pid_t pid, int sig_num)
  4620. {
  4621. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4622. (void)CloseHandle((HANDLE)pid);
  4623. return 0;
  4624. }
  4625. #if !defined(WNOHANG)
  4626. #define WNOHANG (1)
  4627. #endif
  4628. static pid_t
  4629. waitpid(pid_t pid, int *status, int flags)
  4630. {
  4631. DWORD timeout = INFINITE;
  4632. DWORD waitres;
  4633. (void)status; /* Currently not used by any client here */
  4634. if ((flags | WNOHANG) == WNOHANG) {
  4635. timeout = 0;
  4636. }
  4637. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4638. if (waitres == WAIT_OBJECT_0) {
  4639. return pid;
  4640. }
  4641. if (waitres == WAIT_TIMEOUT) {
  4642. return 0;
  4643. }
  4644. return (pid_t)-1;
  4645. }
  4646. static void
  4647. trim_trailing_whitespaces(char *s)
  4648. {
  4649. char *e = s + strlen(s);
  4650. while ((e > s) && isspace((unsigned char)e[-1])) {
  4651. *(--e) = '\0';
  4652. }
  4653. }
  4654. static pid_t
  4655. spawn_process(struct mg_connection *conn,
  4656. const char *prog,
  4657. char *envblk,
  4658. char *envp[],
  4659. int fdin[2],
  4660. int fdout[2],
  4661. int fderr[2],
  4662. const char *dir,
  4663. int cgi_config_idx)
  4664. {
  4665. HANDLE me;
  4666. char *interp;
  4667. char *interp_arg = 0;
  4668. char full_dir[UTF8_PATH_MAX], cmdline[UTF8_PATH_MAX], buf[UTF8_PATH_MAX];
  4669. int truncated;
  4670. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4671. STARTUPINFOA si;
  4672. PROCESS_INFORMATION pi = {0};
  4673. (void)envp;
  4674. memset(&si, 0, sizeof(si));
  4675. si.cb = sizeof(si);
  4676. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4677. si.wShowWindow = SW_HIDE;
  4678. me = GetCurrentProcess();
  4679. DuplicateHandle(me,
  4680. (HANDLE)_get_osfhandle(fdin[0]),
  4681. me,
  4682. &si.hStdInput,
  4683. 0,
  4684. TRUE,
  4685. DUPLICATE_SAME_ACCESS);
  4686. DuplicateHandle(me,
  4687. (HANDLE)_get_osfhandle(fdout[1]),
  4688. me,
  4689. &si.hStdOutput,
  4690. 0,
  4691. TRUE,
  4692. DUPLICATE_SAME_ACCESS);
  4693. DuplicateHandle(me,
  4694. (HANDLE)_get_osfhandle(fderr[1]),
  4695. me,
  4696. &si.hStdError,
  4697. 0,
  4698. TRUE,
  4699. DUPLICATE_SAME_ACCESS);
  4700. /* Mark handles that should not be inherited. See
  4701. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4702. */
  4703. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4704. HANDLE_FLAG_INHERIT,
  4705. 0);
  4706. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4707. HANDLE_FLAG_INHERIT,
  4708. 0);
  4709. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4710. HANDLE_FLAG_INHERIT,
  4711. 0);
  4712. /* First check, if there is a CGI interpreter configured for all CGI
  4713. * scripts. */
  4714. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4715. if (interp != NULL) {
  4716. /* If there is a configured interpreter, check for additional arguments
  4717. */
  4718. interp_arg =
  4719. conn->dom_ctx->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  4720. } else {
  4721. /* Otherwise, the interpreter must be stated in the first line of the
  4722. * CGI script file, after a #! (shebang) mark. */
  4723. buf[0] = buf[1] = '\0';
  4724. /* Get the full script path */
  4725. mg_snprintf(
  4726. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4727. if (truncated) {
  4728. pi.hProcess = (pid_t)-1;
  4729. goto spawn_cleanup;
  4730. }
  4731. /* Open the script file, to read the first line */
  4732. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4733. /* Read the first line of the script into the buffer */
  4734. mg_fgets(buf, sizeof(buf), &file);
  4735. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4736. buf[sizeof(buf) - 1] = '\0';
  4737. }
  4738. if ((buf[0] == '#') && (buf[1] == '!')) {
  4739. trim_trailing_whitespaces(buf + 2);
  4740. } else {
  4741. buf[2] = '\0';
  4742. }
  4743. interp = buf + 2;
  4744. }
  4745. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4746. if (interp[0] != '\0') {
  4747. /* This is an interpreted script file. We must call the interpreter. */
  4748. if ((interp_arg != 0) && (interp_arg[0] != 0)) {
  4749. mg_snprintf(conn,
  4750. &truncated,
  4751. cmdline,
  4752. sizeof(cmdline),
  4753. "\"%s\" %s \"%s\\%s\"",
  4754. interp,
  4755. interp_arg,
  4756. full_dir,
  4757. prog);
  4758. } else {
  4759. mg_snprintf(conn,
  4760. &truncated,
  4761. cmdline,
  4762. sizeof(cmdline),
  4763. "\"%s\" \"%s\\%s\"",
  4764. interp,
  4765. full_dir,
  4766. prog);
  4767. }
  4768. } else {
  4769. /* This is (probably) a compiled program. We call it directly. */
  4770. mg_snprintf(conn,
  4771. &truncated,
  4772. cmdline,
  4773. sizeof(cmdline),
  4774. "\"%s\\%s\"",
  4775. full_dir,
  4776. prog);
  4777. }
  4778. if (truncated) {
  4779. pi.hProcess = (pid_t)-1;
  4780. goto spawn_cleanup;
  4781. }
  4782. DEBUG_TRACE("Running [%s]", cmdline);
  4783. if (CreateProcessA(NULL,
  4784. cmdline,
  4785. NULL,
  4786. NULL,
  4787. TRUE,
  4788. CREATE_NEW_PROCESS_GROUP,
  4789. envblk,
  4790. NULL,
  4791. &si,
  4792. &pi)
  4793. == 0) {
  4794. mg_cry_internal(
  4795. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4796. pi.hProcess = (pid_t)-1;
  4797. /* goto spawn_cleanup; */
  4798. }
  4799. spawn_cleanup:
  4800. (void)CloseHandle(si.hStdOutput);
  4801. (void)CloseHandle(si.hStdError);
  4802. (void)CloseHandle(si.hStdInput);
  4803. if (pi.hThread != NULL) {
  4804. (void)CloseHandle(pi.hThread);
  4805. }
  4806. return (pid_t)pi.hProcess;
  4807. }
  4808. #endif /* !NO_CGI */
  4809. static int
  4810. set_blocking_mode(SOCKET sock)
  4811. {
  4812. unsigned long non_blocking = 0;
  4813. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4814. }
  4815. static int
  4816. set_non_blocking_mode(SOCKET sock)
  4817. {
  4818. unsigned long non_blocking = 1;
  4819. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4820. }
  4821. #else
  4822. #if !defined(NO_FILESYSTEMS)
  4823. static int
  4824. mg_stat(const struct mg_connection *conn,
  4825. const char *path,
  4826. struct mg_file_stat *filep)
  4827. {
  4828. struct stat st;
  4829. if (!filep) {
  4830. return 0;
  4831. }
  4832. memset(filep, 0, sizeof(*filep));
  4833. if (mg_path_suspicious(conn, path)) {
  4834. return 0;
  4835. }
  4836. if (0 == stat(path, &st)) {
  4837. filep->size = (uint64_t)(st.st_size);
  4838. filep->last_modified = st.st_mtime;
  4839. filep->is_directory = S_ISDIR(st.st_mode);
  4840. return 1;
  4841. }
  4842. return 0;
  4843. }
  4844. #endif /* NO_FILESYSTEMS */
  4845. static void
  4846. set_close_on_exec(int fd,
  4847. const struct mg_connection *conn /* may be null */,
  4848. struct mg_context *ctx /* may be null */)
  4849. {
  4850. #if defined(__ZEPHYR__)
  4851. (void)fd;
  4852. (void)conn;
  4853. (void)ctx;
  4854. #else
  4855. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4856. if (conn || ctx) {
  4857. struct mg_connection fc;
  4858. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4859. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4860. __func__,
  4861. strerror(ERRNO));
  4862. }
  4863. }
  4864. #endif
  4865. }
  4866. CIVETWEB_API int
  4867. mg_start_thread(mg_thread_func_t func, void *param)
  4868. {
  4869. pthread_t thread_id;
  4870. pthread_attr_t attr;
  4871. int result;
  4872. (void)pthread_attr_init(&attr);
  4873. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4874. #if defined(__ZEPHYR__)
  4875. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  4876. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4877. /* Compile-time option to control stack size,
  4878. * e.g. -DUSE_STACK_SIZE=16384 */
  4879. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4880. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4881. result = pthread_create(&thread_id, &attr, func, param);
  4882. pthread_attr_destroy(&attr);
  4883. return result;
  4884. }
  4885. /* Start a thread storing the thread context. */
  4886. static int
  4887. mg_start_thread_with_id(mg_thread_func_t func,
  4888. void *param,
  4889. pthread_t *threadidptr)
  4890. {
  4891. pthread_t thread_id;
  4892. pthread_attr_t attr;
  4893. int result;
  4894. (void)pthread_attr_init(&attr);
  4895. #if defined(__ZEPHYR__)
  4896. pthread_attr_setstack(&attr,
  4897. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  4898. ZEPHYR_STACK_SIZE);
  4899. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4900. /* Compile-time option to control stack size,
  4901. * e.g. -DUSE_STACK_SIZE=16384 */
  4902. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4903. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4904. result = pthread_create(&thread_id, &attr, func, param);
  4905. pthread_attr_destroy(&attr);
  4906. if ((result == 0) && (threadidptr != NULL)) {
  4907. *threadidptr = thread_id;
  4908. }
  4909. return result;
  4910. }
  4911. /* Wait for a thread to finish. */
  4912. static int
  4913. mg_join_thread(pthread_t threadid)
  4914. {
  4915. int result;
  4916. result = pthread_join(threadid, NULL);
  4917. return result;
  4918. }
  4919. #if !defined(NO_CGI)
  4920. static pid_t
  4921. spawn_process(struct mg_connection *conn,
  4922. const char *prog,
  4923. char *envblk,
  4924. char *envp[],
  4925. int fdin[2],
  4926. int fdout[2],
  4927. int fderr[2],
  4928. const char *dir,
  4929. int cgi_config_idx)
  4930. {
  4931. pid_t pid;
  4932. const char *interp;
  4933. (void)envblk;
  4934. if ((pid = fork()) == -1) {
  4935. /* Parent */
  4936. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  4937. } else if (pid != 0) {
  4938. /* Make sure children close parent-side descriptors.
  4939. * The caller will close the child-side immediately. */
  4940. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  4941. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  4942. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  4943. } else {
  4944. /* Child */
  4945. if (chdir(dir) != 0) {
  4946. mg_cry_internal(
  4947. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4948. } else if (dup2(fdin[0], 0) == -1) {
  4949. mg_cry_internal(conn,
  4950. "%s: dup2(%d, 0): %s",
  4951. __func__,
  4952. fdin[0],
  4953. strerror(ERRNO));
  4954. } else if (dup2(fdout[1], 1) == -1) {
  4955. mg_cry_internal(conn,
  4956. "%s: dup2(%d, 1): %s",
  4957. __func__,
  4958. fdout[1],
  4959. strerror(ERRNO));
  4960. } else if (dup2(fderr[1], 2) == -1) {
  4961. mg_cry_internal(conn,
  4962. "%s: dup2(%d, 2): %s",
  4963. __func__,
  4964. fderr[1],
  4965. strerror(ERRNO));
  4966. } else {
  4967. struct sigaction sa;
  4968. /* Keep stderr and stdout in two different pipes.
  4969. * Stdout will be sent back to the client,
  4970. * stderr should go into a server error log. */
  4971. (void)close(fdin[0]);
  4972. (void)close(fdout[1]);
  4973. (void)close(fderr[1]);
  4974. /* Close write end fdin and read end fdout and fderr */
  4975. (void)close(fdin[1]);
  4976. (void)close(fdout[0]);
  4977. (void)close(fderr[0]);
  4978. /* After exec, all signal handlers are restored to their default
  4979. * values, with one exception of SIGCHLD. According to
  4980. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4981. * will leave unchanged after exec if it was set to be ignored.
  4982. * Restore it to default action. */
  4983. memset(&sa, 0, sizeof(sa));
  4984. sa.sa_handler = SIG_DFL;
  4985. sigaction(SIGCHLD, &sa, NULL);
  4986. interp = conn->dom_ctx->config[CGI_INTERPRETER + cgi_config_idx];
  4987. if (interp == NULL) {
  4988. /* no interpreter configured, call the program directly */
  4989. (void)execle(prog, prog, NULL, envp);
  4990. mg_cry_internal(conn,
  4991. "%s: execle(%s): %s",
  4992. __func__,
  4993. prog,
  4994. strerror(ERRNO));
  4995. } else {
  4996. /* call the configured interpreter */
  4997. const char *interp_args =
  4998. conn->dom_ctx
  4999. ->config[CGI_INTERPRETER_ARGS + cgi_config_idx];
  5000. if ((interp_args != NULL) && (interp_args[0] != 0)) {
  5001. (void)execle(interp, interp, interp_args, prog, NULL, envp);
  5002. } else {
  5003. (void)execle(interp, interp, prog, NULL, envp);
  5004. }
  5005. mg_cry_internal(conn,
  5006. "%s: execle(%s %s): %s",
  5007. __func__,
  5008. interp,
  5009. prog,
  5010. strerror(ERRNO));
  5011. }
  5012. }
  5013. exit(EXIT_FAILURE);
  5014. }
  5015. return pid;
  5016. }
  5017. #endif /* !NO_CGI */
  5018. static int
  5019. set_non_blocking_mode(SOCKET sock)
  5020. {
  5021. int flags = fcntl(sock, F_GETFL, 0);
  5022. if (flags < 0) {
  5023. return -1;
  5024. }
  5025. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5026. return -1;
  5027. }
  5028. return 0;
  5029. }
  5030. static int
  5031. set_blocking_mode(SOCKET sock)
  5032. {
  5033. int flags = fcntl(sock, F_GETFL, 0);
  5034. if (flags < 0) {
  5035. return -1;
  5036. }
  5037. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5038. return -1;
  5039. }
  5040. return 0;
  5041. }
  5042. #endif /* _WIN32 / else */
  5043. /* End of initial operating system specific define block. */
  5044. /* Get a random number (independent of C rand function) */
  5045. static uint64_t
  5046. get_random(void)
  5047. {
  5048. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5049. static uint64_t lcg = 0; /* Linear congruential generator */
  5050. uint64_t now = mg_get_current_time_ns();
  5051. if (lfsr == 0) {
  5052. /* lfsr will be only 0 if has not been initialized,
  5053. * so this code is called only once. */
  5054. lfsr = mg_get_current_time_ns();
  5055. lcg = mg_get_current_time_ns();
  5056. } else {
  5057. /* Get the next step of both random number generators. */
  5058. lfsr = (lfsr >> 1)
  5059. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5060. << 63);
  5061. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5062. }
  5063. /* Combining two pseudo-random number generators and a high resolution
  5064. * part
  5065. * of the current server time will make it hard (impossible?) to guess
  5066. * the
  5067. * next number. */
  5068. return (lfsr ^ lcg ^ now);
  5069. }
  5070. static int
  5071. mg_poll(struct mg_pollfd *pfd,
  5072. unsigned int n,
  5073. int milliseconds,
  5074. const stop_flag_t *stop_flag)
  5075. {
  5076. /* Call poll, but only for a maximum time of a few seconds.
  5077. * This will allow to stop the server after some seconds, instead
  5078. * of having to wait for a long socket timeout. */
  5079. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5080. int check_pollerr = 0;
  5081. if ((n == 1) && ((pfd[0].events & POLLERR) == 0)) {
  5082. /* If we wait for only one file descriptor, wait on error as well */
  5083. pfd[0].events |= POLLERR;
  5084. check_pollerr = 1;
  5085. }
  5086. do {
  5087. int result;
  5088. if (!STOP_FLAG_IS_ZERO(&*stop_flag)) {
  5089. /* Shut down signal */
  5090. return -2;
  5091. }
  5092. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5093. ms_now = milliseconds;
  5094. }
  5095. result = poll(pfd, n, ms_now);
  5096. if (result != 0) {
  5097. int err = ERRNO;
  5098. if ((result == 1) || (!ERROR_TRY_AGAIN(err))) {
  5099. /* Poll returned either success (1) or error (-1).
  5100. * Forward both to the caller. */
  5101. if ((check_pollerr)
  5102. && ((pfd[0].revents & (POLLIN | POLLOUT | POLLERR))
  5103. == POLLERR)) {
  5104. /* One and only file descriptor returned error */
  5105. return -1;
  5106. }
  5107. return result;
  5108. }
  5109. }
  5110. /* Poll returned timeout (0). */
  5111. if (milliseconds > 0) {
  5112. milliseconds -= ms_now;
  5113. }
  5114. } while (milliseconds > 0);
  5115. /* timeout: return 0 */
  5116. return 0;
  5117. }
  5118. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5119. * descriptor.
  5120. * Return value:
  5121. * >=0 .. number of bytes successfully written
  5122. * -1 .. timeout
  5123. * -2 .. error
  5124. */
  5125. static int
  5126. push_inner(struct mg_context *ctx,
  5127. FILE *fp,
  5128. SOCKET sock,
  5129. SSL *ssl,
  5130. const char *buf,
  5131. int len,
  5132. double timeout)
  5133. {
  5134. uint64_t start = 0, now = 0, timeout_ns = 0;
  5135. int n, err;
  5136. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5137. #if defined(_WIN32)
  5138. typedef int len_t;
  5139. #else
  5140. typedef size_t len_t;
  5141. #endif
  5142. if (timeout > 0) {
  5143. now = mg_get_current_time_ns();
  5144. start = now;
  5145. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5146. }
  5147. if (ctx == NULL) {
  5148. return -2;
  5149. }
  5150. #if defined(NO_SSL) && !defined(USE_MBEDTLS)
  5151. if (ssl) {
  5152. return -2;
  5153. }
  5154. #endif
  5155. /* Try to read until it succeeds, fails, times out, or the server
  5156. * shuts down. */
  5157. for (;;) {
  5158. #if defined(USE_MBEDTLS)
  5159. if (ssl != NULL) {
  5160. n = mbed_ssl_write(ssl, (const unsigned char *)buf, len);
  5161. if (n <= 0) {
  5162. if ((n == MBEDTLS_ERR_SSL_WANT_READ)
  5163. || (n == MBEDTLS_ERR_SSL_WANT_WRITE)
  5164. || n == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5165. n = 0;
  5166. } else {
  5167. fprintf(stderr, "SSL write failed, error %d\n", n);
  5168. return -2;
  5169. }
  5170. } else {
  5171. err = 0;
  5172. }
  5173. } else
  5174. #elif !defined(NO_SSL)
  5175. if (ssl != NULL) {
  5176. ERR_clear_error();
  5177. n = SSL_write(ssl, buf, len);
  5178. if (n <= 0) {
  5179. err = SSL_get_error(ssl, n);
  5180. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5181. err = ERRNO;
  5182. } else if ((err == SSL_ERROR_WANT_READ)
  5183. || (err == SSL_ERROR_WANT_WRITE)) {
  5184. n = 0;
  5185. } else {
  5186. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5187. ERR_clear_error();
  5188. return -2;
  5189. }
  5190. ERR_clear_error();
  5191. } else {
  5192. err = 0;
  5193. }
  5194. } else
  5195. #endif
  5196. if (fp != NULL) {
  5197. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5198. if (ferror(fp)) {
  5199. n = -1;
  5200. err = ERRNO;
  5201. } else {
  5202. err = 0;
  5203. }
  5204. } else {
  5205. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5206. err = (n < 0) ? ERRNO : 0;
  5207. if (ERROR_TRY_AGAIN(err)) {
  5208. err = 0;
  5209. n = 0;
  5210. }
  5211. if (n < 0) {
  5212. /* shutdown of the socket at client side */
  5213. return -2;
  5214. }
  5215. }
  5216. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5217. return -2;
  5218. }
  5219. if ((n > 0) || ((n == 0) && (len == 0))) {
  5220. /* some data has been read, or no data was requested */
  5221. return n;
  5222. }
  5223. if (n < 0) {
  5224. /* socket error - check errno */
  5225. DEBUG_TRACE("send() failed, error %d", err);
  5226. /* TODO (mid): error handling depending on the error code.
  5227. * These codes are different between Windows and Linux.
  5228. * Currently there is no problem with failing send calls,
  5229. * if there is a reproducible situation, it should be
  5230. * investigated in detail.
  5231. */
  5232. return -2;
  5233. }
  5234. /* Only in case n=0 (timeout), repeat calling the write function */
  5235. /* If send failed, wait before retry */
  5236. if (fp != NULL) {
  5237. /* For files, just wait a fixed time.
  5238. * Maybe it helps, maybe not. */
  5239. mg_sleep(5);
  5240. } else {
  5241. /* For sockets, wait for the socket using poll */
  5242. struct mg_pollfd pfd[2];
  5243. int pollres;
  5244. pfd[0].fd = sock;
  5245. pfd[0].events = POLLOUT;
  5246. pfd[1].fd = ctx->thread_shutdown_notification_socket;
  5247. pfd[1].events = POLLIN;
  5248. pollres = mg_poll(pfd, 2, (int)(ms_wait), &(ctx->stop_flag));
  5249. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5250. return -2;
  5251. }
  5252. if (pollres > 0) {
  5253. continue;
  5254. }
  5255. }
  5256. if (timeout > 0) {
  5257. now = mg_get_current_time_ns();
  5258. if ((now - start) > timeout_ns) {
  5259. /* Timeout */
  5260. break;
  5261. }
  5262. }
  5263. }
  5264. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5265. used */
  5266. return -1;
  5267. }
  5268. static int
  5269. push_all(struct mg_context *ctx,
  5270. FILE *fp,
  5271. SOCKET sock,
  5272. SSL *ssl,
  5273. const char *buf,
  5274. int len)
  5275. {
  5276. double timeout = -1.0;
  5277. int n, nwritten = 0;
  5278. if (ctx == NULL) {
  5279. return -1;
  5280. }
  5281. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5282. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5283. }
  5284. if (timeout <= 0.0) {
  5285. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5286. / 1000.0;
  5287. }
  5288. while ((len > 0) && STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  5289. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5290. if (n < 0) {
  5291. if (nwritten == 0) {
  5292. nwritten = -1; /* Propagate the error */
  5293. }
  5294. break;
  5295. } else if (n == 0) {
  5296. break; /* No more data to write */
  5297. } else {
  5298. nwritten += n;
  5299. len -= n;
  5300. }
  5301. }
  5302. return nwritten;
  5303. }
  5304. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5305. * Return value:
  5306. * >=0 .. number of bytes successfully read
  5307. * -1 .. timeout
  5308. * -2 .. error
  5309. */
  5310. static int
  5311. pull_inner(FILE *fp,
  5312. struct mg_connection *conn,
  5313. char *buf,
  5314. int len,
  5315. double timeout)
  5316. {
  5317. int nread, err = 0;
  5318. #if defined(_WIN32)
  5319. typedef int len_t;
  5320. #else
  5321. typedef size_t len_t;
  5322. #endif
  5323. /* We need an additional wait loop around this, because in some cases
  5324. * with TLSwe may get data from the socket but not from SSL_read.
  5325. * In this case we need to repeat at least once.
  5326. */
  5327. if (fp != NULL) {
  5328. /* Use read() instead of fread(), because if we're reading from the
  5329. * CGI pipe, fread() may block until IO buffer is filled up. We
  5330. * cannot afford to block and must pass all read bytes immediately
  5331. * to the client. */
  5332. nread = (int)read(fileno(fp), buf, (size_t)len);
  5333. err = (nread < 0) ? ERRNO : 0;
  5334. if ((nread == 0) && (len > 0)) {
  5335. /* Should get data, but got EOL */
  5336. return -2;
  5337. }
  5338. #if defined(USE_MBEDTLS)
  5339. } else if (conn->ssl != NULL) {
  5340. struct mg_pollfd pfd[2];
  5341. int to_read;
  5342. int pollres;
  5343. to_read = mbedtls_ssl_get_bytes_avail(conn->ssl);
  5344. if (to_read > 0) {
  5345. /* We already know there is no more data buffered in conn->buf
  5346. * but there is more available in the SSL layer. So don't poll
  5347. * conn->client.sock yet. */
  5348. pollres = 1;
  5349. if (to_read > len)
  5350. to_read = len;
  5351. } else {
  5352. pfd[0].fd = conn->client.sock;
  5353. pfd[0].events = POLLIN;
  5354. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5355. pfd[1].events = POLLIN;
  5356. to_read = len;
  5357. pollres = mg_poll(pfd,
  5358. 2,
  5359. (int)(timeout * 1000.0),
  5360. &(conn->phys_ctx->stop_flag));
  5361. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5362. return -2;
  5363. }
  5364. }
  5365. if (pollres > 0) {
  5366. nread = mbed_ssl_read(conn->ssl, (unsigned char *)buf, to_read);
  5367. if (nread <= 0) {
  5368. if ((nread == MBEDTLS_ERR_SSL_WANT_READ)
  5369. || (nread == MBEDTLS_ERR_SSL_WANT_WRITE)
  5370. || nread == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
  5371. nread = 0;
  5372. } else {
  5373. fprintf(stderr, "SSL read failed, error %d\n", nread);
  5374. return -2;
  5375. }
  5376. } else {
  5377. err = 0;
  5378. }
  5379. } else if (pollres < 0) {
  5380. /* Error */
  5381. return -2;
  5382. } else {
  5383. /* pollres = 0 means timeout */
  5384. nread = 0;
  5385. }
  5386. #elif !defined(NO_SSL)
  5387. } else if (conn->ssl != NULL) {
  5388. int ssl_pending;
  5389. struct mg_pollfd pfd[2];
  5390. int pollres;
  5391. if ((ssl_pending = SSL_pending(conn->ssl)) > 0) {
  5392. /* We already know there is no more data buffered in conn->buf
  5393. * but there is more available in the SSL layer. So don't poll
  5394. * conn->client.sock yet. */
  5395. if (ssl_pending > len) {
  5396. ssl_pending = len;
  5397. }
  5398. pollres = 1;
  5399. } else {
  5400. pfd[0].fd = conn->client.sock;
  5401. pfd[0].events = POLLIN;
  5402. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5403. pfd[1].events = POLLIN;
  5404. pollres = mg_poll(pfd,
  5405. 2,
  5406. (int)(timeout * 1000.0),
  5407. &(conn->phys_ctx->stop_flag));
  5408. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5409. return -2;
  5410. }
  5411. }
  5412. if (pollres > 0) {
  5413. ERR_clear_error();
  5414. nread =
  5415. SSL_read(conn->ssl, buf, (ssl_pending > 0) ? ssl_pending : len);
  5416. if (nread <= 0) {
  5417. err = SSL_get_error(conn->ssl, nread);
  5418. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5419. err = ERRNO;
  5420. } else if ((err == SSL_ERROR_WANT_READ)
  5421. || (err == SSL_ERROR_WANT_WRITE)) {
  5422. nread = 0;
  5423. } else {
  5424. /* All errors should return -2 */
  5425. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5426. ERR_clear_error();
  5427. return -2;
  5428. }
  5429. ERR_clear_error();
  5430. } else {
  5431. err = 0;
  5432. }
  5433. } else if (pollres < 0) {
  5434. /* Error */
  5435. return -2;
  5436. } else {
  5437. /* pollres = 0 means timeout */
  5438. nread = 0;
  5439. }
  5440. #endif
  5441. } else {
  5442. struct mg_pollfd pfd[2];
  5443. int pollres;
  5444. pfd[0].fd = conn->client.sock;
  5445. pfd[0].events = POLLIN;
  5446. pfd[1].fd = conn->phys_ctx->thread_shutdown_notification_socket;
  5447. pfd[1].events = POLLIN;
  5448. pollres = mg_poll(pfd,
  5449. 2,
  5450. (int)(timeout * 1000.0),
  5451. &(conn->phys_ctx->stop_flag));
  5452. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5453. return -2;
  5454. }
  5455. if (pollres > 0) {
  5456. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5457. err = (nread < 0) ? ERRNO : 0;
  5458. if (nread <= 0) {
  5459. /* shutdown of the socket at client side */
  5460. return -2;
  5461. }
  5462. } else if (pollres < 0) {
  5463. /* error calling poll */
  5464. return -2;
  5465. } else {
  5466. /* pollres = 0 means timeout */
  5467. nread = 0;
  5468. }
  5469. }
  5470. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5471. return -2;
  5472. }
  5473. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5474. /* some data has been read, or no data was requested */
  5475. return nread;
  5476. }
  5477. if (nread < 0) {
  5478. /* socket error - check errno */
  5479. #if defined(_WIN32)
  5480. if (err == WSAEWOULDBLOCK) {
  5481. /* TODO (low): check if this is still required */
  5482. /* standard case if called from close_socket_gracefully */
  5483. return -2;
  5484. } else if (err == WSAETIMEDOUT) {
  5485. /* TODO (low): check if this is still required */
  5486. /* timeout is handled by the while loop */
  5487. return 0;
  5488. } else if (err == WSAECONNABORTED) {
  5489. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5490. return -2;
  5491. } else {
  5492. DEBUG_TRACE("recv() failed, error %d", err);
  5493. return -2;
  5494. }
  5495. #else
  5496. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5497. * if the timeout is reached and if the socket was set to non-
  5498. * blocking in close_socket_gracefully, so we can not distinguish
  5499. * here. We have to wait for the timeout in both cases for now.
  5500. */
  5501. if (ERROR_TRY_AGAIN(err)) {
  5502. /* TODO (low): check if this is still required */
  5503. /* EAGAIN/EWOULDBLOCK:
  5504. * standard case if called from close_socket_gracefully
  5505. * => should return -1 */
  5506. /* or timeout occurred
  5507. * => the code must stay in the while loop */
  5508. /* EINTR can be generated on a socket with a timeout set even
  5509. * when SA_RESTART is effective for all relevant signals
  5510. * (see signal(7)).
  5511. * => stay in the while loop */
  5512. } else {
  5513. DEBUG_TRACE("recv() failed, error %d", err);
  5514. return -2;
  5515. }
  5516. #endif
  5517. }
  5518. /* Timeout occurred, but no data available. */
  5519. return -1;
  5520. }
  5521. static int
  5522. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5523. {
  5524. int n, nread = 0;
  5525. double timeout = -1.0;
  5526. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5527. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5528. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5529. }
  5530. if (timeout <= 0.0) {
  5531. timeout = strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  5532. / 1000.0;
  5533. }
  5534. start_time = mg_get_current_time_ns();
  5535. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5536. while ((len > 0) && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5537. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5538. if (n == -2) {
  5539. if (nread == 0) {
  5540. nread = -1; /* Propagate the error */
  5541. }
  5542. break;
  5543. } else if (n == -1) {
  5544. /* timeout */
  5545. if (timeout >= 0.0) {
  5546. now = mg_get_current_time_ns();
  5547. if ((now - start_time) <= timeout_ns) {
  5548. continue;
  5549. }
  5550. }
  5551. break;
  5552. } else if (n == 0) {
  5553. break; /* No more data to read */
  5554. } else {
  5555. nread += n;
  5556. len -= n;
  5557. }
  5558. }
  5559. return nread;
  5560. }
  5561. static void
  5562. discard_unread_request_data(struct mg_connection *conn)
  5563. {
  5564. char buf[MG_BUF_LEN];
  5565. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5566. ;
  5567. }
  5568. static int
  5569. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5570. {
  5571. int64_t content_len, n, buffered_len, nread;
  5572. int64_t len64 =
  5573. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5574. * int, we may not read more
  5575. * bytes */
  5576. const char *body;
  5577. if (conn == NULL) {
  5578. return 0;
  5579. }
  5580. /* If Content-Length is not set for a response with body data,
  5581. * we do not know in advance how much data should be read. */
  5582. content_len = conn->content_len;
  5583. if (content_len < 0) {
  5584. /* The body data is completed when the connection is closed. */
  5585. content_len = INT64_MAX;
  5586. }
  5587. nread = 0;
  5588. if (conn->consumed_content < content_len) {
  5589. /* Adjust number of bytes to read. */
  5590. int64_t left_to_read = content_len - conn->consumed_content;
  5591. if (left_to_read < len64) {
  5592. /* Do not read more than the total content length of the
  5593. * request.
  5594. */
  5595. len64 = left_to_read;
  5596. }
  5597. /* Return buffered data */
  5598. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5599. - conn->consumed_content;
  5600. if (buffered_len > 0) {
  5601. if (len64 < buffered_len) {
  5602. buffered_len = len64;
  5603. }
  5604. body = conn->buf + conn->request_len + conn->consumed_content;
  5605. memcpy(buf, body, (size_t)buffered_len);
  5606. len64 -= buffered_len;
  5607. conn->consumed_content += buffered_len;
  5608. nread += buffered_len;
  5609. buf = (char *)buf + buffered_len;
  5610. }
  5611. /* We have returned all buffered data. Read new data from the remote
  5612. * socket.
  5613. */
  5614. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5615. conn->consumed_content += n;
  5616. nread += n;
  5617. } else {
  5618. nread = ((nread > 0) ? nread : n);
  5619. }
  5620. }
  5621. return (int)nread;
  5622. }
  5623. /* Forward declarations */
  5624. static void handle_request(struct mg_connection *);
  5625. static void log_access(const struct mg_connection *);
  5626. /* Handle request, update statistics and call access log */
  5627. static void
  5628. handle_request_stat_log(struct mg_connection *conn)
  5629. {
  5630. #if defined(USE_SERVER_STATS)
  5631. struct timespec tnow;
  5632. conn->conn_state = 4; /* processing */
  5633. #endif
  5634. handle_request(conn);
  5635. #if defined(USE_SERVER_STATS)
  5636. conn->conn_state = 5; /* processed */
  5637. clock_gettime(CLOCK_MONOTONIC, &tnow);
  5638. conn->processing_time = mg_difftimespec(&tnow, &(conn->req_time));
  5639. mg_atomic_add64(&(conn->phys_ctx->total_data_read), conn->consumed_content);
  5640. mg_atomic_add64(&(conn->phys_ctx->total_data_written),
  5641. conn->num_bytes_sent);
  5642. #endif
  5643. DEBUG_TRACE("%s", "handle_request done");
  5644. if (conn->phys_ctx->callbacks.end_request != NULL) {
  5645. conn->phys_ctx->callbacks.end_request(conn, conn->status_code);
  5646. DEBUG_TRACE("%s", "end_request callback done");
  5647. }
  5648. log_access(conn);
  5649. }
  5650. #if defined(USE_HTTP2)
  5651. #if defined(NO_SSL)
  5652. #error "HTTP2 requires ALPN, ALPN requires SSL/TLS"
  5653. #endif
  5654. #define USE_ALPN
  5655. #include "http2.inl"
  5656. /* Not supported with HTTP/2 */
  5657. #define HTTP1_only \
  5658. { \
  5659. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) { \
  5660. http2_must_use_http1(conn); \
  5661. DEBUG_TRACE("%s", "must use HTTP/1.x"); \
  5662. return; \
  5663. } \
  5664. }
  5665. #else
  5666. #define HTTP1_only
  5667. #endif
  5668. CIVETWEB_API int
  5669. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5670. {
  5671. if (len > INT_MAX) {
  5672. len = INT_MAX;
  5673. }
  5674. if (conn == NULL) {
  5675. return 0;
  5676. }
  5677. if (conn->is_chunked) {
  5678. size_t all_read = 0;
  5679. while (len > 0) {
  5680. if (conn->is_chunked >= 3) {
  5681. /* No more data left to read */
  5682. return 0;
  5683. }
  5684. if (conn->is_chunked != 1) {
  5685. /* Has error */
  5686. return -1;
  5687. }
  5688. if (conn->consumed_content != conn->content_len) {
  5689. /* copy from the current chunk */
  5690. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5691. if (read_ret < 1) {
  5692. /* read error */
  5693. conn->is_chunked = 2;
  5694. return -1;
  5695. }
  5696. all_read += (size_t)read_ret;
  5697. len -= (size_t)read_ret;
  5698. if (conn->consumed_content == conn->content_len) {
  5699. /* Add data bytes in the current chunk have been read,
  5700. * so we are expecting \r\n now. */
  5701. char x[2];
  5702. conn->content_len += 2;
  5703. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5704. || (x[1] != '\n')) {
  5705. /* Protocol violation */
  5706. conn->is_chunked = 2;
  5707. return -1;
  5708. }
  5709. }
  5710. } else {
  5711. /* fetch a new chunk */
  5712. size_t i;
  5713. char lenbuf[64];
  5714. char *end = NULL;
  5715. unsigned long chunkSize = 0;
  5716. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5717. conn->content_len++;
  5718. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5719. lenbuf[i] = 0;
  5720. }
  5721. if ((i > 0) && (lenbuf[i] == ';')) {
  5722. // chunk extension --> skip chars until next CR
  5723. //
  5724. // RFC 2616, 3.6.1 Chunked Transfer Coding
  5725. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5726. //
  5727. // chunk = chunk-size [ chunk-extension ] CRLF
  5728. // chunk-data CRLF
  5729. // ...
  5730. // chunk-extension= *( ";" chunk-ext-name [ "="
  5731. // chunk-ext-val ] )
  5732. do
  5733. ++conn->content_len;
  5734. while (mg_read_inner(conn, lenbuf + i, 1) == 1
  5735. && lenbuf[i] != '\r');
  5736. }
  5737. if ((i > 0) && (lenbuf[i] == '\r')
  5738. && (lenbuf[i - 1] != '\r')) {
  5739. continue;
  5740. }
  5741. if ((i > 1) && (lenbuf[i] == '\n')
  5742. && (lenbuf[i - 1] == '\r')) {
  5743. lenbuf[i + 1] = 0;
  5744. chunkSize = strtoul(lenbuf, &end, 16);
  5745. if (chunkSize == 0) {
  5746. /* regular end of content */
  5747. conn->is_chunked = 3;
  5748. }
  5749. break;
  5750. }
  5751. if (!isxdigit((unsigned char)lenbuf[i])) {
  5752. /* illegal character for chunk length */
  5753. conn->is_chunked = 2;
  5754. return -1;
  5755. }
  5756. }
  5757. if ((end == NULL) || (*end != '\r')) {
  5758. /* chunksize not set correctly */
  5759. conn->is_chunked = 2;
  5760. return -1;
  5761. }
  5762. if (conn->is_chunked == 3) {
  5763. /* try discarding trailer for keep-alive */
  5764. // We found the last chunk (length 0) including the
  5765. // CRLF that terminates that chunk. Now follows a possibly
  5766. // empty trailer and a final CRLF.
  5767. //
  5768. // see RFC 2616, 3.6.1 Chunked Transfer Coding
  5769. // (https://www.rfc-editor.org/rfc/rfc2616#page-25)
  5770. //
  5771. // Chunked-Body = *chunk
  5772. // last-chunk
  5773. // trailer
  5774. // CRLF
  5775. // ...
  5776. // last-chunk = 1*("0") [ chunk-extension ] CRLF
  5777. // ...
  5778. // trailer = *(entity-header CRLF)
  5779. int crlf_count = 2; // one CRLF already determined
  5780. while (crlf_count < 4 && conn->is_chunked == 3) {
  5781. ++conn->content_len;
  5782. if (mg_read_inner(conn, lenbuf, 1) == 1) {
  5783. if ((crlf_count == 0 || crlf_count == 2)) {
  5784. if (lenbuf[0] == '\r')
  5785. ++crlf_count;
  5786. else
  5787. crlf_count = 0;
  5788. } else {
  5789. // previous character was a CR
  5790. // --> next character must be LF
  5791. if (lenbuf[0] == '\n')
  5792. ++crlf_count;
  5793. else
  5794. conn->is_chunked = 2;
  5795. }
  5796. } else
  5797. // premature end of trailer
  5798. conn->is_chunked = 2;
  5799. }
  5800. if (conn->is_chunked == 2)
  5801. return -1;
  5802. else
  5803. conn->is_chunked = 4;
  5804. break;
  5805. }
  5806. /* append a new chunk */
  5807. conn->content_len += (int64_t)chunkSize;
  5808. }
  5809. }
  5810. return (int)all_read;
  5811. }
  5812. return mg_read_inner(conn, buf, len);
  5813. }
  5814. CIVETWEB_API int
  5815. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5816. {
  5817. time_t now;
  5818. int n, total, allowed;
  5819. if (conn == NULL) {
  5820. return 0;
  5821. }
  5822. if (len > INT_MAX) {
  5823. return -1;
  5824. }
  5825. /* Mark connection as "data sent" */
  5826. conn->request_state = 10;
  5827. #if defined(USE_HTTP2)
  5828. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  5829. http2_data_frame_head(conn, len, 0);
  5830. }
  5831. #endif
  5832. if (conn->throttle > 0) {
  5833. if ((now = time(NULL)) != conn->last_throttle_time) {
  5834. conn->last_throttle_time = now;
  5835. conn->last_throttle_bytes = 0;
  5836. }
  5837. allowed = conn->throttle - conn->last_throttle_bytes;
  5838. if (allowed > (int)len) {
  5839. allowed = (int)len;
  5840. }
  5841. total = push_all(conn->phys_ctx,
  5842. NULL,
  5843. conn->client.sock,
  5844. conn->ssl,
  5845. (const char *)buf,
  5846. allowed);
  5847. if (total == allowed) {
  5848. buf = (const char *)buf + total;
  5849. conn->last_throttle_bytes += total;
  5850. while ((total < (int)len)
  5851. && STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  5852. allowed = (conn->throttle > ((int)len - total))
  5853. ? (int)len - total
  5854. : conn->throttle;
  5855. n = push_all(conn->phys_ctx,
  5856. NULL,
  5857. conn->client.sock,
  5858. conn->ssl,
  5859. (const char *)buf,
  5860. allowed);
  5861. if (n != allowed) {
  5862. break;
  5863. }
  5864. sleep(1);
  5865. conn->last_throttle_bytes = allowed;
  5866. conn->last_throttle_time = time(NULL);
  5867. buf = (const char *)buf + n;
  5868. total += n;
  5869. }
  5870. }
  5871. } else {
  5872. total = push_all(conn->phys_ctx,
  5873. NULL,
  5874. conn->client.sock,
  5875. conn->ssl,
  5876. (const char *)buf,
  5877. (int)len);
  5878. }
  5879. if (total > 0) {
  5880. conn->num_bytes_sent += total;
  5881. }
  5882. return total;
  5883. }
  5884. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5885. CIVETWEB_API int
  5886. mg_send_chunk(struct mg_connection *conn,
  5887. const char *chunk,
  5888. unsigned int chunk_len)
  5889. {
  5890. char lenbuf[16];
  5891. size_t lenbuf_len;
  5892. int ret;
  5893. int t;
  5894. /* First store the length information in a text buffer. */
  5895. sprintf(lenbuf, "%x\r\n", chunk_len);
  5896. lenbuf_len = strlen(lenbuf);
  5897. /* Then send length information, chunk and terminating \r\n. */
  5898. ret = mg_write(conn, lenbuf, lenbuf_len);
  5899. if (ret != (int)lenbuf_len) {
  5900. return -1;
  5901. }
  5902. t = ret;
  5903. ret = mg_write(conn, chunk, chunk_len);
  5904. if (ret != (int)chunk_len) {
  5905. return -1;
  5906. }
  5907. t += ret;
  5908. ret = mg_write(conn, "\r\n", 2);
  5909. if (ret != 2) {
  5910. return -1;
  5911. }
  5912. t += ret;
  5913. return t;
  5914. }
  5915. #if defined(GCC_DIAGNOSTIC)
  5916. /* This block forwards format strings to printf implementations,
  5917. * so we need to disable the format-nonliteral warning. */
  5918. #pragma GCC diagnostic push
  5919. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5920. #endif
  5921. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5922. static int
  5923. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5924. {
  5925. va_list ap_copy;
  5926. size_t size = MG_BUF_LEN / 4;
  5927. int len = -1;
  5928. *buf = NULL;
  5929. while (len < 0) {
  5930. if (*buf) {
  5931. mg_free(*buf);
  5932. }
  5933. size *= 4;
  5934. *buf = (char *)mg_malloc(size);
  5935. if (!*buf) {
  5936. break;
  5937. }
  5938. va_copy(ap_copy, ap);
  5939. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5940. va_end(ap_copy);
  5941. (*buf)[size - 1] = 0;
  5942. }
  5943. return len;
  5944. }
  5945. /* Print message to buffer. If buffer is large enough to hold the message,
  5946. * return buffer. If buffer is to small, allocate large enough buffer on
  5947. * heap,
  5948. * and return allocated buffer. */
  5949. static int
  5950. alloc_vprintf(char **out_buf,
  5951. char *prealloc_buf,
  5952. size_t prealloc_size,
  5953. const char *fmt,
  5954. va_list ap)
  5955. {
  5956. va_list ap_copy;
  5957. int len;
  5958. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5959. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5960. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5961. * Therefore, we make two passes: on first pass, get required message
  5962. * length.
  5963. * On second pass, actually print the message. */
  5964. va_copy(ap_copy, ap);
  5965. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5966. va_end(ap_copy);
  5967. if (len < 0) {
  5968. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5969. * Switch to alternative code path that uses incremental
  5970. * allocations.
  5971. */
  5972. va_copy(ap_copy, ap);
  5973. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5974. va_end(ap_copy);
  5975. } else if ((size_t)(len) >= prealloc_size) {
  5976. /* The pre-allocated buffer not large enough. */
  5977. /* Allocate a new buffer. */
  5978. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5979. if (!*out_buf) {
  5980. /* Allocation failed. Return -1 as "out of memory" error. */
  5981. return -1;
  5982. }
  5983. /* Buffer allocation successful. Store the string there. */
  5984. va_copy(ap_copy, ap);
  5985. IGNORE_UNUSED_RESULT(
  5986. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5987. va_end(ap_copy);
  5988. } else {
  5989. /* The pre-allocated buffer is large enough.
  5990. * Use it to store the string and return the address. */
  5991. va_copy(ap_copy, ap);
  5992. IGNORE_UNUSED_RESULT(
  5993. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5994. va_end(ap_copy);
  5995. *out_buf = prealloc_buf;
  5996. }
  5997. return len;
  5998. }
  5999. static int
  6000. alloc_printf(char **out_buf, const char *fmt, ...)
  6001. {
  6002. va_list ap;
  6003. int result;
  6004. va_start(ap, fmt);
  6005. result = alloc_vprintf(out_buf, NULL, 0, fmt, ap);
  6006. va_end(ap);
  6007. return result;
  6008. }
  6009. #if defined(GCC_DIAGNOSTIC)
  6010. /* Enable format-nonliteral warning again. */
  6011. #pragma GCC diagnostic pop
  6012. #endif
  6013. static int
  6014. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  6015. {
  6016. char mem[MG_BUF_LEN];
  6017. char *buf = NULL;
  6018. int len;
  6019. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  6020. len = mg_write(conn, buf, (size_t)len);
  6021. }
  6022. if (buf != mem) {
  6023. mg_free(buf);
  6024. }
  6025. return len;
  6026. }
  6027. CIVETWEB_API int
  6028. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  6029. {
  6030. va_list ap;
  6031. int result;
  6032. va_start(ap, fmt);
  6033. result = mg_vprintf(conn, fmt, ap);
  6034. va_end(ap);
  6035. return result;
  6036. }
  6037. CIVETWEB_API int
  6038. mg_url_decode(const char *src,
  6039. int src_len,
  6040. char *dst,
  6041. int dst_len,
  6042. int is_form_url_encoded)
  6043. {
  6044. int i, j, a, b;
  6045. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6046. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6047. if ((i < src_len - 2) && (src[i] == '%')
  6048. && isxdigit((unsigned char)src[i + 1])
  6049. && isxdigit((unsigned char)src[i + 2])) {
  6050. a = tolower((unsigned char)src[i + 1]);
  6051. b = tolower((unsigned char)src[i + 2]);
  6052. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6053. i += 2;
  6054. } else if (is_form_url_encoded && (src[i] == '+')) {
  6055. dst[j] = ' ';
  6056. } else {
  6057. dst[j] = src[i];
  6058. }
  6059. }
  6060. dst[j] = '\0'; /* Null-terminate the destination */
  6061. return (i >= src_len) ? j : -1;
  6062. }
  6063. /* form url decoding of an entire string */
  6064. static void
  6065. url_decode_in_place(char *buf)
  6066. {
  6067. int len = (int)strlen(buf);
  6068. (void)mg_url_decode(buf, len, buf, len + 1, 1);
  6069. }
  6070. CIVETWEB_API int
  6071. mg_get_var(const char *data,
  6072. size_t data_len,
  6073. const char *name,
  6074. char *dst,
  6075. size_t dst_len)
  6076. {
  6077. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6078. }
  6079. CIVETWEB_API int
  6080. mg_get_var2(const char *data,
  6081. size_t data_len,
  6082. const char *name,
  6083. char *dst,
  6084. size_t dst_len,
  6085. size_t occurrence)
  6086. {
  6087. const char *p, *e, *s;
  6088. size_t name_len;
  6089. int len;
  6090. if ((dst == NULL) || (dst_len == 0)) {
  6091. len = -2;
  6092. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6093. len = -1;
  6094. dst[0] = '\0';
  6095. } else {
  6096. name_len = strlen(name);
  6097. e = data + data_len;
  6098. len = -1;
  6099. dst[0] = '\0';
  6100. /* data is "var1=val1&var2=val2...". Find variable first */
  6101. for (p = data; p + name_len < e; p++) {
  6102. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6103. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6104. /* Point p to variable value */
  6105. p += name_len + 1;
  6106. /* Point s to the end of the value */
  6107. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6108. if (s == NULL) {
  6109. s = e;
  6110. }
  6111. DEBUG_ASSERT(s >= p);
  6112. if (s < p) {
  6113. return -3;
  6114. }
  6115. /* Decode variable into destination buffer */
  6116. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6117. /* Redirect error code from -1 to -2 (destination buffer too
  6118. * small). */
  6119. if (len == -1) {
  6120. len = -2;
  6121. }
  6122. break;
  6123. }
  6124. }
  6125. }
  6126. return len;
  6127. }
  6128. /* split a string "key1=val1&key2=val2" into key/value pairs */
  6129. CIVETWEB_API int
  6130. mg_split_form_urlencoded(char *data,
  6131. struct mg_header *form_fields,
  6132. unsigned num_form_fields)
  6133. {
  6134. char *b;
  6135. int i;
  6136. int num = 0;
  6137. if (data == NULL) {
  6138. /* parameter error */
  6139. return -1;
  6140. }
  6141. if ((form_fields == NULL) && (num_form_fields == 0)) {
  6142. /* determine the number of expected fields */
  6143. if (data[0] == 0) {
  6144. return 0;
  6145. }
  6146. /* count number of & to return the number of key-value-pairs */
  6147. num = 1;
  6148. while (*data) {
  6149. if (*data == '&') {
  6150. num++;
  6151. }
  6152. data++;
  6153. }
  6154. return num;
  6155. }
  6156. if ((form_fields == NULL) || ((int)num_form_fields <= 0)) {
  6157. /* parameter error */
  6158. return -1;
  6159. }
  6160. for (i = 0; i < (int)num_form_fields; i++) {
  6161. /* extract key-value pairs from input data */
  6162. while ((*data == ' ') || (*data == '\t')) {
  6163. /* skip initial spaces */
  6164. data++;
  6165. }
  6166. if (*data == 0) {
  6167. /* end of string reached */
  6168. break;
  6169. }
  6170. form_fields[num].name = data;
  6171. /* find & or = */
  6172. b = data;
  6173. while ((*b != 0) && (*b != '&') && (*b != '=')) {
  6174. b++;
  6175. }
  6176. if (*b == 0) {
  6177. /* last key without value */
  6178. form_fields[num].value = NULL;
  6179. } else if (*b == '&') {
  6180. /* mid key without value */
  6181. form_fields[num].value = NULL;
  6182. } else {
  6183. /* terminate string */
  6184. *b = 0;
  6185. /* value starts after '=' */
  6186. data = b + 1;
  6187. form_fields[num].value = data;
  6188. }
  6189. /* new field is stored */
  6190. num++;
  6191. /* find a next key */
  6192. b = strchr(data, '&');
  6193. if (b == 0) {
  6194. /* no more data */
  6195. break;
  6196. } else {
  6197. /* terminate value of last field at '&' */
  6198. *b = 0;
  6199. /* next key-value-pairs starts after '&' */
  6200. data = b + 1;
  6201. }
  6202. }
  6203. /* Decode all values */
  6204. for (i = 0; i < num; i++) {
  6205. if (form_fields[i].name) {
  6206. url_decode_in_place((char *)form_fields[i].name);
  6207. }
  6208. if (form_fields[i].value) {
  6209. url_decode_in_place((char *)form_fields[i].value);
  6210. }
  6211. }
  6212. /* return number of fields found */
  6213. return num;
  6214. }
  6215. /* HCP24: some changes to compare whole var_name */
  6216. CIVETWEB_API int
  6217. mg_get_cookie(const char *cookie_header,
  6218. const char *var_name,
  6219. char *dst,
  6220. size_t dst_size)
  6221. {
  6222. const char *s, *p, *end;
  6223. int name_len, len = -1;
  6224. if ((dst == NULL) || (dst_size == 0)) {
  6225. return -2;
  6226. }
  6227. dst[0] = '\0';
  6228. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6229. return -1;
  6230. }
  6231. name_len = (int)strlen(var_name);
  6232. end = s + strlen(s);
  6233. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6234. if (s[name_len] == '=') {
  6235. /* HCP24: now check is it a substring or a full cookie name */
  6236. if ((s == cookie_header) || (s[-1] == ' ')) {
  6237. s += name_len + 1;
  6238. if ((p = strchr(s, ' ')) == NULL) {
  6239. p = end;
  6240. }
  6241. if (p[-1] == ';') {
  6242. p--;
  6243. }
  6244. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6245. s++;
  6246. p--;
  6247. }
  6248. if ((size_t)(p - s) < dst_size) {
  6249. len = (int)(p - s);
  6250. mg_strlcpy(dst, s, (size_t)len + 1);
  6251. } else {
  6252. len = -3;
  6253. }
  6254. break;
  6255. }
  6256. }
  6257. }
  6258. return len;
  6259. }
  6260. CIVETWEB_API int
  6261. mg_base64_encode(const unsigned char *src,
  6262. size_t src_len,
  6263. char *dst,
  6264. size_t *dst_len)
  6265. {
  6266. static const char *b64 =
  6267. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6268. size_t i, j;
  6269. int a, b, c;
  6270. if (dst_len != NULL) {
  6271. /* Expected length including 0 termination: */
  6272. /* IN 1 -> OUT 5, IN 2 -> OUT 5, IN 3 -> OUT 5, IN 4 -> OUT 9,
  6273. * IN 5 -> OUT 9, IN 6 -> OUT 9, IN 7 -> OUT 13, etc. */
  6274. size_t expected_len = ((src_len + 2) / 3) * 4 + 1;
  6275. if (*dst_len < expected_len) {
  6276. if (*dst_len > 0) {
  6277. dst[0] = '\0';
  6278. }
  6279. *dst_len = expected_len;
  6280. return 0;
  6281. }
  6282. }
  6283. for (i = j = 0; i < src_len; i += 3) {
  6284. a = src[i];
  6285. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6286. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6287. dst[j++] = b64[a >> 2];
  6288. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6289. if (i + 1 < src_len) {
  6290. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6291. }
  6292. if (i + 2 < src_len) {
  6293. dst[j++] = b64[c & 63];
  6294. }
  6295. }
  6296. while (j % 4 != 0) {
  6297. dst[j++] = '=';
  6298. }
  6299. dst[j++] = '\0';
  6300. if (dst_len != NULL) {
  6301. *dst_len = (size_t)j;
  6302. }
  6303. /* Return -1 for "OK" */
  6304. return -1;
  6305. }
  6306. static unsigned char
  6307. b64reverse(char letter)
  6308. {
  6309. if ((letter >= 'A') && (letter <= 'Z')) {
  6310. return (unsigned char)(letter - 'A');
  6311. }
  6312. if ((letter >= 'a') && (letter <= 'z')) {
  6313. return (unsigned char)(letter - 'a' + 26);
  6314. }
  6315. if ((letter >= '0') && (letter <= '9')) {
  6316. return (unsigned char)(letter - '0' + 52);
  6317. }
  6318. if (letter == '+') {
  6319. return 62;
  6320. }
  6321. if (letter == '/') {
  6322. return 63;
  6323. }
  6324. if (letter == '=') {
  6325. return 255; /* normal end */
  6326. }
  6327. return 254; /* error */
  6328. }
  6329. CIVETWEB_API int
  6330. mg_base64_decode(const char *src,
  6331. size_t src_len,
  6332. unsigned char *dst,
  6333. size_t *dst_len)
  6334. {
  6335. size_t i;
  6336. unsigned char a, b, c, d;
  6337. size_t dst_len_limit = (size_t)-1;
  6338. size_t dst_len_used = 0;
  6339. if (dst_len != NULL) {
  6340. dst_len_limit = *dst_len;
  6341. *dst_len = 0;
  6342. }
  6343. for (i = 0; i < src_len; i += 4) {
  6344. /* Read 4 characters from BASE64 string */
  6345. a = b64reverse(src[i]);
  6346. if (a >= 254) {
  6347. return (int)i;
  6348. }
  6349. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6350. if (b >= 254) {
  6351. return (int)i + 1;
  6352. }
  6353. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6354. if (c == 254) {
  6355. return (int)i + 2;
  6356. }
  6357. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6358. if (d == 254) {
  6359. return (int)i + 3;
  6360. }
  6361. /* Add first (of 3) decoded character */
  6362. if (dst_len_used < dst_len_limit) {
  6363. dst[dst_len_used] = (unsigned char)((unsigned char)(a << 2)
  6364. + (unsigned char)(b >> 4));
  6365. }
  6366. dst_len_used++;
  6367. if (c != 255) {
  6368. if (dst_len_used < dst_len_limit) {
  6369. dst[dst_len_used] = (unsigned char)((unsigned char)(b << 4)
  6370. + (unsigned char)(c >> 2));
  6371. }
  6372. dst_len_used++;
  6373. if (d != 255) {
  6374. if (dst_len_used < dst_len_limit) {
  6375. dst[dst_len_used] =
  6376. (unsigned char)((unsigned char)(c << 6) + d);
  6377. }
  6378. dst_len_used++;
  6379. }
  6380. }
  6381. }
  6382. /* Add terminating zero */
  6383. if (dst_len_used < dst_len_limit) {
  6384. dst[dst_len_used] = '\0';
  6385. }
  6386. dst_len_used++;
  6387. if (dst_len != NULL) {
  6388. *dst_len = dst_len_used;
  6389. }
  6390. if (dst_len_used > dst_len_limit) {
  6391. /* Out of memory */
  6392. return 0;
  6393. }
  6394. /* Return -1 for "OK" */
  6395. return -1;
  6396. }
  6397. static int
  6398. is_put_or_delete_method(const struct mg_connection *conn)
  6399. {
  6400. if (conn) {
  6401. const char *s = conn->request_info.request_method;
  6402. if (s != NULL) {
  6403. /* PUT, DELETE, MKCOL, PATCH, LOCK, UNLOCK, PROPPATCH, MOVE, COPY */
  6404. return (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6405. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")
  6406. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6407. || !strcmp(s, "PROPPATCH") || !strcmp(s, "MOVE")
  6408. || !strcmp(s, "COPY"));
  6409. }
  6410. }
  6411. return 0;
  6412. }
  6413. static int
  6414. is_civetweb_webdav_method(const struct mg_connection *conn)
  6415. {
  6416. /* Note: Here we only have to identify the WebDav methods that need special
  6417. * handling in the CivetWeb code - not all methods used in WebDav. In
  6418. * particular, methods used on directories (when using Windows Explorer as
  6419. * WebDav client).
  6420. */
  6421. if (conn) {
  6422. const char *s = conn->request_info.request_method;
  6423. if (s != NULL) {
  6424. /* These are the civetweb builtin DAV methods */
  6425. return (!strcmp(s, "PROPFIND") || !strcmp(s, "PROPPATCH")
  6426. || !strcmp(s, "LOCK") || !strcmp(s, "UNLOCK")
  6427. || !strcmp(s, "MOVE") || !strcmp(s, "COPY"));
  6428. }
  6429. }
  6430. return 0;
  6431. }
  6432. #if !defined(NO_FILES)
  6433. static int
  6434. extention_matches_script(
  6435. struct mg_connection *conn, /* in: request (must be valid) */
  6436. const char *filename /* in: filename (must be valid) */
  6437. )
  6438. {
  6439. #if !defined(NO_CGI)
  6440. int cgi_config_idx, inc, max;
  6441. #endif
  6442. #if defined(USE_LUA)
  6443. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6444. filename)
  6445. > 0) {
  6446. return 1;
  6447. }
  6448. #endif
  6449. #if defined(USE_DUKTAPE)
  6450. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6451. filename)
  6452. > 0) {
  6453. return 1;
  6454. }
  6455. #endif
  6456. #if !defined(NO_CGI)
  6457. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  6458. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  6459. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  6460. if ((conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL)
  6461. && (match_prefix_strlen(
  6462. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  6463. filename)
  6464. > 0)) {
  6465. return 1;
  6466. }
  6467. }
  6468. #endif
  6469. /* filename and conn could be unused, if all preocessor conditions
  6470. * are false (no script language supported). */
  6471. (void)filename;
  6472. (void)conn;
  6473. return 0;
  6474. }
  6475. static int
  6476. extention_matches_template_text(
  6477. struct mg_connection *conn, /* in: request (must be valid) */
  6478. const char *filename /* in: filename (must be valid) */
  6479. )
  6480. {
  6481. #if defined(USE_LUA)
  6482. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6483. filename)
  6484. > 0) {
  6485. return 1;
  6486. }
  6487. #endif
  6488. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], filename)
  6489. > 0) {
  6490. return 1;
  6491. }
  6492. return 0;
  6493. }
  6494. /* For given directory path, substitute it to valid index file.
  6495. * Return 1 if index file has been found, 0 if not found.
  6496. * If the file is found, it's stats is returned in stp. */
  6497. static int
  6498. substitute_index_file_aux(struct mg_connection *conn,
  6499. char *path,
  6500. size_t path_len,
  6501. struct mg_file_stat *filestat)
  6502. {
  6503. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6504. struct vec filename_vec;
  6505. size_t n = strlen(path);
  6506. int found = 0;
  6507. /* The 'path' given to us points to the directory. Remove all trailing
  6508. * directory separator characters from the end of the path, and
  6509. * then append single directory separator character. */
  6510. while ((n > 0) && (path[n - 1] == '/')) {
  6511. n--;
  6512. }
  6513. path[n] = '/';
  6514. /* Traverse index files list. For each entry, append it to the given
  6515. * path and see if the file exists. If it exists, break the loop */
  6516. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6517. /* Ignore too long entries that may overflow path buffer */
  6518. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6519. continue;
  6520. }
  6521. /* Prepare full path to the index file */
  6522. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6523. /* Does it exist? */
  6524. if (mg_stat(conn, path, filestat)) {
  6525. /* Yes it does, break the loop */
  6526. found = 1;
  6527. break;
  6528. }
  6529. }
  6530. /* If no index file exists, restore directory path */
  6531. if (!found) {
  6532. path[n] = '\0';
  6533. }
  6534. return found;
  6535. }
  6536. /* Same as above, except if the first try fails and a fallback-root is
  6537. * configured, we'll try there also */
  6538. static int
  6539. substitute_index_file(struct mg_connection *conn,
  6540. char *path,
  6541. size_t path_len,
  6542. struct mg_file_stat *filestat)
  6543. {
  6544. int ret = substitute_index_file_aux(conn, path, path_len, filestat);
  6545. if (ret == 0) {
  6546. const char *root_prefix = conn->dom_ctx->config[DOCUMENT_ROOT];
  6547. const char *fallback_root_prefix =
  6548. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT];
  6549. if ((root_prefix) && (fallback_root_prefix)) {
  6550. const size_t root_prefix_len = strlen(root_prefix);
  6551. if ((strncmp(path, root_prefix, root_prefix_len) == 0)) {
  6552. char scratch_path[UTF8_PATH_MAX]; /* separate storage, to avoid
  6553. side effects if we fail */
  6554. size_t sub_path_len;
  6555. const size_t fallback_root_prefix_len =
  6556. strlen(fallback_root_prefix);
  6557. const char *sub_path = path + root_prefix_len;
  6558. while (*sub_path == '/') {
  6559. sub_path++;
  6560. }
  6561. sub_path_len = strlen(sub_path);
  6562. if (((fallback_root_prefix_len + 1 + sub_path_len + 1)
  6563. < sizeof(scratch_path))) {
  6564. /* The concatenations below are all safe because we
  6565. * pre-verified string lengths above */
  6566. char *nul;
  6567. strcpy(scratch_path, fallback_root_prefix);
  6568. nul = strchr(scratch_path, '\0');
  6569. if ((nul > scratch_path) && (*(nul - 1) != '/')) {
  6570. *nul++ = '/';
  6571. *nul = '\0';
  6572. }
  6573. strcat(scratch_path, sub_path);
  6574. if (substitute_index_file_aux(conn,
  6575. scratch_path,
  6576. sizeof(scratch_path),
  6577. filestat)) {
  6578. mg_strlcpy(path, scratch_path, path_len);
  6579. return 1;
  6580. }
  6581. }
  6582. }
  6583. }
  6584. }
  6585. return ret;
  6586. }
  6587. #endif
  6588. static void
  6589. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6590. char *filename, /* out: filename */
  6591. size_t filename_buf_len, /* in: size of filename buffer */
  6592. struct mg_file_stat *filestat, /* out: file status structure */
  6593. int *is_found, /* out: file found (directly) */
  6594. int *is_script_resource, /* out: handled by a script? */
  6595. int *is_websocket_request, /* out: websocket connection? */
  6596. int *is_put_or_delete_request, /* out: put/delete a file? */
  6597. int *is_webdav_request, /* out: webdav request? */
  6598. int *is_template_text /* out: SSI file or LSP file? */
  6599. )
  6600. {
  6601. char const *accept_encoding;
  6602. #if !defined(NO_FILES)
  6603. const char *uri = conn->request_info.local_uri;
  6604. const char *roots[] = {conn->dom_ctx->config[DOCUMENT_ROOT],
  6605. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT],
  6606. NULL};
  6607. int fileExists = 0;
  6608. const char *rewrite;
  6609. struct vec a, b;
  6610. ptrdiff_t match_len;
  6611. char gz_path[UTF8_PATH_MAX];
  6612. int truncated;
  6613. int i;
  6614. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6615. char *tmp_str;
  6616. size_t tmp_str_len, sep_pos;
  6617. int allow_substitute_script_subresources;
  6618. #endif
  6619. #else
  6620. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6621. #endif
  6622. /* Step 1: Set all initially unknown outputs to zero */
  6623. memset(filestat, 0, sizeof(*filestat));
  6624. *filename = 0;
  6625. *is_found = 0;
  6626. *is_script_resource = 0;
  6627. *is_template_text = 0;
  6628. /* Step 2: Classify the request method */
  6629. /* Step 2a: Check if the request attempts to modify the file system */
  6630. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6631. /* Step 2b: Check if the request uses WebDav method that requires special
  6632. * handling */
  6633. *is_webdav_request = is_civetweb_webdav_method(conn);
  6634. /* Step 3: Check if it is a websocket request, and modify the document
  6635. * root if required */
  6636. #if defined(USE_WEBSOCKET)
  6637. *is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  6638. #if !defined(NO_FILES)
  6639. if ((*is_websocket_request) && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6640. roots[0] = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6641. roots[1] = conn->dom_ctx->config[FALLBACK_WEBSOCKET_ROOT];
  6642. }
  6643. #endif /* !NO_FILES */
  6644. #else /* USE_WEBSOCKET */
  6645. *is_websocket_request = 0;
  6646. #endif /* USE_WEBSOCKET */
  6647. /* Step 4: Check if gzip encoded response is allowed */
  6648. conn->accept_gzip = 0;
  6649. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6650. if (strstr(accept_encoding, "gzip") != NULL) {
  6651. conn->accept_gzip = 1;
  6652. }
  6653. }
  6654. #if !defined(NO_FILES)
  6655. /* Step 5: If there is no root directory, don't look for files. */
  6656. /* Note that roots[0] == NULL is a regular use case here. This occurs,
  6657. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6658. * config is not required. */
  6659. if (roots[0] == NULL) {
  6660. /* all file related outputs have already been set to 0, just return
  6661. */
  6662. return;
  6663. }
  6664. for (i = 0; roots[i] != NULL; i++) {
  6665. /* Step 6: Determine the local file path from the root path and the
  6666. * request uri. */
  6667. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6668. * part of the path one byte on the right. */
  6669. truncated = 0;
  6670. mg_snprintf(conn,
  6671. &truncated,
  6672. filename,
  6673. filename_buf_len - 1,
  6674. "%s%s",
  6675. roots[i],
  6676. uri);
  6677. if (truncated) {
  6678. goto interpret_cleanup;
  6679. }
  6680. /* Step 7: URI rewriting */
  6681. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6682. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6683. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6684. mg_snprintf(conn,
  6685. &truncated,
  6686. filename,
  6687. filename_buf_len - 1,
  6688. "%.*s%s",
  6689. (int)b.len,
  6690. b.ptr,
  6691. uri + match_len);
  6692. break;
  6693. }
  6694. }
  6695. if (truncated) {
  6696. goto interpret_cleanup;
  6697. }
  6698. /* Step 8: Check if the file exists at the server */
  6699. /* Local file path and name, corresponding to requested URI
  6700. * is now stored in "filename" variable. */
  6701. if (mg_stat(conn, filename, filestat)) {
  6702. fileExists = 1;
  6703. break;
  6704. }
  6705. }
  6706. if (fileExists) {
  6707. int uri_len = (int)strlen(uri);
  6708. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6709. /* 8.1: File exists. */
  6710. *is_found = 1;
  6711. /* 8.2: Check if it is a script type. */
  6712. if (extention_matches_script(conn, filename)) {
  6713. /* The request addresses a CGI resource, Lua script or
  6714. * server-side javascript.
  6715. * The URI corresponds to the script itself (like
  6716. * /path/script.cgi), and there is no additional resource
  6717. * path (like /path/script.cgi/something).
  6718. * Requests that modify (replace or delete) a resource, like
  6719. * PUT and DELETE requests, should replace/delete the script
  6720. * file.
  6721. * Requests that read or write from/to a resource, like GET and
  6722. * POST requests, should call the script and return the
  6723. * generated response. */
  6724. *is_script_resource = (!*is_put_or_delete_request);
  6725. }
  6726. /* 8.3: Check for SSI and LSP files */
  6727. if (extention_matches_template_text(conn, filename)) {
  6728. /* Same as above, but for *.lsp and *.shtml files. */
  6729. /* A "template text" is a file delivered directly to the client,
  6730. * but with some text tags replaced by dynamic content.
  6731. * E.g. a Server Side Include (SSI) or Lua Page/Lua Server Page
  6732. * (LP, LSP) file. */
  6733. *is_template_text = (!*is_put_or_delete_request);
  6734. }
  6735. /* 8.4: If the request target is a directory, there could be
  6736. * a substitute file (index.html, index.cgi, ...). */
  6737. /* But do not substitute a directory for a WebDav request */
  6738. if (filestat->is_directory && is_uri_end_slash
  6739. && (!*is_webdav_request)) {
  6740. /* Use a local copy here, since substitute_index_file will
  6741. * change the content of the file status */
  6742. struct mg_file_stat tmp_filestat;
  6743. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6744. if (substitute_index_file(
  6745. conn, filename, filename_buf_len, &tmp_filestat)) {
  6746. /* Substitute file found. Copy stat to the output, then
  6747. * check if the file is a script file */
  6748. *filestat = tmp_filestat;
  6749. if (extention_matches_script(conn, filename)) {
  6750. /* Substitute file is a script file */
  6751. *is_script_resource = 1;
  6752. } else if (extention_matches_template_text(conn, filename)) {
  6753. /* Substitute file is a LSP or SSI file */
  6754. *is_template_text = 1;
  6755. } else {
  6756. /* Substitute file is a regular file */
  6757. *is_script_resource = 0;
  6758. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6759. }
  6760. }
  6761. /* If there is no substitute file, the server could return
  6762. * a directory listing in a later step */
  6763. }
  6764. return;
  6765. }
  6766. /* Step 9: Check for zipped files: */
  6767. /* If we can't find the actual file, look for the file
  6768. * with the same name but a .gz extension. If we find it,
  6769. * use that and set the gzipped flag in the file struct
  6770. * to indicate that the response need to have the content-
  6771. * encoding: gzip header.
  6772. * We can only do this if the browser declares support. */
  6773. if (conn->accept_gzip) {
  6774. mg_snprintf(
  6775. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6776. if (truncated) {
  6777. goto interpret_cleanup;
  6778. }
  6779. if (mg_stat(conn, gz_path, filestat)) {
  6780. if (filestat) {
  6781. filestat->is_gzipped = 1;
  6782. *is_found = 1;
  6783. }
  6784. /* Currently gz files can not be scripts. */
  6785. return;
  6786. }
  6787. }
  6788. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6789. /* Step 10: Script resources may handle sub-resources */
  6790. /* Support PATH_INFO for CGI scripts. */
  6791. tmp_str_len = strlen(filename);
  6792. tmp_str =
  6793. (char *)mg_malloc_ctx(tmp_str_len + UTF8_PATH_MAX + 1, conn->phys_ctx);
  6794. if (!tmp_str) {
  6795. /* Out of memory */
  6796. goto interpret_cleanup;
  6797. }
  6798. memcpy(tmp_str, filename, tmp_str_len + 1);
  6799. /* Check config, if index scripts may have sub-resources */
  6800. allow_substitute_script_subresources =
  6801. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6802. "yes");
  6803. if (*is_webdav_request) {
  6804. /* TO BE DEFINED: Should scripts handle special WebDAV methods lile
  6805. * PROPFIND for their subresources? */
  6806. /* allow_substitute_script_subresources = 0; */
  6807. }
  6808. sep_pos = tmp_str_len;
  6809. while (sep_pos > 0) {
  6810. sep_pos--;
  6811. if (tmp_str[sep_pos] == '/') {
  6812. int is_script = 0, does_exist = 0;
  6813. tmp_str[sep_pos] = 0;
  6814. if (tmp_str[0]) {
  6815. is_script = extention_matches_script(conn, tmp_str);
  6816. does_exist = mg_stat(conn, tmp_str, filestat);
  6817. }
  6818. if (does_exist && is_script) {
  6819. filename[sep_pos] = 0;
  6820. memmove(filename + sep_pos + 2,
  6821. filename + sep_pos + 1,
  6822. strlen(filename + sep_pos + 1) + 1);
  6823. conn->path_info = filename + sep_pos + 1;
  6824. filename[sep_pos + 1] = '/';
  6825. *is_script_resource = 1;
  6826. *is_found = 1;
  6827. break;
  6828. }
  6829. if (allow_substitute_script_subresources) {
  6830. if (substitute_index_file(
  6831. conn, tmp_str, tmp_str_len + UTF8_PATH_MAX, filestat)) {
  6832. /* some intermediate directory has an index file */
  6833. if (extention_matches_script(conn, tmp_str)) {
  6834. size_t script_name_len = strlen(tmp_str);
  6835. /* subres_name read before this memory locatio will be
  6836. overwritten */
  6837. char *subres_name = filename + sep_pos;
  6838. size_t subres_name_len = strlen(subres_name);
  6839. DEBUG_TRACE("Substitute script %s serving path %s",
  6840. tmp_str,
  6841. filename);
  6842. /* this index file is a script */
  6843. if ((script_name_len + subres_name_len + 2)
  6844. >= filename_buf_len) {
  6845. mg_free(tmp_str);
  6846. goto interpret_cleanup;
  6847. }
  6848. conn->path_info =
  6849. filename + script_name_len + 1; /* new target */
  6850. memmove(conn->path_info, subres_name, subres_name_len);
  6851. conn->path_info[subres_name_len] = 0;
  6852. memcpy(filename, tmp_str, script_name_len + 1);
  6853. *is_script_resource = 1;
  6854. *is_found = 1;
  6855. break;
  6856. } else {
  6857. DEBUG_TRACE("Substitute file %s serving path %s",
  6858. tmp_str,
  6859. filename);
  6860. /* non-script files will not have sub-resources */
  6861. filename[sep_pos] = 0;
  6862. conn->path_info = 0;
  6863. *is_script_resource = 0;
  6864. *is_found = 0;
  6865. break;
  6866. }
  6867. }
  6868. }
  6869. tmp_str[sep_pos] = '/';
  6870. }
  6871. }
  6872. mg_free(tmp_str);
  6873. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6874. #endif /* !defined(NO_FILES) */
  6875. return;
  6876. #if !defined(NO_FILES)
  6877. /* Reset all outputs */
  6878. interpret_cleanup:
  6879. memset(filestat, 0, sizeof(*filestat));
  6880. *filename = 0;
  6881. *is_found = 0;
  6882. *is_script_resource = 0;
  6883. *is_websocket_request = 0;
  6884. *is_put_or_delete_request = 0;
  6885. #endif /* !defined(NO_FILES) */
  6886. }
  6887. /* Check whether full request is buffered. Return:
  6888. * -1 if request or response is malformed
  6889. * 0 if request or response is not yet fully buffered
  6890. * >0 actual request length, including last \r\n\r\n */
  6891. static int
  6892. get_http_header_len(const char *buf, int buflen)
  6893. {
  6894. int i;
  6895. for (i = 0; i < buflen; i++) {
  6896. /* Do an unsigned comparison in some conditions below */
  6897. const unsigned char c = (unsigned char)buf[i];
  6898. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6899. && !isprint(c)) {
  6900. /* abort scan as soon as one malformed character is found */
  6901. return -1;
  6902. }
  6903. if (i < buflen - 1) {
  6904. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6905. /* Two newline, no carriage return - not standard compliant,
  6906. * but it should be accepted */
  6907. return i + 2;
  6908. }
  6909. }
  6910. if (i < buflen - 3) {
  6911. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6912. && (buf[i + 3] == '\n')) {
  6913. /* Two \r\n - standard compliant */
  6914. return i + 4;
  6915. }
  6916. }
  6917. }
  6918. return 0;
  6919. }
  6920. #if !defined(NO_CACHING)
  6921. /* Convert month to the month number. Return -1 on error, or month number */
  6922. static int
  6923. get_month_index(const char *s)
  6924. {
  6925. size_t i;
  6926. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6927. if (!strcmp(s, month_names[i])) {
  6928. return (int)i;
  6929. }
  6930. }
  6931. return -1;
  6932. }
  6933. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6934. static time_t
  6935. parse_date_string(const char *datetime)
  6936. {
  6937. char month_str[32] = {0};
  6938. int second, minute, hour, day, month, year;
  6939. time_t result = (time_t)0;
  6940. struct tm tm;
  6941. if ((sscanf(datetime,
  6942. "%d/%3s/%d %d:%d:%d",
  6943. &day,
  6944. month_str,
  6945. &year,
  6946. &hour,
  6947. &minute,
  6948. &second)
  6949. == 6)
  6950. || (sscanf(datetime,
  6951. "%d %3s %d %d:%d:%d",
  6952. &day,
  6953. month_str,
  6954. &year,
  6955. &hour,
  6956. &minute,
  6957. &second)
  6958. == 6)
  6959. || (sscanf(datetime,
  6960. "%*3s, %d %3s %d %d:%d:%d",
  6961. &day,
  6962. month_str,
  6963. &year,
  6964. &hour,
  6965. &minute,
  6966. &second)
  6967. == 6)
  6968. || (sscanf(datetime,
  6969. "%d-%3s-%d %d:%d:%d",
  6970. &day,
  6971. month_str,
  6972. &year,
  6973. &hour,
  6974. &minute,
  6975. &second)
  6976. == 6)) {
  6977. month = get_month_index(month_str);
  6978. if ((month >= 0) && (year >= 1970)) {
  6979. memset(&tm, 0, sizeof(tm));
  6980. tm.tm_year = year - 1900;
  6981. tm.tm_mon = month;
  6982. tm.tm_mday = day;
  6983. tm.tm_hour = hour;
  6984. tm.tm_min = minute;
  6985. tm.tm_sec = second;
  6986. result = timegm(&tm);
  6987. }
  6988. }
  6989. return result;
  6990. }
  6991. #endif /* !NO_CACHING */
  6992. /* Pre-process URIs according to RFC + protect against directory disclosure
  6993. * attacks by removing '..', excessive '/' and '\' characters */
  6994. static void
  6995. remove_dot_segments(char *inout)
  6996. {
  6997. /* Windows backend protection
  6998. * (https://tools.ietf.org/html/rfc3986#section-7.3): Replace backslash
  6999. * in URI by slash */
  7000. char *out_end = inout;
  7001. char *in = inout;
  7002. if (!in) {
  7003. /* Param error. */
  7004. return;
  7005. }
  7006. while (*in) {
  7007. if (*in == '\\') {
  7008. *in = '/';
  7009. }
  7010. in++;
  7011. }
  7012. /* Algorithm "remove_dot_segments" from
  7013. * https://tools.ietf.org/html/rfc3986#section-5.2.4 */
  7014. /* Step 1:
  7015. * The input buffer is initialized.
  7016. * The output buffer is initialized to the empty string.
  7017. */
  7018. in = inout;
  7019. /* Step 2:
  7020. * While the input buffer is not empty, loop as follows:
  7021. */
  7022. /* Less than out_end of the inout buffer is used as output, so keep
  7023. * condition: out_end <= in */
  7024. while (*in) {
  7025. /* Step 2a:
  7026. * If the input buffer begins with a prefix of "../" or "./",
  7027. * then remove that prefix from the input buffer;
  7028. */
  7029. if (!strncmp(in, "../", 3)) {
  7030. in += 3;
  7031. } else if (!strncmp(in, "./", 2)) {
  7032. in += 2;
  7033. }
  7034. /* otherwise */
  7035. /* Step 2b:
  7036. * if the input buffer begins with a prefix of "/./" or "/.",
  7037. * where "." is a complete path segment, then replace that
  7038. * prefix with "/" in the input buffer;
  7039. */
  7040. else if (!strncmp(in, "/./", 3)) {
  7041. in += 2;
  7042. } else if (!strcmp(in, "/.")) {
  7043. in[1] = 0;
  7044. }
  7045. /* otherwise */
  7046. /* Step 2c:
  7047. * if the input buffer begins with a prefix of "/../" or "/..",
  7048. * where ".." is a complete path segment, then replace that
  7049. * prefix with "/" in the input buffer and remove the last
  7050. * segment and its preceding "/" (if any) from the output
  7051. * buffer;
  7052. */
  7053. else if (!strncmp(in, "/../", 4)) {
  7054. in += 3;
  7055. if (inout != out_end) {
  7056. /* remove last segment */
  7057. do {
  7058. out_end--;
  7059. } while ((inout != out_end) && (*out_end != '/'));
  7060. }
  7061. } else if (!strcmp(in, "/..")) {
  7062. in[1] = 0;
  7063. if (inout != out_end) {
  7064. /* remove last segment */
  7065. do {
  7066. out_end--;
  7067. } while ((inout != out_end) && (*out_end != '/'));
  7068. }
  7069. }
  7070. /* otherwise */
  7071. /* Step 2d:
  7072. * if the input buffer consists only of "." or "..", then remove
  7073. * that from the input buffer;
  7074. */
  7075. else if (!strcmp(in, ".") || !strcmp(in, "..")) {
  7076. *in = 0;
  7077. }
  7078. /* otherwise */
  7079. /* Step 2e:
  7080. * move the first path segment in the input buffer to the end of
  7081. * the output buffer, including the initial "/" character (if
  7082. * any) and any subsequent characters up to, but not including,
  7083. * the next "/" character or the end of the input buffer.
  7084. */
  7085. else {
  7086. do {
  7087. *out_end = *in;
  7088. out_end++;
  7089. in++;
  7090. } while ((*in != 0) && (*in != '/'));
  7091. }
  7092. }
  7093. /* Step 3:
  7094. * Finally, the output buffer is returned as the result of
  7095. * remove_dot_segments.
  7096. */
  7097. /* Terminate output */
  7098. *out_end = 0;
  7099. /* For Windows, the files/folders "x" and "x." (with a dot but without
  7100. * extension) are identical. Replace all "./" by "/" and remove a "." at
  7101. * the end. Also replace all "//" by "/". Repeat until there is no "./"
  7102. * or "//" anymore.
  7103. */
  7104. out_end = in = inout;
  7105. while (*in) {
  7106. if (*in == '.') {
  7107. /* remove . at the end or preceding of / */
  7108. char *in_ahead = in;
  7109. do {
  7110. in_ahead++;
  7111. } while (*in_ahead == '.');
  7112. if (*in_ahead == '/') {
  7113. in = in_ahead;
  7114. if ((out_end != inout) && (out_end[-1] == '/')) {
  7115. /* remove generated // */
  7116. out_end--;
  7117. }
  7118. } else if (*in_ahead == 0) {
  7119. in = in_ahead;
  7120. } else {
  7121. do {
  7122. *out_end++ = '.';
  7123. in++;
  7124. } while (in != in_ahead);
  7125. }
  7126. } else if (*in == '/') {
  7127. /* replace // by / */
  7128. *out_end++ = '/';
  7129. do {
  7130. in++;
  7131. } while (*in == '/');
  7132. } else {
  7133. *out_end++ = *in;
  7134. in++;
  7135. }
  7136. }
  7137. *out_end = 0;
  7138. }
  7139. static const struct {
  7140. const char *extension;
  7141. size_t ext_len;
  7142. const char *mime_type;
  7143. } builtin_mime_types[] = {
  7144. /* IANA registered MIME types
  7145. * (http://www.iana.org/assignments/media-types)
  7146. * application types */
  7147. {".bin", 4, "application/octet-stream"},
  7148. {".deb", 4, "application/octet-stream"},
  7149. {".dmg", 4, "application/octet-stream"},
  7150. {".dll", 4, "application/octet-stream"},
  7151. {".doc", 4, "application/msword"},
  7152. {".eps", 4, "application/postscript"},
  7153. {".exe", 4, "application/octet-stream"},
  7154. {".iso", 4, "application/octet-stream"},
  7155. {".js", 3, "application/javascript"},
  7156. {".json", 5, "application/json"},
  7157. {".msi", 4, "application/octet-stream"},
  7158. {".pdf", 4, "application/pdf"},
  7159. {".ps", 3, "application/postscript"},
  7160. {".rtf", 4, "application/rtf"},
  7161. {".wasm", 5, "application/wasm"},
  7162. {".xhtml", 6, "application/xhtml+xml"},
  7163. {".xsl", 4, "application/xml"},
  7164. {".xslt", 5, "application/xml"},
  7165. /* fonts */
  7166. {".ttf", 4, "application/font-sfnt"},
  7167. {".cff", 4, "application/font-sfnt"},
  7168. {".otf", 4, "application/font-sfnt"},
  7169. {".aat", 4, "application/font-sfnt"},
  7170. {".sil", 4, "application/font-sfnt"},
  7171. {".pfr", 4, "application/font-tdpfr"},
  7172. {".woff", 5, "application/font-woff"},
  7173. {".woff2", 6, "application/font-woff2"},
  7174. /* audio */
  7175. {".mp3", 4, "audio/mpeg"},
  7176. {".oga", 4, "audio/ogg"},
  7177. {".ogg", 4, "audio/ogg"},
  7178. /* image */
  7179. {".gif", 4, "image/gif"},
  7180. {".ief", 4, "image/ief"},
  7181. {".jpeg", 5, "image/jpeg"},
  7182. {".jpg", 4, "image/jpeg"},
  7183. {".jpm", 4, "image/jpm"},
  7184. {".jpx", 4, "image/jpx"},
  7185. {".png", 4, "image/png"},
  7186. {".svg", 4, "image/svg+xml"},
  7187. {".tif", 4, "image/tiff"},
  7188. {".tiff", 5, "image/tiff"},
  7189. /* model */
  7190. {".wrl", 4, "model/vrml"},
  7191. /* text */
  7192. {".css", 4, "text/css"},
  7193. {".csv", 4, "text/csv"},
  7194. {".htm", 4, "text/html"},
  7195. {".html", 5, "text/html"},
  7196. {".sgm", 4, "text/sgml"},
  7197. {".shtm", 5, "text/html"},
  7198. {".shtml", 6, "text/html"},
  7199. {".txt", 4, "text/plain"},
  7200. {".xml", 4, "text/xml"},
  7201. /* video */
  7202. {".mov", 4, "video/quicktime"},
  7203. {".mp4", 4, "video/mp4"},
  7204. {".mpeg", 5, "video/mpeg"},
  7205. {".mpg", 4, "video/mpeg"},
  7206. {".ogv", 4, "video/ogg"},
  7207. {".qt", 3, "video/quicktime"},
  7208. /* not registered types
  7209. * (http://reference.sitepoint.com/html/mime-types-full,
  7210. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  7211. {".arj", 4, "application/x-arj-compressed"},
  7212. {".gz", 3, "application/x-gunzip"},
  7213. {".rar", 4, "application/x-arj-compressed"},
  7214. {".swf", 4, "application/x-shockwave-flash"},
  7215. {".tar", 4, "application/x-tar"},
  7216. {".tgz", 4, "application/x-tar-gz"},
  7217. {".torrent", 8, "application/x-bittorrent"},
  7218. {".ppt", 4, "application/x-mspowerpoint"},
  7219. {".xls", 4, "application/x-msexcel"},
  7220. {".zip", 4, "application/x-zip-compressed"},
  7221. {".aac",
  7222. 4,
  7223. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  7224. {".flac", 5, "audio/flac"},
  7225. {".aif", 4, "audio/x-aif"},
  7226. {".m3u", 4, "audio/x-mpegurl"},
  7227. {".mid", 4, "audio/x-midi"},
  7228. {".ra", 3, "audio/x-pn-realaudio"},
  7229. {".ram", 4, "audio/x-pn-realaudio"},
  7230. {".wav", 4, "audio/x-wav"},
  7231. {".bmp", 4, "image/bmp"},
  7232. {".ico", 4, "image/x-icon"},
  7233. {".pct", 4, "image/x-pct"},
  7234. {".pict", 5, "image/pict"},
  7235. {".rgb", 4, "image/x-rgb"},
  7236. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  7237. {".asf", 4, "video/x-ms-asf"},
  7238. {".avi", 4, "video/x-msvideo"},
  7239. {".m4v", 4, "video/x-m4v"},
  7240. {NULL, 0, NULL}};
  7241. CIVETWEB_API const char *
  7242. mg_get_builtin_mime_type(const char *path)
  7243. {
  7244. const char *ext;
  7245. size_t i, path_len;
  7246. path_len = strlen(path);
  7247. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  7248. ext = path + (path_len - builtin_mime_types[i].ext_len);
  7249. if ((path_len > builtin_mime_types[i].ext_len)
  7250. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  7251. return builtin_mime_types[i].mime_type;
  7252. }
  7253. }
  7254. return "text/plain";
  7255. }
  7256. /* Look at the "path" extension and figure what mime type it has.
  7257. * Store mime type in the vector. */
  7258. static void
  7259. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  7260. {
  7261. struct vec ext_vec, mime_vec;
  7262. const char *list, *ext;
  7263. size_t path_len;
  7264. path_len = strlen(path);
  7265. if ((conn == NULL) || (vec == NULL)) {
  7266. if (vec != NULL) {
  7267. memset(vec, '\0', sizeof(struct vec));
  7268. }
  7269. return;
  7270. }
  7271. /* Scan user-defined mime types first, in case user wants to
  7272. * override default mime types. */
  7273. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  7274. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  7275. /* ext now points to the path suffix */
  7276. ext = path + path_len - ext_vec.len;
  7277. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  7278. *vec = mime_vec;
  7279. return;
  7280. }
  7281. }
  7282. vec->ptr = mg_get_builtin_mime_type(path);
  7283. vec->len = strlen(vec->ptr);
  7284. }
  7285. /* Stringify binary data. Output buffer must be twice as big as input,
  7286. * because each byte takes 2 bytes in string representation */
  7287. static void
  7288. bin2str(char *to, const unsigned char *p, size_t len)
  7289. {
  7290. static const char *hex = "0123456789abcdef";
  7291. for (; len--; p++) {
  7292. *to++ = hex[p[0] >> 4];
  7293. *to++ = hex[p[0] & 0x0f];
  7294. }
  7295. *to = '\0';
  7296. }
  7297. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  7298. */
  7299. CIVETWEB_API char *
  7300. mg_md5(char buf[33], ...)
  7301. {
  7302. md5_byte_t hash[16];
  7303. const char *p;
  7304. va_list ap;
  7305. md5_state_t ctx;
  7306. md5_init(&ctx);
  7307. va_start(ap, buf);
  7308. while ((p = va_arg(ap, const char *)) != NULL) {
  7309. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  7310. }
  7311. va_end(ap);
  7312. md5_finish(&ctx, hash);
  7313. bin2str(buf, hash, sizeof(hash));
  7314. return buf;
  7315. }
  7316. /* Check the user's password, return 1 if OK */
  7317. static int
  7318. check_password_digest(const char *method,
  7319. const char *ha1,
  7320. const char *uri,
  7321. const char *nonce,
  7322. const char *nc,
  7323. const char *cnonce,
  7324. const char *qop,
  7325. const char *response)
  7326. {
  7327. char ha2[32 + 1], expected_response[32 + 1];
  7328. /* Some of the parameters may be NULL */
  7329. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  7330. || (qop == NULL) || (response == NULL)) {
  7331. return 0;
  7332. }
  7333. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  7334. if (strlen(response) != 32) {
  7335. return 0;
  7336. }
  7337. mg_md5(ha2, method, ":", uri, NULL);
  7338. mg_md5(expected_response,
  7339. ha1,
  7340. ":",
  7341. nonce,
  7342. ":",
  7343. nc,
  7344. ":",
  7345. cnonce,
  7346. ":",
  7347. qop,
  7348. ":",
  7349. ha2,
  7350. NULL);
  7351. return mg_strcasecmp(response, expected_response) == 0;
  7352. }
  7353. #if !defined(NO_FILESYSTEMS)
  7354. /* Use the global passwords file, if specified by auth_gpass option,
  7355. * or search for .htpasswd in the requested directory. */
  7356. static void
  7357. open_auth_file(struct mg_connection *conn,
  7358. const char *path,
  7359. struct mg_file *filep)
  7360. {
  7361. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  7362. char name[UTF8_PATH_MAX];
  7363. const char *p, *e,
  7364. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  7365. int truncated;
  7366. if (gpass != NULL) {
  7367. /* Use global passwords file */
  7368. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  7369. #if defined(DEBUG)
  7370. /* Use mg_cry_internal here, since gpass has been
  7371. * configured. */
  7372. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  7373. #endif
  7374. }
  7375. /* Important: using local struct mg_file to test path for
  7376. * is_directory flag. If filep is used, mg_stat() makes it
  7377. * appear as if auth file was opened.
  7378. * TODO(mid): Check if this is still required after rewriting
  7379. * mg_stat */
  7380. } else if (mg_stat(conn, path, &filep->stat)
  7381. && filep->stat.is_directory) {
  7382. mg_snprintf(conn,
  7383. &truncated,
  7384. name,
  7385. sizeof(name),
  7386. "%s/%s",
  7387. path,
  7388. PASSWORDS_FILE_NAME);
  7389. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7390. #if defined(DEBUG)
  7391. /* Don't use mg_cry_internal here, but only a trace, since
  7392. * this is a typical case. It will occur for every directory
  7393. * without a password file. */
  7394. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7395. #endif
  7396. }
  7397. } else {
  7398. /* Try to find .htpasswd in requested directory. */
  7399. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  7400. if (e[0] == '/') {
  7401. break;
  7402. }
  7403. }
  7404. mg_snprintf(conn,
  7405. &truncated,
  7406. name,
  7407. sizeof(name),
  7408. "%.*s/%s",
  7409. (int)(e - p),
  7410. p,
  7411. PASSWORDS_FILE_NAME);
  7412. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  7413. #if defined(DEBUG)
  7414. /* Don't use mg_cry_internal here, but only a trace, since
  7415. * this is a typical case. It will occur for every directory
  7416. * without a password file. */
  7417. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  7418. #endif
  7419. }
  7420. }
  7421. }
  7422. }
  7423. #endif /* NO_FILESYSTEMS */
  7424. /* Parsed Authorization header */
  7425. struct ah {
  7426. char *user;
  7427. int type; /* 1 = basic, 2 = digest */
  7428. char *plain_password; /* Basic only */
  7429. char *uri, *cnonce, *response, *qop, *nc, *nonce; /* Digest only */
  7430. };
  7431. /* Return 1 on success. Always initializes the ah structure. */
  7432. static int
  7433. parse_auth_header(struct mg_connection *conn,
  7434. char *buf,
  7435. size_t buf_size,
  7436. struct ah *ah)
  7437. {
  7438. char *name, *value, *s;
  7439. const char *auth_header;
  7440. uint64_t nonce;
  7441. if (!ah || !conn) {
  7442. return 0;
  7443. }
  7444. (void)memset(ah, 0, sizeof(*ah));
  7445. auth_header = mg_get_header(conn, "Authorization");
  7446. if (auth_header == NULL) {
  7447. /* No Authorization header at all */
  7448. return 0;
  7449. }
  7450. if (0 == mg_strncasecmp(auth_header, "Basic ", 6)) {
  7451. /* Basic Auth (we never asked for this, but some client may send it) */
  7452. char *split;
  7453. const char *userpw_b64 = auth_header + 6;
  7454. size_t userpw_b64_len = strlen(userpw_b64);
  7455. size_t buf_len_r = buf_size;
  7456. if (mg_base64_decode(
  7457. userpw_b64, userpw_b64_len, (unsigned char *)buf, &buf_len_r)
  7458. != -1) {
  7459. return 0; /* decode error */
  7460. }
  7461. split = strchr(buf, ':');
  7462. if (!split) {
  7463. return 0; /* Format error */
  7464. }
  7465. /* Separate string at ':' */
  7466. *split = 0;
  7467. /* User name is before ':', Password is after ':' */
  7468. ah->user = buf;
  7469. ah->type = 1;
  7470. ah->plain_password = split + 1;
  7471. return 1;
  7472. } else if (0 == mg_strncasecmp(auth_header, "Digest ", 7)) {
  7473. /* Digest Auth ... implemented below */
  7474. ah->type = 2;
  7475. } else {
  7476. /* Unknown or invalid Auth method */
  7477. return 0;
  7478. }
  7479. /* Make modifiable copy of the auth header */
  7480. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  7481. s = buf;
  7482. /* Parse authorization header */
  7483. for (;;) {
  7484. /* Gobble initial spaces */
  7485. while (isspace((unsigned char)*s)) {
  7486. s++;
  7487. }
  7488. name = skip_quoted(&s, "=", " ", 0);
  7489. /* Value is either quote-delimited, or ends at first comma or space.
  7490. */
  7491. if (s[0] == '\"') {
  7492. s++;
  7493. value = skip_quoted(&s, "\"", " ", '\\');
  7494. if (s[0] == ',') {
  7495. s++;
  7496. }
  7497. } else {
  7498. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF
  7499. * uses spaces */
  7500. }
  7501. if (*name == '\0') {
  7502. break;
  7503. }
  7504. if (!strcmp(name, "username")) {
  7505. ah->user = value;
  7506. } else if (!strcmp(name, "cnonce")) {
  7507. ah->cnonce = value;
  7508. } else if (!strcmp(name, "response")) {
  7509. ah->response = value;
  7510. } else if (!strcmp(name, "uri")) {
  7511. ah->uri = value;
  7512. } else if (!strcmp(name, "qop")) {
  7513. ah->qop = value;
  7514. } else if (!strcmp(name, "nc")) {
  7515. ah->nc = value;
  7516. } else if (!strcmp(name, "nonce")) {
  7517. ah->nonce = value;
  7518. }
  7519. }
  7520. #if !defined(NO_NONCE_CHECK)
  7521. /* Read the nonce from the response. */
  7522. if (ah->nonce == NULL) {
  7523. return 0;
  7524. }
  7525. s = NULL;
  7526. nonce = strtoull(ah->nonce, &s, 10);
  7527. if ((s == NULL) || (*s != 0)) {
  7528. return 0;
  7529. }
  7530. /* Convert the nonce from the client to a number. */
  7531. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7532. /* The converted number corresponds to the time the nounce has been
  7533. * created. This should not be earlier than the server start. */
  7534. /* Server side nonce check is valuable in all situations but one:
  7535. * if the server restarts frequently, but the client should not see
  7536. * that, so the server should accept nonces from previous starts. */
  7537. /* However, the reasonable default is to not accept a nonce from a
  7538. * previous start, so if anyone changed the access rights between
  7539. * two restarts, a new login is required. */
  7540. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7541. /* nonce is from a previous start of the server and no longer valid
  7542. * (replay attack?) */
  7543. return 0;
  7544. }
  7545. /* Check if the nonce is too high, so it has not (yet) been used by the
  7546. * server. */
  7547. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7548. + conn->dom_ctx->nonce_count)) {
  7549. return 0;
  7550. }
  7551. #else
  7552. (void)nonce;
  7553. #endif
  7554. return (ah->user != NULL);
  7555. }
  7556. static const char *
  7557. mg_fgets(char *buf, size_t size, struct mg_file *filep)
  7558. {
  7559. if (!filep) {
  7560. return NULL;
  7561. }
  7562. if (filep->access.fp != NULL) {
  7563. return fgets(buf, (int)size, filep->access.fp);
  7564. } else {
  7565. return NULL;
  7566. }
  7567. }
  7568. /* Define the initial recursion depth for procesesing htpasswd files that
  7569. * include other htpasswd
  7570. * (or even the same) files. It is not difficult to provide a file or files
  7571. * s.t. they force civetweb
  7572. * to infinitely recurse and then crash.
  7573. */
  7574. #define INITIAL_DEPTH 9
  7575. #if INITIAL_DEPTH <= 0
  7576. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7577. #endif
  7578. #if !defined(NO_FILESYSTEMS)
  7579. struct read_auth_file_struct {
  7580. struct mg_connection *conn;
  7581. struct ah ah;
  7582. const char *domain;
  7583. char buf[256 + 256 + 40];
  7584. const char *f_user;
  7585. const char *f_domain;
  7586. const char *f_ha1;
  7587. };
  7588. static int
  7589. read_auth_file(struct mg_file *filep,
  7590. struct read_auth_file_struct *workdata,
  7591. int depth)
  7592. {
  7593. int is_authorized = 0;
  7594. struct mg_file fp;
  7595. size_t l;
  7596. if (!filep || !workdata || (0 == depth)) {
  7597. return 0;
  7598. }
  7599. /* Loop over passwords file */
  7600. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep) != NULL) {
  7601. l = strlen(workdata->buf);
  7602. while (l > 0) {
  7603. if (isspace((unsigned char)workdata->buf[l - 1])
  7604. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7605. l--;
  7606. workdata->buf[l] = 0;
  7607. } else
  7608. break;
  7609. }
  7610. if (l < 1) {
  7611. continue;
  7612. }
  7613. workdata->f_user = workdata->buf;
  7614. if (workdata->f_user[0] == ':') {
  7615. /* user names may not contain a ':' and may not be empty,
  7616. * so lines starting with ':' may be used for a special purpose
  7617. */
  7618. if (workdata->f_user[1] == '#') {
  7619. /* :# is a comment */
  7620. continue;
  7621. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7622. if (mg_fopen(workdata->conn,
  7623. workdata->f_user + 9,
  7624. MG_FOPEN_MODE_READ,
  7625. &fp)) {
  7626. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7627. (void)mg_fclose(
  7628. &fp.access); /* ignore error on read only file */
  7629. /* No need to continue processing files once we have a
  7630. * match, since nothing will reset it back
  7631. * to 0.
  7632. */
  7633. if (is_authorized) {
  7634. return is_authorized;
  7635. }
  7636. } else {
  7637. mg_cry_internal(workdata->conn,
  7638. "%s: cannot open authorization file: %s",
  7639. __func__,
  7640. workdata->buf);
  7641. }
  7642. continue;
  7643. }
  7644. /* everything is invalid for the moment (might change in the
  7645. * future) */
  7646. mg_cry_internal(workdata->conn,
  7647. "%s: syntax error in authorization file: %s",
  7648. __func__,
  7649. workdata->buf);
  7650. continue;
  7651. }
  7652. workdata->f_domain = strchr(workdata->f_user, ':');
  7653. if (workdata->f_domain == NULL) {
  7654. mg_cry_internal(workdata->conn,
  7655. "%s: syntax error in authorization file: %s",
  7656. __func__,
  7657. workdata->buf);
  7658. continue;
  7659. }
  7660. *(char *)(workdata->f_domain) = 0;
  7661. (workdata->f_domain)++;
  7662. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7663. if (workdata->f_ha1 == NULL) {
  7664. mg_cry_internal(workdata->conn,
  7665. "%s: syntax error in authorization file: %s",
  7666. __func__,
  7667. workdata->buf);
  7668. continue;
  7669. }
  7670. *(char *)(workdata->f_ha1) = 0;
  7671. (workdata->f_ha1)++;
  7672. if (!strcmp(workdata->ah.user, workdata->f_user)
  7673. && !strcmp(workdata->domain, workdata->f_domain)) {
  7674. switch (workdata->ah.type) {
  7675. case 1: /* Basic */
  7676. {
  7677. char md5[33];
  7678. mg_md5(md5,
  7679. workdata->f_user,
  7680. ":",
  7681. workdata->domain,
  7682. ":",
  7683. workdata->ah.plain_password,
  7684. NULL);
  7685. return 0 == memcmp(workdata->f_ha1, md5, 33);
  7686. }
  7687. case 2: /* Digest */
  7688. return check_password_digest(
  7689. workdata->conn->request_info.request_method,
  7690. workdata->f_ha1,
  7691. workdata->ah.uri,
  7692. workdata->ah.nonce,
  7693. workdata->ah.nc,
  7694. workdata->ah.cnonce,
  7695. workdata->ah.qop,
  7696. workdata->ah.response);
  7697. default: /* None/Other/Unknown */
  7698. return 0;
  7699. }
  7700. }
  7701. }
  7702. return is_authorized;
  7703. }
  7704. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7705. static int
  7706. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7707. {
  7708. struct read_auth_file_struct workdata;
  7709. char buf[MG_BUF_LEN];
  7710. if (!conn || !conn->dom_ctx) {
  7711. return 0;
  7712. }
  7713. memset(&workdata, 0, sizeof(workdata));
  7714. workdata.conn = conn;
  7715. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7716. return 0;
  7717. }
  7718. /* CGI needs it as REMOTE_USER */
  7719. conn->request_info.remote_user =
  7720. mg_strdup_ctx(workdata.ah.user, conn->phys_ctx);
  7721. if (realm) {
  7722. workdata.domain = realm;
  7723. } else {
  7724. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7725. }
  7726. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7727. }
  7728. /* Public function to check http digest authentication header */
  7729. CIVETWEB_API int
  7730. mg_check_digest_access_authentication(struct mg_connection *conn,
  7731. const char *realm,
  7732. const char *filename)
  7733. {
  7734. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7735. int auth;
  7736. if (!conn || !filename) {
  7737. return -1;
  7738. }
  7739. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7740. return -2;
  7741. }
  7742. auth = authorize(conn, &file, realm);
  7743. mg_fclose(&file.access);
  7744. return auth;
  7745. }
  7746. #endif /* NO_FILESYSTEMS */
  7747. /* Return 1 if request is authorised, 0 otherwise. */
  7748. static int
  7749. check_authorization(struct mg_connection *conn, const char *path)
  7750. {
  7751. #if !defined(NO_FILESYSTEMS)
  7752. char fname[UTF8_PATH_MAX];
  7753. struct vec uri_vec, filename_vec;
  7754. const char *list;
  7755. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7756. int authorized = 1, truncated;
  7757. if (!conn || !conn->dom_ctx) {
  7758. return 0;
  7759. }
  7760. list = conn->dom_ctx->config[PROTECT_URI];
  7761. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7762. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7763. mg_snprintf(conn,
  7764. &truncated,
  7765. fname,
  7766. sizeof(fname),
  7767. "%.*s",
  7768. (int)filename_vec.len,
  7769. filename_vec.ptr);
  7770. if (truncated
  7771. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7772. mg_cry_internal(conn,
  7773. "%s: cannot open %s: %s",
  7774. __func__,
  7775. fname,
  7776. strerror(errno));
  7777. }
  7778. break;
  7779. }
  7780. }
  7781. if (!is_file_opened(&file.access)) {
  7782. open_auth_file(conn, path, &file);
  7783. }
  7784. if (is_file_opened(&file.access)) {
  7785. authorized = authorize(conn, &file, NULL);
  7786. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7787. }
  7788. return authorized;
  7789. #else
  7790. (void)conn;
  7791. (void)path;
  7792. return 1;
  7793. #endif /* NO_FILESYSTEMS */
  7794. }
  7795. /* Internal function. Assumes conn is valid */
  7796. static void
  7797. send_authorization_request(struct mg_connection *conn, const char *realm)
  7798. {
  7799. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7800. int trunc = 0;
  7801. char buf[128];
  7802. if (!realm) {
  7803. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7804. }
  7805. mg_lock_context(conn->phys_ctx);
  7806. nonce += conn->dom_ctx->nonce_count;
  7807. ++conn->dom_ctx->nonce_count;
  7808. mg_unlock_context(conn->phys_ctx);
  7809. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7810. conn->must_close = 1;
  7811. /* Create 401 response */
  7812. mg_response_header_start(conn, 401);
  7813. send_no_cache_header(conn);
  7814. send_additional_header(conn);
  7815. mg_response_header_add(conn, "Content-Length", "0", -1);
  7816. /* Content for "WWW-Authenticate" header */
  7817. mg_snprintf(conn,
  7818. &trunc,
  7819. buf,
  7820. sizeof(buf),
  7821. "Digest qop=\"auth\", realm=\"%s\", "
  7822. "nonce=\"%" UINT64_FMT "\"",
  7823. realm,
  7824. nonce);
  7825. if (!trunc) {
  7826. /* !trunc should always be true */
  7827. mg_response_header_add(conn, "WWW-Authenticate", buf, -1);
  7828. }
  7829. /* Send all headers */
  7830. mg_response_header_send(conn);
  7831. }
  7832. /* Interface function. Parameters are provided by the user, so do
  7833. * at least some basic checks.
  7834. */
  7835. CIVETWEB_API int
  7836. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7837. const char *realm)
  7838. {
  7839. if (conn && conn->dom_ctx) {
  7840. send_authorization_request(conn, realm);
  7841. return 0;
  7842. }
  7843. return -1;
  7844. }
  7845. #if !defined(NO_FILES)
  7846. static int
  7847. is_authorized_for_put(struct mg_connection *conn)
  7848. {
  7849. int ret = 0;
  7850. if (conn) {
  7851. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7852. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7853. if (passfile != NULL
  7854. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7855. ret = authorize(conn, &file, NULL);
  7856. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7857. }
  7858. }
  7859. DEBUG_TRACE("file write authorization: %i", ret);
  7860. return ret;
  7861. }
  7862. #endif
  7863. CIVETWEB_API int
  7864. mg_modify_passwords_file_ha1(const char *fname,
  7865. const char *domain,
  7866. const char *user,
  7867. const char *ha1)
  7868. {
  7869. int found = 0, i, result = 1;
  7870. char line[512], u[256], d[256], h[256];
  7871. struct stat st = {0};
  7872. FILE *fp = NULL;
  7873. char *temp_file = NULL;
  7874. int temp_file_offs = 0;
  7875. /* Regard empty password as no password - remove user record. */
  7876. if ((ha1 != NULL) && (ha1[0] == '\0')) {
  7877. ha1 = NULL;
  7878. }
  7879. /* Other arguments must not be empty */
  7880. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7881. return 0;
  7882. }
  7883. /* Using the given file format, user name and domain must not contain
  7884. * the ':' character */
  7885. if (strchr(user, ':') != NULL) {
  7886. return 0;
  7887. }
  7888. if (strchr(domain, ':') != NULL) {
  7889. return 0;
  7890. }
  7891. /* Do not allow control characters like newline in user name and domain.
  7892. * Do not allow excessively long names either. */
  7893. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7894. if (iscntrl((unsigned char)user[i])) {
  7895. return 0;
  7896. }
  7897. }
  7898. if (user[i]) {
  7899. return 0; /* user name too long */
  7900. }
  7901. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7902. if (iscntrl((unsigned char)domain[i])) {
  7903. return 0;
  7904. }
  7905. }
  7906. if (domain[i]) {
  7907. return 0; /* domain name too long */
  7908. }
  7909. /* The maximum length of the path to the password file is limited */
  7910. if (strlen(fname) >= UTF8_PATH_MAX) {
  7911. return 0;
  7912. }
  7913. /* Check if the file exists, and get file size */
  7914. if (0 == stat(fname, &st)) {
  7915. int temp_buf_len;
  7916. if (st.st_size > 10485760) {
  7917. /* Some funster provided a >10 MB text file */
  7918. return 0;
  7919. }
  7920. /* Add enough space for one more line */
  7921. temp_buf_len = (int)st.st_size + 1024;
  7922. /* Allocate memory (instead of using a temporary file) */
  7923. temp_file = (char *)mg_calloc((size_t)temp_buf_len, 1);
  7924. if (!temp_file) {
  7925. /* Out of memory */
  7926. return 0;
  7927. }
  7928. /* File exists. Read it into a memory buffer. */
  7929. fp = fopen(fname, "r");
  7930. if (fp == NULL) {
  7931. /* Cannot read file. No permission? */
  7932. mg_free(temp_file);
  7933. return 0;
  7934. }
  7935. /* Read content and store in memory */
  7936. while ((fgets(line, sizeof(line), fp) != NULL)
  7937. && ((temp_file_offs + 600) < temp_buf_len)) {
  7938. /* file format is "user:domain:hash\n" */
  7939. if (sscanf(line, "%255[^:]:%255[^:]:%255s", u, d, h) != 3) {
  7940. continue;
  7941. }
  7942. u[255] = 0;
  7943. d[255] = 0;
  7944. h[255] = 0;
  7945. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7946. /* Found the user: change the password hash or drop the user
  7947. */
  7948. if ((ha1 != NULL) && (!found)) {
  7949. i = sprintf(temp_file + temp_file_offs,
  7950. "%s:%s:%s\n",
  7951. user,
  7952. domain,
  7953. ha1);
  7954. if (i < 1) {
  7955. fclose(fp);
  7956. mg_free(temp_file);
  7957. return 0;
  7958. }
  7959. temp_file_offs += i;
  7960. }
  7961. found = 1;
  7962. } else {
  7963. /* Copy existing user, including password hash */
  7964. i = sprintf(temp_file + temp_file_offs, "%s:%s:%s\n", u, d, h);
  7965. if (i < 1) {
  7966. fclose(fp);
  7967. mg_free(temp_file);
  7968. return 0;
  7969. }
  7970. temp_file_offs += i;
  7971. }
  7972. }
  7973. fclose(fp);
  7974. }
  7975. /* Create new file */
  7976. fp = fopen(fname, "w");
  7977. if (!fp) {
  7978. mg_free(temp_file);
  7979. return 0;
  7980. }
  7981. #if !defined(_WIN32)
  7982. /* On Linux & co., restrict file read/write permissions to the owner */
  7983. if (fchmod(fileno(fp), S_IRUSR | S_IWUSR) != 0) {
  7984. result = 0;
  7985. }
  7986. #endif
  7987. if ((temp_file != NULL) && (temp_file_offs > 0)) {
  7988. /* Store buffered content of old file */
  7989. if (fwrite(temp_file, 1, (size_t)temp_file_offs, fp)
  7990. != (size_t)temp_file_offs) {
  7991. result = 0;
  7992. }
  7993. }
  7994. /* If new user, just add it */
  7995. if ((ha1 != NULL) && (!found)) {
  7996. if (fprintf(fp, "%s:%s:%s\n", user, domain, ha1) < 6) {
  7997. result = 0;
  7998. }
  7999. }
  8000. /* All data written */
  8001. if (fclose(fp) != 0) {
  8002. result = 0;
  8003. }
  8004. mg_free(temp_file);
  8005. return result;
  8006. }
  8007. CIVETWEB_API int
  8008. mg_modify_passwords_file(const char *fname,
  8009. const char *domain,
  8010. const char *user,
  8011. const char *pass)
  8012. {
  8013. char ha1buf[33];
  8014. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  8015. return 0;
  8016. }
  8017. if ((pass == NULL) || (pass[0] == 0)) {
  8018. return mg_modify_passwords_file_ha1(fname, domain, user, NULL);
  8019. }
  8020. mg_md5(ha1buf, user, ":", domain, ":", pass, NULL);
  8021. return mg_modify_passwords_file_ha1(fname, domain, user, ha1buf);
  8022. }
  8023. static int
  8024. is_valid_port(unsigned long port)
  8025. {
  8026. return (port <= 0xffff);
  8027. }
  8028. static int
  8029. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen, int resolve_src)
  8030. {
  8031. struct addrinfo hints, *res, *ressave;
  8032. int func_ret = 0;
  8033. int gai_ret;
  8034. memset(&hints, 0, sizeof(struct addrinfo));
  8035. hints.ai_family = af;
  8036. if (!resolve_src) {
  8037. hints.ai_flags = AI_NUMERICHOST;
  8038. }
  8039. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  8040. if (gai_ret != 0) {
  8041. /* gai_strerror could be used to convert gai_ret to a string */
  8042. /* POSIX return values: see
  8043. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  8044. */
  8045. /* Windows return values: see
  8046. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  8047. */
  8048. return 0;
  8049. }
  8050. ressave = res;
  8051. while (res) {
  8052. if ((dstlen >= (size_t)res->ai_addrlen)
  8053. && (res->ai_addr->sa_family == af)) {
  8054. memcpy(dst, res->ai_addr, res->ai_addrlen);
  8055. func_ret = 1;
  8056. }
  8057. res = res->ai_next;
  8058. }
  8059. freeaddrinfo(ressave);
  8060. return func_ret;
  8061. }
  8062. static int
  8063. connect_socket(
  8064. struct mg_context *ctx /* may be NULL */,
  8065. const char *host,
  8066. int port, /* 1..65535, or -99 for domain sockets (may be changed) */
  8067. int use_ssl, /* 0 or 1 */
  8068. struct mg_error_data *error,
  8069. SOCKET *sock /* output: socket, must not be NULL */,
  8070. union usa *sa /* output: socket address, must not be NULL */
  8071. )
  8072. {
  8073. int ip_ver = 0;
  8074. int conn_ret = -1;
  8075. int sockerr = 0;
  8076. *sock = INVALID_SOCKET;
  8077. memset(sa, 0, sizeof(*sa));
  8078. if (host == NULL) {
  8079. if (error != NULL) {
  8080. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8081. mg_snprintf(NULL,
  8082. NULL, /* No truncation check for ebuf */
  8083. error->text,
  8084. error->text_buffer_size,
  8085. "%s",
  8086. "NULL host");
  8087. }
  8088. return 0;
  8089. }
  8090. #if defined(USE_X_DOM_SOCKET)
  8091. if (port == -99) {
  8092. /* Unix domain socket */
  8093. size_t hostlen = strlen(host);
  8094. if (hostlen >= sizeof(sa->sun.sun_path)) {
  8095. if (error != NULL) {
  8096. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8097. mg_snprintf(NULL,
  8098. NULL, /* No truncation check for ebuf */
  8099. error->text,
  8100. error->text_buffer_size,
  8101. "%s",
  8102. "host length exceeds limit");
  8103. }
  8104. return 0;
  8105. }
  8106. } else
  8107. #endif
  8108. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  8109. if (error != NULL) {
  8110. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  8111. mg_snprintf(NULL,
  8112. NULL, /* No truncation check for ebuf */
  8113. error->text,
  8114. error->text_buffer_size,
  8115. "%s",
  8116. "invalid port");
  8117. }
  8118. return 0;
  8119. }
  8120. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) && !defined(NO_SSL_DL)
  8121. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  8122. if (use_ssl && (TLS_client_method == NULL)) {
  8123. if (error != NULL) {
  8124. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8125. mg_snprintf(NULL,
  8126. NULL, /* No truncation check for ebuf */
  8127. error->text,
  8128. error->text_buffer_size,
  8129. "%s",
  8130. "SSL is not initialized");
  8131. }
  8132. return 0;
  8133. }
  8134. #else
  8135. if (use_ssl && (SSLv23_client_method == NULL)) {
  8136. if (error != 0) {
  8137. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  8138. mg_snprintf(NULL,
  8139. NULL, /* No truncation check for ebuf */
  8140. error->text,
  8141. error->text_buffer_size,
  8142. "%s",
  8143. "SSL is not initialized");
  8144. }
  8145. return 0;
  8146. }
  8147. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0*/
  8148. #else
  8149. (void)use_ssl;
  8150. #endif /* NO SSL */
  8151. #if defined(USE_X_DOM_SOCKET)
  8152. if (port == -99) {
  8153. size_t hostlen = strlen(host);
  8154. /* check (hostlen < sizeof(sun.sun_path)) already passed above */
  8155. ip_ver = -99;
  8156. sa->sun.sun_family = AF_UNIX;
  8157. memset(sa->sun.sun_path, 0, sizeof(sa->sun.sun_path));
  8158. memcpy(sa->sun.sun_path, host, hostlen);
  8159. } else
  8160. #endif
  8161. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin), 1)) {
  8162. sa->sin.sin_port = htons((uint16_t)port);
  8163. ip_ver = 4;
  8164. #if defined(USE_IPV6)
  8165. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6), 1)) {
  8166. sa->sin6.sin6_port = htons((uint16_t)port);
  8167. ip_ver = 6;
  8168. } else if (host[0] == '[') {
  8169. /* While getaddrinfo on Windows will work with [::1],
  8170. * getaddrinfo on Linux only works with ::1 (without []). */
  8171. size_t l = strlen(host + 1);
  8172. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  8173. if (h) {
  8174. h[l - 1] = 0;
  8175. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6), 0)) {
  8176. sa->sin6.sin6_port = htons((uint16_t)port);
  8177. ip_ver = 6;
  8178. }
  8179. mg_free(h);
  8180. }
  8181. #endif
  8182. }
  8183. if (ip_ver == 0) {
  8184. if (error != NULL) {
  8185. error->code = MG_ERROR_DATA_CODE_HOST_NOT_FOUND;
  8186. mg_snprintf(NULL,
  8187. NULL, /* No truncation check for ebuf */
  8188. error->text,
  8189. error->text_buffer_size,
  8190. "%s",
  8191. "host not found");
  8192. }
  8193. return 0;
  8194. }
  8195. if (ip_ver == 4) {
  8196. *sock = socket(PF_INET, SOCK_STREAM, 0);
  8197. }
  8198. #if defined(USE_IPV6)
  8199. else if (ip_ver == 6) {
  8200. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  8201. }
  8202. #endif
  8203. #if defined(USE_X_DOM_SOCKET)
  8204. else if (ip_ver == -99) {
  8205. *sock = socket(AF_UNIX, SOCK_STREAM, 0);
  8206. }
  8207. #endif
  8208. if (*sock == INVALID_SOCKET) {
  8209. if (error != NULL) {
  8210. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8211. error->code_sub = (unsigned)ERRNO;
  8212. mg_snprintf(NULL,
  8213. NULL, /* No truncation check for ebuf */
  8214. error->text,
  8215. error->text_buffer_size,
  8216. "socket(): %s",
  8217. strerror(ERRNO));
  8218. }
  8219. return 0;
  8220. }
  8221. if (0 != set_non_blocking_mode(*sock)) {
  8222. if (error != NULL) {
  8223. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  8224. error->code_sub = (unsigned)ERRNO;
  8225. mg_snprintf(NULL,
  8226. NULL, /* No truncation check for ebuf */
  8227. error->text,
  8228. error->text_buffer_size,
  8229. "Cannot set socket to non-blocking: %s",
  8230. strerror(ERRNO));
  8231. }
  8232. closesocket(*sock);
  8233. *sock = INVALID_SOCKET;
  8234. return 0;
  8235. }
  8236. set_close_on_exec(*sock, NULL, ctx);
  8237. if (ip_ver == 4) {
  8238. /* connected with IPv4 */
  8239. conn_ret = connect(*sock,
  8240. (struct sockaddr *)((void *)&sa->sin),
  8241. sizeof(sa->sin));
  8242. }
  8243. #if defined(USE_IPV6)
  8244. else if (ip_ver == 6) {
  8245. /* connected with IPv6 */
  8246. conn_ret = connect(*sock,
  8247. (struct sockaddr *)((void *)&sa->sin6),
  8248. sizeof(sa->sin6));
  8249. }
  8250. #endif
  8251. #if defined(USE_X_DOM_SOCKET)
  8252. else if (ip_ver == -99) {
  8253. /* connected to domain socket */
  8254. conn_ret = connect(*sock,
  8255. (struct sockaddr *)((void *)&sa->sun),
  8256. sizeof(sa->sun));
  8257. }
  8258. #endif
  8259. if (conn_ret != 0) {
  8260. sockerr = ERRNO;
  8261. }
  8262. #if defined(_WIN32)
  8263. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  8264. #else
  8265. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  8266. #endif
  8267. /* Data for getsockopt */
  8268. void *psockerr = &sockerr;
  8269. int ret;
  8270. #if defined(_WIN32)
  8271. int len = (int)sizeof(sockerr);
  8272. #else
  8273. socklen_t len = (socklen_t)sizeof(sockerr);
  8274. #endif
  8275. /* Data for poll */
  8276. struct mg_pollfd pfd[2];
  8277. int pollres;
  8278. int ms_wait = 10000; /* 10 second timeout */
  8279. stop_flag_t nonstop = 0; /* STOP_FLAG_ASSIGN(&nonstop, 0); */
  8280. unsigned int num_sock = 1; /* use one or two sockets */
  8281. /* For a non-blocking socket, the connect sequence is:
  8282. * 1) call connect (will not block)
  8283. * 2) wait until the socket is ready for writing (select or poll)
  8284. * 3) check connection state with getsockopt
  8285. */
  8286. pfd[0].fd = *sock;
  8287. pfd[0].events = POLLOUT;
  8288. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  8289. pfd[num_sock].fd = ctx->thread_shutdown_notification_socket;
  8290. pfd[num_sock].events = POLLIN;
  8291. num_sock++;
  8292. }
  8293. pollres =
  8294. mg_poll(pfd, num_sock, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  8295. if (pollres != 1) {
  8296. /* Not connected */
  8297. if (error != NULL) {
  8298. error->code = MG_ERROR_DATA_CODE_CONNECT_TIMEOUT;
  8299. mg_snprintf(NULL,
  8300. NULL, /* No truncation check for ebuf */
  8301. error->text,
  8302. error->text_buffer_size,
  8303. "connect(%s:%d): timeout",
  8304. host,
  8305. port);
  8306. }
  8307. closesocket(*sock);
  8308. *sock = INVALID_SOCKET;
  8309. return 0;
  8310. }
  8311. #if defined(_WIN32)
  8312. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  8313. #else
  8314. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  8315. #endif
  8316. if ((ret == 0) && (sockerr == 0)) {
  8317. conn_ret = 0;
  8318. }
  8319. }
  8320. if (conn_ret != 0) {
  8321. /* Not connected */
  8322. if (error != NULL) {
  8323. error->code = MG_ERROR_DATA_CODE_CONNECT_FAILED;
  8324. error->code_sub = (unsigned)ERRNO;
  8325. mg_snprintf(NULL,
  8326. NULL, /* No truncation check for ebuf */
  8327. error->text,
  8328. error->text_buffer_size,
  8329. "connect(%s:%d): error %s",
  8330. host,
  8331. port,
  8332. strerror(sockerr));
  8333. }
  8334. closesocket(*sock);
  8335. *sock = INVALID_SOCKET;
  8336. return 0;
  8337. }
  8338. return 1;
  8339. }
  8340. CIVETWEB_API int
  8341. mg_url_encode(const char *src, char *dst, size_t dst_len)
  8342. {
  8343. static const char *dont_escape = "._-$,;~()";
  8344. static const char *hex = "0123456789abcdef";
  8345. char *pos = dst;
  8346. const char *end = dst + dst_len - 1;
  8347. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  8348. if (isalnum((unsigned char)*src)
  8349. || (strchr(dont_escape, *src) != NULL)) {
  8350. *pos = *src;
  8351. } else if (pos + 2 < end) {
  8352. pos[0] = '%';
  8353. pos[1] = hex[(unsigned char)*src >> 4];
  8354. pos[2] = hex[(unsigned char)*src & 0xf];
  8355. pos += 2;
  8356. } else {
  8357. break;
  8358. }
  8359. }
  8360. *pos = '\0';
  8361. return (*src == '\0') ? (int)(pos - dst) : -1;
  8362. }
  8363. /* Return 0 on success, non-zero if an error occurs. */
  8364. static int
  8365. print_dir_entry(struct mg_connection *conn, struct de *de)
  8366. {
  8367. size_t namesize, escsize, i;
  8368. char *href, *esc, *p;
  8369. char size[64], mod[64];
  8370. #if defined(REENTRANT_TIME)
  8371. struct tm _tm;
  8372. struct tm *tm = &_tm;
  8373. #else
  8374. struct tm *tm;
  8375. #endif
  8376. /* Estimate worst case size for encoding and escaping */
  8377. namesize = strlen(de->file_name) + 1;
  8378. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  8379. href = (char *)mg_malloc(namesize * 3 + escsize);
  8380. if (href == NULL) {
  8381. return -1;
  8382. }
  8383. mg_url_encode(de->file_name, href, namesize * 3);
  8384. esc = NULL;
  8385. if (escsize > 0) {
  8386. /* HTML escaping needed */
  8387. esc = href + namesize * 3;
  8388. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  8389. mg_strlcpy(p, de->file_name + i, 2);
  8390. if (*p == '&') {
  8391. strcpy(p, "&amp;");
  8392. } else if (*p == '<') {
  8393. strcpy(p, "&lt;");
  8394. } else if (*p == '>') {
  8395. strcpy(p, "&gt;");
  8396. }
  8397. }
  8398. }
  8399. if (de->file.is_directory) {
  8400. mg_snprintf(conn,
  8401. NULL, /* Buffer is big enough */
  8402. size,
  8403. sizeof(size),
  8404. "%s",
  8405. "[DIRECTORY]");
  8406. } else {
  8407. /* We use (signed) cast below because MSVC 6 compiler cannot
  8408. * convert unsigned __int64 to double. Sigh. */
  8409. if (de->file.size < 1024) {
  8410. mg_snprintf(conn,
  8411. NULL, /* Buffer is big enough */
  8412. size,
  8413. sizeof(size),
  8414. "%d",
  8415. (int)de->file.size);
  8416. } else if (de->file.size < 0x100000) {
  8417. mg_snprintf(conn,
  8418. NULL, /* Buffer is big enough */
  8419. size,
  8420. sizeof(size),
  8421. "%.1fk",
  8422. (double)de->file.size / 1024.0);
  8423. } else if (de->file.size < 0x40000000) {
  8424. mg_snprintf(conn,
  8425. NULL, /* Buffer is big enough */
  8426. size,
  8427. sizeof(size),
  8428. "%.1fM",
  8429. (double)de->file.size / 1048576);
  8430. } else {
  8431. mg_snprintf(conn,
  8432. NULL, /* Buffer is big enough */
  8433. size,
  8434. sizeof(size),
  8435. "%.1fG",
  8436. (double)de->file.size / 1073741824);
  8437. }
  8438. }
  8439. /* Note: mg_snprintf will not cause a buffer overflow above.
  8440. * So, string truncation checks are not required here. */
  8441. #if defined(REENTRANT_TIME)
  8442. localtime_r(&de->file.last_modified, tm);
  8443. #else
  8444. tm = localtime(&de->file.last_modified);
  8445. #endif
  8446. if (tm != NULL) {
  8447. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  8448. } else {
  8449. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  8450. }
  8451. mg_printf(conn,
  8452. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  8453. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8454. href,
  8455. de->file.is_directory ? "/" : "",
  8456. esc ? esc : de->file_name,
  8457. de->file.is_directory ? "/" : "",
  8458. mod,
  8459. size);
  8460. mg_free(href);
  8461. return 0;
  8462. }
  8463. /* This function is called from send_directory() and used for
  8464. * sorting directory entries by size, name, or modification time. */
  8465. static int
  8466. compare_dir_entries(const void *p1, const void *p2, void *arg)
  8467. {
  8468. const char *query_string = (const char *)(arg != NULL ? arg : "");
  8469. if (p1 && p2) {
  8470. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  8471. int cmp_result = 0;
  8472. if ((query_string == NULL) || (query_string[0] == '\0')) {
  8473. query_string = "n";
  8474. }
  8475. /* Sort Directories vs Files */
  8476. if (a->file.is_directory && !b->file.is_directory) {
  8477. return -1; /* Always put directories on top */
  8478. } else if (!a->file.is_directory && b->file.is_directory) {
  8479. return 1; /* Always put directories on top */
  8480. }
  8481. /* Sort by size or date */
  8482. if (*query_string == 's') {
  8483. cmp_result = (a->file.size == b->file.size)
  8484. ? 0
  8485. : ((a->file.size > b->file.size) ? 1 : -1);
  8486. } else if (*query_string == 'd') {
  8487. cmp_result =
  8488. (a->file.last_modified == b->file.last_modified)
  8489. ? 0
  8490. : ((a->file.last_modified > b->file.last_modified) ? 1
  8491. : -1);
  8492. }
  8493. /* Sort by name:
  8494. * if (*query_string == 'n') ...
  8495. * but also sort files of same size/date by name as secondary criterion.
  8496. */
  8497. if (cmp_result == 0) {
  8498. cmp_result = strcmp(a->file_name, b->file_name);
  8499. }
  8500. /* For descending order, invert result */
  8501. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  8502. }
  8503. return 0;
  8504. }
  8505. static int
  8506. must_hide_file(struct mg_connection *conn, const char *path)
  8507. {
  8508. if (conn && conn->dom_ctx) {
  8509. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  8510. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  8511. return (match_prefix_strlen(pw_pattern, path) > 0)
  8512. || (match_prefix_strlen(pattern, path) > 0);
  8513. }
  8514. return 0;
  8515. }
  8516. #if !defined(NO_FILESYSTEMS)
  8517. static int
  8518. scan_directory(struct mg_connection *conn,
  8519. const char *dir,
  8520. void *data,
  8521. int (*cb)(struct de *, void *))
  8522. {
  8523. char path[UTF8_PATH_MAX];
  8524. struct dirent *dp;
  8525. DIR *dirp;
  8526. struct de de;
  8527. int truncated;
  8528. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8529. return 0;
  8530. } else {
  8531. while ((dp = mg_readdir(dirp)) != NULL) {
  8532. /* Do not show current dir and hidden files */
  8533. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  8534. || must_hide_file(conn, dp->d_name)) {
  8535. continue;
  8536. }
  8537. mg_snprintf(
  8538. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8539. /* If we don't memset stat structure to zero, mtime will have
  8540. * garbage and strftime() will segfault later on in
  8541. * print_dir_entry(). memset is required only if mg_stat()
  8542. * fails. For more details, see
  8543. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8544. memset(&de.file, 0, sizeof(de.file));
  8545. if (truncated) {
  8546. /* If the path is not complete, skip processing. */
  8547. continue;
  8548. }
  8549. if (!mg_stat(conn, path, &de.file)) {
  8550. mg_cry_internal(conn,
  8551. "%s: mg_stat(%s) failed: %s",
  8552. __func__,
  8553. path,
  8554. strerror(ERRNO));
  8555. }
  8556. de.file_name = dp->d_name;
  8557. if (cb(&de, data)) {
  8558. /* stopped */
  8559. break;
  8560. }
  8561. }
  8562. (void)mg_closedir(dirp);
  8563. }
  8564. return 1;
  8565. }
  8566. #endif /* NO_FILESYSTEMS */
  8567. #if !defined(NO_FILES)
  8568. static int
  8569. remove_directory(struct mg_connection *conn, const char *dir)
  8570. {
  8571. char path[UTF8_PATH_MAX];
  8572. struct dirent *dp;
  8573. DIR *dirp;
  8574. struct de de;
  8575. int truncated;
  8576. int ok = 1;
  8577. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  8578. return 0;
  8579. } else {
  8580. while ((dp = mg_readdir(dirp)) != NULL) {
  8581. /* Do not show current dir (but show hidden files as they will
  8582. * also be removed) */
  8583. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  8584. continue;
  8585. }
  8586. mg_snprintf(
  8587. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  8588. /* If we don't memset stat structure to zero, mtime will have
  8589. * garbage and strftime() will segfault later on in
  8590. * print_dir_entry(). memset is required only if mg_stat()
  8591. * fails. For more details, see
  8592. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  8593. memset(&de.file, 0, sizeof(de.file));
  8594. if (truncated) {
  8595. /* Do not delete anything shorter */
  8596. ok = 0;
  8597. continue;
  8598. }
  8599. if (!mg_stat(conn, path, &de.file)) {
  8600. mg_cry_internal(conn,
  8601. "%s: mg_stat(%s) failed: %s",
  8602. __func__,
  8603. path,
  8604. strerror(ERRNO));
  8605. ok = 0;
  8606. }
  8607. if (de.file.is_directory) {
  8608. if (remove_directory(conn, path) == 0) {
  8609. ok = 0;
  8610. }
  8611. } else {
  8612. /* This will fail file is the file is in memory */
  8613. if (mg_remove(conn, path) == 0) {
  8614. ok = 0;
  8615. }
  8616. }
  8617. }
  8618. (void)mg_closedir(dirp);
  8619. IGNORE_UNUSED_RESULT(rmdir(dir));
  8620. }
  8621. return ok;
  8622. }
  8623. #endif
  8624. struct dir_scan_data {
  8625. struct de *entries;
  8626. size_t num_entries;
  8627. size_t arr_size;
  8628. };
  8629. #if !defined(NO_FILESYSTEMS)
  8630. static int
  8631. dir_scan_callback(struct de *de, void *data)
  8632. {
  8633. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8634. struct de *entries = dsd->entries;
  8635. if ((entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8636. /* Here "entries" is a temporary pointer and can be replaced,
  8637. * "dsd->entries" is the original pointer */
  8638. entries =
  8639. (struct de *)mg_realloc(entries,
  8640. dsd->arr_size * 2 * sizeof(entries[0]));
  8641. if (entries == NULL) {
  8642. /* stop scan */
  8643. return 1;
  8644. }
  8645. dsd->entries = entries;
  8646. dsd->arr_size *= 2;
  8647. }
  8648. entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8649. if (entries[dsd->num_entries].file_name == NULL) {
  8650. /* stop scan */
  8651. return 1;
  8652. }
  8653. entries[dsd->num_entries].file = de->file;
  8654. dsd->num_entries++;
  8655. return 0;
  8656. }
  8657. static void
  8658. handle_directory_request(struct mg_connection *conn, const char *dir)
  8659. {
  8660. size_t i;
  8661. int sort_direction;
  8662. struct dir_scan_data data = {NULL, 0, 128};
  8663. char date[64], *esc, *p;
  8664. const char *title;
  8665. time_t curtime = time(NULL);
  8666. if (!conn) {
  8667. return;
  8668. }
  8669. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8670. mg_send_http_error(conn,
  8671. 500,
  8672. "Error: Cannot open directory\nopendir(%s): %s",
  8673. dir,
  8674. strerror(ERRNO));
  8675. return;
  8676. }
  8677. gmt_time_string(date, sizeof(date), &curtime);
  8678. esc = NULL;
  8679. title = conn->request_info.local_uri;
  8680. if (title[strcspn(title, "&<>")]) {
  8681. /* HTML escaping needed */
  8682. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8683. if (esc) {
  8684. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8685. mg_strlcpy(p, title + i, 2);
  8686. if (*p == '&') {
  8687. strcpy(p, "&amp;");
  8688. } else if (*p == '<') {
  8689. strcpy(p, "&lt;");
  8690. } else if (*p == '>') {
  8691. strcpy(p, "&gt;");
  8692. }
  8693. }
  8694. } else {
  8695. title = "";
  8696. }
  8697. }
  8698. sort_direction = ((conn->request_info.query_string != NULL)
  8699. && (conn->request_info.query_string[0] != '\0')
  8700. && (conn->request_info.query_string[1] == 'd'))
  8701. ? 'a'
  8702. : 'd';
  8703. conn->must_close = 1;
  8704. /* Create 200 OK response */
  8705. mg_response_header_start(conn, 200);
  8706. send_static_cache_header(conn);
  8707. send_additional_header(conn);
  8708. mg_response_header_add(conn,
  8709. "Content-Type",
  8710. "text/html; charset=utf-8",
  8711. -1);
  8712. /* Send all headers */
  8713. mg_response_header_send(conn);
  8714. /* Body */
  8715. mg_printf(conn,
  8716. "<!DOCTYPE html>"
  8717. "<html><head><title>Index of %s</title>"
  8718. "<style>th {text-align: left;}</style></head>"
  8719. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8720. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8721. "<th><a href=\"?d%c\">Modified</a></th>"
  8722. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8723. "<tr><td colspan=\"3\"><hr></td></tr>",
  8724. esc ? esc : title,
  8725. esc ? esc : title,
  8726. sort_direction,
  8727. sort_direction,
  8728. sort_direction);
  8729. mg_free(esc);
  8730. /* Print first entry - link to a parent directory */
  8731. mg_printf(conn,
  8732. "<tr><td><a href=\"%s\">%s</a></td>"
  8733. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8734. "..",
  8735. "Parent directory",
  8736. "-",
  8737. "-");
  8738. /* Sort and print directory entries */
  8739. if (data.entries != NULL) {
  8740. mg_sort(data.entries,
  8741. data.num_entries,
  8742. sizeof(data.entries[0]),
  8743. compare_dir_entries,
  8744. (void *)conn->request_info.query_string);
  8745. for (i = 0; i < data.num_entries; i++) {
  8746. print_dir_entry(conn, &data.entries[i]);
  8747. mg_free(data.entries[i].file_name);
  8748. }
  8749. mg_free(data.entries);
  8750. }
  8751. mg_printf(conn, "%s", "</table></pre></body></html>");
  8752. conn->status_code = 200;
  8753. }
  8754. #endif /* NO_FILESYSTEMS */
  8755. /* Send len bytes from the opened file to the client. */
  8756. static void
  8757. send_file_data(struct mg_connection *conn,
  8758. struct mg_file *filep,
  8759. int64_t offset,
  8760. int64_t len,
  8761. int no_buffering)
  8762. {
  8763. char buf[MG_BUF_LEN];
  8764. int to_read, num_read, num_written;
  8765. int64_t size;
  8766. if (!filep || !conn) {
  8767. return;
  8768. }
  8769. /* Sanity check the offset */
  8770. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8771. : (int64_t)(filep->stat.size);
  8772. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8773. if (len > 0 && filep->access.fp != NULL) {
  8774. /* file stored on disk */
  8775. #if defined(__linux__)
  8776. /* sendfile is only available for Linux */
  8777. if ((conn->ssl == 0) && (conn->throttle == 0)
  8778. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8779. "yes"))) {
  8780. off_t sf_offs = (off_t)offset;
  8781. ssize_t sf_sent;
  8782. int sf_file = fileno(filep->access.fp);
  8783. int loop_cnt = 0;
  8784. do {
  8785. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8786. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8787. size_t sf_tosend =
  8788. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8789. sf_sent =
  8790. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8791. if (sf_sent > 0) {
  8792. len -= sf_sent;
  8793. offset += sf_sent;
  8794. } else if (loop_cnt == 0) {
  8795. /* This file can not be sent using sendfile.
  8796. * This might be the case for pseudo-files in the
  8797. * /sys/ and /proc/ file system.
  8798. * Use the regular user mode copy code instead. */
  8799. break;
  8800. } else if (sf_sent == 0) {
  8801. /* No error, but 0 bytes sent. May be EOF? */
  8802. return;
  8803. }
  8804. loop_cnt++;
  8805. } while ((len > 0) && (sf_sent >= 0));
  8806. if (sf_sent > 0) {
  8807. return; /* OK */
  8808. }
  8809. /* sf_sent<0 means error, thus fall back to the classic way */
  8810. /* This is always the case, if sf_file is not a "normal" file,
  8811. * e.g., for sending data from the output of a CGI process. */
  8812. offset = (int64_t)sf_offs;
  8813. }
  8814. #endif
  8815. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8816. mg_cry_internal(conn,
  8817. "%s: fseeko() failed: %s",
  8818. __func__,
  8819. strerror(ERRNO));
  8820. mg_send_http_error(
  8821. conn,
  8822. 500,
  8823. "%s",
  8824. "Error: Unable to access file at requested position.");
  8825. } else {
  8826. while (len > 0) {
  8827. /* Calculate how much to read from the file into the buffer. */
  8828. /* If no_buffering is set, we should not wait until the
  8829. * CGI->Server buffer is filled, but send everything
  8830. * immediately. In theory buffering could be turned off using
  8831. * setbuf(filep->access.fp, NULL);
  8832. * setvbuf(filep->access.fp, NULL, _IONBF, 0);
  8833. * but in practice this does not work. A "Linux only" solution
  8834. * may be to use select(). The only portable way is to read byte
  8835. * by byte, but this is quite inefficient from a performance
  8836. * point of view. */
  8837. to_read = no_buffering ? 1 : sizeof(buf);
  8838. if ((int64_t)to_read > len) {
  8839. to_read = (int)len;
  8840. }
  8841. /* Read from file, exit the loop on error */
  8842. if ((num_read =
  8843. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8844. <= 0) {
  8845. break;
  8846. }
  8847. /* Send read bytes to the client, exit the loop on error */
  8848. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8849. != num_read) {
  8850. break;
  8851. }
  8852. /* Both read and were successful, adjust counters */
  8853. len -= num_written;
  8854. }
  8855. }
  8856. }
  8857. }
  8858. static int
  8859. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8860. {
  8861. return sscanf(header,
  8862. "bytes=%" INT64_FMT "-%" INT64_FMT,
  8863. a,
  8864. b); // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  8865. // to an integer value, but function will not report
  8866. // conversion errors; consider using 'strtol' instead
  8867. }
  8868. static void
  8869. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8870. {
  8871. if ((filestat != NULL) && (buf != NULL)) {
  8872. mg_snprintf(NULL,
  8873. NULL, /* All calls to construct_etag use 64 byte buffer */
  8874. buf,
  8875. buf_len,
  8876. "\"%lx.%" INT64_FMT "\"",
  8877. (unsigned long)filestat->last_modified,
  8878. filestat->size);
  8879. }
  8880. }
  8881. static void
  8882. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8883. {
  8884. if (filep != NULL && filep->fp != NULL) {
  8885. #if defined(_WIN32)
  8886. (void)conn; /* Unused. */
  8887. #else
  8888. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8889. mg_cry_internal(conn,
  8890. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8891. __func__,
  8892. strerror(ERRNO));
  8893. }
  8894. #endif
  8895. }
  8896. }
  8897. #if defined(USE_ZLIB)
  8898. #include "mod_zlib.inl"
  8899. #endif
  8900. #if !defined(NO_FILESYSTEMS)
  8901. static void
  8902. handle_static_file_request(struct mg_connection *conn,
  8903. const char *path,
  8904. struct mg_file *filep,
  8905. const char *mime_type,
  8906. const char *additional_headers)
  8907. {
  8908. char lm[64], etag[64];
  8909. char range[128]; /* large enough, so there will be no overflow */
  8910. const char *range_hdr;
  8911. int64_t cl, r1, r2;
  8912. struct vec mime_vec;
  8913. int n, truncated;
  8914. char gz_path[UTF8_PATH_MAX];
  8915. const char *encoding = 0;
  8916. int is_head_request;
  8917. #if defined(USE_ZLIB)
  8918. /* Compression is allowed, unless there is a reason not to use
  8919. * compression. If the file is already compressed, too small or a
  8920. * "range" request was made, on the fly compression is not possible. */
  8921. int allow_on_the_fly_compression = 1;
  8922. #endif
  8923. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8924. return;
  8925. }
  8926. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8927. if (mime_type == NULL) {
  8928. get_mime_type(conn, path, &mime_vec);
  8929. } else {
  8930. mime_vec.ptr = mime_type;
  8931. mime_vec.len = strlen(mime_type);
  8932. }
  8933. if (filep->stat.size > INT64_MAX) {
  8934. mg_send_http_error(conn,
  8935. 500,
  8936. "Error: File size is too large to send\n%" INT64_FMT,
  8937. filep->stat.size);
  8938. return;
  8939. }
  8940. cl = (int64_t)filep->stat.size;
  8941. conn->status_code = 200;
  8942. range[0] = '\0';
  8943. #if defined(USE_ZLIB)
  8944. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8945. * it's important to rewrite the filename after resolving
  8946. * the mime type from it, to preserve the actual file's type */
  8947. if (!conn->accept_gzip) {
  8948. allow_on_the_fly_compression = 0;
  8949. }
  8950. #endif
  8951. /* Check if there is a range header */
  8952. range_hdr = mg_get_header(conn, "Range");
  8953. /* For gzipped files, add *.gz */
  8954. if (filep->stat.is_gzipped) {
  8955. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8956. if (truncated) {
  8957. mg_send_http_error(conn,
  8958. 500,
  8959. "Error: Path of zipped file too long (%s)",
  8960. path);
  8961. return;
  8962. }
  8963. path = gz_path;
  8964. encoding = "gzip";
  8965. #if defined(USE_ZLIB)
  8966. /* File is already compressed. No "on the fly" compression. */
  8967. allow_on_the_fly_compression = 0;
  8968. #endif
  8969. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8970. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8971. struct mg_file_stat file_stat;
  8972. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8973. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8974. && !file_stat.is_directory) {
  8975. file_stat.is_gzipped = 1;
  8976. filep->stat = file_stat;
  8977. cl = (int64_t)filep->stat.size;
  8978. path = gz_path;
  8979. encoding = "gzip";
  8980. #if defined(USE_ZLIB)
  8981. /* File is already compressed. No "on the fly" compression. */
  8982. allow_on_the_fly_compression = 0;
  8983. #endif
  8984. }
  8985. }
  8986. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8987. mg_send_http_error(conn,
  8988. 500,
  8989. "Error: Cannot open file\nfopen(%s): %s",
  8990. path,
  8991. strerror(ERRNO));
  8992. return;
  8993. }
  8994. fclose_on_exec(&filep->access, conn);
  8995. /* If "Range" request was made: parse header, send only selected part
  8996. * of the file. */
  8997. r1 = r2 = 0;
  8998. if ((range_hdr != NULL)
  8999. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  9000. && (r2 >= 0)) {
  9001. /* actually, range requests don't play well with a pre-gzipped
  9002. * file (since the range is specified in the uncompressed space) */
  9003. if (filep->stat.is_gzipped) {
  9004. mg_send_http_error(
  9005. conn,
  9006. 416, /* 416 = Range Not Satisfiable */
  9007. "%s",
  9008. "Error: Range requests in gzipped files are not supported");
  9009. (void)mg_fclose(
  9010. &filep->access); /* ignore error on read only file */
  9011. return;
  9012. }
  9013. conn->status_code = 206;
  9014. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  9015. mg_snprintf(conn,
  9016. NULL, /* range buffer is big enough */
  9017. range,
  9018. sizeof(range),
  9019. "bytes "
  9020. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT,
  9021. r1,
  9022. r1 + cl - 1,
  9023. filep->stat.size);
  9024. #if defined(USE_ZLIB)
  9025. /* Do not compress ranges. */
  9026. allow_on_the_fly_compression = 0;
  9027. #endif
  9028. }
  9029. /* Do not compress small files. Small files do not benefit from file
  9030. * compression, but there is still some overhead. */
  9031. #if defined(USE_ZLIB)
  9032. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  9033. /* File is below the size limit. */
  9034. allow_on_the_fly_compression = 0;
  9035. }
  9036. #endif
  9037. /* Prepare Etag, and Last-Modified headers. */
  9038. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9039. construct_etag(etag, sizeof(etag), &filep->stat);
  9040. /* Create 2xx (200, 206) response */
  9041. mg_response_header_start(conn, conn->status_code);
  9042. send_static_cache_header(conn);
  9043. send_additional_header(conn);
  9044. send_cors_header(conn);
  9045. mg_response_header_add(conn,
  9046. "Content-Type",
  9047. mime_vec.ptr,
  9048. (int)mime_vec.len);
  9049. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9050. mg_response_header_add(conn, "Etag", etag, -1);
  9051. #if defined(USE_ZLIB)
  9052. /* On the fly compression allowed */
  9053. if (allow_on_the_fly_compression) {
  9054. /* For on the fly compression, we don't know the content size in
  9055. * advance, so we have to use chunked encoding */
  9056. encoding = "gzip";
  9057. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  9058. /* HTTP/2 is always using "chunks" (frames) */
  9059. mg_response_header_add(conn, "Transfer-Encoding", "chunked", -1);
  9060. }
  9061. } else
  9062. #endif
  9063. {
  9064. /* Without on-the-fly compression, we know the content-length
  9065. * and we can use ranges (with on-the-fly compression we cannot).
  9066. * So we send these response headers only in this case. */
  9067. char len[32];
  9068. int trunc = 0;
  9069. mg_snprintf(conn, &trunc, len, sizeof(len), "%" INT64_FMT, cl);
  9070. if (!trunc) {
  9071. mg_response_header_add(conn, "Content-Length", len, -1);
  9072. }
  9073. mg_response_header_add(conn, "Accept-Ranges", "bytes", -1);
  9074. }
  9075. if (encoding) {
  9076. mg_response_header_add(conn, "Content-Encoding", encoding, -1);
  9077. }
  9078. if (range[0] != 0) {
  9079. mg_response_header_add(conn, "Content-Range", range, -1);
  9080. }
  9081. /* The code above does not add any header starting with X- to make
  9082. * sure no one of the additional_headers is included twice */
  9083. if ((additional_headers != NULL) && (*additional_headers != 0)) {
  9084. mg_response_header_add_lines(conn, additional_headers);
  9085. }
  9086. /* Send all headers */
  9087. mg_response_header_send(conn);
  9088. if (!is_head_request) {
  9089. #if defined(USE_ZLIB)
  9090. if (allow_on_the_fly_compression) {
  9091. /* Compress and send */
  9092. send_compressed_data(conn, filep);
  9093. } else
  9094. #endif
  9095. {
  9096. /* Send file directly */
  9097. send_file_data(conn, filep, r1, cl, 0); /* send static file */
  9098. }
  9099. }
  9100. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  9101. }
  9102. CIVETWEB_API int
  9103. mg_send_file_body(struct mg_connection *conn, const char *path)
  9104. {
  9105. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9106. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9107. return -1;
  9108. }
  9109. fclose_on_exec(&file.access, conn);
  9110. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  9111. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9112. return 0; /* >= 0 for OK */
  9113. }
  9114. #endif /* NO_FILESYSTEMS */
  9115. #if !defined(NO_CACHING)
  9116. /* Return True if we should reply 304 Not Modified. */
  9117. static int
  9118. is_not_modified(const struct mg_connection *conn,
  9119. const struct mg_file_stat *filestat)
  9120. {
  9121. char etag[64];
  9122. const char *ims = mg_get_header(conn, "If-Modified-Since");
  9123. const char *inm = mg_get_header(conn, "If-None-Match");
  9124. construct_etag(etag, sizeof(etag), filestat);
  9125. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  9126. || ((ims != NULL)
  9127. && (filestat->last_modified <= parse_date_string(ims)));
  9128. }
  9129. static void
  9130. handle_not_modified_static_file_request(struct mg_connection *conn,
  9131. struct mg_file *filep)
  9132. {
  9133. char lm[64], etag[64];
  9134. if ((conn == NULL) || (filep == NULL)) {
  9135. return;
  9136. }
  9137. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  9138. construct_etag(etag, sizeof(etag), &filep->stat);
  9139. /* Create 304 "not modified" response */
  9140. mg_response_header_start(conn, 304);
  9141. send_static_cache_header(conn);
  9142. send_additional_header(conn);
  9143. mg_response_header_add(conn, "Last-Modified", lm, -1);
  9144. mg_response_header_add(conn, "Etag", etag, -1);
  9145. /* Send all headers */
  9146. mg_response_header_send(conn);
  9147. }
  9148. #endif
  9149. #if !defined(NO_FILESYSTEMS)
  9150. CIVETWEB_API void
  9151. mg_send_file(struct mg_connection *conn, const char *path)
  9152. {
  9153. mg_send_mime_file2(conn, path, NULL, NULL);
  9154. }
  9155. CIVETWEB_API void
  9156. mg_send_mime_file(struct mg_connection *conn,
  9157. const char *path,
  9158. const char *mime_type)
  9159. {
  9160. mg_send_mime_file2(conn, path, mime_type, NULL);
  9161. }
  9162. CIVETWEB_API void
  9163. mg_send_mime_file2(struct mg_connection *conn,
  9164. const char *path,
  9165. const char *mime_type,
  9166. const char *additional_headers)
  9167. {
  9168. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9169. if (!conn) {
  9170. /* No conn */
  9171. return;
  9172. }
  9173. if (mg_stat(conn, path, &file.stat)) {
  9174. #if !defined(NO_CACHING)
  9175. if (is_not_modified(conn, &file.stat)) {
  9176. /* Send 304 "Not Modified" - this must not send any body data */
  9177. handle_not_modified_static_file_request(conn, &file);
  9178. } else
  9179. #endif /* NO_CACHING */
  9180. if (file.stat.is_directory) {
  9181. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9182. "yes")) {
  9183. handle_directory_request(conn, path);
  9184. } else {
  9185. mg_send_http_error(conn,
  9186. 403,
  9187. "%s",
  9188. "Error: Directory listing denied");
  9189. }
  9190. } else {
  9191. handle_static_file_request(
  9192. conn, path, &file, mime_type, additional_headers);
  9193. }
  9194. } else {
  9195. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  9196. }
  9197. }
  9198. /* For a given PUT path, create all intermediate subdirectories.
  9199. * Return 0 if the path itself is a directory.
  9200. * Return 1 if the path leads to a file.
  9201. * Return -1 for if the path is too long.
  9202. * Return -2 if path can not be created.
  9203. */
  9204. static int
  9205. put_dir(struct mg_connection *conn, const char *path)
  9206. {
  9207. char buf[UTF8_PATH_MAX];
  9208. const char *s, *p;
  9209. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9210. size_t len;
  9211. int res = 1;
  9212. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  9213. len = (size_t)(p - path);
  9214. if (len >= sizeof(buf)) {
  9215. /* path too long */
  9216. res = -1;
  9217. break;
  9218. }
  9219. memcpy(buf, path, len);
  9220. buf[len] = '\0';
  9221. /* Try to create intermediate directory */
  9222. DEBUG_TRACE("mkdir(%s)", buf);
  9223. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  9224. /* path does not exist and can not be created */
  9225. res = -2;
  9226. break;
  9227. }
  9228. /* Is path itself a directory? */
  9229. if (p[1] == '\0') {
  9230. res = 0;
  9231. }
  9232. }
  9233. return res;
  9234. }
  9235. static void
  9236. remove_bad_file(const struct mg_connection *conn, const char *path)
  9237. {
  9238. int r = mg_remove(conn, path);
  9239. if (r != 0) {
  9240. mg_cry_internal(conn,
  9241. "%s: Cannot remove invalid file %s",
  9242. __func__,
  9243. path);
  9244. }
  9245. }
  9246. CIVETWEB_API long long
  9247. mg_store_body(struct mg_connection *conn, const char *path)
  9248. {
  9249. char buf[MG_BUF_LEN];
  9250. long long len = 0;
  9251. int ret, n;
  9252. struct mg_file fi;
  9253. if (conn->consumed_content != 0) {
  9254. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  9255. return -11;
  9256. }
  9257. ret = put_dir(conn, path);
  9258. if (ret < 0) {
  9259. /* -1 for path too long,
  9260. * -2 for path can not be created. */
  9261. return ret;
  9262. }
  9263. if (ret != 1) {
  9264. /* Return 0 means, path itself is a directory. */
  9265. return 0;
  9266. }
  9267. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  9268. return -12;
  9269. }
  9270. ret = mg_read(conn, buf, sizeof(buf));
  9271. while (ret > 0) {
  9272. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  9273. if (n != ret) {
  9274. (void)mg_fclose(
  9275. &fi.access); /* File is bad and will be removed anyway. */
  9276. remove_bad_file(conn, path);
  9277. return -13;
  9278. }
  9279. len += ret;
  9280. ret = mg_read(conn, buf, sizeof(buf));
  9281. }
  9282. /* File is open for writing. If fclose fails, there was probably an
  9283. * error flushing the buffer to disk, so the file on disk might be
  9284. * broken. Delete it and return an error to the caller. */
  9285. if (mg_fclose(&fi.access) != 0) {
  9286. remove_bad_file(conn, path);
  9287. return -14;
  9288. }
  9289. return len;
  9290. }
  9291. #endif /* NO_FILESYSTEMS */
  9292. /* Parse a buffer:
  9293. * Forward the string pointer till the end of a word, then
  9294. * terminate it and forward till the begin of the next word.
  9295. */
  9296. static int
  9297. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  9298. {
  9299. /* Forward until a space is found - use isgraph here */
  9300. /* Extended ASCII characters are also treated as word characters. */
  9301. /* See http://www.cplusplus.com/reference/cctype/ */
  9302. while ((unsigned char)**ppw > 127 || isgraph((unsigned char)**ppw)) {
  9303. (*ppw)++;
  9304. }
  9305. /* Check end of word */
  9306. if (eol) {
  9307. /* must be a end of line */
  9308. if ((**ppw != '\r') && (**ppw != '\n')) {
  9309. return -1;
  9310. }
  9311. } else {
  9312. /* must be a end of a word, but not a line */
  9313. if (**ppw != ' ') {
  9314. return -1;
  9315. }
  9316. }
  9317. /* Terminate and forward to the next word */
  9318. do {
  9319. **ppw = 0;
  9320. (*ppw)++;
  9321. } while (isspace((unsigned char)**ppw));
  9322. /* Check after term */
  9323. if (!eol) {
  9324. /* if it's not the end of line, there must be a next word */
  9325. if (!isgraph((unsigned char)**ppw)) {
  9326. return -1;
  9327. }
  9328. }
  9329. /* ok */
  9330. return 1;
  9331. }
  9332. /* Parse HTTP headers from the given buffer, advance buf pointer
  9333. * to the point where parsing stopped.
  9334. * All parameters must be valid pointers (not NULL).
  9335. * Return <0 on error. */
  9336. static int
  9337. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  9338. {
  9339. int i;
  9340. int num_headers = 0;
  9341. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  9342. char *dp = *buf;
  9343. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  9344. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  9345. dp++;
  9346. }
  9347. if (dp == *buf) {
  9348. /* End of headers reached. */
  9349. break;
  9350. }
  9351. /* Drop all spaces after header name before : */
  9352. while (*dp == ' ') {
  9353. *dp = 0;
  9354. dp++;
  9355. }
  9356. if (*dp != ':') {
  9357. /* This is not a valid field. */
  9358. return -1;
  9359. }
  9360. /* End of header key (*dp == ':') */
  9361. /* Truncate here and set the key name */
  9362. *dp = 0;
  9363. hdr[i].name = *buf;
  9364. /* Skip all spaces */
  9365. do {
  9366. dp++;
  9367. } while ((*dp == ' ') || (*dp == '\t'));
  9368. /* The rest of the line is the value */
  9369. hdr[i].value = dp;
  9370. /* Find end of line */
  9371. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  9372. dp++;
  9373. };
  9374. /* eliminate \r */
  9375. if (*dp == '\r') {
  9376. *dp = 0;
  9377. dp++;
  9378. if (*dp != '\n') {
  9379. /* This is not a valid line. */
  9380. return -1;
  9381. }
  9382. }
  9383. /* here *dp is either 0 or '\n' */
  9384. /* in any case, we have a new header */
  9385. num_headers = i + 1;
  9386. if (*dp) {
  9387. *dp = 0;
  9388. dp++;
  9389. *buf = dp;
  9390. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  9391. /* This is the end of the header */
  9392. break;
  9393. }
  9394. } else {
  9395. *buf = dp;
  9396. break;
  9397. }
  9398. }
  9399. return num_headers;
  9400. }
  9401. struct mg_http_method_info {
  9402. const char *name;
  9403. int request_has_body;
  9404. int response_has_body;
  9405. int is_safe;
  9406. int is_idempotent;
  9407. int is_cacheable;
  9408. };
  9409. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  9410. static const struct mg_http_method_info http_methods[] = {
  9411. /* HTTP (RFC 2616) */
  9412. {"GET", 0, 1, 1, 1, 1},
  9413. {"POST", 1, 1, 0, 0, 0},
  9414. {"PUT", 1, 0, 0, 1, 0},
  9415. {"DELETE", 0, 0, 0, 1, 0},
  9416. {"HEAD", 0, 0, 1, 1, 1},
  9417. {"OPTIONS", 0, 0, 1, 1, 0},
  9418. {"CONNECT", 1, 1, 0, 0, 0},
  9419. /* TRACE method (RFC 2616) is not supported for security reasons */
  9420. /* PATCH method (RFC 5789) */
  9421. {"PATCH", 1, 0, 0, 0, 0},
  9422. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  9423. /* WEBDAV (RFC 2518) */
  9424. {"PROPFIND", 0, 1, 1, 1, 0},
  9425. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9426. * Some PROPFIND results MAY be cached, with care,
  9427. * as there is no cache validation mechanism for
  9428. * most properties. This method is both safe and
  9429. * idempotent (see Section 9.1 of [RFC2616]). */
  9430. {"MKCOL", 0, 0, 0, 1, 0},
  9431. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  9432. * When MKCOL is invoked without a request body,
  9433. * the newly created collection SHOULD have no
  9434. * members. A MKCOL request message may contain
  9435. * a message body. The precise behavior of a MKCOL
  9436. * request when the body is present is undefined,
  9437. * ... ==> We do not support MKCOL with body data.
  9438. * This method is idempotent, but not safe (see
  9439. * Section 9.1 of [RFC2616]). Responses to this
  9440. * method MUST NOT be cached. */
  9441. /* Methods for write access to files on WEBDAV (RFC 2518) */
  9442. {"LOCK", 1, 1, 0, 0, 0},
  9443. {"UNLOCK", 1, 0, 0, 0, 0},
  9444. {"PROPPATCH", 1, 1, 0, 0, 0},
  9445. {"COPY", 1, 0, 0, 0, 0},
  9446. {"MOVE", 1, 1, 0, 0, 0},
  9447. /* Unsupported WEBDAV Methods: */
  9448. /* + 11 methods from RFC 3253 */
  9449. /* ORDERPATCH (RFC 3648) */
  9450. /* ACL (RFC 3744) */
  9451. /* SEARCH (RFC 5323) */
  9452. /* + MicroSoft extensions
  9453. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  9454. /* REPORT method (RFC 3253) */
  9455. {"REPORT", 1, 1, 1, 1, 1},
  9456. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  9457. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  9458. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  9459. * to be useful for REST in case a "GET request with body" is
  9460. * required. */
  9461. {NULL, 0, 0, 0, 0, 0}
  9462. /* end of list */
  9463. };
  9464. /* All method names */
  9465. static char *all_methods = NULL; /* Built by mg_init_library */
  9466. static const struct mg_http_method_info *
  9467. get_http_method_info(const char *method)
  9468. {
  9469. /* Check if the method is known to the server. The list of all known
  9470. * HTTP methods can be found here at
  9471. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  9472. */
  9473. const struct mg_http_method_info *m = http_methods;
  9474. while (m->name) {
  9475. if (!strcmp(m->name, method)) {
  9476. return m;
  9477. }
  9478. m++;
  9479. }
  9480. return NULL;
  9481. }
  9482. static int
  9483. is_valid_http_method(const char *method)
  9484. {
  9485. return (get_http_method_info(method) != NULL);
  9486. }
  9487. /* Parse HTTP request, fill in mg_request_info structure.
  9488. * This function modifies the buffer by NUL-terminating
  9489. * HTTP request components, header names and header values.
  9490. * Parameters:
  9491. * buf (in/out): pointer to the HTTP header to parse and split
  9492. * len (in): length of HTTP header buffer
  9493. * re (out): parsed header as mg_request_info
  9494. * buf and ri must be valid pointers (not NULL), len>0.
  9495. * Returns <0 on error. */
  9496. static int
  9497. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  9498. {
  9499. int request_length;
  9500. int init_skip = 0;
  9501. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  9502. * remote_port */
  9503. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  9504. NULL;
  9505. ri->num_headers = 0;
  9506. /* RFC says that all initial whitespaces should be ignored */
  9507. /* This included all leading \r and \n (isspace) */
  9508. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9509. while ((len > 0) && isspace((unsigned char)*buf)) {
  9510. buf++;
  9511. len--;
  9512. init_skip++;
  9513. }
  9514. if (len == 0) {
  9515. /* Incomplete request */
  9516. return 0;
  9517. }
  9518. /* Control characters are not allowed, including zero */
  9519. if (iscntrl((unsigned char)*buf)) {
  9520. return -1;
  9521. }
  9522. /* Find end of HTTP header */
  9523. request_length = get_http_header_len(buf, len);
  9524. if (request_length <= 0) {
  9525. return request_length;
  9526. }
  9527. buf[request_length - 1] = '\0';
  9528. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9529. return -1;
  9530. }
  9531. /* The first word has to be the HTTP method */
  9532. ri->request_method = buf;
  9533. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9534. return -1;
  9535. }
  9536. /* The second word is the URI */
  9537. ri->request_uri = buf;
  9538. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9539. return -1;
  9540. }
  9541. /* Next would be the HTTP version */
  9542. ri->http_version = buf;
  9543. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  9544. return -1;
  9545. }
  9546. /* Check for a valid HTTP version key */
  9547. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  9548. /* Invalid request */
  9549. return -1;
  9550. }
  9551. ri->http_version += 5;
  9552. /* Check for a valid http method */
  9553. if (!is_valid_http_method(ri->request_method)) {
  9554. return -1;
  9555. }
  9556. /* Parse all HTTP headers */
  9557. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9558. if (ri->num_headers < 0) {
  9559. /* Error while parsing headers */
  9560. return -1;
  9561. }
  9562. return request_length + init_skip;
  9563. }
  9564. static int
  9565. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  9566. {
  9567. int response_length;
  9568. int init_skip = 0;
  9569. char *tmp, *tmp2;
  9570. long l;
  9571. /* Initialize elements. */
  9572. ri->http_version = ri->status_text = NULL;
  9573. ri->num_headers = ri->status_code = 0;
  9574. /* RFC says that all initial whitespaces should be ignored */
  9575. /* This included all leading \r and \n (isspace) */
  9576. /* See table: http://www.cplusplus.com/reference/cctype/ */
  9577. while ((len > 0) && isspace((unsigned char)*buf)) {
  9578. buf++;
  9579. len--;
  9580. init_skip++;
  9581. }
  9582. if (len == 0) {
  9583. /* Incomplete request */
  9584. return 0;
  9585. }
  9586. /* Control characters are not allowed, including zero */
  9587. if (iscntrl((unsigned char)*buf)) {
  9588. return -1;
  9589. }
  9590. /* Find end of HTTP header */
  9591. response_length = get_http_header_len(buf, len);
  9592. if (response_length <= 0) {
  9593. return response_length;
  9594. }
  9595. buf[response_length - 1] = '\0';
  9596. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9597. return -1;
  9598. }
  9599. /* The first word is the HTTP version */
  9600. /* Check for a valid HTTP version key */
  9601. if (strncmp(buf, "HTTP/", 5) != 0) {
  9602. /* Invalid request */
  9603. return -1;
  9604. }
  9605. buf += 5;
  9606. if (!isgraph((unsigned char)buf[0])) {
  9607. /* Invalid request */
  9608. return -1;
  9609. }
  9610. ri->http_version = buf;
  9611. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9612. return -1;
  9613. }
  9614. /* The second word is the status as a number */
  9615. tmp = buf;
  9616. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9617. return -1;
  9618. }
  9619. l = strtol(tmp, &tmp2, 10);
  9620. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9621. /* Everything else but a 3 digit code is invalid */
  9622. return -1;
  9623. }
  9624. ri->status_code = (int)l;
  9625. /* The rest of the line is the status text */
  9626. ri->status_text = buf;
  9627. /* Find end of status text */
  9628. /* isgraph or isspace = isprint */
  9629. while (isprint((unsigned char)*buf)) {
  9630. buf++;
  9631. }
  9632. if ((*buf != '\r') && (*buf != '\n')) {
  9633. return -1;
  9634. }
  9635. /* Terminate string and forward buf to next line */
  9636. do {
  9637. *buf = 0;
  9638. buf++;
  9639. } while (isspace((unsigned char)*buf));
  9640. /* Parse all HTTP headers */
  9641. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9642. if (ri->num_headers < 0) {
  9643. /* Error while parsing headers */
  9644. return -1;
  9645. }
  9646. return response_length + init_skip;
  9647. }
  9648. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9649. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9650. * buffer (which marks the end of HTTP request). Buffer buf may already
  9651. * have some data. The length of the data is stored in nread.
  9652. * Upon every read operation, increase nread by the number of bytes read. */
  9653. static int
  9654. read_message(FILE *fp,
  9655. struct mg_connection *conn,
  9656. char *buf,
  9657. int bufsiz,
  9658. int *nread)
  9659. {
  9660. int request_len, n = 0;
  9661. struct timespec last_action_time;
  9662. double request_timeout;
  9663. if (!conn) {
  9664. return 0;
  9665. }
  9666. memset(&last_action_time, 0, sizeof(last_action_time));
  9667. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9668. /* value of request_timeout is in seconds, config in milliseconds */
  9669. request_timeout =
  9670. strtod(conn->dom_ctx->config[REQUEST_TIMEOUT], NULL) / 1000.0;
  9671. } else {
  9672. request_timeout =
  9673. strtod(config_options[REQUEST_TIMEOUT].default_value, NULL)
  9674. / 1000.0;
  9675. }
  9676. if (conn->handled_requests > 0) {
  9677. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9678. request_timeout =
  9679. strtod(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT], NULL)
  9680. / 1000.0;
  9681. }
  9682. }
  9683. request_len = get_http_header_len(buf, *nread);
  9684. while (request_len == 0) {
  9685. /* Full request not yet received */
  9686. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  9687. /* Server is to be stopped. */
  9688. return -1;
  9689. }
  9690. if (*nread >= bufsiz) {
  9691. /* Request too long */
  9692. return -2;
  9693. }
  9694. n = pull_inner(
  9695. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9696. if (n == -2) {
  9697. /* Receive error */
  9698. return -1;
  9699. }
  9700. /* update clock after every read request */
  9701. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9702. if (n > 0) {
  9703. *nread += n;
  9704. request_len = get_http_header_len(buf, *nread);
  9705. }
  9706. if ((n <= 0) && (request_timeout >= 0)) {
  9707. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9708. > request_timeout) {
  9709. /* Timeout */
  9710. return -3;
  9711. }
  9712. }
  9713. }
  9714. return request_len;
  9715. }
  9716. #if !defined(NO_CGI) || !defined(NO_FILES)
  9717. static int
  9718. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9719. {
  9720. const char *expect;
  9721. char buf[MG_BUF_LEN];
  9722. int success = 0;
  9723. if (!conn) {
  9724. return 0;
  9725. }
  9726. expect = mg_get_header(conn, "Expect");
  9727. DEBUG_ASSERT(fp != NULL);
  9728. if (!fp) {
  9729. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9730. return 0;
  9731. }
  9732. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9733. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9734. */
  9735. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9736. } else {
  9737. if (expect != NULL) {
  9738. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9739. conn->status_code = 100;
  9740. } else {
  9741. conn->status_code = 200;
  9742. }
  9743. DEBUG_ASSERT(conn->consumed_content == 0);
  9744. if (conn->consumed_content != 0) {
  9745. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9746. return 0;
  9747. }
  9748. for (;;) {
  9749. int nread = mg_read(conn, buf, sizeof(buf));
  9750. if (nread <= 0) {
  9751. success = (nread == 0);
  9752. break;
  9753. }
  9754. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9755. break;
  9756. }
  9757. }
  9758. /* Each error code path in this function must send an error */
  9759. if (!success) {
  9760. /* NOTE: Maybe some data has already been sent. */
  9761. /* TODO (low): If some data has been sent, a correct error
  9762. * reply can no longer be sent, so just close the connection */
  9763. mg_send_http_error(conn, 500, "%s", "");
  9764. }
  9765. }
  9766. return success;
  9767. }
  9768. #endif
  9769. #if defined(USE_TIMERS)
  9770. #define TIMER_API static
  9771. #include "timer.inl"
  9772. #endif /* USE_TIMERS */
  9773. #if !defined(NO_CGI)
  9774. /* This structure helps to create an environment for the spawned CGI
  9775. * program.
  9776. * Environment is an array of "VARIABLE=VALUE\0" ASCII strings,
  9777. * last element must be NULL.
  9778. * However, on Windows there is a requirement that all these
  9779. * VARIABLE=VALUE\0
  9780. * strings must reside in a contiguous buffer. The end of the buffer is
  9781. * marked by two '\0' characters.
  9782. * We satisfy both worlds: we create an envp array (which is vars), all
  9783. * entries are actually pointers inside buf. */
  9784. struct cgi_environment {
  9785. struct mg_connection *conn;
  9786. /* Data block */
  9787. char *buf; /* Environment buffer */
  9788. size_t buflen; /* Space available in buf */
  9789. size_t bufused; /* Space taken in buf */
  9790. /* Index block */
  9791. char **var; /* char **envp */
  9792. size_t varlen; /* Number of variables available in var */
  9793. size_t varused; /* Number of variables stored in var */
  9794. };
  9795. static void addenv(struct cgi_environment *env,
  9796. PRINTF_FORMAT_STRING(const char *fmt),
  9797. ...) PRINTF_ARGS(2, 3);
  9798. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9799. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9800. static void
  9801. addenv(struct cgi_environment *env, const char *fmt, ...)
  9802. {
  9803. size_t i, n, space;
  9804. int truncated = 0;
  9805. char *added;
  9806. va_list ap;
  9807. if ((env->varlen - env->varused) < 2) {
  9808. mg_cry_internal(env->conn,
  9809. "%s: Cannot register CGI variable [%s]",
  9810. __func__,
  9811. fmt);
  9812. return;
  9813. }
  9814. /* Calculate how much space is left in the buffer */
  9815. space = (env->buflen - env->bufused);
  9816. do {
  9817. /* Space for "\0\0" is always needed. */
  9818. if (space <= 2) {
  9819. /* Allocate new buffer */
  9820. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9821. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9822. if (!added) {
  9823. /* Out of memory */
  9824. mg_cry_internal(
  9825. env->conn,
  9826. "%s: Cannot allocate memory for CGI variable [%s]",
  9827. __func__,
  9828. fmt);
  9829. return;
  9830. }
  9831. /* Retarget pointers */
  9832. env->buf = added;
  9833. env->buflen = n;
  9834. for (i = 0, n = 0; i < env->varused; i++) {
  9835. env->var[i] = added + n;
  9836. n += strlen(added + n) + 1;
  9837. }
  9838. space = (env->buflen - env->bufused);
  9839. }
  9840. /* Make a pointer to the free space int the buffer */
  9841. added = env->buf + env->bufused;
  9842. /* Copy VARIABLE=VALUE\0 string into the free space */
  9843. va_start(ap, fmt);
  9844. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9845. va_end(ap);
  9846. /* Do not add truncated strings to the environment */
  9847. if (truncated) {
  9848. /* Reallocate the buffer */
  9849. space = 0;
  9850. }
  9851. } while (truncated);
  9852. /* Calculate number of bytes added to the environment */
  9853. n = strlen(added) + 1;
  9854. env->bufused += n;
  9855. /* Append a pointer to the added string into the envp array */
  9856. env->var[env->varused] = added;
  9857. env->varused++;
  9858. }
  9859. /* Return 0 on success, non-zero if an error occurs. */
  9860. static int
  9861. prepare_cgi_environment(struct mg_connection *conn,
  9862. const char *prog,
  9863. struct cgi_environment *env,
  9864. int cgi_config_idx)
  9865. {
  9866. const char *s;
  9867. struct vec var_vec;
  9868. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9869. int i, truncated, uri_len;
  9870. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9871. return -1;
  9872. }
  9873. env->conn = conn;
  9874. env->buflen = CGI_ENVIRONMENT_SIZE;
  9875. env->bufused = 0;
  9876. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9877. if (env->buf == NULL) {
  9878. mg_cry_internal(conn,
  9879. "%s: Not enough memory for environmental buffer",
  9880. __func__);
  9881. return -1;
  9882. }
  9883. env->varlen = MAX_CGI_ENVIR_VARS;
  9884. env->varused = 0;
  9885. env->var =
  9886. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9887. if (env->var == NULL) {
  9888. mg_cry_internal(conn,
  9889. "%s: Not enough memory for environmental variables",
  9890. __func__);
  9891. mg_free(env->buf);
  9892. return -1;
  9893. }
  9894. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9895. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9896. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9897. if (conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]) {
  9898. addenv(env,
  9899. "FALLBACK_DOCUMENT_ROOT=%s",
  9900. conn->dom_ctx->config[FALLBACK_DOCUMENT_ROOT]);
  9901. }
  9902. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9903. /* Prepare the environment block */
  9904. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9905. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9906. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9907. addenv(env, "SERVER_PORT=%d", conn->request_info.server_port);
  9908. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9909. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9910. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9911. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9912. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9913. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9914. addenv(env, "LOCAL_URI_RAW=%s", conn->request_info.local_uri_raw);
  9915. /* SCRIPT_NAME */
  9916. uri_len = (int)strlen(conn->request_info.local_uri);
  9917. if (conn->path_info == NULL) {
  9918. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9919. /* URI: /path_to_script/script.cgi */
  9920. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9921. } else {
  9922. /* URI: /path_to_script/ ... using index.cgi */
  9923. const char *index_file = strrchr(prog, '/');
  9924. if (index_file) {
  9925. addenv(env,
  9926. "SCRIPT_NAME=%s%s",
  9927. conn->request_info.local_uri,
  9928. index_file + 1);
  9929. }
  9930. }
  9931. } else {
  9932. /* URI: /path_to_script/script.cgi/path_info */
  9933. addenv(env,
  9934. "SCRIPT_NAME=%.*s",
  9935. uri_len - (int)strlen(conn->path_info),
  9936. conn->request_info.local_uri);
  9937. }
  9938. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9939. if (conn->path_info == NULL) {
  9940. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9941. } else {
  9942. addenv(env,
  9943. "PATH_TRANSLATED=%s%s",
  9944. conn->dom_ctx->config[DOCUMENT_ROOT],
  9945. conn->path_info);
  9946. }
  9947. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9948. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9949. addenv(env, "CONTENT_TYPE=%s", s);
  9950. }
  9951. if (conn->request_info.query_string != NULL) {
  9952. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9953. }
  9954. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9955. addenv(env, "CONTENT_LENGTH=%s", s);
  9956. }
  9957. if ((s = getenv("PATH")) != NULL) {
  9958. addenv(env, "PATH=%s", s);
  9959. }
  9960. if (conn->path_info != NULL) {
  9961. addenv(env, "PATH_INFO=%s", conn->path_info);
  9962. }
  9963. if (conn->status_code > 0) {
  9964. /* CGI error handler should show the status code */
  9965. addenv(env, "STATUS=%d", conn->status_code);
  9966. }
  9967. #if defined(_WIN32)
  9968. if ((s = getenv("COMSPEC")) != NULL) {
  9969. addenv(env, "COMSPEC=%s", s);
  9970. }
  9971. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9972. addenv(env, "SYSTEMROOT=%s", s);
  9973. }
  9974. if ((s = getenv("SystemDrive")) != NULL) {
  9975. addenv(env, "SystemDrive=%s", s);
  9976. }
  9977. if ((s = getenv("ProgramFiles")) != NULL) {
  9978. addenv(env, "ProgramFiles=%s", s);
  9979. }
  9980. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9981. addenv(env, "ProgramFiles(x86)=%s", s);
  9982. }
  9983. #else
  9984. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9985. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9986. }
  9987. #endif /* _WIN32 */
  9988. if ((s = getenv("PERLLIB")) != NULL) {
  9989. addenv(env, "PERLLIB=%s", s);
  9990. }
  9991. if (conn->request_info.remote_user != NULL) {
  9992. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9993. addenv(env, "%s", "AUTH_TYPE=Digest");
  9994. }
  9995. /* Add all headers as HTTP_* variables */
  9996. for (i = 0; i < conn->request_info.num_headers; i++) {
  9997. (void)mg_snprintf(conn,
  9998. &truncated,
  9999. http_var_name,
  10000. sizeof(http_var_name),
  10001. "HTTP_%s",
  10002. conn->request_info.http_headers[i].name);
  10003. if (truncated) {
  10004. mg_cry_internal(conn,
  10005. "%s: HTTP header variable too long [%s]",
  10006. __func__,
  10007. conn->request_info.http_headers[i].name);
  10008. continue;
  10009. }
  10010. /* Convert variable name into uppercase, and change - to _ */
  10011. for (p = http_var_name; *p != '\0'; p++) {
  10012. if (*p == '-') {
  10013. *p = '_';
  10014. }
  10015. *p = (char)toupper((unsigned char)*p);
  10016. }
  10017. addenv(env,
  10018. "%s=%s",
  10019. http_var_name,
  10020. conn->request_info.http_headers[i].value);
  10021. }
  10022. /* Add user-specified variables */
  10023. s = conn->dom_ctx->config[CGI_ENVIRONMENT + cgi_config_idx];
  10024. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  10025. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  10026. }
  10027. env->var[env->varused] = NULL;
  10028. env->buf[env->bufused] = '\0';
  10029. return 0;
  10030. }
  10031. /* Data for CGI process control: PID and number of references */
  10032. struct process_control_data {
  10033. pid_t pid;
  10034. ptrdiff_t references;
  10035. };
  10036. static int
  10037. abort_cgi_process(void *data)
  10038. {
  10039. /* Waitpid checks for child status and won't work for a pid that does
  10040. * not identify a child of the current process. Thus, if the pid is
  10041. * reused, we will not affect a different process. */
  10042. struct process_control_data *proc = (struct process_control_data *)data;
  10043. int status = 0;
  10044. ptrdiff_t refs;
  10045. pid_t ret_pid;
  10046. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  10047. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  10048. /* Stop child process */
  10049. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  10050. kill(proc->pid, SIGABRT);
  10051. /* Wait until process is terminated (don't leave zombies) */
  10052. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  10053. ;
  10054. } else {
  10055. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  10056. }
  10057. /* Dec reference counter */
  10058. refs = mg_atomic_dec(&proc->references);
  10059. if (refs == 0) {
  10060. /* no more references - free data */
  10061. mg_free(data);
  10062. }
  10063. return 0;
  10064. }
  10065. /* Local (static) function assumes all arguments are valid. */
  10066. static void
  10067. handle_cgi_request(struct mg_connection *conn,
  10068. const char *prog,
  10069. int cgi_config_idx)
  10070. {
  10071. char *buf;
  10072. size_t buflen;
  10073. int headers_len, data_len, i, truncated;
  10074. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  10075. const char *status, *status_text;
  10076. char *pbuf, dir[UTF8_PATH_MAX], *p;
  10077. struct mg_request_info ri;
  10078. struct cgi_environment blk;
  10079. FILE *in = NULL, *out = NULL, *err = NULL;
  10080. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  10081. pid_t pid = (pid_t)-1;
  10082. struct process_control_data *proc = NULL;
  10083. char *cfg_buffering = conn->dom_ctx->config[CGI_BUFFERING + cgi_config_idx];
  10084. int no_buffering = 0;
  10085. #if defined(USE_TIMERS)
  10086. double cgi_timeout;
  10087. if (conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) {
  10088. /* Get timeout in seconds */
  10089. cgi_timeout =
  10090. atof(conn->dom_ctx->config[CGI_TIMEOUT + cgi_config_idx]) * 0.001;
  10091. } else {
  10092. cgi_timeout =
  10093. atof(config_options[REQUEST_TIMEOUT].default_value) * 0.001;
  10094. }
  10095. #endif
  10096. if (cfg_buffering != NULL) {
  10097. if (!mg_strcasecmp(cfg_buffering, "no")) {
  10098. no_buffering = 1;
  10099. }
  10100. }
  10101. buf = NULL;
  10102. buflen = conn->phys_ctx->max_request_size;
  10103. i = prepare_cgi_environment(conn, prog, &blk, cgi_config_idx);
  10104. if (i != 0) {
  10105. blk.buf = NULL;
  10106. blk.var = NULL;
  10107. goto done;
  10108. }
  10109. /* CGI must be executed in its own directory. 'dir' must point to the
  10110. * directory containing executable program, 'p' must point to the
  10111. * executable program name relative to 'dir'. */
  10112. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  10113. if (truncated) {
  10114. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  10115. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  10116. goto done;
  10117. }
  10118. if ((p = strrchr(dir, '/')) != NULL) {
  10119. *p++ = '\0';
  10120. } else {
  10121. dir[0] = '.';
  10122. dir[1] = '\0';
  10123. p = (char *)prog;
  10124. }
  10125. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  10126. status = strerror(ERRNO);
  10127. mg_cry_internal(
  10128. conn,
  10129. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  10130. prog,
  10131. status);
  10132. mg_send_http_error(conn,
  10133. 500,
  10134. "Error: Cannot create CGI pipe: %s",
  10135. status);
  10136. goto done;
  10137. }
  10138. proc = (struct process_control_data *)
  10139. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  10140. if (proc == NULL) {
  10141. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  10142. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  10143. goto done;
  10144. }
  10145. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  10146. pid = spawn_process(
  10147. conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir, cgi_config_idx);
  10148. if (pid == (pid_t)-1) {
  10149. status = strerror(ERRNO);
  10150. mg_cry_internal(
  10151. conn,
  10152. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  10153. prog,
  10154. status);
  10155. mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process");
  10156. mg_free(proc);
  10157. proc = NULL;
  10158. goto done;
  10159. }
  10160. /* Store data in shared process_control_data */
  10161. proc->pid = pid;
  10162. proc->references = 1;
  10163. #if defined(USE_TIMERS)
  10164. if (cgi_timeout > 0.0) {
  10165. proc->references = 2;
  10166. // Start a timer for CGI
  10167. timer_add(conn->phys_ctx,
  10168. cgi_timeout /* in seconds */,
  10169. 0.0,
  10170. 1,
  10171. abort_cgi_process,
  10172. (void *)proc,
  10173. NULL);
  10174. }
  10175. #endif
  10176. /* Parent closes only one side of the pipes.
  10177. * If we don't mark them as closed, close() attempt before
  10178. * return from this function throws an exception on Windows.
  10179. * Windows does not like when closed descriptor is closed again. */
  10180. (void)close(fdin[0]);
  10181. (void)close(fdout[1]);
  10182. (void)close(fderr[1]);
  10183. fdin[0] = fdout[1] = fderr[1] = -1;
  10184. if (((in = fdopen(fdin[1], "wb")) == NULL)
  10185. || ((out = fdopen(fdout[0], "rb")) == NULL)
  10186. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  10187. status = strerror(ERRNO);
  10188. mg_cry_internal(conn,
  10189. "Error: CGI program \"%s\": Can not open fd: %s",
  10190. prog,
  10191. status);
  10192. mg_send_http_error(conn,
  10193. 500,
  10194. "Error: CGI can not open fd\nfdopen: %s",
  10195. status);
  10196. goto done;
  10197. }
  10198. setbuf(in, NULL);
  10199. setbuf(out, NULL);
  10200. setbuf(err, NULL);
  10201. fout.access.fp = out;
  10202. if ((conn->content_len != 0) || (conn->is_chunked)) {
  10203. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  10204. conn->content_len);
  10205. /* This is a POST/PUT request, or another request with body data. */
  10206. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  10207. /* Error sending the body data */
  10208. mg_cry_internal(
  10209. conn,
  10210. "Error: CGI program \"%s\": Forward body data failed",
  10211. prog);
  10212. goto done;
  10213. }
  10214. }
  10215. /* Close so child gets an EOF. */
  10216. fclose(in);
  10217. in = NULL;
  10218. fdin[1] = -1;
  10219. /* Now read CGI reply into a buffer. We need to set correct
  10220. * status code, thus we need to see all HTTP headers first.
  10221. * Do not send anything back to client, until we buffer in all
  10222. * HTTP headers. */
  10223. data_len = 0;
  10224. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  10225. if (buf == NULL) {
  10226. mg_send_http_error(conn,
  10227. 500,
  10228. "Error: Not enough memory for CGI buffer (%u bytes)",
  10229. (unsigned int)buflen);
  10230. mg_cry_internal(
  10231. conn,
  10232. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  10233. "bytes)",
  10234. prog,
  10235. (unsigned int)buflen);
  10236. goto done;
  10237. }
  10238. DEBUG_TRACE("CGI: %s", "wait for response");
  10239. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  10240. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  10241. if (headers_len <= 0) {
  10242. /* Could not parse the CGI response. Check if some error message on
  10243. * stderr. */
  10244. i = pull_all(err, conn, buf, (int)buflen);
  10245. if (i > 0) {
  10246. /* CGI program explicitly sent an error */
  10247. /* Write the error message to the internal log */
  10248. mg_cry_internal(conn,
  10249. "Error: CGI program \"%s\" sent error "
  10250. "message: [%.*s]",
  10251. prog,
  10252. i,
  10253. buf);
  10254. /* Don't send the error message back to the client */
  10255. mg_send_http_error(conn,
  10256. 500,
  10257. "Error: CGI program \"%s\" failed.",
  10258. prog);
  10259. } else {
  10260. /* CGI program did not explicitly send an error, but a broken
  10261. * respon header */
  10262. mg_cry_internal(conn,
  10263. "Error: CGI program sent malformed or too big "
  10264. "(>%u bytes) HTTP headers: [%.*s]",
  10265. (unsigned)buflen,
  10266. data_len,
  10267. buf);
  10268. mg_send_http_error(conn,
  10269. 500,
  10270. "Error: CGI program sent malformed or too big "
  10271. "(>%u bytes) HTTP headers: [%.*s]",
  10272. (unsigned)buflen,
  10273. data_len,
  10274. buf);
  10275. }
  10276. /* in both cases, abort processing CGI */
  10277. goto done;
  10278. }
  10279. pbuf = buf;
  10280. buf[headers_len - 1] = '\0';
  10281. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  10282. /* Make up and send the status line */
  10283. status_text = "OK";
  10284. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  10285. != NULL) {
  10286. conn->status_code = atoi(status);
  10287. status_text = status;
  10288. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  10289. status_text++;
  10290. }
  10291. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  10292. != NULL) {
  10293. conn->status_code = 307;
  10294. } else {
  10295. conn->status_code = 200;
  10296. }
  10297. if (!should_keep_alive(conn)) {
  10298. conn->must_close = 1;
  10299. }
  10300. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  10301. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  10302. /* Send headers */
  10303. for (i = 0; i < ri.num_headers; i++) {
  10304. DEBUG_TRACE("CGI header: %s: %s",
  10305. ri.http_headers[i].name,
  10306. ri.http_headers[i].value);
  10307. mg_printf(conn,
  10308. "%s: %s\r\n",
  10309. ri.http_headers[i].name,
  10310. ri.http_headers[i].value);
  10311. }
  10312. mg_write(conn, "\r\n", 2);
  10313. /* Send chunk of data that may have been read after the headers */
  10314. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  10315. /* Read the rest of CGI output and send to the client */
  10316. DEBUG_TRACE("CGI: %s", "forward all data");
  10317. send_file_data(conn, &fout, 0, INT64_MAX, no_buffering); /* send CGI data */
  10318. DEBUG_TRACE("CGI: %s", "all data sent");
  10319. done:
  10320. mg_free(blk.var);
  10321. mg_free(blk.buf);
  10322. if (pid != (pid_t)-1) {
  10323. abort_cgi_process((void *)proc);
  10324. }
  10325. if (fdin[0] != -1) {
  10326. close(fdin[0]);
  10327. }
  10328. if (fdout[1] != -1) {
  10329. close(fdout[1]);
  10330. }
  10331. if (fderr[1] != -1) {
  10332. close(fderr[1]);
  10333. }
  10334. if (in != NULL) {
  10335. fclose(in);
  10336. } else if (fdin[1] != -1) {
  10337. close(fdin[1]);
  10338. }
  10339. if (out != NULL) {
  10340. fclose(out);
  10341. } else if (fdout[0] != -1) {
  10342. close(fdout[0]);
  10343. }
  10344. if (err != NULL) {
  10345. fclose(err);
  10346. } else if (fderr[0] != -1) {
  10347. close(fderr[0]);
  10348. }
  10349. mg_free(buf);
  10350. }
  10351. #endif /* !NO_CGI */
  10352. #if !defined(NO_FILES)
  10353. static void
  10354. dav_mkcol(struct mg_connection *conn, const char *path)
  10355. {
  10356. int rc, body_len;
  10357. struct de de;
  10358. if (conn == NULL) {
  10359. return;
  10360. }
  10361. /* TODO (mid): Check the mg_send_http_error situations in this function
  10362. */
  10363. memset(&de.file, 0, sizeof(de.file));
  10364. if (!mg_stat(conn, path, &de.file)) {
  10365. mg_cry_internal(conn,
  10366. "%s: mg_stat(%s) failed: %s",
  10367. __func__,
  10368. path,
  10369. strerror(ERRNO));
  10370. }
  10371. if (de.file.last_modified) {
  10372. /* TODO (mid): This check does not seem to make any sense ! */
  10373. /* TODO (mid): Add a webdav unit test first, before changing
  10374. * anything here. */
  10375. mg_send_http_error(
  10376. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10377. return;
  10378. }
  10379. body_len = conn->data_len - conn->request_len;
  10380. if (body_len > 0) {
  10381. mg_send_http_error(
  10382. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  10383. return;
  10384. }
  10385. rc = mg_mkdir(conn, path, 0755);
  10386. DEBUG_TRACE("mkdir %s: %i", path, rc);
  10387. if (rc == 0) {
  10388. /* Create 201 "Created" response */
  10389. mg_response_header_start(conn, 201);
  10390. send_static_cache_header(conn);
  10391. send_additional_header(conn);
  10392. mg_response_header_add(conn, "Content-Length", "0", -1);
  10393. /* Send all headers - there is no body */
  10394. mg_response_header_send(conn);
  10395. } else {
  10396. int http_status = 500;
  10397. switch (errno) {
  10398. case EEXIST:
  10399. http_status = 405;
  10400. break;
  10401. case EACCES:
  10402. http_status = 403;
  10403. break;
  10404. case ENOENT:
  10405. http_status = 409;
  10406. break;
  10407. }
  10408. mg_send_http_error(conn,
  10409. http_status,
  10410. "Error processing %s: %s",
  10411. path,
  10412. strerror(ERRNO));
  10413. }
  10414. }
  10415. /* Forward decrlaration */
  10416. static int get_uri_type(const char *uri);
  10417. static const char *
  10418. get_rel_url_at_current_server(const char *uri,
  10419. const struct mg_connection *conn);
  10420. static void
  10421. dav_move_file(struct mg_connection *conn, const char *path, int do_copy)
  10422. {
  10423. const char *overwrite_hdr;
  10424. const char *destination_hdr;
  10425. const char *root;
  10426. int rc, dest_uri_type;
  10427. int http_status = 400;
  10428. int do_overwrite = 0;
  10429. int destination_ok = 0;
  10430. char dest_path[UTF8_PATH_MAX];
  10431. struct mg_file_stat ignored;
  10432. if (conn == NULL) {
  10433. return;
  10434. }
  10435. root = conn->dom_ctx->config[DOCUMENT_ROOT];
  10436. overwrite_hdr = mg_get_header(conn, "Overwrite");
  10437. destination_hdr = mg_get_header(conn, "Destination");
  10438. if ((overwrite_hdr != NULL) && (toupper(overwrite_hdr[0]) == 'T')) {
  10439. do_overwrite = 1;
  10440. }
  10441. if ((destination_hdr == NULL) || (destination_hdr[0] == 0)) {
  10442. mg_send_http_error(conn, 400, "%s", "Missing destination");
  10443. return;
  10444. }
  10445. if (root != NULL) {
  10446. char *local_dest = NULL;
  10447. dest_uri_type = get_uri_type(destination_hdr);
  10448. if (dest_uri_type == 2) {
  10449. local_dest = mg_strdup_ctx(destination_hdr, conn->phys_ctx);
  10450. } else if ((dest_uri_type == 3) || (dest_uri_type == 4)) {
  10451. const char *h =
  10452. get_rel_url_at_current_server(destination_hdr, conn);
  10453. if (h) {
  10454. size_t len = strlen(h);
  10455. local_dest = mg_malloc_ctx(len + 1, conn->phys_ctx);
  10456. mg_url_decode(h, (int)len, local_dest, (int)len + 1, 0);
  10457. }
  10458. }
  10459. if (local_dest != NULL) {
  10460. remove_dot_segments(local_dest);
  10461. if (local_dest[0] == '/') {
  10462. int trunc_check = 0;
  10463. mg_snprintf(conn,
  10464. &trunc_check,
  10465. dest_path,
  10466. sizeof(dest_path),
  10467. "%s/%s",
  10468. root,
  10469. local_dest);
  10470. if (trunc_check == 0) {
  10471. destination_ok = 1;
  10472. }
  10473. }
  10474. mg_free(local_dest);
  10475. }
  10476. }
  10477. if (!destination_ok) {
  10478. mg_send_http_error(conn, 502, "%s", "Illegal destination");
  10479. return;
  10480. }
  10481. /* Check now if this file exists */
  10482. if (mg_stat(conn, dest_path, &ignored)) {
  10483. /* File exists */
  10484. if (do_overwrite) {
  10485. /* Overwrite allowed: delete the file first */
  10486. if (0 != remove(dest_path)) {
  10487. /* No overwrite: return error */
  10488. mg_send_http_error(conn,
  10489. 403,
  10490. "Cannot overwrite file: %s",
  10491. dest_path);
  10492. return;
  10493. }
  10494. } else {
  10495. /* No overwrite: return error */
  10496. mg_send_http_error(conn,
  10497. 412,
  10498. "Destination already exists: %s",
  10499. dest_path);
  10500. return;
  10501. }
  10502. }
  10503. /* Copy / Move / Rename operation. */
  10504. DEBUG_TRACE("%s %s to %s", (do_copy ? "copy" : "move"), path, dest_path);
  10505. #if defined(_WIN32)
  10506. {
  10507. /* For Windows, we need to convert from UTF-8 to UTF-16 first. */
  10508. wchar_t wSource[UTF16_PATH_MAX];
  10509. wchar_t wDest[UTF16_PATH_MAX];
  10510. BOOL ok;
  10511. path_to_unicode(conn, path, wSource, ARRAY_SIZE(wSource));
  10512. path_to_unicode(conn, dest_path, wDest, ARRAY_SIZE(wDest));
  10513. if (do_copy) {
  10514. ok = CopyFileW(wSource, wDest, do_overwrite ? FALSE : TRUE);
  10515. } else {
  10516. ok = MoveFileExW(wSource,
  10517. wDest,
  10518. do_overwrite ? MOVEFILE_REPLACE_EXISTING : 0);
  10519. }
  10520. if (ok) {
  10521. rc = 0;
  10522. } else {
  10523. DWORD lastErr = GetLastError();
  10524. if (lastErr == ERROR_ALREADY_EXISTS) {
  10525. mg_send_http_error(conn,
  10526. 412,
  10527. "Destination already exists: %s",
  10528. dest_path);
  10529. return;
  10530. }
  10531. rc = -1;
  10532. http_status = 400;
  10533. }
  10534. }
  10535. #else
  10536. {
  10537. /* Linux uses already UTF-8, we don't need to convert file names. */
  10538. if (do_copy) {
  10539. /* TODO: COPY for Linux. */
  10540. mg_send_http_error(conn, 403, "%s", "COPY forbidden");
  10541. return;
  10542. }
  10543. rc = rename(path, dest_path);
  10544. if (rc) {
  10545. switch (errno) {
  10546. case EEXIST:
  10547. http_status = 412;
  10548. break;
  10549. case EACCES:
  10550. http_status = 403;
  10551. break;
  10552. case ENOENT:
  10553. http_status = 409;
  10554. break;
  10555. }
  10556. }
  10557. }
  10558. #endif
  10559. if (rc == 0) {
  10560. /* Create 204 "No Content" response */
  10561. mg_response_header_start(conn, 204);
  10562. mg_response_header_add(conn, "Content-Length", "0", -1);
  10563. /* Send all headers - there is no body */
  10564. mg_response_header_send(conn);
  10565. } else {
  10566. mg_send_http_error(conn, http_status, "Operation failed");
  10567. }
  10568. }
  10569. static void
  10570. put_file(struct mg_connection *conn, const char *path)
  10571. {
  10572. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10573. const char *range;
  10574. int64_t r1, r2;
  10575. int rc;
  10576. if (conn == NULL) {
  10577. return;
  10578. }
  10579. DEBUG_TRACE("store %s", path);
  10580. if (mg_stat(conn, path, &file.stat)) {
  10581. /* File already exists */
  10582. conn->status_code = 200;
  10583. if (file.stat.is_directory) {
  10584. /* This is an already existing directory,
  10585. * so there is nothing to do for the server. */
  10586. rc = 0;
  10587. } else {
  10588. /* File exists and is not a directory. */
  10589. /* Can it be replaced? */
  10590. /* Check if the server may write this file */
  10591. if (access(path, W_OK) == 0) {
  10592. /* Access granted */
  10593. rc = 1;
  10594. } else {
  10595. mg_send_http_error(
  10596. conn,
  10597. 403,
  10598. "Error: Put not possible\nReplacing %s is not allowed",
  10599. path);
  10600. return;
  10601. }
  10602. }
  10603. } else {
  10604. /* File should be created */
  10605. conn->status_code = 201;
  10606. rc = put_dir(conn, path);
  10607. }
  10608. if (rc == 0) {
  10609. /* put_dir returns 0 if path is a directory */
  10610. /* Create response */
  10611. mg_response_header_start(conn, conn->status_code);
  10612. send_no_cache_header(conn);
  10613. send_additional_header(conn);
  10614. mg_response_header_add(conn, "Content-Length", "0", -1);
  10615. /* Send all headers - there is no body */
  10616. mg_response_header_send(conn);
  10617. /* Request to create a directory has been fulfilled successfully.
  10618. * No need to put a file. */
  10619. return;
  10620. }
  10621. if (rc == -1) {
  10622. /* put_dir returns -1 if the path is too long */
  10623. mg_send_http_error(conn,
  10624. 414,
  10625. "Error: Path too long\nput_dir(%s): %s",
  10626. path,
  10627. strerror(ERRNO));
  10628. return;
  10629. }
  10630. if (rc == -2) {
  10631. /* put_dir returns -2 if the directory can not be created */
  10632. mg_send_http_error(conn,
  10633. 500,
  10634. "Error: Can not create directory\nput_dir(%s): %s",
  10635. path,
  10636. strerror(ERRNO));
  10637. return;
  10638. }
  10639. /* A file should be created or overwritten. */
  10640. /* Currently CivetWeb does not need read+write access. */
  10641. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  10642. || file.access.fp == NULL) {
  10643. (void)mg_fclose(&file.access);
  10644. mg_send_http_error(conn,
  10645. 500,
  10646. "Error: Can not create file\nfopen(%s): %s",
  10647. path,
  10648. strerror(ERRNO));
  10649. return;
  10650. }
  10651. fclose_on_exec(&file.access, conn);
  10652. range = mg_get_header(conn, "Content-Range");
  10653. r1 = r2 = 0;
  10654. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  10655. conn->status_code = 206; /* Partial content */
  10656. if (0 != fseeko(file.access.fp, r1, SEEK_SET)) {
  10657. mg_send_http_error(conn,
  10658. 500,
  10659. "Error: Internal error processing file %s",
  10660. path);
  10661. return;
  10662. }
  10663. }
  10664. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  10665. /* forward_body_data failed.
  10666. * The error code has already been sent to the client,
  10667. * and conn->status_code is already set. */
  10668. (void)mg_fclose(&file.access);
  10669. return;
  10670. }
  10671. if (mg_fclose(&file.access) != 0) {
  10672. /* fclose failed. This might have different reasons, but a likely
  10673. * one is "no space on disk", http 507. */
  10674. conn->status_code = 507;
  10675. }
  10676. /* Create response (status_code has been set before) */
  10677. mg_response_header_start(conn, conn->status_code);
  10678. send_no_cache_header(conn);
  10679. send_additional_header(conn);
  10680. mg_response_header_add(conn, "Content-Length", "0", -1);
  10681. /* Send all headers - there is no body */
  10682. mg_response_header_send(conn);
  10683. }
  10684. static void
  10685. delete_file(struct mg_connection *conn, const char *path)
  10686. {
  10687. struct de de;
  10688. memset(&de.file, 0, sizeof(de.file));
  10689. if (!mg_stat(conn, path, &de.file)) {
  10690. /* mg_stat returns 0 if the file does not exist */
  10691. mg_send_http_error(conn,
  10692. 404,
  10693. "Error: Cannot delete file\nFile %s not found",
  10694. path);
  10695. return;
  10696. }
  10697. DEBUG_TRACE("delete %s", path);
  10698. if (de.file.is_directory) {
  10699. if (remove_directory(conn, path)) {
  10700. /* Delete is successful: Return 204 without content. */
  10701. mg_send_http_error(conn, 204, "%s", "");
  10702. } else {
  10703. /* Delete is not successful: Return 500 (Server error). */
  10704. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  10705. }
  10706. return;
  10707. }
  10708. /* This is an existing file (not a directory).
  10709. * Check if write permission is granted. */
  10710. if (access(path, W_OK) != 0) {
  10711. /* File is read only */
  10712. mg_send_http_error(
  10713. conn,
  10714. 403,
  10715. "Error: Delete not possible\nDeleting %s is not allowed",
  10716. path);
  10717. return;
  10718. }
  10719. /* Try to delete it. */
  10720. if (mg_remove(conn, path) == 0) {
  10721. /* Delete was successful: Return 204 without content. */
  10722. mg_response_header_start(conn, 204);
  10723. send_no_cache_header(conn);
  10724. send_additional_header(conn);
  10725. mg_response_header_add(conn, "Content-Length", "0", -1);
  10726. mg_response_header_send(conn);
  10727. } else {
  10728. /* Delete not successful (file locked). */
  10729. mg_send_http_error(conn,
  10730. 423,
  10731. "Error: Cannot delete file\nremove(%s): %s",
  10732. path,
  10733. strerror(ERRNO));
  10734. }
  10735. }
  10736. #endif /* !NO_FILES */
  10737. #if !defined(NO_FILESYSTEMS)
  10738. static void
  10739. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10740. static void
  10741. do_ssi_include(struct mg_connection *conn,
  10742. const char *ssi,
  10743. char *tag,
  10744. int include_level)
  10745. {
  10746. char file_name[MG_BUF_LEN], path[512], *p;
  10747. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10748. size_t len;
  10749. int truncated = 0;
  10750. if (conn == NULL) {
  10751. return;
  10752. }
  10753. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10754. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10755. * always < MG_BUF_LEN. */
  10756. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10757. /* File name is relative to the webserver root */
  10758. file_name[511] = 0;
  10759. (void)mg_snprintf(conn,
  10760. &truncated,
  10761. path,
  10762. sizeof(path),
  10763. "%s/%s",
  10764. conn->dom_ctx->config[DOCUMENT_ROOT],
  10765. file_name);
  10766. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10767. /* File name is relative to the webserver working directory
  10768. * or it is absolute system path */
  10769. file_name[511] = 0;
  10770. (void)
  10771. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10772. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10773. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10774. /* File name is relative to the current document */
  10775. file_name[511] = 0;
  10776. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10777. if (!truncated) {
  10778. if ((p = strrchr(path, '/')) != NULL) {
  10779. p[1] = '\0';
  10780. }
  10781. len = strlen(path);
  10782. (void)mg_snprintf(conn,
  10783. &truncated,
  10784. path + len,
  10785. sizeof(path) - len,
  10786. "%s",
  10787. file_name);
  10788. }
  10789. } else {
  10790. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10791. return;
  10792. }
  10793. if (truncated) {
  10794. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10795. return;
  10796. }
  10797. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10798. mg_cry_internal(conn,
  10799. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10800. tag,
  10801. path,
  10802. strerror(ERRNO));
  10803. } else {
  10804. fclose_on_exec(&file.access, conn);
  10805. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path)
  10806. > 0) {
  10807. send_ssi_file(conn, path, &file, include_level + 1);
  10808. } else {
  10809. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10810. }
  10811. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10812. }
  10813. }
  10814. #if !defined(NO_POPEN)
  10815. static void
  10816. do_ssi_exec(struct mg_connection *conn, char *tag)
  10817. {
  10818. char cmd[1024] = "";
  10819. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10820. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10821. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10822. } else {
  10823. cmd[1023] = 0;
  10824. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10825. mg_cry_internal(conn,
  10826. "Cannot SSI #exec: [%s]: %s",
  10827. cmd,
  10828. strerror(ERRNO));
  10829. } else {
  10830. send_file_data(conn, &file, 0, INT64_MAX, 0); /* send static file */
  10831. pclose(file.access.fp);
  10832. }
  10833. }
  10834. }
  10835. #endif /* !NO_POPEN */
  10836. static int
  10837. mg_fgetc(struct mg_file *filep)
  10838. {
  10839. if (filep == NULL) {
  10840. return EOF;
  10841. }
  10842. if (filep->access.fp != NULL) {
  10843. return fgetc(filep->access.fp);
  10844. } else {
  10845. return EOF;
  10846. }
  10847. }
  10848. static void
  10849. send_ssi_file(struct mg_connection *conn,
  10850. const char *path,
  10851. struct mg_file *filep,
  10852. int include_level)
  10853. {
  10854. char buf[MG_BUF_LEN];
  10855. int ch, len, in_tag, in_ssi_tag;
  10856. if (include_level > 10) {
  10857. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10858. return;
  10859. }
  10860. in_tag = in_ssi_tag = len = 0;
  10861. /* Read file, byte by byte, and look for SSI include tags */
  10862. while ((ch = mg_fgetc(filep)) != EOF) {
  10863. if (in_tag) {
  10864. /* We are in a tag, either SSI tag or html tag */
  10865. if (ch == '>') {
  10866. /* Tag is closing */
  10867. buf[len++] = '>';
  10868. if (in_ssi_tag) {
  10869. /* Handle SSI tag */
  10870. buf[len] = 0;
  10871. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10872. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10873. #if !defined(NO_POPEN)
  10874. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10875. do_ssi_exec(conn, buf + 9);
  10876. #endif /* !NO_POPEN */
  10877. } else {
  10878. mg_cry_internal(conn,
  10879. "%s: unknown SSI "
  10880. "command: \"%s\"",
  10881. path,
  10882. buf);
  10883. }
  10884. len = 0;
  10885. in_ssi_tag = in_tag = 0;
  10886. } else {
  10887. /* Not an SSI tag */
  10888. /* Flush buffer */
  10889. (void)mg_write(conn, buf, (size_t)len);
  10890. len = 0;
  10891. in_tag = 0;
  10892. }
  10893. } else {
  10894. /* Tag is still open */
  10895. buf[len++] = (char)(ch & 0xff);
  10896. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10897. /* All SSI tags start with <!--# */
  10898. in_ssi_tag = 1;
  10899. }
  10900. if ((len + 2) > (int)sizeof(buf)) {
  10901. /* Tag to long for buffer */
  10902. mg_cry_internal(conn, "%s: tag is too large", path);
  10903. return;
  10904. }
  10905. }
  10906. } else {
  10907. /* We are not in a tag yet. */
  10908. if (ch == '<') {
  10909. /* Tag is opening */
  10910. in_tag = 1;
  10911. if (len > 0) {
  10912. /* Flush current buffer.
  10913. * Buffer is filled with "len" bytes. */
  10914. (void)mg_write(conn, buf, (size_t)len);
  10915. }
  10916. /* Store the < */
  10917. len = 1;
  10918. buf[0] = '<';
  10919. } else {
  10920. /* No Tag */
  10921. /* Add data to buffer */
  10922. buf[len++] = (char)(ch & 0xff);
  10923. /* Flush if buffer is full */
  10924. if (len == (int)sizeof(buf)) {
  10925. mg_write(conn, buf, (size_t)len);
  10926. len = 0;
  10927. }
  10928. }
  10929. }
  10930. }
  10931. /* Send the rest of buffered data */
  10932. if (len > 0) {
  10933. mg_write(conn, buf, (size_t)len);
  10934. }
  10935. }
  10936. static void
  10937. handle_ssi_file_request(struct mg_connection *conn,
  10938. const char *path,
  10939. struct mg_file *filep)
  10940. {
  10941. char date[64];
  10942. time_t curtime = time(NULL);
  10943. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10944. return;
  10945. }
  10946. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10947. /* File exists (precondition for calling this function),
  10948. * but can not be opened by the server. */
  10949. mg_send_http_error(conn,
  10950. 500,
  10951. "Error: Cannot read file\nfopen(%s): %s",
  10952. path,
  10953. strerror(ERRNO));
  10954. } else {
  10955. /* Set "must_close" for HTTP/1.x, since we do not know the
  10956. * content length */
  10957. conn->must_close = 1;
  10958. gmt_time_string(date, sizeof(date), &curtime);
  10959. fclose_on_exec(&filep->access, conn);
  10960. /* 200 OK response */
  10961. mg_response_header_start(conn, 200);
  10962. send_no_cache_header(conn);
  10963. send_additional_header(conn);
  10964. send_cors_header(conn);
  10965. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10966. mg_response_header_send(conn);
  10967. /* Header sent, now send body */
  10968. send_ssi_file(conn, path, filep, 0);
  10969. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10970. }
  10971. }
  10972. #endif /* NO_FILESYSTEMS */
  10973. #if !defined(NO_FILES)
  10974. static void
  10975. send_options(struct mg_connection *conn)
  10976. {
  10977. if (!conn || !all_methods) {
  10978. return;
  10979. }
  10980. /* We do not set a "Cache-Control" header here, but leave the default.
  10981. * Since browsers do not send an OPTIONS request, we can not test the
  10982. * effect anyway. */
  10983. mg_response_header_start(conn, 200);
  10984. mg_response_header_add(conn, "Content-Type", "text/html", -1);
  10985. if (conn->protocol_type == PROTOCOL_TYPE_HTTP1) {
  10986. /* Use the same as before */
  10987. mg_response_header_add(conn, "Allow", all_methods, -1);
  10988. mg_response_header_add(conn, "DAV", "1", -1);
  10989. } else {
  10990. /* TODO: Check this later for HTTP/2 */
  10991. mg_response_header_add(conn, "Allow", "GET, POST", -1);
  10992. }
  10993. send_additional_header(conn);
  10994. mg_response_header_send(conn);
  10995. }
  10996. /* Writes PROPFIND properties for a collection element */
  10997. static int
  10998. print_props(struct mg_connection *conn,
  10999. const char *uri,
  11000. const char *name,
  11001. struct mg_file_stat *filep)
  11002. {
  11003. size_t i;
  11004. char mtime[64];
  11005. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11006. char *link_concat;
  11007. size_t link_concat_len;
  11008. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  11009. return 0;
  11010. }
  11011. link_concat_len = strlen(uri) + strlen(name) + 1;
  11012. link_concat = mg_malloc_ctx(link_concat_len, conn->phys_ctx);
  11013. if (!link_concat) {
  11014. return 0;
  11015. }
  11016. strcpy(link_concat, uri);
  11017. strcat(link_concat, name);
  11018. /* Get full link used in request */
  11019. mg_construct_local_link(
  11020. conn, link_buf, sizeof(link_buf), NULL, 0, link_concat);
  11021. /*
  11022. OutputDebugStringA("print_props:\n uri: ");
  11023. OutputDebugStringA(uri);
  11024. OutputDebugStringA("\n name: ");
  11025. OutputDebugStringA(name);
  11026. OutputDebugStringA("\n link: ");
  11027. OutputDebugStringA(link_buf);
  11028. OutputDebugStringA("\n");
  11029. */
  11030. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  11031. mg_printf(conn,
  11032. "<d:response>"
  11033. "<d:href>%s</d:href>"
  11034. "<d:propstat>"
  11035. "<d:prop>"
  11036. "<d:resourcetype>%s</d:resourcetype>"
  11037. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  11038. "<d:getlastmodified>%s</d:getlastmodified>"
  11039. "<d:lockdiscovery>",
  11040. link_buf,
  11041. filep->is_directory ? "<d:collection/>" : "",
  11042. filep->size,
  11043. mtime);
  11044. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11045. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11046. if (!strcmp(dav_lock[i].path, link_buf)) {
  11047. mg_printf(conn,
  11048. "<d:activelock>"
  11049. "<d:locktype><d:write/></d:locktype>"
  11050. "<d:lockscope><d:exclusive/></d:lockscope>"
  11051. "<d:depth>0</d:depth>"
  11052. "<d:owner>%s</d:owner>"
  11053. "<d:timeout>Second-%u</d:timeout>"
  11054. "<d:locktoken>"
  11055. "<d:href>%s</d:href>"
  11056. "</d:locktoken>"
  11057. "</d:activelock>\n",
  11058. dav_lock[i].user,
  11059. (unsigned)LOCK_DURATION_S,
  11060. dav_lock[i].token);
  11061. }
  11062. }
  11063. mg_printf(conn,
  11064. "</d:lockdiscovery>"
  11065. "</d:prop>"
  11066. "<d:status>HTTP/1.1 200 OK</d:status>"
  11067. "</d:propstat>"
  11068. "</d:response>\n");
  11069. mg_free(link_concat);
  11070. return 1;
  11071. }
  11072. static int
  11073. print_dav_dir_entry(struct de *de, void *data)
  11074. {
  11075. struct mg_connection *conn = (struct mg_connection *)data;
  11076. if (!de || !conn
  11077. || !print_props(
  11078. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  11079. /* stop scan */
  11080. return 1;
  11081. }
  11082. return 0;
  11083. }
  11084. static void
  11085. handle_propfind(struct mg_connection *conn,
  11086. const char *path,
  11087. struct mg_file_stat *filep)
  11088. {
  11089. const char *depth = mg_get_header(conn, "Depth");
  11090. if (!conn || !path || !filep || !conn->dom_ctx) {
  11091. return;
  11092. }
  11093. /* return 207 "Multi-Status" */
  11094. conn->must_close = 1;
  11095. mg_response_header_start(conn, 207);
  11096. send_static_cache_header(conn);
  11097. send_additional_header(conn);
  11098. mg_response_header_add(conn,
  11099. "Content-Type",
  11100. "application/xml; charset=utf-8",
  11101. -1);
  11102. mg_response_header_send(conn);
  11103. /* Content */
  11104. mg_printf(conn,
  11105. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11106. "<d:multistatus xmlns:d='DAV:'>\n");
  11107. /* Print properties for the requested resource itself */
  11108. print_props(conn, conn->request_info.local_uri, "", filep);
  11109. /* If it is a directory, print directory entries too if Depth is not 0
  11110. */
  11111. if (filep->is_directory
  11112. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11113. "yes")
  11114. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  11115. scan_directory(conn, path, conn, &print_dav_dir_entry);
  11116. }
  11117. mg_printf(conn, "%s\n", "</d:multistatus>");
  11118. }
  11119. static void
  11120. dav_lock_file(struct mg_connection *conn, const char *path)
  11121. {
  11122. /* internal function - therefore conn is assumed to be valid */
  11123. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11124. uint64_t new_locktime;
  11125. int lock_index = -1;
  11126. int i;
  11127. uint64_t LOCK_DURATION_NS =
  11128. (uint64_t)(LOCK_DURATION_S) * (uint64_t)1000000000;
  11129. struct twebdav_lock *dav_lock = NULL;
  11130. if (!path || !conn || !conn->dom_ctx || !conn->request_info.remote_user
  11131. || !conn->phys_ctx) {
  11132. return;
  11133. }
  11134. dav_lock = conn->phys_ctx->webdav_lock;
  11135. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11136. /* const char *refresh = mg_get_header(conn, "If"); */
  11137. /* Link refresh should have an "If" header:
  11138. * http://www.webdav.org/specs/rfc2518.html#n-example---refreshing-a-write-lock
  11139. * But it seems Windows Explorer does not send them.
  11140. */
  11141. mg_lock_context(conn->phys_ctx);
  11142. new_locktime = mg_get_current_time_ns();
  11143. /* Find a slot for a lock */
  11144. while (lock_index < 0) {
  11145. /* find existing lock */
  11146. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11147. if (!strcmp(dav_lock[i].path, link_buf)) {
  11148. if (!strcmp(conn->request_info.remote_user, dav_lock[i].user)) {
  11149. /* locked by the same user */
  11150. dav_lock[i].locktime = new_locktime;
  11151. lock_index = i;
  11152. break;
  11153. } else {
  11154. /* already locked by someone else */
  11155. if (new_locktime
  11156. > (dav_lock[i].locktime + LOCK_DURATION_NS)) {
  11157. /* Lock expired */
  11158. dav_lock[i].path[0] = 0;
  11159. } else {
  11160. /* Lock still valid */
  11161. mg_unlock_context(conn->phys_ctx);
  11162. mg_send_http_error(conn, 423, "%s", "Already locked");
  11163. return;
  11164. }
  11165. }
  11166. }
  11167. }
  11168. /* create new lock token */
  11169. for (i = 0; i < NUM_WEBDAV_LOCKS; i++) {
  11170. if (dav_lock[i].path[0] == 0) {
  11171. char s[32];
  11172. dav_lock[i].locktime = mg_get_current_time_ns();
  11173. sprintf(s, "%" UINT64_FMT, (uint64_t)dav_lock[i].locktime);
  11174. mg_md5(dav_lock[i].token,
  11175. link_buf,
  11176. "\x01",
  11177. s,
  11178. "\x01",
  11179. conn->request_info.remote_user,
  11180. NULL);
  11181. mg_strlcpy(dav_lock[i].path,
  11182. link_buf,
  11183. sizeof(dav_lock[i].path));
  11184. mg_strlcpy(dav_lock[i].user,
  11185. conn->request_info.remote_user,
  11186. sizeof(dav_lock[i].user));
  11187. lock_index = i;
  11188. break;
  11189. }
  11190. }
  11191. if (lock_index < 0) {
  11192. /* too many locks. Find oldest lock */
  11193. uint64_t oldest_locktime = dav_lock[0].locktime;
  11194. lock_index = 0;
  11195. for (i = 1; i < NUM_WEBDAV_LOCKS; i++) {
  11196. if (dav_lock[i].locktime < oldest_locktime) {
  11197. oldest_locktime = dav_lock[i].locktime;
  11198. lock_index = i;
  11199. }
  11200. }
  11201. /* invalidate oldest lock */
  11202. dav_lock[lock_index].path[0] = 0;
  11203. }
  11204. }
  11205. mg_unlock_context(conn->phys_ctx);
  11206. /* return 200 "OK" */
  11207. conn->must_close = 1;
  11208. mg_response_header_start(conn, 200);
  11209. send_static_cache_header(conn);
  11210. send_additional_header(conn);
  11211. mg_response_header_add(conn,
  11212. "Content-Type",
  11213. "application/xml; charset=utf-8",
  11214. -1);
  11215. mg_response_header_add(conn, "Lock-Token", dav_lock[lock_index].token, -1);
  11216. mg_response_header_send(conn);
  11217. /* Content */
  11218. mg_printf(conn,
  11219. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11220. "<d:prop xmlns:d=\"DAV:\">\n"
  11221. " <d:lockdiscovery>\n"
  11222. " <d:activelock>\n"
  11223. " <d:lockscope><d:exclusive/></d:lockscope>\n"
  11224. " <d:locktype><d:write/></d:locktype>\n"
  11225. " <d:owner>\n"
  11226. " <d:href>%s</d:href>\n"
  11227. " </d:owner>\n"
  11228. " <d:timeout>Second-%u</d:timeout>\n"
  11229. " <d:locktoken><d:href>%s</d:href></d:locktoken>\n"
  11230. " <d:lockroot>\n"
  11231. " <d:href>%s</d:href>\n"
  11232. " </d:lockroot>\n"
  11233. " </d:activelock>\n"
  11234. " </d:lockdiscovery>\n"
  11235. " </d:prop>\n",
  11236. dav_lock[lock_index].user,
  11237. (LOCK_DURATION_S),
  11238. dav_lock[lock_index].token,
  11239. dav_lock[lock_index].path);
  11240. }
  11241. static void
  11242. dav_unlock_file(struct mg_connection *conn, const char *path)
  11243. {
  11244. /* internal function - therefore conn is assumed to be valid */
  11245. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11246. struct twebdav_lock *dav_lock = conn->phys_ctx->webdav_lock;
  11247. int lock_index;
  11248. if (!path || !conn->dom_ctx || !conn->request_info.remote_user) {
  11249. return;
  11250. }
  11251. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11252. mg_lock_context(conn->phys_ctx);
  11253. /* find existing lock */
  11254. for (lock_index = 0; lock_index < NUM_WEBDAV_LOCKS; lock_index++) {
  11255. if (!strcmp(dav_lock[lock_index].path, link_buf)) {
  11256. /* Success: return 204 "No Content" */
  11257. mg_unlock_context(conn->phys_ctx);
  11258. conn->must_close = 1;
  11259. mg_response_header_start(conn, 204);
  11260. mg_response_header_send(conn);
  11261. return;
  11262. }
  11263. }
  11264. mg_unlock_context(conn->phys_ctx);
  11265. /* Error: Cannot unlock a resource that is not locked */
  11266. mg_send_http_error(conn, 423, "%s", "Lock not found");
  11267. }
  11268. static void
  11269. dav_proppatch(struct mg_connection *conn, const char *path)
  11270. {
  11271. char link_buf[UTF8_PATH_MAX * 2]; /* Path + server root */
  11272. if (!conn || !path || !conn->dom_ctx) {
  11273. return;
  11274. }
  11275. /* return 207 "Multi-Status" */
  11276. conn->must_close = 1;
  11277. mg_response_header_start(conn, 207);
  11278. send_static_cache_header(conn);
  11279. send_additional_header(conn);
  11280. mg_response_header_add(conn,
  11281. "Content-Type",
  11282. "application/xml; charset=utf-8",
  11283. -1);
  11284. mg_response_header_send(conn);
  11285. mg_get_request_link(conn, link_buf, sizeof(link_buf));
  11286. /* Content */
  11287. mg_printf(conn,
  11288. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  11289. "<d:multistatus xmlns:d='DAV:'>\n"
  11290. "<d:response>\n<d:href>%s</d:href>\n",
  11291. link_buf);
  11292. mg_printf(conn,
  11293. "<d:propstat><d:status>HTTP/1.1 403 "
  11294. "Forbidden</d:status></d:propstat>\n");
  11295. mg_printf(conn, "%s\n", "</d:response></d:multistatus>");
  11296. }
  11297. #endif
  11298. CIVETWEB_API void
  11299. mg_lock_connection(struct mg_connection *conn)
  11300. {
  11301. if (conn) {
  11302. (void)pthread_mutex_lock(&conn->mutex);
  11303. }
  11304. }
  11305. CIVETWEB_API void
  11306. mg_unlock_connection(struct mg_connection *conn)
  11307. {
  11308. if (conn) {
  11309. (void)pthread_mutex_unlock(&conn->mutex);
  11310. }
  11311. }
  11312. CIVETWEB_API void
  11313. mg_lock_context(struct mg_context *ctx)
  11314. {
  11315. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11316. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  11317. }
  11318. }
  11319. CIVETWEB_API void
  11320. mg_unlock_context(struct mg_context *ctx)
  11321. {
  11322. if (ctx && (ctx->context_type == CONTEXT_SERVER)) {
  11323. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  11324. }
  11325. }
  11326. #if defined(USE_LUA)
  11327. #include "mod_lua.inl"
  11328. #endif /* USE_LUA */
  11329. #if defined(USE_DUKTAPE)
  11330. #include "mod_duktape.inl"
  11331. #endif /* USE_DUKTAPE */
  11332. #if defined(USE_WEBSOCKET)
  11333. #if !defined(NO_SSL_DL)
  11334. #if !defined(OPENSSL_API_3_0)
  11335. #define SHA_API static
  11336. #include "sha1.inl"
  11337. #endif
  11338. #endif
  11339. static int
  11340. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  11341. {
  11342. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  11343. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  11344. size_t dst_len = sizeof(b64_sha);
  11345. #if !defined(OPENSSL_API_3_0)
  11346. SHA_CTX sha_ctx;
  11347. #endif
  11348. int truncated;
  11349. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  11350. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  11351. if (truncated) {
  11352. conn->must_close = 1;
  11353. return 0;
  11354. }
  11355. DEBUG_TRACE("%s", "Send websocket handshake");
  11356. #if defined(OPENSSL_API_3_0)
  11357. EVP_Digest((unsigned char *)buf,
  11358. (uint32_t)strlen(buf),
  11359. (unsigned char *)sha,
  11360. NULL,
  11361. EVP_get_digestbyname("sha1"),
  11362. NULL);
  11363. #else
  11364. SHA1_Init(&sha_ctx);
  11365. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  11366. SHA1_Final((unsigned char *)sha, &sha_ctx);
  11367. #endif
  11368. mg_base64_encode((unsigned char *)sha, sizeof(sha), b64_sha, &dst_len);
  11369. mg_printf(conn,
  11370. "HTTP/1.1 101 Switching Protocols\r\n"
  11371. "Upgrade: websocket\r\n"
  11372. "Connection: Upgrade\r\n"
  11373. "Sec-WebSocket-Accept: %s\r\n",
  11374. b64_sha);
  11375. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11376. // Send negotiated compression extension parameters
  11377. websocket_deflate_response(conn);
  11378. #endif
  11379. if (conn->request_info.acceptedWebSocketSubprotocol) {
  11380. mg_printf(conn,
  11381. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  11382. conn->request_info.acceptedWebSocketSubprotocol);
  11383. } else {
  11384. mg_printf(conn, "%s", "\r\n");
  11385. }
  11386. return 1;
  11387. }
  11388. #if !defined(MG_MAX_UNANSWERED_PING)
  11389. /* Configuration of the maximum number of websocket PINGs that might
  11390. * stay unanswered before the connection is considered broken.
  11391. * Note: The name of this define may still change (until it is
  11392. * defined as a compile parameter in a documentation).
  11393. */
  11394. #define MG_MAX_UNANSWERED_PING (5)
  11395. #endif
  11396. static void
  11397. read_websocket(struct mg_connection *conn,
  11398. mg_websocket_data_handler ws_data_handler,
  11399. void *callback_data)
  11400. {
  11401. /* Pointer to the beginning of the portion of the incoming websocket
  11402. * message queue.
  11403. * The original websocket upgrade request is never removed, so the queue
  11404. * begins after it. */
  11405. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  11406. int n, error, exit_by_callback;
  11407. int ret;
  11408. /* body_len is the length of the entire queue in bytes
  11409. * len is the length of the current message
  11410. * data_len is the length of the current message's data payload
  11411. * header_len is the length of the current message's header */
  11412. size_t i, len, mask_len = 0, header_len, body_len;
  11413. uint64_t data_len = 0;
  11414. /* "The masking key is a 32-bit value chosen at random by the client."
  11415. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  11416. */
  11417. unsigned char mask[4];
  11418. /* data points to the place where the message is stored when passed to
  11419. * the websocket_data callback. This is either mem on the stack, or a
  11420. * dynamically allocated buffer if it is too large. */
  11421. unsigned char mem[4096];
  11422. unsigned char mop; /* mask flag and opcode */
  11423. /* Variables used for connection monitoring */
  11424. double timeout = -1.0;
  11425. int enable_ping_pong = 0;
  11426. int ping_count = 0;
  11427. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  11428. enable_ping_pong =
  11429. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  11430. "yes");
  11431. }
  11432. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  11433. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  11434. }
  11435. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  11436. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  11437. }
  11438. if (timeout <= 0.0) {
  11439. timeout = atof(config_options[REQUEST_TIMEOUT].default_value) / 1000.0;
  11440. }
  11441. /* Enter data processing loop */
  11442. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  11443. conn->request_info.remote_addr,
  11444. conn->request_info.remote_port);
  11445. conn->in_websocket_handling = 1;
  11446. mg_set_thread_name("wsock");
  11447. /* Loop continuously, reading messages from the socket, invoking the
  11448. * callback, and waiting repeatedly until an error occurs. */
  11449. while (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11450. && (!conn->must_close)) {
  11451. header_len = 0;
  11452. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  11453. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  11454. len = buf[1] & 127;
  11455. mask_len = (buf[1] & 128) ? 4 : 0;
  11456. if ((len < 126) && (body_len >= mask_len)) {
  11457. /* inline 7-bit length field */
  11458. data_len = len;
  11459. header_len = 2 + mask_len;
  11460. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  11461. /* 16-bit length field */
  11462. header_len = 4 + mask_len;
  11463. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  11464. } else if (body_len >= (10 + mask_len)) {
  11465. /* 64-bit length field */
  11466. uint32_t l1, l2;
  11467. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  11468. memcpy(&l2, &buf[6], 4);
  11469. header_len = 10 + mask_len;
  11470. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  11471. if (data_len > (uint64_t)0x7FFF0000ul) {
  11472. /* no can do */
  11473. mg_cry_internal(
  11474. conn,
  11475. "%s",
  11476. "websocket out of memory; closing connection");
  11477. break;
  11478. }
  11479. }
  11480. }
  11481. if ((header_len > 0) && (body_len >= header_len)) {
  11482. /* Allocate space to hold websocket payload */
  11483. unsigned char *data = mem;
  11484. if ((size_t)data_len > (size_t)sizeof(mem)) {
  11485. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  11486. conn->phys_ctx);
  11487. if (data == NULL) {
  11488. /* Allocation failed, exit the loop and then close the
  11489. * connection */
  11490. mg_cry_internal(
  11491. conn,
  11492. "%s",
  11493. "websocket out of memory; closing connection");
  11494. break;
  11495. }
  11496. }
  11497. /* Copy the mask before we shift the queue and destroy it */
  11498. if (mask_len > 0) {
  11499. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  11500. } else {
  11501. memset(mask, 0, sizeof(mask));
  11502. }
  11503. /* Read frame payload from the first message in the queue into
  11504. * data and advance the queue by moving the memory in place. */
  11505. DEBUG_ASSERT(body_len >= header_len);
  11506. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  11507. mop = buf[0]; /* current mask and opcode */
  11508. /* Overflow case */
  11509. len = body_len - header_len;
  11510. memcpy(data, buf + header_len, len);
  11511. error = 0;
  11512. while ((uint64_t)len < data_len) {
  11513. n = pull_inner(NULL,
  11514. conn,
  11515. (char *)(data + len),
  11516. (int)(data_len - len),
  11517. timeout);
  11518. if (n <= -2) {
  11519. error = 1;
  11520. break;
  11521. } else if (n > 0) {
  11522. len += (size_t)n;
  11523. } else {
  11524. /* Timeout: should retry */
  11525. /* TODO: retry condition */
  11526. }
  11527. }
  11528. if (error) {
  11529. mg_cry_internal(
  11530. conn,
  11531. "%s",
  11532. "Websocket pull failed; closing connection");
  11533. if (data != mem) {
  11534. mg_free(data);
  11535. }
  11536. break;
  11537. }
  11538. conn->data_len = conn->request_len;
  11539. } else {
  11540. mop = buf[0]; /* current mask and opcode, overwritten by
  11541. * memmove() */
  11542. /* Length of the message being read at the front of the
  11543. * queue. Cast to 31 bit is OK, since we limited
  11544. * data_len before. */
  11545. len = (size_t)data_len + header_len;
  11546. /* Copy the data payload into the data pointer for the
  11547. * callback. Cast to 31 bit is OK, since we
  11548. * limited data_len */
  11549. memcpy(data, buf + header_len, (size_t)data_len);
  11550. /* Move the queue forward len bytes */
  11551. memmove(buf, buf + len, body_len - len);
  11552. /* Mark the queue as advanced */
  11553. conn->data_len -= (int)len;
  11554. }
  11555. /* Apply mask if necessary */
  11556. if (mask_len > 0) {
  11557. for (i = 0; i < (size_t)data_len; i++) {
  11558. data[i] ^= mask[i & 3];
  11559. }
  11560. }
  11561. exit_by_callback = 0;
  11562. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  11563. /* filter PONG messages */
  11564. DEBUG_TRACE("PONG from %s:%u",
  11565. conn->request_info.remote_addr,
  11566. conn->request_info.remote_port);
  11567. /* No unanwered PINGs left */
  11568. ping_count = 0;
  11569. } else if (enable_ping_pong
  11570. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  11571. /* reply PING messages */
  11572. DEBUG_TRACE("Reply PING from %s:%u",
  11573. conn->request_info.remote_addr,
  11574. conn->request_info.remote_port);
  11575. ret = mg_websocket_write(conn,
  11576. MG_WEBSOCKET_OPCODE_PONG,
  11577. (char *)data,
  11578. (size_t)data_len);
  11579. if (ret <= 0) {
  11580. /* Error: send failed */
  11581. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  11582. break;
  11583. }
  11584. } else {
  11585. /* Exit the loop if callback signals to exit (server side),
  11586. * or "connection close" opcode received (client side). */
  11587. if (ws_data_handler != NULL) {
  11588. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11589. if (mop & 0x40) {
  11590. /* Inflate the data received if bit RSV1 is set. */
  11591. if (!conn->websocket_deflate_initialized) {
  11592. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11593. exit_by_callback = 1;
  11594. }
  11595. if (!exit_by_callback) {
  11596. size_t inflate_buf_size_old = 0;
  11597. size_t inflate_buf_size =
  11598. data_len
  11599. * 4; // Initial guess of the inflated message
  11600. // size. We double the memory when needed.
  11601. Bytef *inflated = NULL;
  11602. Bytef *new_mem = NULL;
  11603. conn->websocket_inflate_state.avail_in =
  11604. (uInt)(data_len + 4);
  11605. conn->websocket_inflate_state.next_in = data;
  11606. // Add trailing 0x00 0x00 0xff 0xff bytes
  11607. data[data_len] = '\x00';
  11608. data[data_len + 1] = '\x00';
  11609. data[data_len + 2] = '\xff';
  11610. data[data_len + 3] = '\xff';
  11611. do {
  11612. if (inflate_buf_size_old == 0) {
  11613. new_mem =
  11614. (Bytef *)mg_calloc(inflate_buf_size,
  11615. sizeof(Bytef));
  11616. } else {
  11617. inflate_buf_size *= 2;
  11618. new_mem =
  11619. (Bytef *)mg_realloc(inflated,
  11620. inflate_buf_size);
  11621. }
  11622. if (new_mem == NULL) {
  11623. mg_cry_internal(
  11624. conn,
  11625. "Out of memory: Cannot allocate "
  11626. "inflate buffer of %lu bytes",
  11627. (unsigned long)inflate_buf_size);
  11628. exit_by_callback = 1;
  11629. break;
  11630. }
  11631. inflated = new_mem;
  11632. conn->websocket_inflate_state.avail_out =
  11633. (uInt)(inflate_buf_size
  11634. - inflate_buf_size_old);
  11635. conn->websocket_inflate_state.next_out =
  11636. inflated + inflate_buf_size_old;
  11637. ret = inflate(&conn->websocket_inflate_state,
  11638. Z_SYNC_FLUSH);
  11639. if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR
  11640. || ret == Z_MEM_ERROR) {
  11641. mg_cry_internal(
  11642. conn,
  11643. "ZLIB inflate error: %i %s",
  11644. ret,
  11645. (conn->websocket_inflate_state.msg
  11646. ? conn->websocket_inflate_state.msg
  11647. : "<no error message>"));
  11648. exit_by_callback = 1;
  11649. break;
  11650. }
  11651. inflate_buf_size_old = inflate_buf_size;
  11652. } while (conn->websocket_inflate_state.avail_out
  11653. == 0);
  11654. inflate_buf_size -=
  11655. conn->websocket_inflate_state.avail_out;
  11656. if (!ws_data_handler(conn,
  11657. mop,
  11658. (char *)inflated,
  11659. inflate_buf_size,
  11660. callback_data)) {
  11661. exit_by_callback = 1;
  11662. }
  11663. mg_free(inflated);
  11664. }
  11665. } else
  11666. #endif
  11667. if (!ws_data_handler(conn,
  11668. mop,
  11669. (char *)data,
  11670. (size_t)data_len,
  11671. callback_data)) {
  11672. exit_by_callback = 1;
  11673. }
  11674. }
  11675. }
  11676. /* It a buffer has been allocated, free it again */
  11677. if (data != mem) {
  11678. mg_free(data);
  11679. }
  11680. if (exit_by_callback) {
  11681. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  11682. conn->request_info.remote_addr,
  11683. conn->request_info.remote_port);
  11684. break;
  11685. }
  11686. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  11687. /* Opcode == 8, connection close */
  11688. DEBUG_TRACE("Message requests to close connection from %s:%u",
  11689. conn->request_info.remote_addr,
  11690. conn->request_info.remote_port);
  11691. break;
  11692. }
  11693. /* Not breaking the loop, process next websocket frame. */
  11694. } else {
  11695. /* Read from the socket into the next available location in the
  11696. * message queue. */
  11697. n = pull_inner(NULL,
  11698. conn,
  11699. conn->buf + conn->data_len,
  11700. conn->buf_size - conn->data_len,
  11701. timeout);
  11702. if (n <= -2) {
  11703. /* Error, no bytes read */
  11704. DEBUG_TRACE("PULL from %s:%u failed",
  11705. conn->request_info.remote_addr,
  11706. conn->request_info.remote_port);
  11707. break;
  11708. }
  11709. if (n > 0) {
  11710. conn->data_len += n;
  11711. /* Reset open PING count */
  11712. ping_count = 0;
  11713. } else {
  11714. if (STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  11715. && (!conn->must_close)) {
  11716. if (ping_count > MG_MAX_UNANSWERED_PING) {
  11717. /* Stop sending PING */
  11718. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  11719. "- closing connection",
  11720. ping_count,
  11721. conn->request_info.remote_addr,
  11722. conn->request_info.remote_port);
  11723. break;
  11724. }
  11725. if (enable_ping_pong) {
  11726. /* Send Websocket PING message */
  11727. DEBUG_TRACE("PING to %s:%u",
  11728. conn->request_info.remote_addr,
  11729. conn->request_info.remote_port);
  11730. ret = mg_websocket_write(conn,
  11731. MG_WEBSOCKET_OPCODE_PING,
  11732. NULL,
  11733. 0);
  11734. if (ret <= 0) {
  11735. /* Error: send failed */
  11736. DEBUG_TRACE("Send PING failed (%i)", ret);
  11737. break;
  11738. }
  11739. ping_count++;
  11740. }
  11741. }
  11742. /* Timeout: should retry */
  11743. /* TODO: get timeout def */
  11744. }
  11745. }
  11746. }
  11747. /* Leave data processing loop */
  11748. mg_set_thread_name("worker");
  11749. conn->in_websocket_handling = 0;
  11750. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  11751. conn->request_info.remote_addr,
  11752. conn->request_info.remote_port);
  11753. }
  11754. static int
  11755. mg_websocket_write_exec(struct mg_connection *conn,
  11756. int opcode,
  11757. const char *data,
  11758. size_t dataLen,
  11759. uint32_t masking_key)
  11760. {
  11761. unsigned char header[14];
  11762. size_t headerLen;
  11763. int retval;
  11764. #if defined(GCC_DIAGNOSTIC)
  11765. /* Disable spurious conversion warning for GCC */
  11766. #pragma GCC diagnostic push
  11767. #pragma GCC diagnostic ignored "-Wconversion"
  11768. #endif
  11769. /* Note that POSIX/Winsock's send() is threadsafe
  11770. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  11771. * but mongoose's mg_printf/mg_write is not (because of the loop in
  11772. * push(), although that is only a problem if the packet is large or
  11773. * outgoing buffer is full). */
  11774. /* TODO: Check if this lock should be moved to user land.
  11775. * Currently the server sets this lock for websockets, but
  11776. * not for any other connection. It must be set for every
  11777. * conn read/written by more than one thread, no matter if
  11778. * it is a websocket or regular connection. */
  11779. (void)mg_lock_connection(conn);
  11780. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11781. size_t deflated_size = 0;
  11782. Bytef *deflated = 0;
  11783. // Deflate websocket messages over 100kb
  11784. int use_deflate = dataLen > 100 * 1024 && conn->accept_gzip;
  11785. if (use_deflate) {
  11786. if (!conn->websocket_deflate_initialized) {
  11787. if (websocket_deflate_initialize(conn, 1) != Z_OK)
  11788. return 0;
  11789. }
  11790. // Deflating the message
  11791. header[0] = 0xC0u | (unsigned char)((unsigned)opcode & 0xf);
  11792. conn->websocket_deflate_state.avail_in = (uInt)dataLen;
  11793. conn->websocket_deflate_state.next_in = (unsigned char *)data;
  11794. deflated_size = (size_t)compressBound((uLong)dataLen);
  11795. deflated = mg_calloc(deflated_size, sizeof(Bytef));
  11796. if (deflated == NULL) {
  11797. mg_cry_internal(
  11798. conn,
  11799. "Out of memory: Cannot allocate deflate buffer of %lu bytes",
  11800. (unsigned long)deflated_size);
  11801. mg_unlock_connection(conn);
  11802. return -1;
  11803. }
  11804. conn->websocket_deflate_state.avail_out = (uInt)deflated_size;
  11805. conn->websocket_deflate_state.next_out = deflated;
  11806. deflate(&conn->websocket_deflate_state, conn->websocket_deflate_flush);
  11807. dataLen = deflated_size - conn->websocket_deflate_state.avail_out
  11808. - 4; // Strip trailing 0x00 0x00 0xff 0xff bytes
  11809. } else
  11810. #endif
  11811. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  11812. #if defined(GCC_DIAGNOSTIC)
  11813. #pragma GCC diagnostic pop
  11814. #endif
  11815. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  11816. if (dataLen < 126) {
  11817. /* inline 7-bit length field */
  11818. header[1] = (unsigned char)dataLen;
  11819. headerLen = 2;
  11820. } else if (dataLen <= 0xFFFF) {
  11821. /* 16-bit length field */
  11822. uint16_t len = htons((uint16_t)dataLen);
  11823. header[1] = 126;
  11824. memcpy(header + 2, &len, 2);
  11825. headerLen = 4;
  11826. } else {
  11827. /* 64-bit length field */
  11828. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  11829. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  11830. header[1] = 127;
  11831. memcpy(header + 2, &len1, 4);
  11832. memcpy(header + 6, &len2, 4);
  11833. headerLen = 10;
  11834. }
  11835. if (masking_key) {
  11836. /* add mask */
  11837. header[1] |= 0x80;
  11838. memcpy(header + headerLen, &masking_key, 4);
  11839. headerLen += 4;
  11840. }
  11841. retval = mg_write(conn, header, headerLen);
  11842. if (retval != (int)headerLen) {
  11843. /* Did not send complete header */
  11844. retval = -1;
  11845. } else {
  11846. if (dataLen > 0) {
  11847. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  11848. if (use_deflate) {
  11849. retval = mg_write(conn, deflated, dataLen);
  11850. mg_free(deflated);
  11851. } else
  11852. #endif
  11853. retval = mg_write(conn, data, dataLen);
  11854. }
  11855. /* if dataLen == 0, the header length (2) is returned */
  11856. }
  11857. /* TODO: Remove this unlock as well, when lock is removed. */
  11858. mg_unlock_connection(conn);
  11859. return retval;
  11860. }
  11861. CIVETWEB_API int
  11862. mg_websocket_write(struct mg_connection *conn,
  11863. int opcode,
  11864. const char *data,
  11865. size_t dataLen)
  11866. {
  11867. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  11868. }
  11869. static void
  11870. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  11871. {
  11872. size_t i = 0;
  11873. i = 0;
  11874. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  11875. /* Convert in 32 bit words, if data is 4 byte aligned */
  11876. while (i < (in_len - 3)) {
  11877. *(uint32_t *)(void *)(out + i) =
  11878. *(uint32_t *)(void *)(in + i) ^ masking_key;
  11879. i += 4;
  11880. }
  11881. }
  11882. if (i != in_len) {
  11883. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  11884. while (i < in_len) {
  11885. *(uint8_t *)(void *)(out + i) =
  11886. *(uint8_t *)(void *)(in + i)
  11887. ^ *(((uint8_t *)&masking_key) + (i % 4));
  11888. i++;
  11889. }
  11890. }
  11891. }
  11892. CIVETWEB_API int
  11893. mg_websocket_client_write(struct mg_connection *conn,
  11894. int opcode,
  11895. const char *data,
  11896. size_t dataLen)
  11897. {
  11898. int retval = -1;
  11899. char *masked_data =
  11900. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  11901. uint32_t masking_key = 0;
  11902. if (masked_data == NULL) {
  11903. /* Return -1 in an error case */
  11904. mg_cry_internal(conn,
  11905. "%s",
  11906. "Cannot allocate buffer for masked websocket response: "
  11907. "Out of memory");
  11908. return -1;
  11909. }
  11910. do {
  11911. /* Get a masking key - but not 0 */
  11912. masking_key = (uint32_t)get_random();
  11913. } while (masking_key == 0);
  11914. mask_data(data, dataLen, masking_key, masked_data);
  11915. retval = mg_websocket_write_exec(
  11916. conn, opcode, masked_data, dataLen, masking_key);
  11917. mg_free(masked_data);
  11918. return retval;
  11919. }
  11920. static void
  11921. handle_websocket_request(struct mg_connection *conn,
  11922. const char *path,
  11923. int is_callback_resource,
  11924. struct mg_websocket_subprotocols *subprotocols,
  11925. mg_websocket_connect_handler ws_connect_handler,
  11926. mg_websocket_ready_handler ws_ready_handler,
  11927. mg_websocket_data_handler ws_data_handler,
  11928. mg_websocket_close_handler ws_close_handler,
  11929. void *cbData)
  11930. {
  11931. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  11932. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  11933. ptrdiff_t lua_websock = 0;
  11934. #if !defined(USE_LUA)
  11935. (void)path;
  11936. #endif
  11937. /* Step 1: Check websocket protocol version. */
  11938. /* Step 1.1: Check Sec-WebSocket-Key. */
  11939. if (!websock_key) {
  11940. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  11941. * requires a Sec-WebSocket-Key header.
  11942. */
  11943. /* It could be the hixie draft version
  11944. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  11945. */
  11946. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  11947. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  11948. char key3[8];
  11949. if ((key1 != NULL) && (key2 != NULL)) {
  11950. /* This version uses 8 byte body data in a GET request */
  11951. conn->content_len = 8;
  11952. if (8 == mg_read(conn, key3, 8)) {
  11953. /* This is the hixie version */
  11954. mg_send_http_error(conn,
  11955. 426,
  11956. "%s",
  11957. "Protocol upgrade to RFC 6455 required");
  11958. return;
  11959. }
  11960. }
  11961. /* This is an unknown version */
  11962. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  11963. return;
  11964. }
  11965. /* Step 1.2: Check websocket protocol version. */
  11966. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  11967. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  11968. /* Reject wrong versions */
  11969. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  11970. return;
  11971. }
  11972. /* Step 1.3: Could check for "Host", but we do not really need this
  11973. * value for anything, so just ignore it. */
  11974. /* Step 2: If a callback is responsible, call it. */
  11975. if (is_callback_resource) {
  11976. /* Step 2.1 check and select subprotocol */
  11977. const char *protocols[64]; // max 64 headers
  11978. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  11979. "Sec-WebSocket-Protocol",
  11980. protocols,
  11981. 64);
  11982. if ((nbSubprotocolHeader > 0) && subprotocols) {
  11983. int headerNo, idx;
  11984. size_t len;
  11985. const char *sep, *curSubProtocol,
  11986. *acceptedWebSocketSubprotocol = NULL;
  11987. /* look for matching subprotocol */
  11988. for (headerNo = 0; headerNo < nbSubprotocolHeader; headerNo++) {
  11989. /* There might be multiple headers ... */
  11990. const char *protocol = protocols[headerNo];
  11991. curSubProtocol = protocol;
  11992. /* ... and in every header there might be a , separated list */
  11993. while (!acceptedWebSocketSubprotocol && (*curSubProtocol)) {
  11994. while ((*curSubProtocol == ' ') || (*curSubProtocol == ','))
  11995. curSubProtocol++;
  11996. sep = strchr(curSubProtocol, ',');
  11997. if (sep) {
  11998. len = (size_t)(sep - curSubProtocol);
  11999. } else {
  12000. len = strlen(curSubProtocol);
  12001. }
  12002. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  12003. // COMPARE: curSubProtocol ==
  12004. // subprotocols->subprotocols[idx]
  12005. if ((strlen(subprotocols->subprotocols[idx]) == len)
  12006. && (strncmp(curSubProtocol,
  12007. subprotocols->subprotocols[idx],
  12008. len)
  12009. == 0)) {
  12010. acceptedWebSocketSubprotocol =
  12011. subprotocols->subprotocols[idx];
  12012. break;
  12013. }
  12014. }
  12015. curSubProtocol += len;
  12016. }
  12017. }
  12018. conn->request_info.acceptedWebSocketSubprotocol =
  12019. acceptedWebSocketSubprotocol;
  12020. }
  12021. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12022. websocket_deflate_negotiate(conn);
  12023. #endif
  12024. if ((ws_connect_handler != NULL)
  12025. && (ws_connect_handler(conn, cbData) != 0)) {
  12026. /* C callback has returned non-zero, do not proceed with
  12027. * handshake.
  12028. */
  12029. /* Note that C callbacks are no longer called when Lua is
  12030. * responsible, so C can no longer filter callbacks for Lua. */
  12031. return;
  12032. }
  12033. }
  12034. #if defined(USE_LUA)
  12035. /* Step 3: No callback. Check if Lua is responsible. */
  12036. else {
  12037. /* Step 3.1: Check if Lua is responsible. */
  12038. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  12039. lua_websock = match_prefix_strlen(
  12040. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], path);
  12041. }
  12042. if (lua_websock > 0) {
  12043. /* Step 3.2: Lua is responsible: call it. */
  12044. conn->lua_websocket_state = lua_websocket_new(path, conn);
  12045. if (!conn->lua_websocket_state) {
  12046. /* Lua rejected the new client */
  12047. return;
  12048. }
  12049. }
  12050. }
  12051. #endif
  12052. /* Step 4: Check if there is a responsible websocket handler. */
  12053. if (!is_callback_resource && !lua_websock) {
  12054. /* There is no callback, and Lua is not responsible either. */
  12055. /* Reply with a 404 Not Found. We are still at a standard
  12056. * HTTP request here, before the websocket handshake, so
  12057. * we can still send standard HTTP error replies. */
  12058. mg_send_http_error(conn, 404, "%s", "Not found");
  12059. return;
  12060. }
  12061. /* Step 5: The websocket connection has been accepted */
  12062. if (!send_websocket_handshake(conn, websock_key)) {
  12063. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  12064. return;
  12065. }
  12066. /* Step 6: Call the ready handler */
  12067. if (is_callback_resource) {
  12068. if (ws_ready_handler != NULL) {
  12069. ws_ready_handler(conn, cbData);
  12070. }
  12071. #if defined(USE_LUA)
  12072. } else if (lua_websock) {
  12073. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  12074. /* the ready handler returned false */
  12075. return;
  12076. }
  12077. #endif
  12078. }
  12079. /* Step 7: Enter the read loop */
  12080. if (is_callback_resource) {
  12081. read_websocket(conn, ws_data_handler, cbData);
  12082. #if defined(USE_LUA)
  12083. } else if (lua_websock) {
  12084. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  12085. #endif
  12086. }
  12087. #if defined(USE_ZLIB) && defined(MG_EXPERIMENTAL_INTERFACES)
  12088. /* Step 8: Close the deflate & inflate buffers */
  12089. if (conn->websocket_deflate_initialized) {
  12090. deflateEnd(&conn->websocket_deflate_state);
  12091. inflateEnd(&conn->websocket_inflate_state);
  12092. }
  12093. #endif
  12094. /* Step 9: Call the close handler */
  12095. if (ws_close_handler) {
  12096. ws_close_handler(conn, cbData);
  12097. }
  12098. }
  12099. #endif /* !USE_WEBSOCKET */
  12100. /* Is upgrade request:
  12101. * 0 = regular HTTP/1.0 or HTTP/1.1 request
  12102. * 1 = upgrade to websocket
  12103. * 2 = upgrade to HTTP/2
  12104. * -1 = upgrade to unknown protocol
  12105. */
  12106. static int
  12107. should_switch_to_protocol(const struct mg_connection *conn)
  12108. {
  12109. const char *connection_headers[8];
  12110. const char *upgrade_to;
  12111. int connection_header_count, i, should_upgrade;
  12112. /* A websocket protocol has the following HTTP headers:
  12113. *
  12114. * Connection: Upgrade
  12115. * Upgrade: Websocket
  12116. *
  12117. * It seems some clients use multiple headers:
  12118. * see https://github.com/civetweb/civetweb/issues/1083
  12119. */
  12120. connection_header_count = get_req_headers(&conn->request_info,
  12121. "Connection",
  12122. connection_headers,
  12123. 8);
  12124. should_upgrade = 0;
  12125. for (i = 0; i < connection_header_count; i++) {
  12126. if (0 != mg_strcasestr(connection_headers[i], "upgrade")) {
  12127. should_upgrade = 1;
  12128. }
  12129. }
  12130. if (!should_upgrade) {
  12131. return PROTOCOL_TYPE_HTTP1;
  12132. }
  12133. upgrade_to = mg_get_header(conn, "Upgrade");
  12134. if (upgrade_to == NULL) {
  12135. /* "Connection: Upgrade" without "Upgrade" Header --> Error */
  12136. return -1;
  12137. }
  12138. /* Upgrade to ... */
  12139. if (0 != mg_strcasestr(upgrade_to, "websocket")) {
  12140. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  12141. * "Sec-WebSocket-Version" are also required.
  12142. * Don't check them here, since even an unsupported websocket protocol
  12143. * request still IS a websocket request (in contrast to a standard HTTP
  12144. * request). It will fail later in handle_websocket_request.
  12145. */
  12146. return PROTOCOL_TYPE_WEBSOCKET; /* Websocket */
  12147. }
  12148. if (0 != mg_strcasestr(upgrade_to, "h2")) {
  12149. return PROTOCOL_TYPE_HTTP2; /* Websocket */
  12150. }
  12151. /* Upgrade to another protocol */
  12152. return -1;
  12153. }
  12154. static int
  12155. parse_match_net(const struct vec *vec, const union usa *sa, int no_strict)
  12156. {
  12157. int n;
  12158. unsigned int a, b, c, d, slash;
  12159. if (sscanf(vec->ptr, "%u.%u.%u.%u/%u%n", &a, &b, &c, &d, &slash, &n)
  12160. != 5) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to an
  12161. // integer value, but function will not report conversion
  12162. // errors; consider using 'strtol' instead
  12163. slash = 32;
  12164. if (sscanf(vec->ptr, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n)
  12165. != 4) { // NOLINT(cert-err34-c) 'sscanf' used to convert a string to
  12166. // an integer value, but function will not report conversion
  12167. // errors; consider using 'strtol' instead
  12168. n = 0;
  12169. }
  12170. }
  12171. if ((n > 0) && ((size_t)n == vec->len)) {
  12172. if ((a < 256) && (b < 256) && (c < 256) && (d < 256) && (slash < 33)) {
  12173. /* IPv4 format */
  12174. if (sa->sa.sa_family == AF_INET) {
  12175. uint32_t ip = ntohl(sa->sin.sin_addr.s_addr);
  12176. uint32_t net = ((uint32_t)a << 24) | ((uint32_t)b << 16)
  12177. | ((uint32_t)c << 8) | (uint32_t)d;
  12178. uint32_t mask = slash ? (0xFFFFFFFFu << (32 - slash)) : 0;
  12179. return (ip & mask) == net;
  12180. }
  12181. return 0;
  12182. }
  12183. }
  12184. #if defined(USE_IPV6)
  12185. else {
  12186. char ad[50];
  12187. const char *p;
  12188. if (sscanf(vec->ptr, "[%49[^]]]/%u%n", ad, &slash, &n) != 2) {
  12189. slash = 128;
  12190. if (sscanf(vec->ptr, "[%49[^]]]%n", ad, &n) != 1) {
  12191. n = 0;
  12192. }
  12193. }
  12194. if ((n <= 0) && no_strict) {
  12195. /* no square brackets? */
  12196. p = strchr(vec->ptr, '/');
  12197. if (p && (p < (vec->ptr + vec->len))) {
  12198. if (((size_t)(p - vec->ptr) < sizeof(ad))
  12199. && (sscanf(p, "/%u%n", &slash, &n) == 1)) {
  12200. n += (int)(p - vec->ptr);
  12201. mg_strlcpy(ad, vec->ptr, (size_t)(p - vec->ptr) + 1);
  12202. } else {
  12203. n = 0;
  12204. }
  12205. } else if (vec->len < sizeof(ad)) {
  12206. n = (int)vec->len;
  12207. slash = 128;
  12208. mg_strlcpy(ad, vec->ptr, vec->len + 1);
  12209. }
  12210. }
  12211. if ((n > 0) && ((size_t)n == vec->len) && (slash < 129)) {
  12212. p = ad;
  12213. c = 0;
  12214. /* zone indexes are unsupported, at least two colons are needed */
  12215. while (isxdigit((unsigned char)*p) || (*p == '.') || (*p == ':')) {
  12216. if (*(p++) == ':') {
  12217. c++;
  12218. }
  12219. }
  12220. if ((*p == '\0') && (c >= 2)) {
  12221. struct sockaddr_in6 sin6;
  12222. unsigned int i;
  12223. /* for strict validation, an actual IPv6 argument is needed */
  12224. if (sa->sa.sa_family != AF_INET6) {
  12225. return 0;
  12226. }
  12227. if (mg_inet_pton(AF_INET6, ad, &sin6, sizeof(sin6), 0)) {
  12228. /* IPv6 format */
  12229. for (i = 0; i < 16; i++) {
  12230. uint8_t ip = sa->sin6.sin6_addr.s6_addr[i];
  12231. uint8_t net = sin6.sin6_addr.s6_addr[i];
  12232. uint8_t mask = 0;
  12233. if (8 * i + 8 < slash) {
  12234. mask = 0xFFu;
  12235. } else if (8 * i < slash) {
  12236. mask = (uint8_t)(0xFFu << (8 * i + 8 - slash));
  12237. }
  12238. if ((ip & mask) != net) {
  12239. return 0;
  12240. }
  12241. }
  12242. return 1;
  12243. }
  12244. }
  12245. }
  12246. }
  12247. #else
  12248. (void)no_strict;
  12249. #endif
  12250. /* malformed */
  12251. return -1;
  12252. }
  12253. static int
  12254. set_throttle(const char *spec, const union usa *rsa, const char *uri)
  12255. {
  12256. int throttle = 0;
  12257. struct vec vec, val;
  12258. char mult;
  12259. double v;
  12260. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  12261. mult = ',';
  12262. if ((val.ptr == NULL)
  12263. || (sscanf(val.ptr, "%lf%c", &v, &mult)
  12264. < 1) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  12265. // to an integer value, but function will not report
  12266. // conversion errors; consider using 'strtol' instead
  12267. || (v < 0)
  12268. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  12269. && (mult != ','))) {
  12270. continue;
  12271. }
  12272. v *= (lowercase(&mult) == 'k')
  12273. ? 1024
  12274. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  12275. if (vec.len == 1 && vec.ptr[0] == '*') {
  12276. throttle = (int)v;
  12277. } else {
  12278. int matched = parse_match_net(&vec, rsa, 0);
  12279. if (matched >= 0) {
  12280. /* a valid IP subnet */
  12281. if (matched) {
  12282. throttle = (int)v;
  12283. }
  12284. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  12285. throttle = (int)v;
  12286. }
  12287. }
  12288. }
  12289. return throttle;
  12290. }
  12291. /* The mg_upload function is superseded by mg_handle_form_request. */
  12292. #include "handle_form.inl"
  12293. static int
  12294. get_first_ssl_listener_index(const struct mg_context *ctx)
  12295. {
  12296. unsigned int i;
  12297. int idx = -1;
  12298. if (ctx) {
  12299. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  12300. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  12301. }
  12302. }
  12303. return idx;
  12304. }
  12305. /* Return host (without port) */
  12306. static void
  12307. get_host_from_request_info(struct vec *host, const struct mg_request_info *ri)
  12308. {
  12309. const char *host_header =
  12310. get_header(ri->http_headers, ri->num_headers, "Host");
  12311. host->ptr = NULL;
  12312. host->len = 0;
  12313. if (host_header != NULL) {
  12314. const char *pos;
  12315. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  12316. * is found. */
  12317. if (*host_header == '[') {
  12318. pos = strchr(host_header, ']');
  12319. if (!pos) {
  12320. /* Malformed hostname starts with '[', but no ']' found */
  12321. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  12322. return;
  12323. }
  12324. /* terminate after ']' */
  12325. host->ptr = host_header;
  12326. host->len = (size_t)(pos + 1 - host_header);
  12327. } else {
  12328. /* Otherwise, a ':' separates hostname and port number */
  12329. pos = strchr(host_header, ':');
  12330. if (pos != NULL) {
  12331. host->len = (size_t)(pos - host_header);
  12332. } else {
  12333. host->len = strlen(host_header);
  12334. }
  12335. host->ptr = host_header;
  12336. }
  12337. }
  12338. }
  12339. static int
  12340. switch_domain_context(struct mg_connection *conn)
  12341. {
  12342. struct vec host;
  12343. get_host_from_request_info(&host, &conn->request_info);
  12344. if (host.ptr) {
  12345. if (conn->ssl) {
  12346. /* This is a HTTPS connection, maybe we have a hostname
  12347. * from SNI (set in ssl_servername_callback). */
  12348. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  12349. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  12350. /* We are not using the default domain */
  12351. if ((strlen(sslhost) != host.len)
  12352. || mg_strncasecmp(host.ptr, sslhost, host.len)) {
  12353. /* Mismatch between SNI domain and HTTP domain */
  12354. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %.*s",
  12355. sslhost,
  12356. (int)host.len,
  12357. host.ptr);
  12358. return 0;
  12359. }
  12360. }
  12361. } else {
  12362. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  12363. while (dom) {
  12364. const char *domName = dom->config[AUTHENTICATION_DOMAIN];
  12365. size_t domNameLen = strlen(domName);
  12366. if ((domNameLen == host.len)
  12367. && !mg_strncasecmp(host.ptr, domName, host.len)) {
  12368. /* Found matching domain */
  12369. DEBUG_TRACE("HTTP domain %s found",
  12370. dom->config[AUTHENTICATION_DOMAIN]);
  12371. /* TODO: Check if this is a HTTP or HTTPS domain */
  12372. conn->dom_ctx = dom;
  12373. break;
  12374. }
  12375. mg_lock_context(conn->phys_ctx);
  12376. dom = dom->next;
  12377. mg_unlock_context(conn->phys_ctx);
  12378. }
  12379. }
  12380. DEBUG_TRACE("HTTP%s Host: %.*s",
  12381. conn->ssl ? "S" : "",
  12382. (int)host.len,
  12383. host.ptr);
  12384. } else {
  12385. DEBUG_TRACE("HTTP%s Host is not set", conn->ssl ? "S" : "");
  12386. return 1;
  12387. }
  12388. return 1;
  12389. }
  12390. static void
  12391. redirect_to_https_port(struct mg_connection *conn, int port)
  12392. {
  12393. char target_url[MG_BUF_LEN];
  12394. int truncated = 0;
  12395. const char *expect_proto =
  12396. (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET) ? "wss" : "https";
  12397. /* Use "308 Permanent Redirect" */
  12398. int redirect_code = 308;
  12399. /* In any case, close the current connection */
  12400. conn->must_close = 1;
  12401. /* Send host, port, uri and (if it exists) ?query_string */
  12402. if (mg_construct_local_link(
  12403. conn, target_url, sizeof(target_url), expect_proto, port, NULL)
  12404. < 0) {
  12405. truncated = 1;
  12406. } else if (conn->request_info.query_string != NULL) {
  12407. size_t slen1 = strlen(target_url);
  12408. size_t slen2 = strlen(conn->request_info.query_string);
  12409. if ((slen1 + slen2 + 2) < sizeof(target_url)) {
  12410. target_url[slen1] = '?';
  12411. memcpy(target_url + slen1 + 1,
  12412. conn->request_info.query_string,
  12413. slen2);
  12414. target_url[slen1 + slen2 + 1] = 0;
  12415. } else {
  12416. truncated = 1;
  12417. }
  12418. }
  12419. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  12420. * is used as buffer size) */
  12421. if (truncated) {
  12422. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  12423. return;
  12424. }
  12425. /* Use redirect helper function */
  12426. mg_send_http_redirect(conn, target_url, redirect_code);
  12427. }
  12428. static void
  12429. mg_set_handler_type(struct mg_context *phys_ctx,
  12430. struct mg_domain_context *dom_ctx,
  12431. const char *uri,
  12432. int handler_type,
  12433. int is_delete_request,
  12434. mg_request_handler handler,
  12435. struct mg_websocket_subprotocols *subprotocols,
  12436. mg_websocket_connect_handler connect_handler,
  12437. mg_websocket_ready_handler ready_handler,
  12438. mg_websocket_data_handler data_handler,
  12439. mg_websocket_close_handler close_handler,
  12440. mg_authorization_handler auth_handler,
  12441. void *cbdata)
  12442. {
  12443. struct mg_handler_info *tmp_rh, **lastref;
  12444. size_t urilen = strlen(uri);
  12445. if (handler_type == WEBSOCKET_HANDLER) {
  12446. DEBUG_ASSERT(handler == NULL);
  12447. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  12448. || ready_handler != NULL || data_handler != NULL
  12449. || close_handler != NULL);
  12450. DEBUG_ASSERT(auth_handler == NULL);
  12451. if (handler != NULL) {
  12452. return;
  12453. }
  12454. if (!is_delete_request && (connect_handler == NULL)
  12455. && (ready_handler == NULL) && (data_handler == NULL)
  12456. && (close_handler == NULL)) {
  12457. return;
  12458. }
  12459. if (auth_handler != NULL) {
  12460. return;
  12461. }
  12462. } else if (handler_type == REQUEST_HANDLER) {
  12463. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12464. && data_handler == NULL && close_handler == NULL);
  12465. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  12466. DEBUG_ASSERT(auth_handler == NULL);
  12467. if ((connect_handler != NULL) || (ready_handler != NULL)
  12468. || (data_handler != NULL) || (close_handler != NULL)) {
  12469. return;
  12470. }
  12471. if (!is_delete_request && (handler == NULL)) {
  12472. return;
  12473. }
  12474. if (auth_handler != NULL) {
  12475. return;
  12476. }
  12477. } else if (handler_type == AUTH_HANDLER) {
  12478. DEBUG_ASSERT(handler == NULL);
  12479. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  12480. && data_handler == NULL && close_handler == NULL);
  12481. DEBUG_ASSERT(is_delete_request || (auth_handler != NULL));
  12482. if (handler != NULL) {
  12483. return;
  12484. }
  12485. if ((connect_handler != NULL) || (ready_handler != NULL)
  12486. || (data_handler != NULL) || (close_handler != NULL)) {
  12487. return;
  12488. }
  12489. if (!is_delete_request && (auth_handler == NULL)) {
  12490. return;
  12491. }
  12492. } else {
  12493. /* Unknown handler type. */
  12494. return;
  12495. }
  12496. if (!phys_ctx || !dom_ctx) {
  12497. /* no context available */
  12498. return;
  12499. }
  12500. mg_lock_context(phys_ctx);
  12501. /* first try to find an existing handler */
  12502. do {
  12503. lastref = &(dom_ctx->handlers);
  12504. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL;
  12505. tmp_rh = tmp_rh->next) {
  12506. if (tmp_rh->handler_type == handler_type
  12507. && (urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  12508. if (!is_delete_request) {
  12509. /* update existing handler */
  12510. if (handler_type == REQUEST_HANDLER) {
  12511. /* Wait for end of use before updating */
  12512. if (tmp_rh->refcount) {
  12513. mg_unlock_context(phys_ctx);
  12514. mg_sleep(1);
  12515. mg_lock_context(phys_ctx);
  12516. /* tmp_rh might have been freed, search again. */
  12517. break;
  12518. }
  12519. /* Ok, the handler is no more use -> Update it */
  12520. tmp_rh->handler = handler;
  12521. } else if (handler_type == WEBSOCKET_HANDLER) {
  12522. tmp_rh->subprotocols = subprotocols;
  12523. tmp_rh->connect_handler = connect_handler;
  12524. tmp_rh->ready_handler = ready_handler;
  12525. tmp_rh->data_handler = data_handler;
  12526. tmp_rh->close_handler = close_handler;
  12527. } else { /* AUTH_HANDLER */
  12528. tmp_rh->auth_handler = auth_handler;
  12529. }
  12530. tmp_rh->cbdata = cbdata;
  12531. } else {
  12532. /* remove existing handler */
  12533. if (handler_type == REQUEST_HANDLER) {
  12534. /* Wait for end of use before removing */
  12535. if (tmp_rh->refcount) {
  12536. tmp_rh->removing = 1;
  12537. mg_unlock_context(phys_ctx);
  12538. mg_sleep(1);
  12539. mg_lock_context(phys_ctx);
  12540. /* tmp_rh might have been freed, search again. */
  12541. break;
  12542. }
  12543. /* Ok, the handler is no more used */
  12544. }
  12545. *lastref = tmp_rh->next;
  12546. mg_free(tmp_rh->uri);
  12547. mg_free(tmp_rh);
  12548. }
  12549. mg_unlock_context(phys_ctx);
  12550. return;
  12551. }
  12552. lastref = &(tmp_rh->next);
  12553. }
  12554. } while (tmp_rh != NULL);
  12555. if (is_delete_request) {
  12556. /* no handler to set, this was a remove request to a non-existing
  12557. * handler */
  12558. mg_unlock_context(phys_ctx);
  12559. return;
  12560. }
  12561. tmp_rh =
  12562. (struct mg_handler_info *)mg_calloc_ctx(1,
  12563. sizeof(struct mg_handler_info),
  12564. phys_ctx);
  12565. if (tmp_rh == NULL) {
  12566. mg_unlock_context(phys_ctx);
  12567. mg_cry_ctx_internal(phys_ctx,
  12568. "%s",
  12569. "Cannot create new request handler struct, OOM");
  12570. return;
  12571. }
  12572. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  12573. if (!tmp_rh->uri) {
  12574. mg_unlock_context(phys_ctx);
  12575. mg_free(tmp_rh);
  12576. mg_cry_ctx_internal(phys_ctx,
  12577. "%s",
  12578. "Cannot create new request handler struct, OOM");
  12579. return;
  12580. }
  12581. tmp_rh->uri_len = urilen;
  12582. if (handler_type == REQUEST_HANDLER) {
  12583. tmp_rh->refcount = 0;
  12584. tmp_rh->removing = 0;
  12585. tmp_rh->handler = handler;
  12586. } else if (handler_type == WEBSOCKET_HANDLER) {
  12587. tmp_rh->subprotocols = subprotocols;
  12588. tmp_rh->connect_handler = connect_handler;
  12589. tmp_rh->ready_handler = ready_handler;
  12590. tmp_rh->data_handler = data_handler;
  12591. tmp_rh->close_handler = close_handler;
  12592. } else { /* AUTH_HANDLER */
  12593. tmp_rh->auth_handler = auth_handler;
  12594. }
  12595. tmp_rh->cbdata = cbdata;
  12596. tmp_rh->handler_type = handler_type;
  12597. tmp_rh->next = NULL;
  12598. *lastref = tmp_rh;
  12599. mg_unlock_context(phys_ctx);
  12600. }
  12601. CIVETWEB_API void
  12602. mg_set_request_handler(struct mg_context *ctx,
  12603. const char *uri,
  12604. mg_request_handler handler,
  12605. void *cbdata)
  12606. {
  12607. mg_set_handler_type(ctx,
  12608. &(ctx->dd),
  12609. uri,
  12610. REQUEST_HANDLER,
  12611. handler == NULL,
  12612. handler,
  12613. NULL,
  12614. NULL,
  12615. NULL,
  12616. NULL,
  12617. NULL,
  12618. NULL,
  12619. cbdata);
  12620. }
  12621. CIVETWEB_API void
  12622. mg_set_websocket_handler(struct mg_context *ctx,
  12623. const char *uri,
  12624. mg_websocket_connect_handler connect_handler,
  12625. mg_websocket_ready_handler ready_handler,
  12626. mg_websocket_data_handler data_handler,
  12627. mg_websocket_close_handler close_handler,
  12628. void *cbdata)
  12629. {
  12630. mg_set_websocket_handler_with_subprotocols(ctx,
  12631. uri,
  12632. NULL,
  12633. connect_handler,
  12634. ready_handler,
  12635. data_handler,
  12636. close_handler,
  12637. cbdata);
  12638. }
  12639. CIVETWEB_API void
  12640. mg_set_websocket_handler_with_subprotocols(
  12641. struct mg_context *ctx,
  12642. const char *uri,
  12643. struct mg_websocket_subprotocols *subprotocols,
  12644. mg_websocket_connect_handler connect_handler,
  12645. mg_websocket_ready_handler ready_handler,
  12646. mg_websocket_data_handler data_handler,
  12647. mg_websocket_close_handler close_handler,
  12648. void *cbdata)
  12649. {
  12650. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  12651. && (data_handler == NULL)
  12652. && (close_handler == NULL);
  12653. mg_set_handler_type(ctx,
  12654. &(ctx->dd),
  12655. uri,
  12656. WEBSOCKET_HANDLER,
  12657. is_delete_request,
  12658. NULL,
  12659. subprotocols,
  12660. connect_handler,
  12661. ready_handler,
  12662. data_handler,
  12663. close_handler,
  12664. NULL,
  12665. cbdata);
  12666. }
  12667. CIVETWEB_API void
  12668. mg_set_auth_handler(struct mg_context *ctx,
  12669. const char *uri,
  12670. mg_authorization_handler handler,
  12671. void *cbdata)
  12672. {
  12673. mg_set_handler_type(ctx,
  12674. &(ctx->dd),
  12675. uri,
  12676. AUTH_HANDLER,
  12677. handler == NULL,
  12678. NULL,
  12679. NULL,
  12680. NULL,
  12681. NULL,
  12682. NULL,
  12683. NULL,
  12684. handler,
  12685. cbdata);
  12686. }
  12687. static int
  12688. get_request_handler(struct mg_connection *conn,
  12689. int handler_type,
  12690. mg_request_handler *handler,
  12691. struct mg_websocket_subprotocols **subprotocols,
  12692. mg_websocket_connect_handler *connect_handler,
  12693. mg_websocket_ready_handler *ready_handler,
  12694. mg_websocket_data_handler *data_handler,
  12695. mg_websocket_close_handler *close_handler,
  12696. mg_authorization_handler *auth_handler,
  12697. void **cbdata,
  12698. struct mg_handler_info **handler_info)
  12699. {
  12700. const struct mg_request_info *request_info = mg_get_request_info(conn);
  12701. if (request_info) {
  12702. const char *uri = request_info->local_uri;
  12703. size_t urilen = strlen(uri);
  12704. struct mg_handler_info *tmp_rh;
  12705. int step, matched;
  12706. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  12707. return 0;
  12708. }
  12709. mg_lock_context(conn->phys_ctx);
  12710. for (step = 0; step < 3; step++) {
  12711. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  12712. tmp_rh = tmp_rh->next) {
  12713. if (tmp_rh->handler_type != handler_type) {
  12714. continue;
  12715. }
  12716. if (step == 0) {
  12717. /* first try for an exact match */
  12718. matched = (tmp_rh->uri_len == urilen)
  12719. && (strcmp(tmp_rh->uri, uri) == 0);
  12720. } else if (step == 1) {
  12721. /* next try for a partial match, we will accept
  12722. uri/something */
  12723. matched =
  12724. (tmp_rh->uri_len < urilen)
  12725. && (uri[tmp_rh->uri_len] == '/')
  12726. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0);
  12727. } else {
  12728. /* finally try for pattern match */
  12729. matched =
  12730. match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0;
  12731. }
  12732. if (matched) {
  12733. if (handler_type == WEBSOCKET_HANDLER) {
  12734. *subprotocols = tmp_rh->subprotocols;
  12735. *connect_handler = tmp_rh->connect_handler;
  12736. *ready_handler = tmp_rh->ready_handler;
  12737. *data_handler = tmp_rh->data_handler;
  12738. *close_handler = tmp_rh->close_handler;
  12739. } else if (handler_type == REQUEST_HANDLER) {
  12740. if (tmp_rh->removing) {
  12741. /* Treat as none found */
  12742. step = 2;
  12743. break;
  12744. }
  12745. *handler = tmp_rh->handler;
  12746. /* Acquire handler and give it back */
  12747. tmp_rh->refcount++;
  12748. *handler_info = tmp_rh;
  12749. } else { /* AUTH_HANDLER */
  12750. *auth_handler = tmp_rh->auth_handler;
  12751. }
  12752. *cbdata = tmp_rh->cbdata;
  12753. mg_unlock_context(conn->phys_ctx);
  12754. return 1;
  12755. }
  12756. }
  12757. }
  12758. mg_unlock_context(conn->phys_ctx);
  12759. }
  12760. return 0; /* none found */
  12761. }
  12762. /* Check if the script file is in a path, allowed for script files.
  12763. * This can be used if uploading files is possible not only for the server
  12764. * admin, and the upload mechanism does not check the file extension.
  12765. */
  12766. static int
  12767. is_in_script_path(const struct mg_connection *conn, const char *path)
  12768. {
  12769. /* TODO (Feature): Add config value for allowed script path.
  12770. * Default: All allowed. */
  12771. (void)conn;
  12772. (void)path;
  12773. return 1;
  12774. }
  12775. #if defined(USE_WEBSOCKET) && defined(MG_EXPERIMENTAL_INTERFACES)
  12776. static int
  12777. experimental_websocket_client_data_wrapper(struct mg_connection *conn,
  12778. int bits,
  12779. char *data,
  12780. size_t len,
  12781. void *cbdata)
  12782. {
  12783. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12784. if (pcallbacks->websocket_data) {
  12785. return pcallbacks->websocket_data(conn, bits, data, len);
  12786. }
  12787. /* No handler set - assume "OK" */
  12788. return 1;
  12789. }
  12790. static void
  12791. experimental_websocket_client_close_wrapper(const struct mg_connection *conn,
  12792. void *cbdata)
  12793. {
  12794. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  12795. if (pcallbacks->connection_close) {
  12796. pcallbacks->connection_close(conn);
  12797. }
  12798. }
  12799. #endif
  12800. /* Decrement recount of handler. conn must not be NULL, handler_info may be NULL
  12801. */
  12802. static void
  12803. release_handler_ref(struct mg_connection *conn,
  12804. struct mg_handler_info *handler_info)
  12805. {
  12806. if (handler_info != NULL) {
  12807. /* Use context lock for ref counter */
  12808. mg_lock_context(conn->phys_ctx);
  12809. handler_info->refcount--;
  12810. mg_unlock_context(conn->phys_ctx);
  12811. }
  12812. }
  12813. /* This is the heart of the Civetweb's logic.
  12814. * This function is called when the request is read, parsed and validated,
  12815. * and Civetweb must decide what action to take: serve a file, or
  12816. * a directory, or call embedded function, etcetera. */
  12817. static void
  12818. handle_request(struct mg_connection *conn)
  12819. {
  12820. struct mg_request_info *ri = &conn->request_info;
  12821. char path[UTF8_PATH_MAX];
  12822. int uri_len, ssl_index;
  12823. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  12824. is_put_or_delete_request = 0, is_callback_resource = 0,
  12825. is_template_text_file = 0, is_webdav_request = 0;
  12826. int i;
  12827. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12828. mg_request_handler callback_handler = NULL;
  12829. struct mg_handler_info *handler_info = NULL;
  12830. struct mg_websocket_subprotocols *subprotocols;
  12831. mg_websocket_connect_handler ws_connect_handler = NULL;
  12832. mg_websocket_ready_handler ws_ready_handler = NULL;
  12833. mg_websocket_data_handler ws_data_handler = NULL;
  12834. mg_websocket_close_handler ws_close_handler = NULL;
  12835. void *callback_data = NULL;
  12836. mg_authorization_handler auth_handler = NULL;
  12837. void *auth_callback_data = NULL;
  12838. int handler_type;
  12839. time_t curtime = time(NULL);
  12840. char date[64];
  12841. char *tmp;
  12842. path[0] = 0;
  12843. /* 0. Reset internal state (required for HTTP/2 proxy) */
  12844. conn->request_state = 0;
  12845. /* 1. get the request url */
  12846. /* 1.1. split into url and query string */
  12847. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  12848. != NULL) {
  12849. *((char *)conn->request_info.query_string++) = '\0';
  12850. }
  12851. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  12852. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  12853. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  12854. if (ssl_index >= 0) {
  12855. int port = (int)ntohs(USA_IN_PORT_UNSAFE(
  12856. &(conn->phys_ctx->listening_sockets[ssl_index].lsa)));
  12857. redirect_to_https_port(conn, port);
  12858. } else {
  12859. /* A http to https forward port has been specified,
  12860. * but no https port to forward to. */
  12861. mg_send_http_error(conn,
  12862. 503,
  12863. "%s",
  12864. "Error: SSL forward not configured properly");
  12865. mg_cry_internal(conn,
  12866. "%s",
  12867. "Can not redirect to SSL, no SSL port available");
  12868. }
  12869. return;
  12870. }
  12871. uri_len = (int)strlen(ri->local_uri);
  12872. /* 1.3. decode url (if config says so) */
  12873. if (should_decode_url(conn)) {
  12874. url_decode_in_place((char *)ri->local_uri);
  12875. }
  12876. /* URL decode the query-string only if explicitly set in the configuration
  12877. */
  12878. if (conn->request_info.query_string) {
  12879. if (should_decode_query_string(conn)) {
  12880. url_decode_in_place((char *)conn->request_info.query_string);
  12881. }
  12882. }
  12883. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is not
  12884. * possible. The fact that we cleaned the URI is stored in that the
  12885. * pointer to ri->local_ur and ri->local_uri_raw are now different.
  12886. * ri->local_uri_raw still points to memory allocated in
  12887. * worker_thread_run(). ri->local_uri is private to the request so we
  12888. * don't have to use preallocated memory here. */
  12889. tmp = mg_strdup(ri->local_uri_raw);
  12890. if (!tmp) {
  12891. /* Out of memory. We cannot do anything reasonable here. */
  12892. return;
  12893. }
  12894. remove_dot_segments(tmp);
  12895. ri->local_uri = tmp;
  12896. /* step 1. completed, the url is known now */
  12897. DEBUG_TRACE("REQUEST: %s %s", ri->request_method, ri->local_uri);
  12898. /* 2. if this ip has limited speed, set it for this connection */
  12899. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  12900. &conn->client.rsa,
  12901. ri->local_uri);
  12902. /* 3. call a "handle everything" callback, if registered */
  12903. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  12904. /* Note that since V1.7 the "begin_request" function is called
  12905. * before an authorization check. If an authorization check is
  12906. * required, use a request_handler instead. */
  12907. i = conn->phys_ctx->callbacks.begin_request(conn);
  12908. if (i > 0) {
  12909. /* callback already processed the request. Store the
  12910. return value as a status code for the access log. */
  12911. conn->status_code = i;
  12912. if (!conn->must_close) {
  12913. discard_unread_request_data(conn);
  12914. }
  12915. DEBUG_TRACE("%s", "begin_request handled request");
  12916. return;
  12917. } else if (i == 0) {
  12918. /* civetweb should process the request */
  12919. } else {
  12920. /* unspecified - may change with the next version */
  12921. DEBUG_TRACE("%s", "done (undocumented behavior)");
  12922. return;
  12923. }
  12924. }
  12925. /* request not yet handled by a handler or redirect, so the request
  12926. * is processed here */
  12927. /* 4. Check for CORS preflight requests and handle them (if configured).
  12928. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  12929. */
  12930. if (!strcmp(ri->request_method, "OPTIONS")) {
  12931. /* Send a response to CORS preflights only if
  12932. * access_control_allow_methods is not NULL and not an empty string.
  12933. * In this case, scripts can still handle CORS. */
  12934. const char *cors_meth_cfg =
  12935. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  12936. const char *cors_orig_cfg =
  12937. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  12938. const char *cors_origin =
  12939. get_header(ri->http_headers, ri->num_headers, "Origin");
  12940. const char *cors_acrm = get_header(ri->http_headers,
  12941. ri->num_headers,
  12942. "Access-Control-Request-Method");
  12943. /* Todo: check if cors_origin is in cors_orig_cfg.
  12944. * Or, let the client check this. */
  12945. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  12946. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  12947. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  12948. /* This is a valid CORS preflight, and the server is configured
  12949. * to handle it automatically. */
  12950. const char *cors_acrh =
  12951. get_header(ri->http_headers,
  12952. ri->num_headers,
  12953. "Access-Control-Request-Headers");
  12954. const char *cors_cred_cfg =
  12955. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_CREDENTIALS];
  12956. const char *cors_exphdr_cfg =
  12957. conn->dom_ctx->config[ACCESS_CONTROL_EXPOSE_HEADERS];
  12958. gmt_time_string(date, sizeof(date), &curtime);
  12959. mg_printf(conn,
  12960. "HTTP/1.1 200 OK\r\n"
  12961. "Date: %s\r\n"
  12962. "Access-Control-Allow-Origin: %s\r\n"
  12963. "Access-Control-Allow-Methods: %s\r\n"
  12964. "Content-Length: 0\r\n"
  12965. "Connection: %s\r\n",
  12966. date,
  12967. cors_orig_cfg,
  12968. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  12969. suggest_connection_header(conn));
  12970. if (cors_cred_cfg && *cors_cred_cfg) {
  12971. mg_printf(conn,
  12972. "Access-Control-Allow-Credentials: %s\r\n",
  12973. cors_cred_cfg);
  12974. }
  12975. if (cors_exphdr_cfg && *cors_exphdr_cfg) {
  12976. mg_printf(conn,
  12977. "Access-Control-Expose-Headers: %s\r\n",
  12978. cors_exphdr_cfg);
  12979. }
  12980. if (cors_acrh || (cors_cred_cfg && *cors_cred_cfg)) {
  12981. /* CORS request is asking for additional headers */
  12982. const char *cors_hdr_cfg =
  12983. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  12984. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  12985. /* Allow only if access_control_allow_headers is
  12986. * not NULL and not an empty string. If this
  12987. * configuration is set to *, allow everything.
  12988. * Otherwise this configuration must be a list
  12989. * of allowed HTTP header names. */
  12990. mg_printf(conn,
  12991. "Access-Control-Allow-Headers: %s\r\n",
  12992. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  12993. : cors_hdr_cfg));
  12994. }
  12995. }
  12996. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  12997. mg_printf(conn, "\r\n");
  12998. DEBUG_TRACE("%s", "OPTIONS done");
  12999. return;
  13000. }
  13001. }
  13002. /* 5. interpret the url to find out how the request must be handled
  13003. */
  13004. /* 5.1. first test, if the request targets the regular http(s)://
  13005. * protocol namespace or the websocket ws(s):// protocol namespace.
  13006. */
  13007. is_websocket_request = (conn->protocol_type == PROTOCOL_TYPE_WEBSOCKET);
  13008. #if defined(USE_WEBSOCKET)
  13009. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  13010. #else
  13011. handler_type = REQUEST_HANDLER;
  13012. #endif /* defined(USE_WEBSOCKET) */
  13013. if (is_websocket_request) {
  13014. HTTP1_only;
  13015. }
  13016. /* 5.2. check if the request will be handled by a callback */
  13017. if (get_request_handler(conn,
  13018. handler_type,
  13019. &callback_handler,
  13020. &subprotocols,
  13021. &ws_connect_handler,
  13022. &ws_ready_handler,
  13023. &ws_data_handler,
  13024. &ws_close_handler,
  13025. NULL,
  13026. &callback_data,
  13027. &handler_info)) {
  13028. /* 5.2.1. A callback will handle this request. All requests
  13029. * handled by a callback have to be considered as requests
  13030. * to a script resource. */
  13031. is_callback_resource = 1;
  13032. is_script_resource = 1;
  13033. is_put_or_delete_request = is_put_or_delete_method(conn);
  13034. /* Never handle a C callback according to File WebDav rules,
  13035. * even if it is a webdav method */
  13036. is_webdav_request = 0; /* is_civetweb_webdav_method(conn); */
  13037. } else {
  13038. no_callback_resource:
  13039. /* 5.2.2. No callback is responsible for this request. The URI
  13040. * addresses a file based resource (static content or Lua/cgi
  13041. * scripts in the file system). */
  13042. is_callback_resource = 0;
  13043. interpret_uri(conn,
  13044. path,
  13045. sizeof(path),
  13046. &file.stat,
  13047. &is_found,
  13048. &is_script_resource,
  13049. &is_websocket_request,
  13050. &is_put_or_delete_request,
  13051. &is_webdav_request,
  13052. &is_template_text_file);
  13053. }
  13054. /* 5.3. A webdav request (PROPFIND/PROPPATCH/LOCK/UNLOCK) */
  13055. if (is_webdav_request) {
  13056. /* TODO: Do we need a config option? */
  13057. const char *webdav_enable = conn->dom_ctx->config[ENABLE_WEBDAV];
  13058. if (webdav_enable[0] != 'y') {
  13059. mg_send_http_error(conn,
  13060. 405,
  13061. "%s method not allowed",
  13062. conn->request_info.request_method);
  13063. DEBUG_TRACE("%s", "webdav rejected");
  13064. return;
  13065. }
  13066. }
  13067. /* 6. authorization check */
  13068. /* 6.1. a custom authorization handler is installed */
  13069. if (get_request_handler(conn,
  13070. AUTH_HANDLER,
  13071. NULL,
  13072. NULL,
  13073. NULL,
  13074. NULL,
  13075. NULL,
  13076. NULL,
  13077. &auth_handler,
  13078. &auth_callback_data,
  13079. NULL)) {
  13080. if (!auth_handler(conn, auth_callback_data)) {
  13081. /* Callback handler will not be used anymore. Release it */
  13082. release_handler_ref(conn, handler_info);
  13083. DEBUG_TRACE("%s", "auth handler rejected request");
  13084. return;
  13085. }
  13086. } else if (is_put_or_delete_request && !is_script_resource
  13087. && !is_callback_resource) {
  13088. HTTP1_only;
  13089. /* 6.2. this request is a PUT/DELETE to a real file */
  13090. /* 6.2.1. thus, the server must have real files */
  13091. #if defined(NO_FILES)
  13092. if (1) {
  13093. #else
  13094. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL
  13095. || conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL) {
  13096. #endif
  13097. /* This code path will not be called for request handlers */
  13098. DEBUG_ASSERT(handler_info == NULL);
  13099. /* This server does not have any real files, thus the
  13100. * PUT/DELETE methods are not valid. */
  13101. mg_send_http_error(conn,
  13102. 405,
  13103. "%s method not allowed",
  13104. conn->request_info.request_method);
  13105. DEBUG_TRACE("%s", "all file based put/delete requests rejected");
  13106. return;
  13107. }
  13108. #if !defined(NO_FILES)
  13109. /* 6.2.2. Check if put authorization for static files is
  13110. * available.
  13111. */
  13112. if (!is_authorized_for_put(conn)) {
  13113. send_authorization_request(conn, NULL);
  13114. DEBUG_TRACE("%s", "file write needs authorization");
  13115. return;
  13116. }
  13117. #endif
  13118. } else {
  13119. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  13120. * or it is a PUT or DELETE request to a resource that does not
  13121. * correspond to a file. Check authorization. */
  13122. if (!check_authorization(conn, path)) {
  13123. send_authorization_request(conn, NULL);
  13124. /* Callback handler will not be used anymore. Release it */
  13125. release_handler_ref(conn, handler_info);
  13126. DEBUG_TRACE("%s", "access authorization required");
  13127. return;
  13128. }
  13129. }
  13130. /* request is authorized or does not need authorization */
  13131. /* 7. check if there are request handlers for this uri */
  13132. if (is_callback_resource) {
  13133. HTTP1_only;
  13134. if (!is_websocket_request) {
  13135. i = callback_handler(conn, callback_data);
  13136. /* Callback handler will not be used anymore. Release it */
  13137. release_handler_ref(conn, handler_info);
  13138. if (i > 0) {
  13139. /* Do nothing, callback has served the request. Store
  13140. * then return value as status code for the log and discard
  13141. * all data from the client not used by the callback. */
  13142. conn->status_code = i;
  13143. if (!conn->must_close) {
  13144. discard_unread_request_data(conn);
  13145. }
  13146. } else {
  13147. /* The handler did NOT handle the request. */
  13148. /* Some proper reactions would be:
  13149. * a) close the connections without sending anything
  13150. * b) send a 404 not found
  13151. * c) try if there is a file matching the URI
  13152. * It would be possible to do a, b or c in the callback
  13153. * implementation, and return 1 - we cannot do anything
  13154. * here, that is not possible in the callback.
  13155. *
  13156. * TODO: What would be the best reaction here?
  13157. * (Note: The reaction may change, if there is a better
  13158. * idea.)
  13159. */
  13160. /* For the moment, use option c: We look for a proper file,
  13161. * but since a file request is not always a script resource,
  13162. * the authorization check might be different. */
  13163. callback_handler = NULL;
  13164. /* Here we are at a dead end:
  13165. * According to URI matching, a callback should be
  13166. * responsible for handling the request,
  13167. * we called it, but the callback declared itself
  13168. * not responsible.
  13169. * We use a goto here, to get out of this dead end,
  13170. * and continue with the default handling.
  13171. * A goto here is simpler and better to understand
  13172. * than some curious loop. */
  13173. goto no_callback_resource;
  13174. }
  13175. } else {
  13176. #if defined(USE_WEBSOCKET)
  13177. handle_websocket_request(conn,
  13178. path,
  13179. is_callback_resource,
  13180. subprotocols,
  13181. ws_connect_handler,
  13182. ws_ready_handler,
  13183. ws_data_handler,
  13184. ws_close_handler,
  13185. callback_data);
  13186. #endif
  13187. }
  13188. DEBUG_TRACE("%s", "websocket handling done");
  13189. return;
  13190. }
  13191. /* 8. handle websocket requests */
  13192. #if defined(USE_WEBSOCKET)
  13193. if (is_websocket_request) {
  13194. HTTP1_only;
  13195. if (is_script_resource) {
  13196. if (is_in_script_path(conn, path)) {
  13197. /* Websocket Lua script */
  13198. handle_websocket_request(conn,
  13199. path,
  13200. 0 /* Lua Script */,
  13201. NULL,
  13202. NULL,
  13203. NULL,
  13204. NULL,
  13205. NULL,
  13206. conn->phys_ctx->user_data);
  13207. } else {
  13208. /* Script was in an illegal path */
  13209. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13210. }
  13211. } else {
  13212. mg_send_http_error(conn, 404, "%s", "Not found");
  13213. }
  13214. DEBUG_TRACE("%s", "websocket script done");
  13215. return;
  13216. } else
  13217. #endif
  13218. #if defined(NO_FILES)
  13219. /* 9a. In case the server uses only callbacks, this uri is
  13220. * unknown.
  13221. * Then, all request handling ends here. */
  13222. mg_send_http_error(conn, 404, "%s", "Not Found");
  13223. #else
  13224. /* 9b. This request is either for a static file or resource handled
  13225. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  13226. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  13227. mg_send_http_error(conn, 404, "%s", "Not Found");
  13228. DEBUG_TRACE("%s", "no document root available");
  13229. return;
  13230. }
  13231. /* 10. Request is handled by a script */
  13232. if (is_script_resource) {
  13233. HTTP1_only;
  13234. handle_file_based_request(conn, path, &file);
  13235. DEBUG_TRACE("%s", "script handling done");
  13236. return;
  13237. }
  13238. /* Request was not handled by a callback or script. It will be
  13239. * handled by a server internal method. */
  13240. /* 11. Handle put/delete/mkcol requests */
  13241. if (is_put_or_delete_request) {
  13242. HTTP1_only;
  13243. /* 11.1. PUT method */
  13244. if (!strcmp(ri->request_method, "PUT")) {
  13245. put_file(conn, path);
  13246. DEBUG_TRACE("handling %s request to %s done",
  13247. ri->request_method,
  13248. path);
  13249. return;
  13250. }
  13251. /* 11.2. DELETE method */
  13252. if (!strcmp(ri->request_method, "DELETE")) {
  13253. delete_file(conn, path);
  13254. DEBUG_TRACE("handling %s request to %s done",
  13255. ri->request_method,
  13256. path);
  13257. return;
  13258. }
  13259. /* 11.3. MKCOL method */
  13260. if (!strcmp(ri->request_method, "MKCOL")) {
  13261. dav_mkcol(conn, path);
  13262. DEBUG_TRACE("handling %s request to %s done",
  13263. ri->request_method,
  13264. path);
  13265. return;
  13266. }
  13267. /* 11.4. MOVE method */
  13268. if (!strcmp(ri->request_method, "MOVE")) {
  13269. dav_move_file(conn, path, 0);
  13270. DEBUG_TRACE("handling %s request to %s done",
  13271. ri->request_method,
  13272. path);
  13273. return;
  13274. }
  13275. if (!strcmp(ri->request_method, "COPY")) {
  13276. dav_move_file(conn, path, 1);
  13277. DEBUG_TRACE("handling %s request to %s done",
  13278. ri->request_method,
  13279. path);
  13280. return;
  13281. }
  13282. /* 11.5. LOCK method */
  13283. if (!strcmp(ri->request_method, "LOCK")) {
  13284. dav_lock_file(conn, path);
  13285. DEBUG_TRACE("handling %s request to %s done",
  13286. ri->request_method,
  13287. path);
  13288. return;
  13289. }
  13290. /* 11.6. UNLOCK method */
  13291. if (!strcmp(ri->request_method, "UNLOCK")) {
  13292. dav_unlock_file(conn, path);
  13293. DEBUG_TRACE("handling %s request to %s done",
  13294. ri->request_method,
  13295. path);
  13296. return;
  13297. }
  13298. /* 11.7. PROPPATCH method */
  13299. if (!strcmp(ri->request_method, "PROPPATCH")) {
  13300. dav_proppatch(conn, path);
  13301. DEBUG_TRACE("handling %s request to %s done",
  13302. ri->request_method,
  13303. path);
  13304. return;
  13305. }
  13306. /* 11.8. Other methods, e.g.: PATCH
  13307. * This method is not supported for static resources,
  13308. * only for scripts (Lua, CGI) and callbacks. */
  13309. mg_send_http_error(conn,
  13310. 405,
  13311. "%s method not allowed",
  13312. conn->request_info.request_method);
  13313. DEBUG_TRACE("method %s on %s is not supported",
  13314. ri->request_method,
  13315. path);
  13316. return;
  13317. }
  13318. /* 11. File does not exist, or it was configured that it should be
  13319. * hidden */
  13320. if (!is_found || (must_hide_file(conn, path))) {
  13321. mg_send_http_error(conn, 404, "%s", "Not found");
  13322. DEBUG_TRACE("handling %s request to %s: file not found",
  13323. ri->request_method,
  13324. path);
  13325. return;
  13326. }
  13327. /* 12. Directory uris should end with a slash */
  13328. if (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)
  13329. && (ri->local_uri[uri_len - 1] != '/')) {
  13330. /* Path + server root */
  13331. size_t buflen = UTF8_PATH_MAX * 2 + 2;
  13332. char *new_path;
  13333. if (ri->query_string) {
  13334. buflen += strlen(ri->query_string);
  13335. }
  13336. new_path = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  13337. if (!new_path) {
  13338. mg_send_http_error(conn, 500, "out or memory");
  13339. } else {
  13340. mg_get_request_link(conn, new_path, buflen - 1);
  13341. strcat(new_path, "/");
  13342. if (ri->query_string) {
  13343. /* Append ? and query string */
  13344. strcat(new_path, "?");
  13345. strcat(new_path, ri->query_string);
  13346. }
  13347. mg_send_http_redirect(conn, new_path, 301);
  13348. mg_free(new_path);
  13349. }
  13350. DEBUG_TRACE("%s request to %s: directory redirection sent",
  13351. ri->request_method,
  13352. path);
  13353. return;
  13354. }
  13355. /* 13. Handle other methods than GET/HEAD */
  13356. /* 13.1. Handle PROPFIND */
  13357. if (!strcmp(ri->request_method, "PROPFIND")) {
  13358. handle_propfind(conn, path, &file.stat);
  13359. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13360. return;
  13361. }
  13362. /* 13.2. Handle OPTIONS for files */
  13363. if (!strcmp(ri->request_method, "OPTIONS")) {
  13364. /* This standard handler is only used for real files.
  13365. * Scripts should support the OPTIONS method themselves, to allow a
  13366. * maximum flexibility.
  13367. * Lua and CGI scripts may fully support CORS this way (including
  13368. * preflights). */
  13369. send_options(conn);
  13370. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13371. return;
  13372. }
  13373. /* 13.3. everything but GET and HEAD (e.g. POST) */
  13374. if ((0 != strcmp(ri->request_method, "GET"))
  13375. && (0 != strcmp(ri->request_method, "HEAD"))) {
  13376. mg_send_http_error(conn,
  13377. 405,
  13378. "%s method not allowed",
  13379. conn->request_info.request_method);
  13380. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13381. return;
  13382. }
  13383. /* 14. directories */
  13384. if (file.stat.is_directory) {
  13385. /* Substitute files have already been handled above. */
  13386. /* Here we can either generate and send a directory listing,
  13387. * or send an "access denied" error. */
  13388. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  13389. "yes")) {
  13390. handle_directory_request(conn, path);
  13391. } else {
  13392. mg_send_http_error(conn,
  13393. 403,
  13394. "%s",
  13395. "Error: Directory listing denied");
  13396. }
  13397. DEBUG_TRACE("handling %s request to %s done", ri->request_method, path);
  13398. return;
  13399. }
  13400. /* 15. Files with search/replace patterns: LSP and SSI */
  13401. if (is_template_text_file) {
  13402. HTTP1_only;
  13403. handle_file_based_request(conn, path, &file);
  13404. DEBUG_TRACE("handling %s request to %s done (template)",
  13405. ri->request_method,
  13406. path);
  13407. return;
  13408. }
  13409. /* 16. Static file - maybe cached */
  13410. #if !defined(NO_CACHING)
  13411. if ((!conn->in_error_handler) && is_not_modified(conn, &file.stat)) {
  13412. /* Send 304 "Not Modified" - this must not send any body data */
  13413. handle_not_modified_static_file_request(conn, &file);
  13414. DEBUG_TRACE("handling %s request to %s done (not modified)",
  13415. ri->request_method,
  13416. path);
  13417. return;
  13418. }
  13419. #endif /* !NO_CACHING */
  13420. /* 17. Static file - not cached */
  13421. handle_static_file_request(conn, path, &file, NULL, NULL);
  13422. DEBUG_TRACE("handling %s request to %s done (static)",
  13423. ri->request_method,
  13424. path);
  13425. #endif /* !defined(NO_FILES) */
  13426. }
  13427. #if !defined(NO_FILESYSTEMS)
  13428. static void
  13429. handle_file_based_request(struct mg_connection *conn,
  13430. const char *path,
  13431. struct mg_file *file)
  13432. {
  13433. #if !defined(NO_CGI)
  13434. int cgi_config_idx, inc, max;
  13435. #endif
  13436. if (!conn || !conn->dom_ctx) {
  13437. return;
  13438. }
  13439. #if defined(USE_LUA)
  13440. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  13441. path)
  13442. > 0) {
  13443. if (is_in_script_path(conn, path)) {
  13444. /* Lua server page: an SSI like page containing mostly plain
  13445. * html code plus some tags with server generated contents. */
  13446. handle_lsp_request(conn, path, file, NULL);
  13447. } else {
  13448. /* Script was in an illegal path */
  13449. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13450. }
  13451. return;
  13452. }
  13453. if (match_prefix_strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], path)
  13454. > 0) {
  13455. if (is_in_script_path(conn, path)) {
  13456. /* Lua in-server module script: a CGI like script used to
  13457. * generate the entire reply. */
  13458. mg_exec_lua_script(conn, path, NULL);
  13459. } else {
  13460. /* Script was in an illegal path */
  13461. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13462. }
  13463. return;
  13464. }
  13465. #endif
  13466. #if defined(USE_DUKTAPE)
  13467. if (match_prefix_strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  13468. path)
  13469. > 0) {
  13470. if (is_in_script_path(conn, path)) {
  13471. /* Call duktape to generate the page */
  13472. mg_exec_duktape_script(conn, path);
  13473. } else {
  13474. /* Script was in an illegal path */
  13475. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13476. }
  13477. return;
  13478. }
  13479. #endif
  13480. #if !defined(NO_CGI)
  13481. inc = CGI2_EXTENSIONS - CGI_EXTENSIONS;
  13482. max = PUT_DELETE_PASSWORDS_FILE - CGI_EXTENSIONS;
  13483. for (cgi_config_idx = 0; cgi_config_idx < max; cgi_config_idx += inc) {
  13484. if (conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx] != NULL) {
  13485. if (match_prefix_strlen(
  13486. conn->dom_ctx->config[CGI_EXTENSIONS + cgi_config_idx],
  13487. path)
  13488. > 0) {
  13489. if (is_in_script_path(conn, path)) {
  13490. /* CGI scripts may support all HTTP methods */
  13491. handle_cgi_request(conn, path, cgi_config_idx);
  13492. } else {
  13493. /* Script was in an illegal path */
  13494. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13495. }
  13496. return;
  13497. }
  13498. }
  13499. }
  13500. #endif /* !NO_CGI */
  13501. if (match_prefix_strlen(conn->dom_ctx->config[SSI_EXTENSIONS], path) > 0) {
  13502. if (is_in_script_path(conn, path)) {
  13503. handle_ssi_file_request(conn, path, file);
  13504. } else {
  13505. /* Script was in an illegal path */
  13506. mg_send_http_error(conn, 403, "%s", "Forbidden");
  13507. }
  13508. return;
  13509. }
  13510. #if !defined(NO_CACHING)
  13511. if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) {
  13512. /* Send 304 "Not Modified" - this must not send any body data */
  13513. handle_not_modified_static_file_request(conn, file);
  13514. return;
  13515. }
  13516. #endif /* !NO_CACHING */
  13517. handle_static_file_request(conn, path, file, NULL, NULL);
  13518. }
  13519. #endif /* NO_FILESYSTEMS */
  13520. static void
  13521. close_all_listening_sockets(struct mg_context *ctx)
  13522. {
  13523. unsigned int i;
  13524. if (!ctx) {
  13525. return;
  13526. }
  13527. for (i = 0; i < ctx->num_listening_sockets; i++) {
  13528. closesocket(ctx->listening_sockets[i].sock);
  13529. #if defined(USE_X_DOM_SOCKET)
  13530. /* For unix domain sockets, the socket name represents a file that has
  13531. * to be deleted. */
  13532. /* See
  13533. * https://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
  13534. */
  13535. if ((ctx->listening_sockets[i].lsa.sin.sin_family == AF_UNIX)
  13536. && (ctx->listening_sockets[i].sock != INVALID_SOCKET)) {
  13537. IGNORE_UNUSED_RESULT(
  13538. remove(ctx->listening_sockets[i].lsa.sun.sun_path));
  13539. }
  13540. #endif
  13541. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  13542. }
  13543. mg_free(ctx->listening_sockets);
  13544. ctx->listening_sockets = NULL;
  13545. mg_free(ctx->listening_socket_fds);
  13546. ctx->listening_socket_fds = NULL;
  13547. }
  13548. /* Valid listening port specification is: [ip_address:]port[s]
  13549. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  13550. * Examples for IPv6: [::]:80, [::1]:80,
  13551. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  13552. * see https://tools.ietf.org/html/rfc3513#section-2.2
  13553. * In order to bind to both, IPv4 and IPv6, you can either add
  13554. * both ports using 8080,[::]:8080, or the short form +8080.
  13555. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  13556. * one only accepting IPv4 the other only IPv6. +8080 creates
  13557. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  13558. * environment, they might work differently, or might not work
  13559. * at all - it must be tested what options work best in the
  13560. * relevant network environment.
  13561. */
  13562. static int
  13563. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  13564. {
  13565. unsigned int a, b, c, d;
  13566. unsigned port;
  13567. unsigned long portUL;
  13568. int len;
  13569. const char *cb;
  13570. char *endptr;
  13571. #if defined(USE_IPV6)
  13572. char buf[100] = {0};
  13573. #endif
  13574. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  13575. * Also, all-zeroes in the socket address means binding to all addresses
  13576. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  13577. memset(so, 0, sizeof(*so));
  13578. so->lsa.sin.sin_family = AF_INET;
  13579. *ip_version = 0;
  13580. /* Initialize len as invalid. */
  13581. port = 0;
  13582. len = 0;
  13583. /* Test for different ways to format this string */
  13584. if (sscanf(vec->ptr,
  13585. "%u.%u.%u.%u:%u%n",
  13586. &a,
  13587. &b,
  13588. &c,
  13589. &d,
  13590. &port,
  13591. &len) // NOLINT(cert-err34-c) 'sscanf' used to convert a string
  13592. // to an integer value, but function will not report
  13593. // conversion errors; consider using 'strtol' instead
  13594. == 5) {
  13595. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  13596. so->lsa.sin.sin_addr.s_addr =
  13597. htonl((a << 24) | (b << 16) | (c << 8) | d);
  13598. so->lsa.sin.sin_port = htons((uint16_t)port);
  13599. *ip_version = 4;
  13600. #if defined(USE_IPV6)
  13601. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  13602. && ((size_t)len <= vec->len)
  13603. && mg_inet_pton(
  13604. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {
  13605. /* IPv6 address, examples: see above */
  13606. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  13607. */
  13608. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13609. *ip_version = 6;
  13610. #endif
  13611. } else if ((vec->ptr[0] == '+')
  13612. && (sscanf(vec->ptr + 1, "%u%n", &port, &len)
  13613. == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13614. // string to an integer value, but function will not
  13615. // report conversion errors; consider using 'strtol'
  13616. // instead
  13617. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  13618. /* Add 1 to len for the + character we skipped before */
  13619. len++;
  13620. #if defined(USE_IPV6)
  13621. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  13622. so->lsa.sin6.sin6_family = AF_INET6;
  13623. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13624. *ip_version = 4 + 6;
  13625. #else
  13626. /* Bind to IPv4 only, since IPv6 is not built in. */
  13627. so->lsa.sin.sin_port = htons((uint16_t)port);
  13628. *ip_version = 4;
  13629. #endif
  13630. } else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))
  13631. && (vec->ptr != endptr)) {
  13632. len = (int)(endptr - vec->ptr);
  13633. port = (uint16_t)portUL;
  13634. /* If only port is specified, bind to IPv4, INADDR_ANY */
  13635. so->lsa.sin.sin_port = htons((uint16_t)port);
  13636. *ip_version = 4;
  13637. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  13638. /* String could be a hostname. This check algorithm
  13639. * will only work for RFC 952 compliant hostnames,
  13640. * starting with a letter, containing only letters,
  13641. * digits and hyphen ('-'). Newer specs may allow
  13642. * more, but this is not guaranteed here, since it
  13643. * may interfere with rules for port option lists. */
  13644. /* According to RFC 1035, hostnames are restricted to 255 characters
  13645. * in total (63 between two dots). */
  13646. char hostname[256];
  13647. size_t hostnlen = (size_t)(cb - vec->ptr);
  13648. if ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {
  13649. /* This would be invalid in any case */
  13650. *ip_version = 0;
  13651. return 0;
  13652. }
  13653. mg_strlcpy(hostname, vec->ptr, hostnlen + 1);
  13654. if (mg_inet_pton(
  13655. AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {
  13656. if (sscanf(cb + 1, "%u%n", &port, &len)
  13657. == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a
  13658. // string to an integer value, but function will not
  13659. // report conversion errors; consider using 'strtol'
  13660. // instead
  13661. *ip_version = 4;
  13662. so->lsa.sin.sin_port = htons((uint16_t)port);
  13663. len += (int)(hostnlen + 1);
  13664. } else {
  13665. len = 0;
  13666. }
  13667. #if defined(USE_IPV6)
  13668. } else if (mg_inet_pton(AF_INET6,
  13669. hostname,
  13670. &so->lsa.sin6,
  13671. sizeof(so->lsa.sin6),
  13672. 1)) {
  13673. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  13674. *ip_version = 6;
  13675. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  13676. len += (int)(hostnlen + 1);
  13677. } else {
  13678. len = 0;
  13679. }
  13680. #endif
  13681. } else {
  13682. len = 0;
  13683. }
  13684. #if defined(USE_X_DOM_SOCKET)
  13685. } else if (vec->ptr[0] == 'x') {
  13686. /* unix (linux) domain socket */
  13687. if (vec->len < sizeof(so->lsa.sun.sun_path)) {
  13688. len = vec->len;
  13689. so->lsa.sun.sun_family = AF_UNIX;
  13690. memset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));
  13691. memcpy(so->lsa.sun.sun_path, (char *)vec->ptr + 1, vec->len - 1);
  13692. port = 0;
  13693. *ip_version = 99;
  13694. } else {
  13695. /* String too long */
  13696. len = 0;
  13697. }
  13698. #endif
  13699. } else {
  13700. /* Parsing failure. */
  13701. len = 0;
  13702. }
  13703. /* sscanf and the option splitting code ensure the following condition
  13704. * Make sure the port is valid and vector ends with the port, 'o', 's', or
  13705. * 'r' */
  13706. if ((len > 0) && (is_valid_port(port))) {
  13707. int bad_suffix = 0;
  13708. /* Parse any suffix character(s) after the port number */
  13709. for (size_t i = len; i < vec->len; i++) {
  13710. unsigned char *opt = NULL;
  13711. switch (vec->ptr[i]) {
  13712. case 'o':
  13713. opt = &so->is_optional;
  13714. break;
  13715. case 'r':
  13716. opt = &so->ssl_redir;
  13717. break;
  13718. case 's':
  13719. opt = &so->is_ssl;
  13720. break;
  13721. default: /* empty */
  13722. break;
  13723. }
  13724. if ((opt) && (*opt == 0))
  13725. *opt = 1;
  13726. else {
  13727. bad_suffix = 1;
  13728. break;
  13729. }
  13730. }
  13731. if ((bad_suffix == 0) && ((so->is_ssl == 0) || (so->ssl_redir == 0))) {
  13732. return 1;
  13733. }
  13734. }
  13735. /* Reset ip_version to 0 if there is an error */
  13736. *ip_version = 0;
  13737. return 0;
  13738. }
  13739. /* Is there any SSL port in use? */
  13740. static int
  13741. is_ssl_port_used(const char *ports)
  13742. {
  13743. if (ports) {
  13744. /* There are several different allowed syntax variants:
  13745. * - "80" for a single port using every network interface
  13746. * - "localhost:80" for a single port using only localhost
  13747. * - "80,localhost:8080" for two ports, one bound to localhost
  13748. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  13749. * to IPv4 localhost, one to IPv6 localhost
  13750. * - "+80" use port 80 for IPv4 and IPv6
  13751. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  13752. * for both: IPv4 and IPv4
  13753. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  13754. * additionally port 8080 bound to localhost connections
  13755. *
  13756. * If we just look for 's' anywhere in the string, "localhost:80"
  13757. * will be detected as SSL (false positive).
  13758. * Looking for 's' after a digit may cause false positives in
  13759. * "my24service:8080".
  13760. * Looking from 's' backward if there are only ':' and numbers
  13761. * before will not work for "24service:8080" (non SSL, port 8080)
  13762. * or "24s" (SSL, port 24).
  13763. *
  13764. * Remark: Initially hostnames were not allowed to start with a
  13765. * digit (according to RFC 952), this was allowed later (RFC 1123,
  13766. * Section 2.1).
  13767. *
  13768. * To get this correct, the entire string must be parsed as a whole,
  13769. * reading it as a list element for element and parsing with an
  13770. * algorithm equivalent to parse_port_string.
  13771. *
  13772. * In fact, we use local interface names here, not arbitrary
  13773. * hostnames, so in most cases the only name will be "localhost".
  13774. *
  13775. * So, for now, we use this simple algorithm, that may still return
  13776. * a false positive in bizarre cases.
  13777. */
  13778. int i;
  13779. int portslen = (int)strlen(ports);
  13780. char prevIsNumber = 0;
  13781. for (i = 0; i < portslen; i++) {
  13782. if (prevIsNumber) {
  13783. int suffixCharIdx = (ports[i] == 'o')
  13784. ? (i + 1)
  13785. : i; /* allow "os" and "or" suffixes */
  13786. if (ports[suffixCharIdx] == 's'
  13787. || ports[suffixCharIdx] == 'r') {
  13788. return 1;
  13789. }
  13790. }
  13791. if (ports[i] >= '0' && ports[i] <= '9') {
  13792. prevIsNumber = 1;
  13793. } else {
  13794. prevIsNumber = 0;
  13795. }
  13796. }
  13797. }
  13798. return 0;
  13799. }
  13800. static int
  13801. set_ports_option(struct mg_context *phys_ctx)
  13802. {
  13803. const char *list;
  13804. int on = 1;
  13805. #if defined(USE_IPV6)
  13806. int off = 0;
  13807. #endif
  13808. struct vec vec;
  13809. struct socket so, *ptr;
  13810. struct mg_pollfd *pfd;
  13811. union usa usa;
  13812. socklen_t len;
  13813. int ip_version;
  13814. int portsTotal = 0;
  13815. int portsOk = 0;
  13816. const char *opt_txt;
  13817. long opt_listen_backlog;
  13818. if (!phys_ctx) {
  13819. return 0;
  13820. }
  13821. memset(&so, 0, sizeof(so));
  13822. memset(&usa, 0, sizeof(usa));
  13823. len = sizeof(usa);
  13824. list = phys_ctx->dd.config[LISTENING_PORTS];
  13825. while ((list = next_option(list, &vec, NULL)) != NULL) {
  13826. portsTotal++;
  13827. if (!parse_port_string(&vec, &so, &ip_version)) {
  13828. mg_cry_ctx_internal(
  13829. phys_ctx,
  13830. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  13831. (int)vec.len,
  13832. vec.ptr,
  13833. portsTotal,
  13834. "[IP_ADDRESS:]PORT[s|r]");
  13835. continue;
  13836. }
  13837. #if !defined(NO_SSL)
  13838. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  13839. mg_cry_ctx_internal(phys_ctx,
  13840. "Cannot add SSL socket (entry %i)",
  13841. portsTotal);
  13842. continue;
  13843. }
  13844. #endif
  13845. /* Create socket. */
  13846. /* For a list of protocol numbers (e.g., TCP==6) see:
  13847. * https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  13848. */
  13849. if ((so.sock =
  13850. socket(so.lsa.sa.sa_family,
  13851. SOCK_STREAM,
  13852. (ip_version == 99) ? (/* LOCAL */ 0) : (/* TCP */ 6)))
  13853. == INVALID_SOCKET) {
  13854. mg_cry_ctx_internal(phys_ctx,
  13855. "cannot create socket (entry %i)",
  13856. portsTotal);
  13857. continue;
  13858. }
  13859. #if defined(_WIN32)
  13860. /* Windows SO_REUSEADDR lets many procs binds to a
  13861. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  13862. * if someone already has the socket -- DTL */
  13863. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  13864. * Windows might need a few seconds before
  13865. * the same port can be used again in the
  13866. * same process, so a short Sleep may be
  13867. * required between mg_stop and mg_start.
  13868. */
  13869. if (setsockopt(so.sock,
  13870. SOL_SOCKET,
  13871. SO_EXCLUSIVEADDRUSE,
  13872. (SOCK_OPT_TYPE)&on,
  13873. sizeof(on))
  13874. != 0) {
  13875. /* Set reuse option, but don't abort on errors. */
  13876. mg_cry_ctx_internal(
  13877. phys_ctx,
  13878. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  13879. portsTotal);
  13880. }
  13881. #else
  13882. if (setsockopt(so.sock,
  13883. SOL_SOCKET,
  13884. SO_REUSEADDR,
  13885. (SOCK_OPT_TYPE)&on,
  13886. sizeof(on))
  13887. != 0) {
  13888. /* Set reuse option, but don't abort on errors. */
  13889. mg_cry_ctx_internal(
  13890. phys_ctx,
  13891. "cannot set socket option SO_REUSEADDR (entry %i)",
  13892. portsTotal);
  13893. }
  13894. #endif
  13895. #if defined(USE_X_DOM_SOCKET)
  13896. if (ip_version == 99) {
  13897. /* Unix domain socket */
  13898. } else
  13899. #endif
  13900. if (ip_version > 4) {
  13901. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  13902. #if defined(USE_IPV6)
  13903. if (ip_version > 6) {
  13904. if (so.lsa.sa.sa_family == AF_INET6
  13905. && setsockopt(so.sock,
  13906. IPPROTO_IPV6,
  13907. IPV6_V6ONLY,
  13908. (void *)&off,
  13909. sizeof(off))
  13910. != 0) {
  13911. /* Set IPv6 only option, but don't abort on errors. */
  13912. mg_cry_ctx_internal(phys_ctx,
  13913. "cannot set socket option "
  13914. "IPV6_V6ONLY=off (entry %i)",
  13915. portsTotal);
  13916. }
  13917. } else {
  13918. if (so.lsa.sa.sa_family == AF_INET6
  13919. && setsockopt(so.sock,
  13920. IPPROTO_IPV6,
  13921. IPV6_V6ONLY,
  13922. (void *)&on,
  13923. sizeof(on))
  13924. != 0) {
  13925. /* Set IPv6 only option, but don't abort on errors. */
  13926. mg_cry_ctx_internal(phys_ctx,
  13927. "cannot set socket option "
  13928. "IPV6_V6ONLY=on (entry %i)",
  13929. portsTotal);
  13930. }
  13931. }
  13932. #else
  13933. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  13934. closesocket(so.sock);
  13935. so.sock = INVALID_SOCKET;
  13936. continue;
  13937. #endif
  13938. }
  13939. if (so.lsa.sa.sa_family == AF_INET) {
  13940. len = sizeof(so.lsa.sin);
  13941. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13942. mg_cry_ctx_internal(phys_ctx,
  13943. "cannot bind to %.*s: %d (%s)",
  13944. (int)vec.len,
  13945. vec.ptr,
  13946. (int)ERRNO,
  13947. strerror(errno));
  13948. closesocket(so.sock);
  13949. so.sock = INVALID_SOCKET;
  13950. if (so.is_optional) {
  13951. portsOk++; /* it's okay if we couldn't bind, this port is
  13952. optional anyway */
  13953. }
  13954. continue;
  13955. }
  13956. }
  13957. #if defined(USE_IPV6)
  13958. else if (so.lsa.sa.sa_family == AF_INET6) {
  13959. len = sizeof(so.lsa.sin6);
  13960. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13961. mg_cry_ctx_internal(phys_ctx,
  13962. "cannot bind to IPv6 %.*s: %d (%s)",
  13963. (int)vec.len,
  13964. vec.ptr,
  13965. (int)ERRNO,
  13966. strerror(errno));
  13967. closesocket(so.sock);
  13968. so.sock = INVALID_SOCKET;
  13969. if (so.is_optional) {
  13970. portsOk++; /* it's okay if we couldn't bind, this port is
  13971. optional anyway */
  13972. }
  13973. continue;
  13974. }
  13975. }
  13976. #endif
  13977. #if defined(USE_X_DOM_SOCKET)
  13978. else if (so.lsa.sa.sa_family == AF_UNIX) {
  13979. len = sizeof(so.lsa.sun);
  13980. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  13981. mg_cry_ctx_internal(phys_ctx,
  13982. "cannot bind to unix socket %s: %d (%s)",
  13983. so.lsa.sun.sun_path,
  13984. (int)ERRNO,
  13985. strerror(errno));
  13986. closesocket(so.sock);
  13987. so.sock = INVALID_SOCKET;
  13988. if (so.is_optional) {
  13989. portsOk++; /* it's okay if we couldn't bind, this port is
  13990. optional anyway */
  13991. }
  13992. continue;
  13993. }
  13994. }
  13995. #endif
  13996. else {
  13997. mg_cry_ctx_internal(
  13998. phys_ctx,
  13999. "cannot bind: address family not supported (entry %i)",
  14000. portsTotal);
  14001. closesocket(so.sock);
  14002. so.sock = INVALID_SOCKET;
  14003. continue;
  14004. }
  14005. opt_txt = phys_ctx->dd.config[LISTEN_BACKLOG_SIZE];
  14006. opt_listen_backlog = strtol(opt_txt, NULL, 10);
  14007. if ((opt_listen_backlog > INT_MAX) || (opt_listen_backlog < 1)) {
  14008. mg_cry_ctx_internal(phys_ctx,
  14009. "%s value \"%s\" is invalid",
  14010. config_options[LISTEN_BACKLOG_SIZE].name,
  14011. opt_txt);
  14012. closesocket(so.sock);
  14013. so.sock = INVALID_SOCKET;
  14014. continue;
  14015. }
  14016. if (listen(so.sock, (int)opt_listen_backlog) != 0) {
  14017. mg_cry_ctx_internal(phys_ctx,
  14018. "cannot listen to %.*s: %d (%s)",
  14019. (int)vec.len,
  14020. vec.ptr,
  14021. (int)ERRNO,
  14022. strerror(errno));
  14023. closesocket(so.sock);
  14024. so.sock = INVALID_SOCKET;
  14025. continue;
  14026. }
  14027. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  14028. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  14029. int err = (int)ERRNO;
  14030. mg_cry_ctx_internal(phys_ctx,
  14031. "call to getsockname failed %.*s: %d (%s)",
  14032. (int)vec.len,
  14033. vec.ptr,
  14034. err,
  14035. strerror(errno));
  14036. closesocket(so.sock);
  14037. so.sock = INVALID_SOCKET;
  14038. continue;
  14039. }
  14040. /* Update lsa port in case of random free ports */
  14041. #if defined(USE_IPV6)
  14042. if (so.lsa.sa.sa_family == AF_INET6) {
  14043. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  14044. } else
  14045. #endif
  14046. {
  14047. so.lsa.sin.sin_port = usa.sin.sin_port;
  14048. }
  14049. if ((ptr = (struct socket *)
  14050. mg_realloc_ctx(phys_ctx->listening_sockets,
  14051. (phys_ctx->num_listening_sockets + 1)
  14052. * sizeof(phys_ctx->listening_sockets[0]),
  14053. phys_ctx))
  14054. == NULL) {
  14055. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14056. closesocket(so.sock);
  14057. so.sock = INVALID_SOCKET;
  14058. continue;
  14059. }
  14060. /* The +2 below includes the original +1 (for the socket we're about to
  14061. * add), plus another +1 for the thread_shutdown_notification_socket
  14062. * that we'll also want to poll() on so that mg_stop() can return
  14063. * quickly
  14064. */
  14065. if ((pfd = (struct mg_pollfd *)
  14066. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  14067. (phys_ctx->num_listening_sockets + 2)
  14068. * sizeof(phys_ctx->listening_socket_fds[0]),
  14069. phys_ctx))
  14070. == NULL) {
  14071. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  14072. closesocket(so.sock);
  14073. so.sock = INVALID_SOCKET;
  14074. mg_free(ptr);
  14075. continue;
  14076. }
  14077. set_close_on_exec(so.sock, NULL, phys_ctx);
  14078. phys_ctx->listening_sockets = ptr;
  14079. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  14080. phys_ctx->listening_socket_fds = pfd;
  14081. phys_ctx->num_listening_sockets++;
  14082. portsOk++;
  14083. }
  14084. if (portsOk != portsTotal) {
  14085. close_all_listening_sockets(phys_ctx);
  14086. portsOk = 0;
  14087. }
  14088. return portsOk;
  14089. }
  14090. static const char *
  14091. header_val(const struct mg_connection *conn, const char *header)
  14092. {
  14093. const char *header_value;
  14094. if ((header_value = mg_get_header(conn, header)) == NULL) {
  14095. return "-";
  14096. } else {
  14097. return header_value;
  14098. }
  14099. }
  14100. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  14101. #include "external_log_access.inl"
  14102. #elif !defined(NO_FILESYSTEMS)
  14103. static void
  14104. log_access(const struct mg_connection *conn)
  14105. {
  14106. const struct mg_request_info *ri;
  14107. struct mg_file fi;
  14108. char date[64], src_addr[IP_ADDR_STR_LEN];
  14109. #if defined(REENTRANT_TIME)
  14110. struct tm _tm;
  14111. struct tm *tm = &_tm;
  14112. #else
  14113. struct tm *tm;
  14114. #endif
  14115. const char *referer;
  14116. const char *user_agent;
  14117. char log_buf[4096];
  14118. if (!conn || !conn->dom_ctx) {
  14119. return;
  14120. }
  14121. /* Set log message to "empty" */
  14122. log_buf[0] = 0;
  14123. #if defined(USE_LUA)
  14124. if (conn->phys_ctx->lua_bg_log_available) {
  14125. int ret;
  14126. struct mg_context *ctx = conn->phys_ctx;
  14127. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14128. pthread_mutex_lock(&ctx->lua_bg_mutex);
  14129. /* call "log()" in Lua */
  14130. lua_getglobal(lstate, "log");
  14131. prepare_lua_request_info_inner(conn, lstate);
  14132. push_lua_response_log_data(conn, lstate);
  14133. ret = lua_pcall(lstate, /* args */ 2, /* results */ 1, 0);
  14134. if (ret == 0) {
  14135. int t = lua_type(lstate, -1);
  14136. if (t == LUA_TBOOLEAN) {
  14137. if (lua_toboolean(lstate, -1) == 0) {
  14138. /* log() returned false: do not log */
  14139. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14140. return;
  14141. }
  14142. /* log returned true: continue logging */
  14143. } else if (t == LUA_TSTRING) {
  14144. size_t len;
  14145. const char *txt = lua_tolstring(lstate, -1, &len);
  14146. if ((len == 0) || (*txt == 0)) {
  14147. /* log() returned empty string: do not log */
  14148. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14149. return;
  14150. }
  14151. /* Copy test from Lua into log_buf */
  14152. if (len >= sizeof(log_buf)) {
  14153. len = sizeof(log_buf) - 1;
  14154. }
  14155. memcpy(log_buf, txt, len);
  14156. log_buf[len] = 0;
  14157. }
  14158. } else {
  14159. lua_cry(conn, ret, lstate, "lua_background_script", "log");
  14160. }
  14161. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  14162. }
  14163. #endif
  14164. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  14165. if (mg_fopen(conn,
  14166. conn->dom_ctx->config[ACCESS_LOG_FILE],
  14167. MG_FOPEN_MODE_APPEND,
  14168. &fi)
  14169. == 0) {
  14170. fi.access.fp = NULL;
  14171. }
  14172. } else {
  14173. fi.access.fp = NULL;
  14174. }
  14175. /* Log is written to a file and/or a callback. If both are not set,
  14176. * executing the rest of the function is pointless. */
  14177. if ((fi.access.fp == NULL)
  14178. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  14179. return;
  14180. }
  14181. /* If we did not get a log message from Lua, create it here. */
  14182. if (!log_buf[0]) {
  14183. #if defined(REENTRANT_TIME)
  14184. localtime_r(&conn->conn_birth_time, tm);
  14185. #else
  14186. tm = localtime(&conn->conn_birth_time);
  14187. #endif
  14188. if (tm != NULL) {
  14189. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  14190. } else {
  14191. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  14192. }
  14193. ri = &conn->request_info;
  14194. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  14195. referer = header_val(conn, "Referer");
  14196. user_agent = header_val(conn, "User-Agent");
  14197. mg_snprintf(conn,
  14198. NULL, /* Ignore truncation in access log */
  14199. log_buf,
  14200. sizeof(log_buf),
  14201. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT
  14202. " %s %s",
  14203. src_addr,
  14204. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  14205. date,
  14206. ri->request_method ? ri->request_method : "-",
  14207. ri->request_uri ? ri->request_uri : "-",
  14208. ri->query_string ? "?" : "",
  14209. ri->query_string ? ri->query_string : "",
  14210. ri->http_version,
  14211. conn->status_code,
  14212. conn->num_bytes_sent,
  14213. referer,
  14214. user_agent);
  14215. }
  14216. /* Here we have a log message in log_buf. Call the callback */
  14217. if (conn->phys_ctx->callbacks.log_access) {
  14218. if (conn->phys_ctx->callbacks.log_access(conn, log_buf)) {
  14219. /* do not log if callback returns non-zero */
  14220. if (fi.access.fp) {
  14221. mg_fclose(&fi.access);
  14222. }
  14223. return;
  14224. }
  14225. }
  14226. /* Store in file */
  14227. if (fi.access.fp) {
  14228. int ok = 1;
  14229. flockfile(fi.access.fp);
  14230. if (fprintf(fi.access.fp, "%s\n", log_buf) < 1) {
  14231. ok = 0;
  14232. }
  14233. if (fflush(fi.access.fp) != 0) {
  14234. ok = 0;
  14235. }
  14236. funlockfile(fi.access.fp);
  14237. if (mg_fclose(&fi.access) != 0) {
  14238. ok = 0;
  14239. }
  14240. if (!ok) {
  14241. mg_cry_internal(conn,
  14242. "Error writing log file %s",
  14243. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  14244. }
  14245. }
  14246. }
  14247. #else
  14248. #error "Either enable filesystems or provide a custom log_access implementation"
  14249. #endif /* Externally provided function */
  14250. /* Verify given socket address against the ACL.
  14251. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  14252. */
  14253. static int
  14254. check_acl(struct mg_context *phys_ctx, const union usa *sa)
  14255. {
  14256. int allowed, flag, matched;
  14257. struct vec vec;
  14258. if (phys_ctx) {
  14259. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  14260. /* If any ACL is set, deny by default */
  14261. allowed = (list == NULL) ? '+' : '-';
  14262. while ((list = next_option(list, &vec, NULL)) != NULL) {
  14263. flag = vec.ptr[0];
  14264. matched = -1;
  14265. if ((vec.len > 0) && ((flag == '+') || (flag == '-'))) {
  14266. vec.ptr++;
  14267. vec.len--;
  14268. matched = parse_match_net(&vec, sa, 1);
  14269. }
  14270. if (matched < 0) {
  14271. mg_cry_ctx_internal(phys_ctx,
  14272. "%s: subnet must be [+|-]IP-addr[/x]",
  14273. __func__);
  14274. return -1;
  14275. }
  14276. if (matched) {
  14277. allowed = flag;
  14278. }
  14279. }
  14280. return allowed == '+';
  14281. }
  14282. return -1;
  14283. }
  14284. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  14285. static int
  14286. set_uid_option(struct mg_context *phys_ctx)
  14287. {
  14288. int success = 0;
  14289. if (phys_ctx) {
  14290. /* We are currently running as curr_uid. */
  14291. const uid_t curr_uid = getuid();
  14292. /* If set, we want to run as run_as_user. */
  14293. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  14294. const struct passwd *to_pw = NULL;
  14295. if ((run_as_user != NULL) && (to_pw = getpwnam(run_as_user)) == NULL) {
  14296. /* run_as_user does not exist on the system. We can't proceed
  14297. * further. */
  14298. mg_cry_ctx_internal(phys_ctx,
  14299. "%s: unknown user [%s]",
  14300. __func__,
  14301. run_as_user);
  14302. } else if ((run_as_user == NULL) || (curr_uid == to_pw->pw_uid)) {
  14303. /* There was either no request to change user, or we're already
  14304. * running as run_as_user. Nothing else to do.
  14305. */
  14306. success = 1;
  14307. } else {
  14308. /* Valid change request. */
  14309. if (setgid(to_pw->pw_gid) == -1) {
  14310. mg_cry_ctx_internal(phys_ctx,
  14311. "%s: setgid(%s): %s",
  14312. __func__,
  14313. run_as_user,
  14314. strerror(errno));
  14315. } else if (setgroups(0, NULL) == -1) {
  14316. mg_cry_ctx_internal(phys_ctx,
  14317. "%s: setgroups(): %s",
  14318. __func__,
  14319. strerror(errno));
  14320. } else if (setuid(to_pw->pw_uid) == -1) {
  14321. mg_cry_ctx_internal(phys_ctx,
  14322. "%s: setuid(%s): %s",
  14323. __func__,
  14324. run_as_user,
  14325. strerror(errno));
  14326. } else {
  14327. success = 1;
  14328. }
  14329. }
  14330. }
  14331. return success;
  14332. }
  14333. #endif /* !_WIN32 */
  14334. static void
  14335. tls_dtor(void *key)
  14336. {
  14337. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  14338. /* key == pthread_getspecific(sTlsKey); */
  14339. if (tls) {
  14340. if (tls->is_master == 2) {
  14341. tls->is_master = -3; /* Mark memory as dead */
  14342. mg_free(tls);
  14343. }
  14344. }
  14345. pthread_setspecific(sTlsKey, NULL);
  14346. }
  14347. #if defined(USE_MBEDTLS)
  14348. /* Check if SSL is required.
  14349. * If so, set up ctx->ssl_ctx pointer. */
  14350. static int
  14351. mg_sslctx_init(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  14352. {
  14353. if (!phys_ctx) {
  14354. return 0;
  14355. }
  14356. if (!dom_ctx) {
  14357. dom_ctx = &(phys_ctx->dd);
  14358. }
  14359. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  14360. /* No SSL port is set. No need to setup SSL. */
  14361. return 1;
  14362. }
  14363. dom_ctx->ssl_ctx = (SSL_CTX *)mg_calloc(1, sizeof(*dom_ctx->ssl_ctx));
  14364. if (dom_ctx->ssl_ctx == NULL) {
  14365. fprintf(stderr, "ssl_ctx malloc failed\n");
  14366. return 0;
  14367. }
  14368. return mbed_sslctx_init(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CERTIFICATE])
  14369. == 0
  14370. ? 1
  14371. : 0;
  14372. }
  14373. #elif !defined(NO_SSL)
  14374. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  14375. struct mg_domain_context *dom_ctx,
  14376. const char *pem,
  14377. const char *chain);
  14378. static const char *ssl_error(void);
  14379. static int
  14380. refresh_trust(struct mg_connection *conn)
  14381. {
  14382. struct stat cert_buf;
  14383. int64_t t = 0;
  14384. const char *pem;
  14385. const char *chain;
  14386. int should_verify_peer;
  14387. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  14388. /* If pem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  14389. * refresh_trust still can not work. */
  14390. return 0;
  14391. }
  14392. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  14393. if (chain == NULL) {
  14394. /* pem is not NULL here */
  14395. chain = pem;
  14396. }
  14397. if (*chain == 0) {
  14398. chain = NULL;
  14399. }
  14400. if (stat(pem, &cert_buf) != -1) {
  14401. t = (int64_t)cert_buf.st_mtime;
  14402. }
  14403. mg_lock_context(conn->phys_ctx);
  14404. if ((t != 0) && (conn->dom_ctx->ssl_cert_last_mtime != t)) {
  14405. conn->dom_ctx->ssl_cert_last_mtime = t;
  14406. should_verify_peer = 0;
  14407. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  14408. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  14409. == 0) {
  14410. should_verify_peer = 1;
  14411. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  14412. "optional")
  14413. == 0) {
  14414. should_verify_peer = 1;
  14415. }
  14416. }
  14417. if (should_verify_peer) {
  14418. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  14419. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  14420. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14421. ca_file,
  14422. ca_path)
  14423. != 1) {
  14424. mg_unlock_context(conn->phys_ctx);
  14425. mg_cry_ctx_internal(
  14426. conn->phys_ctx,
  14427. "SSL_CTX_load_verify_locations error: %s "
  14428. "ssl_verify_peer requires setting "
  14429. "either ssl_ca_path or ssl_ca_file. Is any of them "
  14430. "present in "
  14431. "the .conf file?",
  14432. ssl_error());
  14433. return 0;
  14434. }
  14435. }
  14436. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) {
  14437. mg_unlock_context(conn->phys_ctx);
  14438. return 0;
  14439. }
  14440. }
  14441. mg_unlock_context(conn->phys_ctx);
  14442. return 1;
  14443. }
  14444. #if defined(OPENSSL_API_1_1)
  14445. #else
  14446. static pthread_mutex_t *ssl_mutexes;
  14447. #endif /* OPENSSL_API_1_1 */
  14448. static int
  14449. sslize(struct mg_connection *conn,
  14450. int (*func)(SSL *),
  14451. const struct mg_client_options *client_options)
  14452. {
  14453. int ret, err;
  14454. int short_trust;
  14455. unsigned timeout = 1024;
  14456. unsigned i;
  14457. if (!conn) {
  14458. return 0;
  14459. }
  14460. short_trust =
  14461. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  14462. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  14463. if (short_trust) {
  14464. int trust_ret = refresh_trust(conn);
  14465. if (!trust_ret) {
  14466. return trust_ret;
  14467. }
  14468. }
  14469. mg_lock_context(conn->phys_ctx);
  14470. conn->ssl = SSL_new(conn->dom_ctx->ssl_ctx);
  14471. mg_unlock_context(conn->phys_ctx);
  14472. if (conn->ssl == NULL) {
  14473. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14474. OPENSSL_REMOVE_THREAD_STATE();
  14475. return 0;
  14476. }
  14477. SSL_set_app_data(conn->ssl, (char *)conn);
  14478. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  14479. if (ret != 1) {
  14480. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14481. SSL_free(conn->ssl);
  14482. conn->ssl = NULL;
  14483. OPENSSL_REMOVE_THREAD_STATE();
  14484. return 0;
  14485. }
  14486. if (client_options) {
  14487. if (client_options->host_name) {
  14488. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  14489. }
  14490. }
  14491. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  14492. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  14493. /* NOTE: The loop below acts as a back-off, so we can end
  14494. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  14495. int to = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  14496. if (to >= 0) {
  14497. timeout = (unsigned)to;
  14498. }
  14499. }
  14500. /* SSL functions may fail and require to be called again:
  14501. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  14502. * Here "func" could be SSL_connect or SSL_accept. */
  14503. for (i = 0; i <= timeout; i += 50) {
  14504. ERR_clear_error();
  14505. /* conn->dom_ctx may be changed here (see ssl_servername_callback) */
  14506. ret = func(conn->ssl);
  14507. if (ret != 1) {
  14508. err = SSL_get_error(conn->ssl, ret);
  14509. if ((err == SSL_ERROR_WANT_CONNECT)
  14510. || (err == SSL_ERROR_WANT_ACCEPT)
  14511. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  14512. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  14513. if (!STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)) {
  14514. /* Don't wait if the server is going to be stopped. */
  14515. break;
  14516. }
  14517. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  14518. /* Simply retry the function call. */
  14519. mg_sleep(50);
  14520. } else {
  14521. /* Need to retry the function call "later".
  14522. * See https://linux.die.net/man/3/ssl_get_error
  14523. * This is typical for non-blocking sockets. */
  14524. struct mg_pollfd pfd[2];
  14525. int pollres;
  14526. pfd[0].fd = conn->client.sock;
  14527. pfd[0].events = ((err == SSL_ERROR_WANT_CONNECT)
  14528. || (err == SSL_ERROR_WANT_WRITE))
  14529. ? POLLOUT
  14530. : POLLIN;
  14531. pfd[1].fd =
  14532. conn->phys_ctx->thread_shutdown_notification_socket;
  14533. pfd[1].events = POLLIN;
  14534. pollres = mg_poll(pfd, 2, 50, &(conn->phys_ctx->stop_flag));
  14535. if (pollres < 0) {
  14536. /* Break if error occurred (-1)
  14537. * or server shutdown (-2) */
  14538. break;
  14539. }
  14540. }
  14541. } else if (err == SSL_ERROR_SYSCALL) {
  14542. /* This is an IO error. Look at errno. */
  14543. mg_cry_internal(conn, "SSL syscall error %i", ERRNO);
  14544. break;
  14545. } else {
  14546. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  14547. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  14548. break;
  14549. }
  14550. } else {
  14551. /* success */
  14552. break;
  14553. }
  14554. }
  14555. ERR_clear_error();
  14556. if (ret != 1) {
  14557. SSL_free(conn->ssl);
  14558. conn->ssl = NULL;
  14559. OPENSSL_REMOVE_THREAD_STATE();
  14560. return 0;
  14561. }
  14562. return 1;
  14563. }
  14564. /* Return OpenSSL error message (from CRYPTO lib) */
  14565. static const char *
  14566. ssl_error(void)
  14567. {
  14568. unsigned long err;
  14569. err = ERR_get_error();
  14570. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  14571. }
  14572. static int
  14573. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  14574. {
  14575. int i;
  14576. const char hexdigit[] = "0123456789abcdef";
  14577. if ((memlen <= 0) || (buflen <= 0)) {
  14578. return 0;
  14579. }
  14580. if (buflen < (3 * memlen)) {
  14581. return 0;
  14582. }
  14583. for (i = 0; i < memlen; i++) {
  14584. if (i > 0) {
  14585. buf[3 * i - 1] = ' ';
  14586. }
  14587. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  14588. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  14589. }
  14590. buf[3 * memlen - 1] = 0;
  14591. return 1;
  14592. }
  14593. static int
  14594. ssl_get_client_cert_info(const struct mg_connection *conn,
  14595. struct mg_client_cert *client_cert)
  14596. {
  14597. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  14598. if (cert) {
  14599. char str_buf[1024];
  14600. unsigned char buf[256];
  14601. char *str_serial = NULL;
  14602. unsigned int ulen;
  14603. int ilen;
  14604. unsigned char *tmp_buf;
  14605. unsigned char *tmp_p;
  14606. /* Handle to algorithm used for fingerprint */
  14607. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  14608. /* Get Subject and issuer */
  14609. X509_NAME *subj = X509_get_subject_name(cert);
  14610. X509_NAME *iss = X509_get_issuer_name(cert);
  14611. /* Get serial number */
  14612. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  14613. /* Translate serial number to a hex string */
  14614. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  14615. if (serial_bn) {
  14616. str_serial = BN_bn2hex(serial_bn);
  14617. BN_free(serial_bn);
  14618. }
  14619. client_cert->serial =
  14620. str_serial ? mg_strdup_ctx(str_serial, conn->phys_ctx) : NULL;
  14621. /* Translate subject and issuer to a string */
  14622. (void)X509_NAME_oneline(subj, str_buf, (int)sizeof(str_buf));
  14623. client_cert->subject = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14624. (void)X509_NAME_oneline(iss, str_buf, (int)sizeof(str_buf));
  14625. client_cert->issuer = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14626. /* Calculate SHA1 fingerprint and store as a hex string */
  14627. ulen = 0;
  14628. /* ASN1_digest is deprecated. Do the calculation manually,
  14629. * using EVP_Digest. */
  14630. ilen = i2d_X509(cert, NULL);
  14631. tmp_buf = (ilen > 0)
  14632. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  14633. conn->phys_ctx)
  14634. : NULL;
  14635. if (tmp_buf) {
  14636. tmp_p = tmp_buf;
  14637. (void)i2d_X509(cert, &tmp_p);
  14638. if (!EVP_Digest(
  14639. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  14640. ulen = 0;
  14641. }
  14642. mg_free(tmp_buf);
  14643. }
  14644. if (!hexdump2string(buf, (int)ulen, str_buf, (int)sizeof(str_buf))) {
  14645. *str_buf = 0;
  14646. }
  14647. client_cert->finger = mg_strdup_ctx(str_buf, conn->phys_ctx);
  14648. client_cert->peer_cert = (void *)cert;
  14649. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  14650. * see https://linux.die.net/man/3/bn_bn2hex */
  14651. OPENSSL_free(str_serial);
  14652. return 1;
  14653. }
  14654. return 0;
  14655. }
  14656. #if defined(OPENSSL_API_1_1)
  14657. #else
  14658. static void
  14659. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  14660. {
  14661. (void)line;
  14662. (void)file;
  14663. if (mode & 1) {
  14664. /* 1 is CRYPTO_LOCK */
  14665. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  14666. } else {
  14667. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  14668. }
  14669. }
  14670. #endif /* OPENSSL_API_1_1 */
  14671. #if !defined(NO_SSL_DL)
  14672. /* Load a DLL/Shared Object with a TLS/SSL implementation. */
  14673. static void *
  14674. load_tls_dll(char *ebuf,
  14675. size_t ebuf_len,
  14676. const char *dll_name,
  14677. struct ssl_func *sw,
  14678. int *feature_missing)
  14679. {
  14680. union {
  14681. void *p;
  14682. void (*fp)(void);
  14683. } u;
  14684. void *dll_handle;
  14685. struct ssl_func *fp;
  14686. int ok;
  14687. int truncated = 0;
  14688. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  14689. mg_snprintf(NULL,
  14690. NULL, /* No truncation check for ebuf */
  14691. ebuf,
  14692. ebuf_len,
  14693. "%s: cannot load %s",
  14694. __func__,
  14695. dll_name);
  14696. return NULL;
  14697. }
  14698. ok = 1;
  14699. for (fp = sw; fp->name != NULL; fp++) {
  14700. #if defined(_WIN32)
  14701. /* GetProcAddress() returns pointer to function */
  14702. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  14703. #else
  14704. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  14705. * pointers to function pointers. We need to use a union to make a
  14706. * cast. */
  14707. u.p = dlsym(dll_handle, fp->name);
  14708. #endif /* _WIN32 */
  14709. /* Set pointer (might be NULL) */
  14710. fp->ptr = u.fp;
  14711. if (u.fp == NULL) {
  14712. DEBUG_TRACE("Missing function: %s\n", fp->name);
  14713. if (feature_missing) {
  14714. feature_missing[fp->required]++;
  14715. }
  14716. if (fp->required == TLS_Mandatory) {
  14717. /* Mandatory function is missing */
  14718. if (ok) {
  14719. /* This is the first missing function.
  14720. * Create a new error message. */
  14721. mg_snprintf(NULL,
  14722. &truncated,
  14723. ebuf,
  14724. ebuf_len,
  14725. "%s: %s: cannot find %s",
  14726. __func__,
  14727. dll_name,
  14728. fp->name);
  14729. ok = 0;
  14730. } else {
  14731. /* This is yet anothermissing function.
  14732. * Append existing error message. */
  14733. size_t cur_len = strlen(ebuf);
  14734. if (!truncated && ((ebuf_len - cur_len) > 3)) {
  14735. mg_snprintf(NULL,
  14736. &truncated,
  14737. ebuf + cur_len,
  14738. ebuf_len - cur_len - 3,
  14739. ", %s",
  14740. fp->name);
  14741. if (truncated) {
  14742. /* If truncated, add "..." */
  14743. strcat(ebuf, "...");
  14744. }
  14745. }
  14746. }
  14747. }
  14748. }
  14749. }
  14750. if (!ok) {
  14751. (void)dlclose(dll_handle);
  14752. return NULL;
  14753. }
  14754. return dll_handle;
  14755. }
  14756. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  14757. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  14758. #endif /* NO_SSL_DL */
  14759. #if defined(SSL_ALREADY_INITIALIZED)
  14760. static volatile ptrdiff_t cryptolib_users =
  14761. 1; /* Reference counter for crypto library. */
  14762. #else
  14763. static volatile ptrdiff_t cryptolib_users =
  14764. 0; /* Reference counter for crypto library. */
  14765. #endif
  14766. static int
  14767. initialize_openssl(char *ebuf, size_t ebuf_len)
  14768. {
  14769. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14770. int i, num_locks;
  14771. size_t size;
  14772. #endif
  14773. if (ebuf_len > 0) {
  14774. ebuf[0] = 0;
  14775. }
  14776. #if !defined(NO_SSL_DL)
  14777. if (!cryptolib_dll_handle) {
  14778. memset(tls_feature_missing, 0, sizeof(tls_feature_missing));
  14779. cryptolib_dll_handle = load_tls_dll(
  14780. ebuf, ebuf_len, CRYPTO_LIB, crypto_sw, tls_feature_missing);
  14781. if (!cryptolib_dll_handle) {
  14782. mg_snprintf(NULL,
  14783. NULL, /* No truncation check for ebuf */
  14784. ebuf,
  14785. ebuf_len,
  14786. "%s: error loading library %s",
  14787. __func__,
  14788. CRYPTO_LIB);
  14789. DEBUG_TRACE("%s", ebuf);
  14790. return 0;
  14791. }
  14792. }
  14793. #endif /* NO_SSL_DL */
  14794. if (mg_atomic_inc(&cryptolib_users) > 1) {
  14795. return 1;
  14796. }
  14797. #if !defined(OPENSSL_API_1_1) && !defined(OPENSSL_API_3_0)
  14798. /* Initialize locking callbacks, needed for thread safety.
  14799. * http://www.openssl.org/support/faq.html#PROG1
  14800. */
  14801. num_locks = CRYPTO_num_locks();
  14802. if (num_locks < 0) {
  14803. num_locks = 0;
  14804. }
  14805. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  14806. /* allocate mutex array, if required */
  14807. if (num_locks == 0) {
  14808. /* No mutex array required */
  14809. ssl_mutexes = NULL;
  14810. } else {
  14811. /* Mutex array required - allocate it */
  14812. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  14813. /* Check OOM */
  14814. if (ssl_mutexes == NULL) {
  14815. mg_snprintf(NULL,
  14816. NULL, /* No truncation check for ebuf */
  14817. ebuf,
  14818. ebuf_len,
  14819. "%s: cannot allocate mutexes: %s",
  14820. __func__,
  14821. ssl_error());
  14822. DEBUG_TRACE("%s", ebuf);
  14823. return 0;
  14824. }
  14825. /* initialize mutex array */
  14826. for (i = 0; i < num_locks; i++) {
  14827. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  14828. mg_snprintf(NULL,
  14829. NULL, /* No truncation check for ebuf */
  14830. ebuf,
  14831. ebuf_len,
  14832. "%s: error initializing mutex %i of %i",
  14833. __func__,
  14834. i,
  14835. num_locks);
  14836. DEBUG_TRACE("%s", ebuf);
  14837. mg_free(ssl_mutexes);
  14838. return 0;
  14839. }
  14840. }
  14841. }
  14842. CRYPTO_set_locking_callback(&ssl_locking_callback);
  14843. CRYPTO_set_id_callback(&mg_current_thread_id);
  14844. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  14845. #if !defined(NO_SSL_DL)
  14846. if (!ssllib_dll_handle) {
  14847. ssllib_dll_handle =
  14848. load_tls_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw, tls_feature_missing);
  14849. if (!ssllib_dll_handle) {
  14850. #if !defined(OPENSSL_API_1_1)
  14851. mg_free(ssl_mutexes);
  14852. #endif
  14853. DEBUG_TRACE("%s", ebuf);
  14854. return 0;
  14855. }
  14856. }
  14857. #endif /* NO_SSL_DL */
  14858. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  14859. && !defined(NO_SSL_DL)
  14860. /* Initialize SSL library */
  14861. OPENSSL_init_ssl(0, NULL);
  14862. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  14863. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  14864. NULL);
  14865. #else
  14866. /* Initialize SSL library */
  14867. SSL_library_init();
  14868. SSL_load_error_strings();
  14869. #endif
  14870. return 1;
  14871. }
  14872. static int
  14873. ssl_use_pem_file(struct mg_context *phys_ctx,
  14874. struct mg_domain_context *dom_ctx,
  14875. const char *pem,
  14876. const char *chain)
  14877. {
  14878. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14879. mg_cry_ctx_internal(phys_ctx,
  14880. "%s: cannot open certificate file %s: %s",
  14881. __func__,
  14882. pem,
  14883. ssl_error());
  14884. return 0;
  14885. }
  14886. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  14887. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  14888. mg_cry_ctx_internal(phys_ctx,
  14889. "%s: cannot open private key file %s: %s",
  14890. __func__,
  14891. pem,
  14892. ssl_error());
  14893. return 0;
  14894. }
  14895. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  14896. mg_cry_ctx_internal(phys_ctx,
  14897. "%s: certificate and private key do not match: %s",
  14898. __func__,
  14899. pem);
  14900. return 0;
  14901. }
  14902. /* In contrast to OpenSSL, wolfSSL does not support certificate
  14903. * chain files that contain private keys and certificates in
  14904. * SSL_CTX_use_certificate_chain_file.
  14905. * The CivetWeb-Server used pem-Files that contained both information.
  14906. * In order to make wolfSSL work, it is split in two files.
  14907. * One file that contains key and certificate used by the server and
  14908. * an optional chain file for the ssl stack.
  14909. */
  14910. if (chain) {
  14911. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  14912. mg_cry_ctx_internal(phys_ctx,
  14913. "%s: cannot use certificate chain file %s: %s",
  14914. __func__,
  14915. chain,
  14916. ssl_error());
  14917. return 0;
  14918. }
  14919. }
  14920. return 1;
  14921. }
  14922. #if defined(OPENSSL_API_1_1)
  14923. static unsigned long
  14924. ssl_get_protocol(int version_id)
  14925. {
  14926. long unsigned ret = (long unsigned)SSL_OP_ALL;
  14927. if (version_id > 0)
  14928. ret |= SSL_OP_NO_SSLv2;
  14929. if (version_id > 1)
  14930. ret |= SSL_OP_NO_SSLv3;
  14931. if (version_id > 2)
  14932. ret |= SSL_OP_NO_TLSv1;
  14933. if (version_id > 3)
  14934. ret |= SSL_OP_NO_TLSv1_1;
  14935. if (version_id > 4)
  14936. ret |= SSL_OP_NO_TLSv1_2;
  14937. #if defined(SSL_OP_NO_TLSv1_3)
  14938. if (version_id > 5)
  14939. ret |= SSL_OP_NO_TLSv1_3;
  14940. #endif
  14941. return ret;
  14942. }
  14943. #else
  14944. static long
  14945. ssl_get_protocol(int version_id)
  14946. {
  14947. unsigned long ret = (unsigned long)SSL_OP_ALL;
  14948. if (version_id > 0)
  14949. ret |= SSL_OP_NO_SSLv2;
  14950. if (version_id > 1)
  14951. ret |= SSL_OP_NO_SSLv3;
  14952. if (version_id > 2)
  14953. ret |= SSL_OP_NO_TLSv1;
  14954. if (version_id > 3)
  14955. ret |= SSL_OP_NO_TLSv1_1;
  14956. if (version_id > 4)
  14957. ret |= SSL_OP_NO_TLSv1_2;
  14958. #if defined(SSL_OP_NO_TLSv1_3)
  14959. if (version_id > 5)
  14960. ret |= SSL_OP_NO_TLSv1_3;
  14961. #endif
  14962. return (long)ret;
  14963. }
  14964. #endif /* OPENSSL_API_1_1 */
  14965. /* SSL callback documentation:
  14966. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  14967. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  14968. * https://linux.die.net/man/3/ssl_set_info_callback */
  14969. /* Note: There is no "const" for the first argument in the documentation
  14970. * examples, however some (maybe most, but not all) headers of OpenSSL
  14971. * versions / OpenSSL compatibility layers have it. Having a different
  14972. * definition will cause a warning in C and an error in C++. Use "const SSL
  14973. * *", while automatic conversion from "SSL *" works for all compilers,
  14974. * but not other way around */
  14975. static void
  14976. ssl_info_callback(const SSL *ssl, int what, int ret)
  14977. {
  14978. (void)ret;
  14979. if (what & SSL_CB_HANDSHAKE_START) {
  14980. SSL_get_app_data(ssl);
  14981. }
  14982. if (what & SSL_CB_HANDSHAKE_DONE) {
  14983. /* TODO: check for openSSL 1.1 */
  14984. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  14985. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  14986. }
  14987. }
  14988. static int
  14989. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  14990. {
  14991. #if defined(GCC_DIAGNOSTIC)
  14992. #pragma GCC diagnostic push
  14993. #pragma GCC diagnostic ignored "-Wcast-align"
  14994. #endif /* defined(GCC_DIAGNOSTIC) */
  14995. /* We used an aligned pointer in SSL_set_app_data */
  14996. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  14997. #if defined(GCC_DIAGNOSTIC)
  14998. #pragma GCC diagnostic pop
  14999. #endif /* defined(GCC_DIAGNOSTIC) */
  15000. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  15001. (void)ad;
  15002. (void)arg;
  15003. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15004. DEBUG_ASSERT(0);
  15005. return SSL_TLSEXT_ERR_NOACK;
  15006. }
  15007. conn->dom_ctx = &(conn->phys_ctx->dd);
  15008. /* Old clients (Win XP) will not support SNI. Then, there
  15009. * is no server name available in the request - we can
  15010. * only work with the default certificate.
  15011. * Multiple HTTPS hosts on one IP+port are only possible
  15012. * with a certificate containing all alternative names.
  15013. */
  15014. if ((servername == NULL) || (*servername == 0)) {
  15015. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  15016. mg_lock_context(conn->phys_ctx);
  15017. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15018. mg_unlock_context(conn->phys_ctx);
  15019. return SSL_TLSEXT_ERR_NOACK;
  15020. }
  15021. DEBUG_TRACE("TLS connection to host %s", servername);
  15022. while (conn->dom_ctx) {
  15023. if (!mg_strcasecmp(servername,
  15024. conn->dom_ctx->config[AUTHENTICATION_DOMAIN])) {
  15025. /* Found matching domain */
  15026. DEBUG_TRACE("TLS domain %s found",
  15027. conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  15028. break;
  15029. }
  15030. mg_lock_context(conn->phys_ctx);
  15031. conn->dom_ctx = conn->dom_ctx->next;
  15032. mg_unlock_context(conn->phys_ctx);
  15033. }
  15034. if (conn->dom_ctx == NULL) {
  15035. /* Default domain */
  15036. DEBUG_TRACE("TLS default domain %s used",
  15037. conn->phys_ctx->dd.config[AUTHENTICATION_DOMAIN]);
  15038. conn->dom_ctx = &(conn->phys_ctx->dd);
  15039. }
  15040. mg_lock_context(conn->phys_ctx);
  15041. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  15042. mg_unlock_context(conn->phys_ctx);
  15043. return SSL_TLSEXT_ERR_OK;
  15044. }
  15045. #if defined(USE_ALPN)
  15046. static const char alpn_proto_list[] = "\x02h2\x08http/1.1\x08http/1.0";
  15047. static const char *alpn_proto_order_http1[] = {alpn_proto_list + 3,
  15048. alpn_proto_list + 3 + 8,
  15049. NULL};
  15050. #if defined(USE_HTTP2)
  15051. static const char *alpn_proto_order_http2[] = {alpn_proto_list,
  15052. alpn_proto_list + 3,
  15053. alpn_proto_list + 3 + 8,
  15054. NULL};
  15055. #endif
  15056. static int
  15057. alpn_select_cb(SSL *ssl,
  15058. const unsigned char **out,
  15059. unsigned char *outlen,
  15060. const unsigned char *in,
  15061. unsigned int inlen,
  15062. void *arg)
  15063. {
  15064. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15065. unsigned int i, j, enable_http2 = 0;
  15066. const char **alpn_proto_order = alpn_proto_order_http1;
  15067. struct mg_workerTLS *tls =
  15068. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  15069. (void)ssl;
  15070. if (tls == NULL) {
  15071. /* Need to store protocol in Thread Local Storage */
  15072. /* If there is no Thread Local Storage, don't use ALPN */
  15073. return SSL_TLSEXT_ERR_NOACK;
  15074. }
  15075. #if defined(USE_HTTP2)
  15076. enable_http2 = (0 == strcmp(dom_ctx->config[ENABLE_HTTP2], "yes"));
  15077. if (enable_http2) {
  15078. alpn_proto_order = alpn_proto_order_http2;
  15079. }
  15080. #endif
  15081. for (j = 0; alpn_proto_order[j] != NULL; j++) {
  15082. /* check all accepted protocols in this order */
  15083. const char *alpn_proto = alpn_proto_order[j];
  15084. /* search input for matching protocol */
  15085. for (i = 0; i < inlen; i++) {
  15086. if (!memcmp(in + i, alpn_proto, (unsigned char)alpn_proto[0])) {
  15087. *out = in + i + 1;
  15088. *outlen = in[i];
  15089. tls->alpn_proto = alpn_proto;
  15090. return SSL_TLSEXT_ERR_OK;
  15091. }
  15092. }
  15093. }
  15094. /* Nothing found */
  15095. return SSL_TLSEXT_ERR_NOACK;
  15096. }
  15097. static int
  15098. next_protos_advertised_cb(SSL *ssl,
  15099. const unsigned char **data,
  15100. unsigned int *len,
  15101. void *arg)
  15102. {
  15103. struct mg_domain_context *dom_ctx = (struct mg_domain_context *)arg;
  15104. *data = (const unsigned char *)alpn_proto_list;
  15105. *len = (unsigned int)strlen((const char *)data);
  15106. (void)ssl;
  15107. (void)dom_ctx;
  15108. return SSL_TLSEXT_ERR_OK;
  15109. }
  15110. static int
  15111. init_alpn(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15112. {
  15113. unsigned int alpn_len = (unsigned int)strlen((char *)alpn_proto_list);
  15114. int ret = SSL_CTX_set_alpn_protos(dom_ctx->ssl_ctx,
  15115. (const unsigned char *)alpn_proto_list,
  15116. alpn_len);
  15117. if (ret != 0) {
  15118. mg_cry_ctx_internal(phys_ctx,
  15119. "SSL_CTX_set_alpn_protos error: %s",
  15120. ssl_error());
  15121. }
  15122. SSL_CTX_set_alpn_select_cb(dom_ctx->ssl_ctx,
  15123. alpn_select_cb,
  15124. (void *)dom_ctx);
  15125. SSL_CTX_set_next_protos_advertised_cb(dom_ctx->ssl_ctx,
  15126. next_protos_advertised_cb,
  15127. (void *)dom_ctx);
  15128. return ret;
  15129. }
  15130. #endif
  15131. /* Setup SSL CTX as required by CivetWeb */
  15132. static int
  15133. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  15134. struct mg_domain_context *dom_ctx,
  15135. const char *pem,
  15136. const char *chain)
  15137. {
  15138. int callback_ret;
  15139. int should_verify_peer;
  15140. int peer_certificate_optional;
  15141. const char *ca_path;
  15142. const char *ca_file;
  15143. int use_default_verify_paths;
  15144. int verify_depth;
  15145. struct timespec now_mt;
  15146. md5_byte_t ssl_context_id[16];
  15147. md5_state_t md5state;
  15148. int protocol_ver;
  15149. int ssl_cache_timeout;
  15150. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15151. && !defined(NO_SSL_DL)
  15152. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  15153. mg_cry_ctx_internal(phys_ctx,
  15154. "SSL_CTX_new (server) error: %s",
  15155. ssl_error());
  15156. return 0;
  15157. }
  15158. #else
  15159. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  15160. mg_cry_ctx_internal(phys_ctx,
  15161. "SSL_CTX_new (server) error: %s",
  15162. ssl_error());
  15163. return 0;
  15164. }
  15165. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15166. #if defined(SSL_OP_NO_TLSv1_3)
  15167. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15168. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15169. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2
  15170. | SSL_OP_NO_TLSv1_3);
  15171. #else
  15172. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  15173. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  15174. | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
  15175. #endif
  15176. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  15177. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  15178. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  15179. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  15180. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  15181. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  15182. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  15183. #if defined(SSL_OP_NO_RENEGOTIATION)
  15184. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  15185. #endif
  15186. #if !defined(NO_SSL_DL)
  15187. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  15188. #endif /* NO_SSL_DL */
  15189. /* In SSL documentation examples callback defined without const
  15190. * specifier 'void (*)(SSL *, int, int)' See:
  15191. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  15192. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  15193. * But in the source code const SSL is used:
  15194. * 'void (*)(const SSL *, int, int)' See:
  15195. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  15196. * Problem about wrong documentation described, but not resolved:
  15197. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  15198. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  15199. * But when compiled with modern C++ compiler, correct const should be
  15200. * provided
  15201. */
  15202. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  15203. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  15204. ssl_servername_callback);
  15205. /* If a callback has been specified, call it. */
  15206. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  15207. ? 0
  15208. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  15209. phys_ctx->user_data));
  15210. /* If callback returns 0, civetweb sets up the SSL certificate.
  15211. * If it returns 1, civetweb assumes the callback already did this.
  15212. * If it returns -1, initializing ssl fails. */
  15213. if (callback_ret < 0) {
  15214. mg_cry_ctx_internal(phys_ctx,
  15215. "SSL callback returned error: %i",
  15216. callback_ret);
  15217. return 0;
  15218. }
  15219. if (callback_ret > 0) {
  15220. /* Callback did everything. */
  15221. return 1;
  15222. }
  15223. /* If a domain callback has been specified, call it. */
  15224. callback_ret = (phys_ctx->callbacks.init_ssl_domain == NULL)
  15225. ? 0
  15226. : (phys_ctx->callbacks.init_ssl_domain(
  15227. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15228. dom_ctx->ssl_ctx,
  15229. phys_ctx->user_data));
  15230. /* If domain callback returns 0, civetweb sets up the SSL certificate.
  15231. * If it returns 1, civetweb assumes the callback already did this.
  15232. * If it returns -1, initializing ssl fails. */
  15233. if (callback_ret < 0) {
  15234. mg_cry_ctx_internal(phys_ctx,
  15235. "Domain SSL callback returned error: %i",
  15236. callback_ret);
  15237. return 0;
  15238. }
  15239. if (callback_ret > 0) {
  15240. /* Domain callback did everything. */
  15241. return 1;
  15242. }
  15243. /* Use some combination of start time, domain and port as a SSL
  15244. * context ID. This should be unique on the current machine. */
  15245. md5_init(&md5state);
  15246. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  15247. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  15248. md5_append(&md5state,
  15249. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  15250. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  15251. md5_append(&md5state,
  15252. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  15253. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  15254. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  15255. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  15256. md5_finish(&md5state, ssl_context_id);
  15257. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  15258. (unsigned char *)ssl_context_id,
  15259. sizeof(ssl_context_id));
  15260. if (pem != NULL) {
  15261. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  15262. return 0;
  15263. }
  15264. }
  15265. /* Should we support client certificates? */
  15266. /* Default is "no". */
  15267. should_verify_peer = 0;
  15268. peer_certificate_optional = 0;
  15269. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  15270. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  15271. /* Yes, they are mandatory */
  15272. should_verify_peer = 1;
  15273. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  15274. "optional")
  15275. == 0) {
  15276. /* Yes, they are optional */
  15277. should_verify_peer = 1;
  15278. peer_certificate_optional = 1;
  15279. }
  15280. }
  15281. use_default_verify_paths =
  15282. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  15283. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  15284. == 0);
  15285. if (should_verify_peer) {
  15286. ca_path = dom_ctx->config[SSL_CA_PATH];
  15287. ca_file = dom_ctx->config[SSL_CA_FILE];
  15288. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  15289. != 1) {
  15290. mg_cry_ctx_internal(phys_ctx,
  15291. "SSL_CTX_load_verify_locations error: %s "
  15292. "ssl_verify_peer requires setting "
  15293. "either ssl_ca_path or ssl_ca_file. "
  15294. "Is any of them present in the "
  15295. ".conf file?",
  15296. ssl_error());
  15297. return 0;
  15298. }
  15299. if (peer_certificate_optional) {
  15300. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15301. } else {
  15302. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  15303. SSL_VERIFY_PEER
  15304. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  15305. NULL);
  15306. }
  15307. if (use_default_verify_paths
  15308. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  15309. mg_cry_ctx_internal(phys_ctx,
  15310. "SSL_CTX_set_default_verify_paths error: %s",
  15311. ssl_error());
  15312. return 0;
  15313. }
  15314. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  15315. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  15316. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  15317. }
  15318. }
  15319. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  15320. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  15321. dom_ctx->config[SSL_CIPHER_LIST])
  15322. != 1) {
  15323. mg_cry_ctx_internal(phys_ctx,
  15324. "SSL_CTX_set_cipher_list error: %s",
  15325. ssl_error());
  15326. }
  15327. }
  15328. /* SSL session caching */
  15329. ssl_cache_timeout = ((dom_ctx->config[SSL_CACHE_TIMEOUT] != NULL)
  15330. ? atoi(dom_ctx->config[SSL_CACHE_TIMEOUT])
  15331. : 0);
  15332. if (ssl_cache_timeout > 0) {
  15333. SSL_CTX_set_session_cache_mode(dom_ctx->ssl_ctx, SSL_SESS_CACHE_BOTH);
  15334. /* SSL_CTX_sess_set_cache_size(dom_ctx->ssl_ctx, 10000); ... use
  15335. * default */
  15336. SSL_CTX_set_timeout(dom_ctx->ssl_ctx, (long)ssl_cache_timeout);
  15337. }
  15338. #if defined(USE_ALPN)
  15339. /* Initialize ALPN only of TLS library (OpenSSL version) supports ALPN */
  15340. #if !defined(NO_SSL_DL)
  15341. if (!tls_feature_missing[TLS_ALPN])
  15342. #endif
  15343. {
  15344. init_alpn(phys_ctx, dom_ctx);
  15345. }
  15346. #endif
  15347. return 1;
  15348. }
  15349. /* Check if SSL is required.
  15350. * If so, dynamically load SSL library
  15351. * and set up ctx->ssl_ctx pointer. */
  15352. static int
  15353. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15354. {
  15355. void *ssl_ctx = 0;
  15356. int callback_ret;
  15357. const char *pem;
  15358. const char *chain;
  15359. char ebuf[128];
  15360. if (!phys_ctx) {
  15361. return 0;
  15362. }
  15363. if (!dom_ctx) {
  15364. dom_ctx = &(phys_ctx->dd);
  15365. }
  15366. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  15367. /* No SSL port is set. No need to setup SSL. */
  15368. return 1;
  15369. }
  15370. /* Check for external SSL_CTX */
  15371. callback_ret =
  15372. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  15373. ? 0
  15374. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  15375. phys_ctx->user_data));
  15376. if (callback_ret < 0) {
  15377. /* Callback exists and returns <0: Initializing failed. */
  15378. mg_cry_ctx_internal(phys_ctx,
  15379. "external_ssl_ctx callback returned error: %i",
  15380. callback_ret);
  15381. return 0;
  15382. } else if (callback_ret > 0) {
  15383. /* Callback exists and returns >0: Initializing complete,
  15384. * civetweb should not modify the SSL context. */
  15385. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15386. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15387. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15388. return 0;
  15389. }
  15390. return 1;
  15391. }
  15392. /* If the callback does not exist or return 0, civetweb must initialize
  15393. * the SSL context. Handle "domain" callback next. */
  15394. /* Check for external domain SSL_CTX callback. */
  15395. callback_ret = (phys_ctx->callbacks.external_ssl_ctx_domain == NULL)
  15396. ? 0
  15397. : (phys_ctx->callbacks.external_ssl_ctx_domain(
  15398. dom_ctx->config[AUTHENTICATION_DOMAIN],
  15399. &ssl_ctx,
  15400. phys_ctx->user_data));
  15401. if (callback_ret < 0) {
  15402. /* Callback < 0: Error. Abort init. */
  15403. mg_cry_ctx_internal(
  15404. phys_ctx,
  15405. "external_ssl_ctx_domain callback returned error: %i",
  15406. callback_ret);
  15407. return 0;
  15408. } else if (callback_ret > 0) {
  15409. /* Callback > 0: Consider init done. */
  15410. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  15411. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15412. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15413. return 0;
  15414. }
  15415. return 1;
  15416. }
  15417. /* else: external_ssl_ctx/external_ssl_ctx_domain do not exist or return
  15418. * 0, CivetWeb should continue initializing SSL */
  15419. /* If PEM file is not specified and the init_ssl callbacks
  15420. * are not specified, setup will fail. */
  15421. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  15422. && (phys_ctx->callbacks.init_ssl == NULL)
  15423. && (phys_ctx->callbacks.init_ssl_domain == NULL)) {
  15424. /* No certificate and no init_ssl callbacks:
  15425. * Essential data to set up TLS is missing.
  15426. */
  15427. mg_cry_ctx_internal(phys_ctx,
  15428. "Initializing SSL failed: -%s is not set",
  15429. config_options[SSL_CERTIFICATE].name);
  15430. return 0;
  15431. }
  15432. /* If a certificate chain is configured, use it. */
  15433. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  15434. if (chain == NULL) {
  15435. /* Default: certificate chain in PEM file */
  15436. chain = pem;
  15437. }
  15438. if ((chain != NULL) && (*chain == 0)) {
  15439. /* If the chain is an empty string, don't use it. */
  15440. chain = NULL;
  15441. }
  15442. if (!initialize_openssl(ebuf, sizeof(ebuf))) {
  15443. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  15444. return 0;
  15445. }
  15446. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  15447. }
  15448. static void
  15449. uninitialize_openssl(void)
  15450. {
  15451. #if defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)
  15452. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15453. /* Shutdown according to
  15454. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15455. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15456. */
  15457. CONF_modules_unload(1);
  15458. #else
  15459. int i;
  15460. if (mg_atomic_dec(&cryptolib_users) == 0) {
  15461. /* Shutdown according to
  15462. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  15463. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  15464. */
  15465. CRYPTO_set_locking_callback(NULL);
  15466. CRYPTO_set_id_callback(NULL);
  15467. ENGINE_cleanup();
  15468. CONF_modules_unload(1);
  15469. ERR_free_strings();
  15470. EVP_cleanup();
  15471. CRYPTO_cleanup_all_ex_data();
  15472. OPENSSL_REMOVE_THREAD_STATE();
  15473. for (i = 0; i < CRYPTO_num_locks(); i++) {
  15474. pthread_mutex_destroy(&ssl_mutexes[i]);
  15475. }
  15476. mg_free(ssl_mutexes);
  15477. ssl_mutexes = NULL;
  15478. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15479. }
  15480. }
  15481. #endif /* !defined(NO_SSL) && !defined(USE_MBEDTLS) */
  15482. #if !defined(NO_FILESYSTEMS)
  15483. static int
  15484. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  15485. {
  15486. if (phys_ctx) {
  15487. struct mg_file file = STRUCT_FILE_INITIALIZER;
  15488. const char *path;
  15489. struct mg_connection fc;
  15490. if (!dom_ctx) {
  15491. dom_ctx = &(phys_ctx->dd);
  15492. }
  15493. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  15494. if ((path != NULL)
  15495. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  15496. mg_cry_ctx_internal(phys_ctx,
  15497. "Cannot open %s: %s",
  15498. path,
  15499. strerror(ERRNO));
  15500. return 0;
  15501. }
  15502. return 1;
  15503. }
  15504. return 0;
  15505. }
  15506. #endif /* NO_FILESYSTEMS */
  15507. static int
  15508. set_acl_option(struct mg_context *phys_ctx)
  15509. {
  15510. union usa sa;
  15511. memset(&sa, 0, sizeof(sa));
  15512. #if defined(USE_IPV6)
  15513. sa.sin6.sin6_family = AF_INET6;
  15514. #else
  15515. sa.sin.sin_family = AF_INET;
  15516. #endif
  15517. return check_acl(phys_ctx, &sa) != -1;
  15518. }
  15519. static void
  15520. reset_per_request_attributes(struct mg_connection *conn)
  15521. {
  15522. if (!conn) {
  15523. return;
  15524. }
  15525. conn->num_bytes_sent = conn->consumed_content = 0;
  15526. conn->path_info = NULL;
  15527. conn->status_code = -1;
  15528. conn->content_len = -1;
  15529. conn->is_chunked = 0;
  15530. conn->must_close = 0;
  15531. conn->request_len = 0;
  15532. conn->request_state = 0;
  15533. conn->throttle = 0;
  15534. conn->accept_gzip = 0;
  15535. conn->response_info.content_length = conn->request_info.content_length = -1;
  15536. conn->response_info.http_version = conn->request_info.http_version = NULL;
  15537. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  15538. conn->response_info.status_text = NULL;
  15539. conn->response_info.status_code = 0;
  15540. conn->request_info.remote_user = NULL;
  15541. conn->request_info.request_method = NULL;
  15542. conn->request_info.request_uri = NULL;
  15543. /* Free cleaned local URI (if any) */
  15544. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  15545. mg_free((void *)conn->request_info.local_uri);
  15546. conn->request_info.local_uri = NULL;
  15547. }
  15548. conn->request_info.local_uri = NULL;
  15549. #if defined(USE_SERVER_STATS)
  15550. conn->processing_time = 0;
  15551. #endif
  15552. }
  15553. static int
  15554. set_tcp_nodelay(const struct socket *so, int nodelay_on)
  15555. {
  15556. if ((so->lsa.sa.sa_family == AF_INET)
  15557. || (so->lsa.sa.sa_family == AF_INET6)) {
  15558. /* Only for TCP sockets */
  15559. if (setsockopt(so->sock,
  15560. IPPROTO_TCP,
  15561. TCP_NODELAY,
  15562. (SOCK_OPT_TYPE)&nodelay_on,
  15563. sizeof(nodelay_on))
  15564. != 0) {
  15565. /* Error */
  15566. return 1;
  15567. }
  15568. }
  15569. /* OK */
  15570. return 0;
  15571. }
  15572. #if !defined(__ZEPHYR__)
  15573. static void
  15574. close_socket_gracefully(struct mg_connection *conn)
  15575. {
  15576. #if defined(_WIN32)
  15577. char buf[MG_BUF_LEN];
  15578. int n;
  15579. #endif
  15580. struct linger linger;
  15581. int error_code = 0;
  15582. int linger_timeout = -2;
  15583. socklen_t opt_len = sizeof(error_code);
  15584. if (!conn) {
  15585. return;
  15586. }
  15587. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  15588. * "Note that enabling a nonzero timeout on a nonblocking socket
  15589. * is not recommended.", so set it to blocking now */
  15590. set_blocking_mode(conn->client.sock);
  15591. /* Send FIN to the client */
  15592. shutdown(conn->client.sock, SHUTDOWN_WR);
  15593. #if defined(_WIN32)
  15594. /* Read and discard pending incoming data. If we do not do that and
  15595. * close
  15596. * the socket, the data in the send buffer may be discarded. This
  15597. * behaviour is seen on Windows, when client keeps sending data
  15598. * when server decides to close the connection; then when client
  15599. * does recv() it gets no data back. */
  15600. do {
  15601. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  15602. } while (n > 0);
  15603. #endif
  15604. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  15605. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  15606. }
  15607. /* Set linger option according to configuration */
  15608. if (linger_timeout >= 0) {
  15609. /* Set linger option to avoid socket hanging out after close. This
  15610. * prevent ephemeral port exhaust problem under high QPS. */
  15611. linger.l_onoff = 1;
  15612. #if defined(_MSC_VER)
  15613. #pragma warning(push)
  15614. #pragma warning(disable : 4244)
  15615. #endif
  15616. #if defined(GCC_DIAGNOSTIC)
  15617. #pragma GCC diagnostic push
  15618. #pragma GCC diagnostic ignored "-Wconversion"
  15619. #endif
  15620. /* Data type of linger structure elements may differ,
  15621. * so we don't know what cast we need here.
  15622. * Disable type conversion warnings. */
  15623. linger.l_linger = (linger_timeout + 999) / 1000;
  15624. #if defined(GCC_DIAGNOSTIC)
  15625. #pragma GCC diagnostic pop
  15626. #endif
  15627. #if defined(_MSC_VER)
  15628. #pragma warning(pop)
  15629. #endif
  15630. } else {
  15631. linger.l_onoff = 0;
  15632. linger.l_linger = 0;
  15633. }
  15634. if (linger_timeout < -1) {
  15635. /* Default: don't configure any linger */
  15636. } else if (getsockopt(conn->client.sock,
  15637. SOL_SOCKET,
  15638. SO_ERROR,
  15639. #if defined(_WIN32) /* WinSock uses different data type here */
  15640. (char *)&error_code,
  15641. #else
  15642. &error_code,
  15643. #endif
  15644. &opt_len)
  15645. != 0) {
  15646. /* Cannot determine if socket is already closed. This should
  15647. * not occur and never did in a test. Log an error message
  15648. * and continue. */
  15649. mg_cry_internal(conn,
  15650. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  15651. __func__,
  15652. strerror(ERRNO));
  15653. #if defined(_WIN32)
  15654. } else if (error_code == WSAECONNRESET) {
  15655. #else
  15656. } else if (error_code == ECONNRESET) {
  15657. #endif
  15658. /* Socket already closed by client/peer, close socket without linger
  15659. */
  15660. } else {
  15661. /* Set linger timeout */
  15662. if (setsockopt(conn->client.sock,
  15663. SOL_SOCKET,
  15664. SO_LINGER,
  15665. (char *)&linger,
  15666. sizeof(linger))
  15667. != 0) {
  15668. mg_cry_internal(
  15669. conn,
  15670. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  15671. __func__,
  15672. linger.l_onoff,
  15673. linger.l_linger,
  15674. strerror(ERRNO));
  15675. }
  15676. }
  15677. /* Now we know that our FIN is ACK-ed, safe to close */
  15678. closesocket(conn->client.sock);
  15679. conn->client.sock = INVALID_SOCKET;
  15680. }
  15681. #endif
  15682. static void
  15683. close_connection(struct mg_connection *conn)
  15684. {
  15685. #if defined(USE_SERVER_STATS)
  15686. conn->conn_state = 6; /* to close */
  15687. #endif
  15688. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15689. if (conn->lua_websocket_state) {
  15690. lua_websocket_close(conn, conn->lua_websocket_state);
  15691. conn->lua_websocket_state = NULL;
  15692. }
  15693. #endif
  15694. mg_lock_connection(conn);
  15695. /* Set close flag, so keep-alive loops will stop */
  15696. conn->must_close = 1;
  15697. /* call the connection_close callback if assigned */
  15698. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  15699. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15700. conn->phys_ctx->callbacks.connection_close(conn);
  15701. }
  15702. }
  15703. /* Reset user data, after close callback is called.
  15704. * Do not reuse it. If the user needs a destructor,
  15705. * it must be done in the connection_close callback. */
  15706. mg_set_user_connection_data(conn, NULL);
  15707. #if defined(USE_SERVER_STATS)
  15708. conn->conn_state = 7; /* closing */
  15709. #endif
  15710. #if defined(USE_MBEDTLS)
  15711. if (conn->ssl != NULL) {
  15712. mbed_ssl_close(conn->ssl);
  15713. conn->ssl = NULL;
  15714. }
  15715. #elif !defined(NO_SSL)
  15716. if (conn->ssl != NULL) {
  15717. /* Run SSL_shutdown twice to ensure completely close SSL connection
  15718. */
  15719. SSL_shutdown(conn->ssl);
  15720. SSL_free(conn->ssl);
  15721. OPENSSL_REMOVE_THREAD_STATE();
  15722. conn->ssl = NULL;
  15723. }
  15724. #endif
  15725. if (conn->client.sock != INVALID_SOCKET) {
  15726. #if defined(__ZEPHYR__)
  15727. closesocket(conn->client.sock);
  15728. #else
  15729. close_socket_gracefully(conn);
  15730. #endif
  15731. conn->client.sock = INVALID_SOCKET;
  15732. }
  15733. /* call the connection_closed callback if assigned */
  15734. if (conn->phys_ctx->callbacks.connection_closed != NULL) {
  15735. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15736. conn->phys_ctx->callbacks.connection_closed(conn);
  15737. }
  15738. }
  15739. mg_unlock_connection(conn);
  15740. #if defined(USE_SERVER_STATS)
  15741. conn->conn_state = 8; /* closed */
  15742. #endif
  15743. }
  15744. CIVETWEB_API void
  15745. mg_close_connection(struct mg_connection *conn)
  15746. {
  15747. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  15748. return;
  15749. }
  15750. #if defined(USE_WEBSOCKET)
  15751. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15752. if (conn->in_websocket_handling) {
  15753. /* Set close flag, so the server thread can exit. */
  15754. conn->must_close = 1;
  15755. return;
  15756. }
  15757. }
  15758. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15759. unsigned int i;
  15760. /* client context: loops must end */
  15761. STOP_FLAG_ASSIGN(&conn->phys_ctx->stop_flag, 1);
  15762. conn->must_close = 1;
  15763. /* We need to get the client thread out of the select/recv call
  15764. * here. */
  15765. /* Since we use a sleep quantum of some seconds to check for recv
  15766. * timeouts, we will just wait a few seconds in mg_join_thread. */
  15767. /* join worker thread */
  15768. for (i = 0; i < conn->phys_ctx->spawned_worker_threads; i++) {
  15769. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  15770. }
  15771. }
  15772. #endif /* defined(USE_WEBSOCKET) */
  15773. close_connection(conn);
  15774. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15775. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  15776. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  15777. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  15778. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  15779. }
  15780. #endif
  15781. #if defined(USE_WEBSOCKET)
  15782. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  15783. mg_free(conn->phys_ctx->worker_threadids);
  15784. (void)pthread_mutex_destroy(&conn->mutex);
  15785. mg_free(conn);
  15786. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  15787. (void)pthread_mutex_destroy(&conn->mutex);
  15788. mg_free(conn);
  15789. }
  15790. #else
  15791. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  15792. (void)pthread_mutex_destroy(&conn->mutex);
  15793. mg_free(conn);
  15794. }
  15795. #endif /* defined(USE_WEBSOCKET) */
  15796. }
  15797. static struct mg_connection *
  15798. mg_connect_client_impl(const struct mg_client_options *client_options,
  15799. int use_ssl,
  15800. struct mg_init_data *init,
  15801. struct mg_error_data *error)
  15802. {
  15803. struct mg_connection *conn = NULL;
  15804. SOCKET sock;
  15805. union usa sa;
  15806. struct sockaddr *psa;
  15807. socklen_t len;
  15808. unsigned max_req_size =
  15809. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  15810. /* Size of structures, aligned to 8 bytes */
  15811. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  15812. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  15813. size_t alloc_size = conn_size + ctx_size + max_req_size;
  15814. (void)init; /* TODO: Implement required options */
  15815. conn = (struct mg_connection *)mg_calloc(1, alloc_size);
  15816. if (error != NULL) {
  15817. error->code = MG_ERROR_DATA_CODE_OK;
  15818. error->code_sub = 0;
  15819. if (error->text_buffer_size > 0) {
  15820. error->text[0] = 0;
  15821. }
  15822. }
  15823. if (conn == NULL) {
  15824. if (error != NULL) {
  15825. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  15826. error->code_sub = (unsigned)alloc_size;
  15827. mg_snprintf(NULL,
  15828. NULL, /* No truncation check for ebuf */
  15829. error->text,
  15830. error->text_buffer_size,
  15831. "calloc(): %s",
  15832. strerror(ERRNO));
  15833. }
  15834. return NULL;
  15835. }
  15836. #if defined(GCC_DIAGNOSTIC)
  15837. #pragma GCC diagnostic push
  15838. #pragma GCC diagnostic ignored "-Wcast-align"
  15839. #endif /* defined(GCC_DIAGNOSTIC) */
  15840. /* conn_size is aligned to 8 bytes */
  15841. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  15842. #if defined(GCC_DIAGNOSTIC)
  15843. #pragma GCC diagnostic pop
  15844. #endif /* defined(GCC_DIAGNOSTIC) */
  15845. conn->buf = (((char *)conn) + conn_size + ctx_size);
  15846. conn->buf_size = (int)max_req_size;
  15847. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  15848. conn->dom_ctx = &(conn->phys_ctx->dd);
  15849. if (!connect_socket(conn->phys_ctx,
  15850. client_options->host,
  15851. client_options->port,
  15852. use_ssl,
  15853. error,
  15854. &sock,
  15855. &sa)) {
  15856. /* "error" will be set by connect_socket. */
  15857. /* free all memory and return NULL; */
  15858. mg_free(conn);
  15859. return NULL;
  15860. }
  15861. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15862. #if (defined(OPENSSL_API_1_1) || defined(OPENSSL_API_3_0)) \
  15863. && !defined(NO_SSL_DL)
  15864. if (use_ssl
  15865. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  15866. == NULL) {
  15867. if (error != NULL) {
  15868. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15869. mg_snprintf(NULL,
  15870. NULL, /* No truncation check for ebuf */
  15871. error->text,
  15872. error->text_buffer_size,
  15873. "SSL_CTX_new error: %s",
  15874. ssl_error());
  15875. }
  15876. closesocket(sock);
  15877. mg_free(conn);
  15878. return NULL;
  15879. }
  15880. #else
  15881. if (use_ssl
  15882. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  15883. == NULL) {
  15884. if (error != NULL) {
  15885. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  15886. mg_snprintf(NULL,
  15887. NULL, /* No truncation check for ebuf */
  15888. error->text,
  15889. error->text_buffer_size,
  15890. "SSL_CTX_new error: %s",
  15891. ssl_error());
  15892. }
  15893. closesocket(sock);
  15894. mg_free(conn);
  15895. return NULL;
  15896. }
  15897. #endif /* OPENSSL_API_1_1 || OPENSSL_API_3_0 */
  15898. #endif /* NO_SSL */
  15899. #if defined(USE_IPV6)
  15900. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  15901. : sizeof(conn->client.rsa.sin6);
  15902. psa = (sa.sa.sa_family == AF_INET)
  15903. ? (struct sockaddr *)&(conn->client.rsa.sin)
  15904. : (struct sockaddr *)&(conn->client.rsa.sin6);
  15905. #else
  15906. len = sizeof(conn->client.rsa.sin);
  15907. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  15908. #endif
  15909. conn->client.sock = sock;
  15910. conn->client.lsa = sa;
  15911. if (getsockname(sock, psa, &len) != 0) {
  15912. mg_cry_internal(conn,
  15913. "%s: getsockname() failed: %s",
  15914. __func__,
  15915. strerror(ERRNO));
  15916. }
  15917. conn->client.is_ssl = use_ssl ? 1 : 0;
  15918. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15919. if (error != NULL) {
  15920. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  15921. error->code_sub = (unsigned)ERRNO;
  15922. mg_snprintf(NULL,
  15923. NULL, /* No truncation check for ebuf */
  15924. error->text,
  15925. error->text_buffer_size,
  15926. "Can not create mutex");
  15927. }
  15928. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15929. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15930. #endif
  15931. closesocket(sock);
  15932. mg_free(conn);
  15933. return NULL;
  15934. }
  15935. #if !defined(NO_SSL) && !defined(USE_MBEDTLS) // TODO: mbedTLS client
  15936. if (use_ssl) {
  15937. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  15938. * SSL_CTX_set_verify call is needed to switch off server
  15939. * certificate checking, which is off by default in OpenSSL and
  15940. * on in yaSSL. */
  15941. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  15942. * SSL_VERIFY_PEER, verify_ssl_server); */
  15943. if (client_options->client_cert) {
  15944. if (!ssl_use_pem_file(conn->phys_ctx,
  15945. conn->dom_ctx,
  15946. client_options->client_cert,
  15947. NULL)) {
  15948. if (error != NULL) {
  15949. error->code = MG_ERROR_DATA_CODE_TLS_CLIENT_CERT_ERROR;
  15950. mg_snprintf(NULL,
  15951. NULL, /* No truncation check for ebuf */
  15952. error->text,
  15953. error->text_buffer_size,
  15954. "Can not use SSL client certificate");
  15955. }
  15956. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15957. closesocket(sock);
  15958. mg_free(conn);
  15959. return NULL;
  15960. }
  15961. }
  15962. if (client_options->server_cert) {
  15963. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  15964. client_options->server_cert,
  15965. NULL)
  15966. != 1) {
  15967. if (error != NULL) {
  15968. error->code = MG_ERROR_DATA_CODE_TLS_SERVER_CERT_ERROR;
  15969. mg_snprintf(NULL,
  15970. NULL, /* No truncation check for ebuf */
  15971. error->text,
  15972. error->text_buffer_size,
  15973. "SSL_CTX_load_verify_locations error: %s",
  15974. ssl_error());
  15975. }
  15976. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15977. closesocket(sock);
  15978. mg_free(conn);
  15979. return NULL;
  15980. }
  15981. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  15982. } else {
  15983. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  15984. }
  15985. if (!sslize(conn, SSL_connect, client_options)) {
  15986. if (error != NULL) {
  15987. error->code = MG_ERROR_DATA_CODE_TLS_CONNECT_ERROR;
  15988. mg_snprintf(NULL,
  15989. NULL, /* No truncation check for ebuf */
  15990. error->text,
  15991. error->text_buffer_size,
  15992. "SSL connection error");
  15993. }
  15994. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  15995. closesocket(sock);
  15996. mg_free(conn);
  15997. return NULL;
  15998. }
  15999. }
  16000. #endif
  16001. return conn;
  16002. }
  16003. CIVETWEB_API struct mg_connection *
  16004. mg_connect_client_secure(const struct mg_client_options *client_options,
  16005. char *error_buffer,
  16006. size_t error_buffer_size)
  16007. {
  16008. struct mg_init_data init;
  16009. struct mg_error_data error;
  16010. memset(&init, 0, sizeof(init));
  16011. memset(&error, 0, sizeof(error));
  16012. error.text_buffer_size = error_buffer_size;
  16013. error.text = error_buffer;
  16014. return mg_connect_client_impl(client_options, 1, &init, &error);
  16015. }
  16016. CIVETWEB_API struct mg_connection *
  16017. mg_connect_client(const char *host,
  16018. int port,
  16019. int use_ssl,
  16020. char *error_buffer,
  16021. size_t error_buffer_size)
  16022. {
  16023. struct mg_client_options opts;
  16024. struct mg_init_data init;
  16025. struct mg_error_data error;
  16026. memset(&init, 0, sizeof(init));
  16027. memset(&error, 0, sizeof(error));
  16028. error.text_buffer_size = error_buffer_size;
  16029. error.text = error_buffer;
  16030. memset(&opts, 0, sizeof(opts));
  16031. opts.host = host;
  16032. opts.port = port;
  16033. if (use_ssl) {
  16034. opts.host_name = host;
  16035. }
  16036. return mg_connect_client_impl(&opts, use_ssl, &init, &error);
  16037. }
  16038. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16039. CIVETWEB_API struct mg_connection *
  16040. mg_connect_client2(const char *host,
  16041. const char *protocol,
  16042. int port,
  16043. const char *path,
  16044. struct mg_init_data *init,
  16045. struct mg_error_data *error)
  16046. {
  16047. (void)path;
  16048. int is_ssl, is_ws;
  16049. /* void *user_data = (init != NULL) ? init->user_data : NULL; -- TODO */
  16050. if (error != NULL) {
  16051. error->code = MG_ERROR_DATA_CODE_OK;
  16052. error->code_sub = 0;
  16053. if (error->text_buffer_size > 0) {
  16054. *error->text = 0;
  16055. }
  16056. }
  16057. if ((host == NULL) || (protocol == NULL)) {
  16058. if (error != NULL) {
  16059. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16060. mg_snprintf(NULL,
  16061. NULL, /* No truncation check for error buffers */
  16062. error->text,
  16063. error->text_buffer_size,
  16064. "%s",
  16065. "Invalid parameters");
  16066. }
  16067. return NULL;
  16068. }
  16069. /* check all known protocols */
  16070. if (!mg_strcasecmp(protocol, "http")) {
  16071. is_ssl = 0;
  16072. is_ws = 0;
  16073. } else if (!mg_strcasecmp(protocol, "https")) {
  16074. is_ssl = 1;
  16075. is_ws = 0;
  16076. #if defined(USE_WEBSOCKET)
  16077. } else if (!mg_strcasecmp(protocol, "ws")) {
  16078. is_ssl = 0;
  16079. is_ws = 1;
  16080. } else if (!mg_strcasecmp(protocol, "wss")) {
  16081. is_ssl = 1;
  16082. is_ws = 1;
  16083. #endif
  16084. } else {
  16085. if (error != NULL) {
  16086. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  16087. mg_snprintf(NULL,
  16088. NULL, /* No truncation check for error buffers */
  16089. error->text,
  16090. error->text_buffer_size,
  16091. "Protocol %s not supported",
  16092. protocol);
  16093. }
  16094. return NULL;
  16095. }
  16096. /* TODO: The current implementation here just calls the old
  16097. * implementations, without using any new options. This is just a first
  16098. * step to test the new interfaces. */
  16099. #if defined(USE_WEBSOCKET)
  16100. if (is_ws) {
  16101. /* TODO: implement all options */
  16102. return mg_connect_websocket_client(
  16103. host,
  16104. port,
  16105. is_ssl,
  16106. ((error != NULL) ? error->text : NULL),
  16107. ((error != NULL) ? error->text_buffer_size : 0),
  16108. (path ? path : ""),
  16109. NULL /* TODO: origin */,
  16110. experimental_websocket_client_data_wrapper,
  16111. experimental_websocket_client_close_wrapper,
  16112. (void *)init->callbacks);
  16113. }
  16114. #else
  16115. (void)is_ws;
  16116. #endif
  16117. /* TODO: all additional options */
  16118. struct mg_client_options opts;
  16119. memset(&opts, 0, sizeof(opts));
  16120. opts.host = host;
  16121. opts.port = port;
  16122. return mg_connect_client_impl(&opts, is_ssl, init, error);
  16123. }
  16124. #endif
  16125. static const struct {
  16126. const char *proto;
  16127. size_t proto_len;
  16128. unsigned default_port;
  16129. } abs_uri_protocols[] = {{"http://", 7, 80},
  16130. {"https://", 8, 443},
  16131. {"ws://", 5, 80},
  16132. {"wss://", 6, 443},
  16133. {NULL, 0, 0}};
  16134. /* Check if the uri is valid.
  16135. * return 0 for invalid uri,
  16136. * return 1 for *,
  16137. * return 2 for relative uri,
  16138. * return 3 for absolute uri without port,
  16139. * return 4 for absolute uri with port */
  16140. static int
  16141. get_uri_type(const char *uri)
  16142. {
  16143. int i;
  16144. const char *hostend, *portbegin;
  16145. char *portend;
  16146. unsigned long port;
  16147. /* According to the HTTP standard
  16148. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  16149. * URI can be an asterisk (*) or should start with slash (relative uri),
  16150. * or it should start with the protocol (absolute uri). */
  16151. if ((uri[0] == '*') && (uri[1] == '\0')) {
  16152. /* asterisk */
  16153. return 1;
  16154. }
  16155. /* Valid URIs according to RFC 3986
  16156. * (https://www.ietf.org/rfc/rfc3986.txt)
  16157. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  16158. * and unreserved characters A-Z a-z 0-9 and -._~
  16159. * and % encoded symbols.
  16160. */
  16161. for (i = 0; uri[i] != 0; i++) {
  16162. if ((unsigned char)uri[i] < 33) {
  16163. /* control characters and spaces are invalid */
  16164. return 0;
  16165. }
  16166. /* Allow everything else here (See #894) */
  16167. }
  16168. /* A relative uri starts with a / character */
  16169. if (uri[0] == '/') {
  16170. /* relative uri */
  16171. return 2;
  16172. }
  16173. /* It could be an absolute uri: */
  16174. /* This function only checks if the uri is valid, not if it is
  16175. * addressing the current server. So civetweb can also be used
  16176. * as a proxy server. */
  16177. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16178. if (mg_strncasecmp(uri,
  16179. abs_uri_protocols[i].proto,
  16180. abs_uri_protocols[i].proto_len)
  16181. == 0) {
  16182. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  16183. if (!hostend) {
  16184. return 0;
  16185. }
  16186. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  16187. if (!portbegin) {
  16188. return 3;
  16189. }
  16190. port = strtoul(portbegin + 1, &portend, 10);
  16191. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  16192. return 0;
  16193. }
  16194. return 4;
  16195. }
  16196. }
  16197. return 0;
  16198. }
  16199. /* Return NULL or the relative uri at the current server */
  16200. static const char *
  16201. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  16202. {
  16203. const char *server_domain;
  16204. size_t server_domain_len;
  16205. size_t request_domain_len = 0;
  16206. unsigned long port = 0;
  16207. int i, auth_domain_check_enabled;
  16208. const char *hostbegin = NULL;
  16209. const char *hostend = NULL;
  16210. const char *portbegin;
  16211. char *portend;
  16212. auth_domain_check_enabled =
  16213. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  16214. /* DNS is case insensitive, so use case insensitive string compare here
  16215. */
  16216. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  16217. if (mg_strncasecmp(uri,
  16218. abs_uri_protocols[i].proto,
  16219. abs_uri_protocols[i].proto_len)
  16220. == 0) {
  16221. hostbegin = uri + abs_uri_protocols[i].proto_len;
  16222. hostend = strchr(hostbegin, '/');
  16223. if (!hostend) {
  16224. return 0;
  16225. }
  16226. portbegin = strchr(hostbegin, ':');
  16227. if ((!portbegin) || (portbegin > hostend)) {
  16228. port = abs_uri_protocols[i].default_port;
  16229. request_domain_len = (size_t)(hostend - hostbegin);
  16230. } else {
  16231. port = strtoul(portbegin + 1, &portend, 10);
  16232. if ((portend != hostend) || (port <= 0)
  16233. || !is_valid_port(port)) {
  16234. return 0;
  16235. }
  16236. request_domain_len = (size_t)(portbegin - hostbegin);
  16237. }
  16238. /* protocol found, port set */
  16239. break;
  16240. }
  16241. }
  16242. if (!port) {
  16243. /* port remains 0 if the protocol is not found */
  16244. return 0;
  16245. }
  16246. /* Check if the request is directed to a different server. */
  16247. /* First check if the port is the same. */
  16248. if (ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa)) != port) {
  16249. /* Request is directed to a different port */
  16250. return 0;
  16251. }
  16252. /* Finally check if the server corresponds to the authentication
  16253. * domain of the server (the server domain).
  16254. * Allow full matches (like http://mydomain.com/path/file.ext), and
  16255. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  16256. * but do not allow substrings (like
  16257. * http://notmydomain.com/path/file.ext
  16258. * or http://mydomain.com.fake/path/file.ext).
  16259. */
  16260. if (auth_domain_check_enabled) {
  16261. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  16262. server_domain_len = strlen(server_domain);
  16263. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  16264. return 0;
  16265. }
  16266. if ((request_domain_len == server_domain_len)
  16267. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  16268. /* Request is directed to this server - full name match. */
  16269. } else {
  16270. if (request_domain_len < (server_domain_len + 2)) {
  16271. /* Request is directed to another server: The server name
  16272. * is longer than the request name.
  16273. * Drop this case here to avoid overflows in the
  16274. * following checks. */
  16275. return 0;
  16276. }
  16277. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  16278. /* Request is directed to another server: It could be a
  16279. * substring
  16280. * like notmyserver.com */
  16281. return 0;
  16282. }
  16283. if (0
  16284. != memcmp(server_domain,
  16285. hostbegin + request_domain_len - server_domain_len,
  16286. server_domain_len)) {
  16287. /* Request is directed to another server:
  16288. * The server name is different. */
  16289. return 0;
  16290. }
  16291. }
  16292. }
  16293. return hostend;
  16294. }
  16295. static int
  16296. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16297. {
  16298. if (ebuf_len > 0) {
  16299. ebuf[0] = '\0';
  16300. }
  16301. *err = 0;
  16302. reset_per_request_attributes(conn);
  16303. if (!conn) {
  16304. mg_snprintf(conn,
  16305. NULL, /* No truncation check for ebuf */
  16306. ebuf,
  16307. ebuf_len,
  16308. "%s",
  16309. "Internal error");
  16310. *err = 500;
  16311. return 0;
  16312. }
  16313. /* Set the time the request was received. This value should be used for
  16314. * timeouts. */
  16315. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  16316. conn->request_len =
  16317. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  16318. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  16319. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  16320. mg_snprintf(conn,
  16321. NULL, /* No truncation check for ebuf */
  16322. ebuf,
  16323. ebuf_len,
  16324. "%s",
  16325. "Invalid message size");
  16326. *err = 500;
  16327. return 0;
  16328. }
  16329. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  16330. mg_snprintf(conn,
  16331. NULL, /* No truncation check for ebuf */
  16332. ebuf,
  16333. ebuf_len,
  16334. "%s",
  16335. "Message too large");
  16336. *err = 413;
  16337. return 0;
  16338. }
  16339. if (conn->request_len <= 0) {
  16340. if (conn->data_len > 0) {
  16341. mg_snprintf(conn,
  16342. NULL, /* No truncation check for ebuf */
  16343. ebuf,
  16344. ebuf_len,
  16345. "%s",
  16346. conn->request_len == -3 ? "Request timeout"
  16347. : "Malformed message");
  16348. *err = 400;
  16349. } else {
  16350. /* Server did not recv anything -> just close the connection */
  16351. conn->must_close = 1;
  16352. mg_snprintf(conn,
  16353. NULL, /* No truncation check for ebuf */
  16354. ebuf,
  16355. ebuf_len,
  16356. "%s",
  16357. "No data received");
  16358. *err = 0;
  16359. }
  16360. return 0;
  16361. }
  16362. return 1;
  16363. }
  16364. static int
  16365. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16366. {
  16367. const char *cl;
  16368. conn->connection_type =
  16369. CONNECTION_TYPE_REQUEST; /* request (valid of not) */
  16370. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16371. return 0;
  16372. }
  16373. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  16374. <= 0) {
  16375. mg_snprintf(conn,
  16376. NULL, /* No truncation check for ebuf */
  16377. ebuf,
  16378. ebuf_len,
  16379. "%s",
  16380. "Bad request");
  16381. *err = 400;
  16382. return 0;
  16383. }
  16384. /* Message is a valid request */
  16385. if (!switch_domain_context(conn)) {
  16386. mg_snprintf(conn,
  16387. NULL, /* No truncation check for ebuf */
  16388. ebuf,
  16389. ebuf_len,
  16390. "%s",
  16391. "Bad request: Host mismatch");
  16392. *err = 400;
  16393. return 0;
  16394. }
  16395. #if USE_ZLIB
  16396. if (((cl = get_header(conn->request_info.http_headers,
  16397. conn->request_info.num_headers,
  16398. "Accept-Encoding"))
  16399. != NULL)
  16400. && strstr(cl, "gzip")) {
  16401. conn->accept_gzip = 1;
  16402. }
  16403. #endif
  16404. if (((cl = get_header(conn->request_info.http_headers,
  16405. conn->request_info.num_headers,
  16406. "Transfer-Encoding"))
  16407. != NULL)
  16408. && mg_strcasecmp(cl, "identity")) {
  16409. if (mg_strcasecmp(cl, "chunked")) {
  16410. mg_snprintf(conn,
  16411. NULL, /* No truncation check for ebuf */
  16412. ebuf,
  16413. ebuf_len,
  16414. "%s",
  16415. "Bad request");
  16416. *err = 400;
  16417. return 0;
  16418. }
  16419. conn->is_chunked = 1;
  16420. conn->content_len = 0; /* not yet read */
  16421. } else if ((cl = get_header(conn->request_info.http_headers,
  16422. conn->request_info.num_headers,
  16423. "Content-Length"))
  16424. != NULL) {
  16425. /* Request has content length set */
  16426. char *endptr = NULL;
  16427. conn->content_len = strtoll(cl, &endptr, 10);
  16428. if ((endptr == cl) || (conn->content_len < 0)) {
  16429. mg_snprintf(conn,
  16430. NULL, /* No truncation check for ebuf */
  16431. ebuf,
  16432. ebuf_len,
  16433. "%s",
  16434. "Bad request");
  16435. *err = 411;
  16436. return 0;
  16437. }
  16438. /* Publish the content length back to the request info. */
  16439. conn->request_info.content_length = conn->content_len;
  16440. } else {
  16441. /* There is no exception, see RFC7230. */
  16442. conn->content_len = 0;
  16443. }
  16444. return 1;
  16445. }
  16446. /* conn is assumed to be valid in this internal function */
  16447. static int
  16448. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  16449. {
  16450. const char *cl;
  16451. conn->connection_type =
  16452. CONNECTION_TYPE_RESPONSE; /* response (valid or not) */
  16453. if (!get_message(conn, ebuf, ebuf_len, err)) {
  16454. return 0;
  16455. }
  16456. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  16457. <= 0) {
  16458. mg_snprintf(conn,
  16459. NULL, /* No truncation check for ebuf */
  16460. ebuf,
  16461. ebuf_len,
  16462. "%s",
  16463. "Bad response");
  16464. *err = 400;
  16465. return 0;
  16466. }
  16467. /* Message is a valid response */
  16468. if (((cl = get_header(conn->response_info.http_headers,
  16469. conn->response_info.num_headers,
  16470. "Transfer-Encoding"))
  16471. != NULL)
  16472. && mg_strcasecmp(cl, "identity")) {
  16473. if (mg_strcasecmp(cl, "chunked")) {
  16474. mg_snprintf(conn,
  16475. NULL, /* No truncation check for ebuf */
  16476. ebuf,
  16477. ebuf_len,
  16478. "%s",
  16479. "Bad request");
  16480. *err = 400;
  16481. return 0;
  16482. }
  16483. conn->is_chunked = 1;
  16484. conn->content_len = 0; /* not yet read */
  16485. } else if ((cl = get_header(conn->response_info.http_headers,
  16486. conn->response_info.num_headers,
  16487. "Content-Length"))
  16488. != NULL) {
  16489. char *endptr = NULL;
  16490. conn->content_len = strtoll(cl, &endptr, 10);
  16491. if ((endptr == cl) || (conn->content_len < 0)) {
  16492. mg_snprintf(conn,
  16493. NULL, /* No truncation check for ebuf */
  16494. ebuf,
  16495. ebuf_len,
  16496. "%s",
  16497. "Bad request");
  16498. *err = 411;
  16499. return 0;
  16500. }
  16501. /* Publish the content length back to the response info. */
  16502. conn->response_info.content_length = conn->content_len;
  16503. /* TODO: check if it is still used in response_info */
  16504. conn->request_info.content_length = conn->content_len;
  16505. /* TODO: we should also consider HEAD method */
  16506. if (conn->response_info.status_code == 304) {
  16507. conn->content_len = 0;
  16508. }
  16509. } else {
  16510. /* TODO: we should also consider HEAD method */
  16511. if (((conn->response_info.status_code >= 100)
  16512. && (conn->response_info.status_code <= 199))
  16513. || (conn->response_info.status_code == 204)
  16514. || (conn->response_info.status_code == 304)) {
  16515. conn->content_len = 0;
  16516. } else {
  16517. conn->content_len = -1; /* unknown content length */
  16518. }
  16519. }
  16520. return 1;
  16521. }
  16522. CIVETWEB_API int
  16523. mg_get_response(struct mg_connection *conn,
  16524. char *ebuf,
  16525. size_t ebuf_len,
  16526. int timeout)
  16527. {
  16528. int err, ret;
  16529. char txt[32]; /* will not overflow */
  16530. char *save_timeout;
  16531. char *new_timeout;
  16532. if (ebuf_len > 0) {
  16533. ebuf[0] = '\0';
  16534. }
  16535. if (!conn) {
  16536. mg_snprintf(conn,
  16537. NULL, /* No truncation check for ebuf */
  16538. ebuf,
  16539. ebuf_len,
  16540. "%s",
  16541. "Parameter error");
  16542. return -1;
  16543. }
  16544. /* Reset the previous responses */
  16545. conn->data_len = 0;
  16546. /* Implementation of API function for HTTP clients */
  16547. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  16548. if (timeout >= 0) {
  16549. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  16550. new_timeout = txt;
  16551. } else {
  16552. new_timeout = NULL;
  16553. }
  16554. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  16555. ret = get_response(conn, ebuf, ebuf_len, &err);
  16556. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  16557. /* TODO: here, the URI is the http response code */
  16558. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16559. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16560. /* TODO (mid): Define proper return values - maybe return length?
  16561. * For the first test use <0 for error and >0 for OK */
  16562. return (ret == 0) ? -1 : +1;
  16563. }
  16564. CIVETWEB_API struct mg_connection *
  16565. mg_download(const char *host,
  16566. int port,
  16567. int use_ssl,
  16568. char *ebuf,
  16569. size_t ebuf_len,
  16570. const char *fmt,
  16571. ...)
  16572. {
  16573. struct mg_connection *conn;
  16574. va_list ap;
  16575. int i;
  16576. int reqerr;
  16577. if (ebuf_len > 0) {
  16578. ebuf[0] = '\0';
  16579. }
  16580. va_start(ap, fmt);
  16581. /* open a connection */
  16582. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  16583. if (conn != NULL) {
  16584. i = mg_vprintf(conn, fmt, ap);
  16585. if (i <= 0) {
  16586. mg_snprintf(conn,
  16587. NULL, /* No truncation check for ebuf */
  16588. ebuf,
  16589. ebuf_len,
  16590. "%s",
  16591. "Error sending request");
  16592. } else {
  16593. /* make sure the buffer is clear */
  16594. conn->data_len = 0;
  16595. get_response(conn, ebuf, ebuf_len, &reqerr);
  16596. /* TODO: here, the URI is the http response code */
  16597. conn->request_info.local_uri = conn->request_info.request_uri;
  16598. }
  16599. }
  16600. /* if an error occurred, close the connection */
  16601. if ((ebuf[0] != '\0') && (conn != NULL)) {
  16602. mg_close_connection(conn);
  16603. conn = NULL;
  16604. }
  16605. va_end(ap);
  16606. return conn;
  16607. }
  16608. struct websocket_client_thread_data {
  16609. struct mg_connection *conn;
  16610. mg_websocket_data_handler data_handler;
  16611. mg_websocket_close_handler close_handler;
  16612. void *callback_data;
  16613. };
  16614. #if defined(USE_WEBSOCKET)
  16615. #if defined(_WIN32)
  16616. static unsigned __stdcall websocket_client_thread(void *data)
  16617. #else
  16618. static void *
  16619. websocket_client_thread(void *data)
  16620. #endif
  16621. {
  16622. struct websocket_client_thread_data *cdata =
  16623. (struct websocket_client_thread_data *)data;
  16624. void *user_thread_ptr = NULL;
  16625. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16626. struct sigaction sa;
  16627. /* Ignore SIGPIPE */
  16628. memset(&sa, 0, sizeof(sa));
  16629. sa.sa_handler = SIG_IGN;
  16630. sigaction(SIGPIPE, &sa, NULL);
  16631. #endif
  16632. mg_set_thread_name("ws-clnt");
  16633. if (cdata->conn->phys_ctx) {
  16634. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  16635. /* 3 indicates a websocket client thread */
  16636. /* TODO: check if conn->phys_ctx can be set */
  16637. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  16638. cdata->conn->phys_ctx, 3);
  16639. }
  16640. }
  16641. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  16642. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  16643. if (cdata->close_handler != NULL) {
  16644. cdata->close_handler(cdata->conn, cdata->callback_data);
  16645. }
  16646. /* The websocket_client context has only this thread. If it runs out,
  16647. set the stop_flag to 2 (= "stopped"). */
  16648. STOP_FLAG_ASSIGN(&cdata->conn->phys_ctx->stop_flag, 2);
  16649. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  16650. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  16651. 3,
  16652. user_thread_ptr);
  16653. }
  16654. mg_free((void *)cdata);
  16655. #if defined(_WIN32)
  16656. return 0;
  16657. #else
  16658. return NULL;
  16659. #endif
  16660. }
  16661. #endif
  16662. static struct mg_connection *
  16663. mg_connect_websocket_client_impl(const struct mg_client_options *client_options,
  16664. int use_ssl,
  16665. char *error_buffer,
  16666. size_t error_buffer_size,
  16667. const char *path,
  16668. const char *origin,
  16669. const char *extensions,
  16670. mg_websocket_data_handler data_func,
  16671. mg_websocket_close_handler close_func,
  16672. void *user_data)
  16673. {
  16674. struct mg_connection *conn = NULL;
  16675. #if defined(USE_WEBSOCKET)
  16676. struct websocket_client_thread_data *thread_data;
  16677. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  16678. const char *host = client_options->host;
  16679. int i;
  16680. struct mg_init_data init;
  16681. struct mg_error_data error;
  16682. memset(&init, 0, sizeof(init));
  16683. memset(&error, 0, sizeof(error));
  16684. error.text_buffer_size = error_buffer_size;
  16685. error.text = error_buffer;
  16686. #if defined(__clang__)
  16687. #pragma clang diagnostic push
  16688. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  16689. #endif
  16690. /* Establish the client connection and request upgrade */
  16691. conn = mg_connect_client_impl(client_options, use_ssl, &init, &error);
  16692. /* Connection object will be null if something goes wrong */
  16693. if (conn == NULL) {
  16694. /* error_buffer should be already filled ... */
  16695. if (!error_buffer[0]) {
  16696. /* ... if not add an error message */
  16697. mg_snprintf(conn,
  16698. NULL, /* No truncation check for ebuf */
  16699. error_buffer,
  16700. error_buffer_size,
  16701. "Unexpected error");
  16702. }
  16703. return NULL;
  16704. }
  16705. if (origin != NULL) {
  16706. if (extensions != NULL) {
  16707. i = mg_printf(conn,
  16708. "GET %s HTTP/1.1\r\n"
  16709. "Host: %s\r\n"
  16710. "Upgrade: websocket\r\n"
  16711. "Connection: Upgrade\r\n"
  16712. "Sec-WebSocket-Key: %s\r\n"
  16713. "Sec-WebSocket-Version: 13\r\n"
  16714. "Sec-WebSocket-Extensions: %s\r\n"
  16715. "Origin: %s\r\n"
  16716. "\r\n",
  16717. path,
  16718. host,
  16719. magic,
  16720. extensions,
  16721. origin);
  16722. } else {
  16723. i = mg_printf(conn,
  16724. "GET %s HTTP/1.1\r\n"
  16725. "Host: %s\r\n"
  16726. "Upgrade: websocket\r\n"
  16727. "Connection: Upgrade\r\n"
  16728. "Sec-WebSocket-Key: %s\r\n"
  16729. "Sec-WebSocket-Version: 13\r\n"
  16730. "Origin: %s\r\n"
  16731. "\r\n",
  16732. path,
  16733. host,
  16734. magic,
  16735. origin);
  16736. }
  16737. } else {
  16738. if (extensions != NULL) {
  16739. i = mg_printf(conn,
  16740. "GET %s HTTP/1.1\r\n"
  16741. "Host: %s\r\n"
  16742. "Upgrade: websocket\r\n"
  16743. "Connection: Upgrade\r\n"
  16744. "Sec-WebSocket-Key: %s\r\n"
  16745. "Sec-WebSocket-Version: 13\r\n"
  16746. "Sec-WebSocket-Extensions: %s\r\n"
  16747. "\r\n",
  16748. path,
  16749. host,
  16750. magic,
  16751. extensions);
  16752. } else {
  16753. i = mg_printf(conn,
  16754. "GET %s HTTP/1.1\r\n"
  16755. "Host: %s\r\n"
  16756. "Upgrade: websocket\r\n"
  16757. "Connection: Upgrade\r\n"
  16758. "Sec-WebSocket-Key: %s\r\n"
  16759. "Sec-WebSocket-Version: 13\r\n"
  16760. "\r\n",
  16761. path,
  16762. host,
  16763. magic);
  16764. }
  16765. }
  16766. if (i <= 0) {
  16767. mg_snprintf(conn,
  16768. NULL, /* No truncation check for ebuf */
  16769. error_buffer,
  16770. error_buffer_size,
  16771. "%s",
  16772. "Error sending request");
  16773. mg_close_connection(conn);
  16774. return NULL;
  16775. }
  16776. conn->data_len = 0;
  16777. if (!get_response(conn, error_buffer, error_buffer_size, &i)) {
  16778. mg_close_connection(conn);
  16779. return NULL;
  16780. }
  16781. conn->request_info.local_uri_raw = conn->request_info.request_uri;
  16782. conn->request_info.local_uri = conn->request_info.local_uri_raw;
  16783. #if defined(__clang__)
  16784. #pragma clang diagnostic pop
  16785. #endif
  16786. if (conn->response_info.status_code != 101) {
  16787. /* We sent an "upgrade" request. For a correct websocket
  16788. * protocol handshake, we expect a "101 Continue" response.
  16789. * Otherwise it is a protocol violation. Maybe the HTTP
  16790. * Server does not know websockets. */
  16791. if (!*error_buffer) {
  16792. /* set an error, if not yet set */
  16793. mg_snprintf(conn,
  16794. NULL, /* No truncation check for ebuf */
  16795. error_buffer,
  16796. error_buffer_size,
  16797. "Unexpected server reply");
  16798. }
  16799. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  16800. mg_close_connection(conn);
  16801. return NULL;
  16802. }
  16803. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  16804. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  16805. if (!thread_data) {
  16806. DEBUG_TRACE("%s\r\n", "Out of memory");
  16807. mg_close_connection(conn);
  16808. return NULL;
  16809. }
  16810. thread_data->conn = conn;
  16811. thread_data->data_handler = data_func;
  16812. thread_data->close_handler = close_func;
  16813. thread_data->callback_data = user_data;
  16814. conn->phys_ctx->worker_threadids =
  16815. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  16816. if (!conn->phys_ctx->worker_threadids) {
  16817. DEBUG_TRACE("%s\r\n", "Out of memory");
  16818. mg_free(thread_data);
  16819. mg_close_connection(conn);
  16820. return NULL;
  16821. }
  16822. /* Now upgrade to ws/wss client context */
  16823. conn->phys_ctx->user_data = user_data;
  16824. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  16825. conn->phys_ctx->cfg_max_worker_threads = 1; /* one worker thread */
  16826. conn->phys_ctx->spawned_worker_threads = 1; /* one worker thread */
  16827. /* Start a thread to read the websocket client connection
  16828. * This thread will automatically stop when mg_disconnect is
  16829. * called on the client connection */
  16830. if (mg_start_thread_with_id(websocket_client_thread,
  16831. thread_data,
  16832. conn->phys_ctx->worker_threadids)
  16833. != 0) {
  16834. conn->phys_ctx->spawned_worker_threads = 0;
  16835. mg_free(thread_data);
  16836. mg_close_connection(conn);
  16837. conn = NULL;
  16838. DEBUG_TRACE("%s",
  16839. "Websocket client connect thread could not be started\r\n");
  16840. }
  16841. #else
  16842. /* Appease "unused parameter" warnings */
  16843. (void)client_options;
  16844. (void)use_ssl;
  16845. (void)error_buffer;
  16846. (void)error_buffer_size;
  16847. (void)path;
  16848. (void)origin;
  16849. (void)extensions;
  16850. (void)user_data;
  16851. (void)data_func;
  16852. (void)close_func;
  16853. #endif
  16854. return conn;
  16855. }
  16856. CIVETWEB_API struct mg_connection *
  16857. mg_connect_websocket_client(const char *host,
  16858. int port,
  16859. int use_ssl,
  16860. char *error_buffer,
  16861. size_t error_buffer_size,
  16862. const char *path,
  16863. const char *origin,
  16864. mg_websocket_data_handler data_func,
  16865. mg_websocket_close_handler close_func,
  16866. void *user_data)
  16867. {
  16868. struct mg_client_options client_options;
  16869. memset(&client_options, 0, sizeof(client_options));
  16870. client_options.host = host;
  16871. client_options.port = port;
  16872. return mg_connect_websocket_client_impl(&client_options,
  16873. use_ssl,
  16874. error_buffer,
  16875. error_buffer_size,
  16876. path,
  16877. origin,
  16878. NULL,
  16879. data_func,
  16880. close_func,
  16881. user_data);
  16882. }
  16883. CIVETWEB_API struct mg_connection *
  16884. mg_connect_websocket_client_secure(
  16885. const struct mg_client_options *client_options,
  16886. char *error_buffer,
  16887. size_t error_buffer_size,
  16888. const char *path,
  16889. const char *origin,
  16890. mg_websocket_data_handler data_func,
  16891. mg_websocket_close_handler close_func,
  16892. void *user_data)
  16893. {
  16894. if (!client_options) {
  16895. return NULL;
  16896. }
  16897. return mg_connect_websocket_client_impl(client_options,
  16898. 1,
  16899. error_buffer,
  16900. error_buffer_size,
  16901. path,
  16902. origin,
  16903. NULL,
  16904. data_func,
  16905. close_func,
  16906. user_data);
  16907. }
  16908. CIVETWEB_API struct mg_connection *
  16909. mg_connect_websocket_client_extensions(const char *host,
  16910. int port,
  16911. int use_ssl,
  16912. char *error_buffer,
  16913. size_t error_buffer_size,
  16914. const char *path,
  16915. const char *origin,
  16916. const char *extensions,
  16917. mg_websocket_data_handler data_func,
  16918. mg_websocket_close_handler close_func,
  16919. void *user_data)
  16920. {
  16921. struct mg_client_options client_options;
  16922. memset(&client_options, 0, sizeof(client_options));
  16923. client_options.host = host;
  16924. client_options.port = port;
  16925. return mg_connect_websocket_client_impl(&client_options,
  16926. use_ssl,
  16927. error_buffer,
  16928. error_buffer_size,
  16929. path,
  16930. origin,
  16931. extensions,
  16932. data_func,
  16933. close_func,
  16934. user_data);
  16935. }
  16936. CIVETWEB_API struct mg_connection *
  16937. mg_connect_websocket_client_secure_extensions(
  16938. const struct mg_client_options *client_options,
  16939. char *error_buffer,
  16940. size_t error_buffer_size,
  16941. const char *path,
  16942. const char *origin,
  16943. const char *extensions,
  16944. mg_websocket_data_handler data_func,
  16945. mg_websocket_close_handler close_func,
  16946. void *user_data)
  16947. {
  16948. if (!client_options) {
  16949. return NULL;
  16950. }
  16951. return mg_connect_websocket_client_impl(client_options,
  16952. 1,
  16953. error_buffer,
  16954. error_buffer_size,
  16955. path,
  16956. origin,
  16957. extensions,
  16958. data_func,
  16959. close_func,
  16960. user_data);
  16961. }
  16962. /* Prepare connection data structure */
  16963. static void
  16964. init_connection(struct mg_connection *conn)
  16965. {
  16966. /* Is keep alive allowed by the server */
  16967. int keep_alive_enabled =
  16968. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  16969. if (!keep_alive_enabled) {
  16970. conn->must_close = 1;
  16971. }
  16972. /* Important: on new connection, reset the receiving buffer. Credit
  16973. * goes to crule42. */
  16974. conn->data_len = 0;
  16975. conn->handled_requests = 0;
  16976. conn->connection_type = CONNECTION_TYPE_INVALID;
  16977. conn->request_info.acceptedWebSocketSubprotocol = NULL;
  16978. mg_set_user_connection_data(conn, NULL);
  16979. #if defined(USE_SERVER_STATS)
  16980. conn->conn_state = 2; /* init */
  16981. #endif
  16982. /* call the init_connection callback if assigned */
  16983. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  16984. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  16985. void *conn_data = NULL;
  16986. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  16987. mg_set_user_connection_data(conn, conn_data);
  16988. }
  16989. }
  16990. }
  16991. /* Process a connection - may handle multiple requests
  16992. * using the same connection.
  16993. * Must be called with a valid connection (conn and
  16994. * conn->phys_ctx must be valid).
  16995. */
  16996. static void
  16997. process_new_connection(struct mg_connection *conn)
  16998. {
  16999. struct mg_request_info *ri = &conn->request_info;
  17000. int keep_alive, discard_len;
  17001. char ebuf[100];
  17002. const char *hostend;
  17003. int reqerr, uri_type;
  17004. #if defined(USE_SERVER_STATS)
  17005. ptrdiff_t mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  17006. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  17007. mg_atomic_max(&(conn->phys_ctx->max_active_connections), mcon);
  17008. #endif
  17009. DEBUG_TRACE("Start processing connection from %s",
  17010. conn->request_info.remote_addr);
  17011. /* Loop over multiple requests sent using the same connection
  17012. * (while "keep alive"). */
  17013. do {
  17014. DEBUG_TRACE("calling get_request (%i times for this connection)",
  17015. conn->handled_requests + 1);
  17016. #if defined(USE_SERVER_STATS)
  17017. conn->conn_state = 3; /* ready */
  17018. #endif
  17019. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  17020. /* The request sent by the client could not be understood by
  17021. * the server, or it was incomplete or a timeout. Send an
  17022. * error message and close the connection. */
  17023. if (reqerr > 0) {
  17024. DEBUG_ASSERT(ebuf[0] != '\0');
  17025. mg_send_http_error(conn, reqerr, "%s", ebuf);
  17026. }
  17027. } else if (strcmp(ri->http_version, "1.0")
  17028. && strcmp(ri->http_version, "1.1")) {
  17029. /* HTTP/2 is not allowed here */
  17030. mg_snprintf(conn,
  17031. NULL, /* No truncation check for ebuf */
  17032. ebuf,
  17033. sizeof(ebuf),
  17034. "Bad HTTP version: [%s]",
  17035. ri->http_version);
  17036. mg_send_http_error(conn, 505, "%s", ebuf);
  17037. }
  17038. if (ebuf[0] == '\0') {
  17039. uri_type = get_uri_type(conn->request_info.request_uri);
  17040. switch (uri_type) {
  17041. case 1:
  17042. /* Asterisk */
  17043. conn->request_info.local_uri_raw = 0;
  17044. /* TODO: Deal with '*'. */
  17045. break;
  17046. case 2:
  17047. /* relative uri */
  17048. conn->request_info.local_uri_raw =
  17049. conn->request_info.request_uri;
  17050. break;
  17051. case 3:
  17052. case 4:
  17053. /* absolute uri (with/without port) */
  17054. hostend = get_rel_url_at_current_server(
  17055. conn->request_info.request_uri, conn);
  17056. if (hostend) {
  17057. conn->request_info.local_uri_raw = hostend;
  17058. } else {
  17059. conn->request_info.local_uri_raw = NULL;
  17060. }
  17061. break;
  17062. default:
  17063. mg_snprintf(conn,
  17064. NULL, /* No truncation check for ebuf */
  17065. ebuf,
  17066. sizeof(ebuf),
  17067. "Invalid URI");
  17068. mg_send_http_error(conn, 400, "%s", ebuf);
  17069. conn->request_info.local_uri_raw = NULL;
  17070. break;
  17071. }
  17072. conn->request_info.local_uri =
  17073. (char *)conn->request_info.local_uri_raw;
  17074. }
  17075. if (ebuf[0] != '\0') {
  17076. conn->protocol_type = -1;
  17077. } else {
  17078. /* HTTP/1 allows protocol upgrade */
  17079. conn->protocol_type = should_switch_to_protocol(conn);
  17080. if (conn->protocol_type == PROTOCOL_TYPE_HTTP2) {
  17081. /* This will occur, if a HTTP/1.1 request should be upgraded
  17082. * to HTTP/2 - but not if HTTP/2 is negotiated using ALPN.
  17083. * Since most (all?) major browsers only support HTTP/2 using
  17084. * ALPN, this is hard to test and very low priority.
  17085. * Deactivate it (at least for now).
  17086. */
  17087. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17088. }
  17089. }
  17090. DEBUG_TRACE("http: %s, error: %s",
  17091. (ri->http_version ? ri->http_version : "none"),
  17092. (ebuf[0] ? ebuf : "none"));
  17093. if (ebuf[0] == '\0') {
  17094. if (conn->request_info.local_uri) {
  17095. /* handle request to local server */
  17096. handle_request_stat_log(conn);
  17097. } else {
  17098. /* TODO: handle non-local request (PROXY) */
  17099. conn->must_close = 1;
  17100. }
  17101. } else {
  17102. conn->must_close = 1;
  17103. }
  17104. /* Response complete. Free header buffer */
  17105. free_buffered_response_header_list(conn);
  17106. if (ri->remote_user != NULL) {
  17107. mg_free((void *)ri->remote_user);
  17108. /* Important! When having connections with and without auth
  17109. * would cause double free and then crash */
  17110. ri->remote_user = NULL;
  17111. }
  17112. /* NOTE(lsm): order is important here. should_keep_alive() call
  17113. * is using parsed request, which will be invalid after
  17114. * memmove's below.
  17115. * Therefore, memorize should_keep_alive() result now for later
  17116. * use in loop exit condition. */
  17117. /* Enable it only if this request is completely discardable. */
  17118. keep_alive = STOP_FLAG_IS_ZERO(&conn->phys_ctx->stop_flag)
  17119. && should_keep_alive(conn) && (conn->content_len >= 0)
  17120. && (conn->request_len > 0)
  17121. && ((conn->is_chunked == 4)
  17122. || (!conn->is_chunked
  17123. && ((conn->consumed_content == conn->content_len)
  17124. || ((conn->request_len + conn->content_len)
  17125. <= conn->data_len))))
  17126. && (conn->protocol_type == PROTOCOL_TYPE_HTTP1);
  17127. if (keep_alive) {
  17128. /* Discard all buffered data for this request */
  17129. discard_len =
  17130. ((conn->request_len + conn->content_len) < conn->data_len)
  17131. ? (int)(conn->request_len + conn->content_len)
  17132. : conn->data_len;
  17133. conn->data_len -= discard_len;
  17134. if (conn->data_len > 0) {
  17135. DEBUG_TRACE("discard_len = %d", discard_len);
  17136. memmove(conn->buf,
  17137. conn->buf + discard_len,
  17138. (size_t)conn->data_len);
  17139. }
  17140. }
  17141. DEBUG_ASSERT(conn->data_len >= 0);
  17142. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  17143. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  17144. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  17145. (long int)conn->data_len,
  17146. (long int)conn->buf_size);
  17147. break;
  17148. }
  17149. conn->handled_requests++;
  17150. } while (keep_alive);
  17151. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  17152. conn->request_info.remote_addr,
  17153. difftime(time(NULL), conn->conn_birth_time));
  17154. close_connection(conn);
  17155. #if defined(USE_SERVER_STATS)
  17156. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  17157. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  17158. #endif
  17159. }
  17160. static int
  17161. mg_start_worker_thread(struct mg_context *ctx,
  17162. int only_if_no_idle_threads); /* forward declaration */
  17163. #if defined(ALTERNATIVE_QUEUE)
  17164. static void
  17165. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17166. {
  17167. unsigned int i;
  17168. (void)mg_start_worker_thread(
  17169. ctx, 1); /* will start a worker-thread only if there aren't currently
  17170. any idle worker-threads */
  17171. while (!ctx->stop_flag) {
  17172. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17173. /* find a free worker slot and signal it */
  17174. if (ctx->client_socks[i].in_use == 2) {
  17175. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17176. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  17177. ctx->client_socks[i] = *sp;
  17178. ctx->client_socks[i].in_use = 1;
  17179. /* socket has been moved to the consumer */
  17180. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17181. (void)event_signal(ctx->client_wait_events[i]);
  17182. return;
  17183. }
  17184. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17185. }
  17186. }
  17187. /* queue is full */
  17188. mg_sleep(1);
  17189. }
  17190. /* must consume */
  17191. set_blocking_mode(sp->sock);
  17192. closesocket(sp->sock);
  17193. }
  17194. static int
  17195. consume_socket(struct mg_context *ctx,
  17196. struct socket *sp,
  17197. int thread_index,
  17198. int counter_was_preincremented)
  17199. {
  17200. DEBUG_TRACE("%s", "going idle");
  17201. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17202. if (counter_was_preincremented
  17203. == 0) { /* first call only: the master-thread pre-incremented this
  17204. before he spawned us */
  17205. ctx->idle_worker_thread_count++;
  17206. }
  17207. ctx->client_socks[thread_index].in_use = 2;
  17208. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17209. event_wait(ctx->client_wait_events[thread_index]);
  17210. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17211. *sp = ctx->client_socks[thread_index];
  17212. if (ctx->stop_flag) {
  17213. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17214. if (sp->in_use == 1) {
  17215. /* must consume */
  17216. set_blocking_mode(sp->sock);
  17217. closesocket(sp->sock);
  17218. }
  17219. return 0;
  17220. }
  17221. ctx->idle_worker_thread_count--;
  17222. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17223. if (sp->in_use == 1) {
  17224. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  17225. return 1;
  17226. }
  17227. /* must not reach here */
  17228. DEBUG_ASSERT(0);
  17229. return 0;
  17230. }
  17231. #else /* ALTERNATIVE_QUEUE */
  17232. /* Worker threads take accepted socket from the queue */
  17233. static int
  17234. consume_socket(struct mg_context *ctx,
  17235. struct socket *sp,
  17236. int thread_index,
  17237. int counter_was_preincremented)
  17238. {
  17239. (void)thread_index;
  17240. DEBUG_TRACE("%s", "going idle");
  17241. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17242. if (counter_was_preincremented
  17243. == 0) { /* first call only: the master-thread pre-incremented this
  17244. before he spawned us */
  17245. ctx->idle_worker_thread_count++;
  17246. }
  17247. /* If the queue is empty, wait. We're idle at this point. */
  17248. while ((ctx->sq_head == ctx->sq_tail)
  17249. && (STOP_FLAG_IS_ZERO(&ctx->stop_flag))) {
  17250. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  17251. }
  17252. /* If we're stopping, sq_head may be equal to sq_tail. */
  17253. if (ctx->sq_head > ctx->sq_tail) {
  17254. /* Copy socket from the queue and increment tail */
  17255. *sp = ctx->squeue[ctx->sq_tail % ctx->sq_size];
  17256. ctx->sq_tail++;
  17257. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  17258. /* Wrap pointers if needed */
  17259. while (ctx->sq_tail > ctx->sq_size) {
  17260. ctx->sq_tail -= ctx->sq_size;
  17261. ctx->sq_head -= ctx->sq_size;
  17262. }
  17263. }
  17264. (void)pthread_cond_signal(&ctx->sq_empty);
  17265. ctx->idle_worker_thread_count--;
  17266. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17267. return STOP_FLAG_IS_ZERO(&ctx->stop_flag);
  17268. }
  17269. /* Master thread adds accepted socket to a queue */
  17270. static void
  17271. produce_socket(struct mg_context *ctx, const struct socket *sp)
  17272. {
  17273. int queue_filled;
  17274. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17275. queue_filled = ctx->sq_head - ctx->sq_tail;
  17276. /* If the queue is full, wait */
  17277. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17278. && (queue_filled >= ctx->sq_size)) {
  17279. ctx->sq_blocked = 1; /* Status information: All threads busy */
  17280. #if defined(USE_SERVER_STATS)
  17281. if (queue_filled > ctx->sq_max_fill) {
  17282. ctx->sq_max_fill = queue_filled;
  17283. }
  17284. #endif
  17285. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  17286. ctx->sq_blocked = 0; /* Not blocked now */
  17287. queue_filled = ctx->sq_head - ctx->sq_tail;
  17288. }
  17289. if (queue_filled < ctx->sq_size) {
  17290. /* Copy socket to the queue and increment head */
  17291. ctx->squeue[ctx->sq_head % ctx->sq_size] = *sp;
  17292. ctx->sq_head++;
  17293. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  17294. }
  17295. queue_filled = ctx->sq_head - ctx->sq_tail;
  17296. #if defined(USE_SERVER_STATS)
  17297. if (queue_filled > ctx->sq_max_fill) {
  17298. ctx->sq_max_fill = queue_filled;
  17299. }
  17300. #endif
  17301. (void)pthread_cond_signal(&ctx->sq_full);
  17302. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17303. (void)mg_start_worker_thread(
  17304. ctx, 1); /* will start a worker-thread only if there aren't currently
  17305. any idle worker-threads */
  17306. }
  17307. #endif /* ALTERNATIVE_QUEUE */
  17308. static void
  17309. worker_thread_run(struct mg_connection *conn)
  17310. {
  17311. struct mg_context *ctx = conn->phys_ctx;
  17312. int thread_index;
  17313. struct mg_workerTLS tls;
  17314. int first_call_to_consume_socket = 1;
  17315. mg_set_thread_name("worker");
  17316. tls.is_master = 0;
  17317. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  17318. #if defined(_WIN32)
  17319. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17320. #endif
  17321. /* Initialize thread local storage before calling any callback */
  17322. pthread_setspecific(sTlsKey, &tls);
  17323. /* Check if there is a user callback */
  17324. if (ctx->callbacks.init_thread) {
  17325. /* call init_thread for a worker thread (type 1), and store the
  17326. * return value */
  17327. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  17328. } else {
  17329. /* No callback: set user pointer to NULL */
  17330. tls.user_ptr = NULL;
  17331. }
  17332. /* Connection structure has been pre-allocated */
  17333. thread_index = (int)(conn - ctx->worker_connections);
  17334. if ((thread_index < 0)
  17335. || ((unsigned)thread_index >= (unsigned)ctx->cfg_max_worker_threads)) {
  17336. mg_cry_ctx_internal(ctx,
  17337. "Internal error: Invalid worker index %i",
  17338. thread_index);
  17339. return;
  17340. }
  17341. /* Request buffers are not pre-allocated. They are private to the
  17342. * request and do not contain any state information that might be
  17343. * of interest to anyone observing a server status. */
  17344. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  17345. if (conn->buf == NULL) {
  17346. mg_cry_ctx_internal(
  17347. ctx,
  17348. "Out of memory: Cannot allocate buffer for worker %i",
  17349. thread_index);
  17350. return;
  17351. }
  17352. conn->buf_size = (int)ctx->max_request_size;
  17353. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  17354. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  17355. conn->request_info.user_data = ctx->user_data;
  17356. /* Allocate a mutex for this connection to allow communication both
  17357. * within the request handler and from elsewhere in the application
  17358. */
  17359. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  17360. mg_free(conn->buf);
  17361. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  17362. return;
  17363. }
  17364. #if defined(USE_SERVER_STATS)
  17365. conn->conn_state = 1; /* not consumed */
  17366. #endif
  17367. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  17368. * signal sq_empty condvar to wake up the master waiting in
  17369. * produce_socket() */
  17370. while (consume_socket(
  17371. ctx, &conn->client, thread_index, first_call_to_consume_socket)) {
  17372. first_call_to_consume_socket = 0;
  17373. /* New connections must start with new protocol negotiation */
  17374. tls.alpn_proto = NULL;
  17375. #if defined(USE_SERVER_STATS)
  17376. conn->conn_close_time = 0;
  17377. #endif
  17378. conn->conn_birth_time = time(NULL);
  17379. /* Fill in IP, port info early so even if SSL setup below fails,
  17380. * error handler would have the corresponding info.
  17381. * Thanks to Johannes Winkelmann for the patch.
  17382. */
  17383. conn->request_info.remote_port =
  17384. ntohs(USA_IN_PORT_UNSAFE(&conn->client.rsa));
  17385. conn->request_info.server_port =
  17386. ntohs(USA_IN_PORT_UNSAFE(&conn->client.lsa));
  17387. sockaddr_to_string(conn->request_info.remote_addr,
  17388. sizeof(conn->request_info.remote_addr),
  17389. &conn->client.rsa);
  17390. DEBUG_TRACE("Incoming %sconnection from %s",
  17391. (conn->client.is_ssl ? "SSL " : ""),
  17392. conn->request_info.remote_addr);
  17393. conn->request_info.is_ssl = conn->client.is_ssl;
  17394. if (conn->client.is_ssl) {
  17395. #if defined(USE_MBEDTLS)
  17396. /* HTTPS connection */
  17397. if (mbed_ssl_accept(&(conn->ssl),
  17398. conn->dom_ctx->ssl_ctx,
  17399. (int *)&(conn->client.sock),
  17400. conn->phys_ctx)
  17401. == 0) {
  17402. /* conn->dom_ctx is set in get_request */
  17403. /* process HTTPS connection */
  17404. init_connection(conn);
  17405. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17406. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17407. process_new_connection(conn);
  17408. } else {
  17409. /* make sure the connection is cleaned up on SSL failure */
  17410. close_connection(conn);
  17411. }
  17412. #elif !defined(NO_SSL)
  17413. /* HTTPS connection */
  17414. if (sslize(conn, SSL_accept, NULL)) {
  17415. /* conn->dom_ctx is set in get_request */
  17416. /* Get SSL client certificate information (if set) */
  17417. struct mg_client_cert client_cert;
  17418. if (ssl_get_client_cert_info(conn, &client_cert)) {
  17419. conn->request_info.client_cert = &client_cert;
  17420. }
  17421. /* process HTTPS connection */
  17422. #if defined(USE_HTTP2)
  17423. if ((tls.alpn_proto != NULL)
  17424. && (!memcmp(tls.alpn_proto, "\x02h2", 3))) {
  17425. /* process HTTPS/2 connection */
  17426. init_connection(conn);
  17427. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17428. conn->protocol_type = PROTOCOL_TYPE_HTTP2;
  17429. conn->content_len =
  17430. -1; /* content length is not predefined */
  17431. conn->is_chunked = 0; /* HTTP2 is never chunked */
  17432. process_new_http2_connection(conn);
  17433. } else
  17434. #endif
  17435. {
  17436. /* process HTTPS/1.x or WEBSOCKET-SECURE connection */
  17437. init_connection(conn);
  17438. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17439. /* Start with HTTP, WS will be an "upgrade" request later */
  17440. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17441. process_new_connection(conn);
  17442. }
  17443. /* Free client certificate info */
  17444. if (conn->request_info.client_cert) {
  17445. mg_free((void *)(conn->request_info.client_cert->subject));
  17446. mg_free((void *)(conn->request_info.client_cert->issuer));
  17447. mg_free((void *)(conn->request_info.client_cert->serial));
  17448. mg_free((void *)(conn->request_info.client_cert->finger));
  17449. /* Free certificate memory */
  17450. X509_free(
  17451. (X509 *)conn->request_info.client_cert->peer_cert);
  17452. conn->request_info.client_cert->peer_cert = 0;
  17453. conn->request_info.client_cert->subject = 0;
  17454. conn->request_info.client_cert->issuer = 0;
  17455. conn->request_info.client_cert->serial = 0;
  17456. conn->request_info.client_cert->finger = 0;
  17457. conn->request_info.client_cert = 0;
  17458. }
  17459. } else {
  17460. /* make sure the connection is cleaned up on SSL failure */
  17461. close_connection(conn);
  17462. }
  17463. #endif
  17464. } else {
  17465. /* process HTTP connection */
  17466. init_connection(conn);
  17467. conn->connection_type = CONNECTION_TYPE_REQUEST;
  17468. /* Start with HTTP, WS will be an "upgrade" request later */
  17469. conn->protocol_type = PROTOCOL_TYPE_HTTP1;
  17470. process_new_connection(conn);
  17471. }
  17472. DEBUG_TRACE("%s", "Connection closed");
  17473. #if defined(USE_SERVER_STATS)
  17474. conn->conn_close_time = time(NULL);
  17475. #endif
  17476. }
  17477. /* Call exit thread user callback */
  17478. if (ctx->callbacks.exit_thread) {
  17479. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  17480. }
  17481. /* delete thread local storage objects */
  17482. pthread_setspecific(sTlsKey, NULL);
  17483. #if defined(_WIN32)
  17484. CloseHandle(tls.pthread_cond_helper_mutex);
  17485. #endif
  17486. pthread_mutex_destroy(&conn->mutex);
  17487. /* Free the request buffer. */
  17488. conn->buf_size = 0;
  17489. mg_free(conn->buf);
  17490. conn->buf = NULL;
  17491. /* Free cleaned URI (if any) */
  17492. if (conn->request_info.local_uri != conn->request_info.local_uri_raw) {
  17493. mg_free((void *)conn->request_info.local_uri);
  17494. conn->request_info.local_uri = NULL;
  17495. }
  17496. #if defined(USE_SERVER_STATS)
  17497. conn->conn_state = 9; /* done */
  17498. #endif
  17499. DEBUG_TRACE("%s", "exiting");
  17500. }
  17501. /* Threads have different return types on Windows and Unix. */
  17502. #if defined(_WIN32)
  17503. static unsigned __stdcall worker_thread(void *thread_func_param)
  17504. {
  17505. worker_thread_run((struct mg_connection *)thread_func_param);
  17506. return 0;
  17507. }
  17508. #else
  17509. static void *
  17510. worker_thread(void *thread_func_param)
  17511. {
  17512. #if !defined(__ZEPHYR__)
  17513. struct sigaction sa;
  17514. /* Ignore SIGPIPE */
  17515. memset(&sa, 0, sizeof(sa));
  17516. sa.sa_handler = SIG_IGN;
  17517. sigaction(SIGPIPE, &sa, NULL);
  17518. #endif
  17519. worker_thread_run((struct mg_connection *)thread_func_param);
  17520. return NULL;
  17521. }
  17522. #endif /* _WIN32 */
  17523. /* This is an internal function, thus all arguments are expected to be
  17524. * valid - a NULL check is not required. */
  17525. static void
  17526. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  17527. {
  17528. struct socket so;
  17529. char src_addr[IP_ADDR_STR_LEN];
  17530. socklen_t len = sizeof(so.rsa);
  17531. #if !defined(__ZEPHYR__)
  17532. int on = 1;
  17533. #endif
  17534. memset(&so, 0, sizeof(so));
  17535. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  17536. == INVALID_SOCKET) {
  17537. } else if (check_acl(ctx, &so.rsa) != 1) {
  17538. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  17539. mg_cry_ctx_internal(ctx,
  17540. "%s: %s is not allowed to connect",
  17541. __func__,
  17542. src_addr);
  17543. closesocket(so.sock);
  17544. } else {
  17545. /* Put so socket structure into the queue */
  17546. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  17547. set_close_on_exec(so.sock, NULL, ctx);
  17548. so.is_ssl = listener->is_ssl;
  17549. so.ssl_redir = listener->ssl_redir;
  17550. so.is_optional = listener->is_optional;
  17551. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  17552. mg_cry_ctx_internal(ctx,
  17553. "%s: getsockname() failed: %s",
  17554. __func__,
  17555. strerror(ERRNO));
  17556. }
  17557. #if !defined(__ZEPHYR__)
  17558. if ((so.lsa.sa.sa_family == AF_INET)
  17559. || (so.lsa.sa.sa_family == AF_INET6)) {
  17560. /* Set TCP keep-alive for TCP sockets (IPv4 and IPv6).
  17561. * This is needed because if HTTP-level keep-alive
  17562. * is enabled, and client resets the connection, server won't get
  17563. * TCP FIN or RST and will keep the connection open forever. With
  17564. * TCP keep-alive, next keep-alive handshake will figure out that
  17565. * the client is down and will close the server end.
  17566. * Thanks to Igor Klopov who suggested the patch. */
  17567. if (setsockopt(so.sock,
  17568. SOL_SOCKET,
  17569. SO_KEEPALIVE,
  17570. (SOCK_OPT_TYPE)&on,
  17571. sizeof(on))
  17572. != 0) {
  17573. mg_cry_ctx_internal(
  17574. ctx,
  17575. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  17576. __func__,
  17577. strerror(ERRNO));
  17578. }
  17579. }
  17580. #endif
  17581. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  17582. * to effectively fill up the underlying IP packet payload and
  17583. * reduce the overhead of sending lots of small buffers. However
  17584. * this hurts the server's throughput (ie. operations per second)
  17585. * when HTTP 1.1 persistent connections are used and the responses
  17586. * are relatively small (eg. less than 1400 bytes).
  17587. */
  17588. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  17589. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  17590. if (set_tcp_nodelay(&so, 1) != 0) {
  17591. mg_cry_ctx_internal(
  17592. ctx,
  17593. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  17594. __func__,
  17595. strerror(ERRNO));
  17596. }
  17597. }
  17598. /* The "non blocking" property should already be
  17599. * inherited from the parent socket. Set it for
  17600. * non-compliant socket implementations. */
  17601. set_non_blocking_mode(so.sock);
  17602. so.in_use = 0;
  17603. produce_socket(ctx, &so);
  17604. }
  17605. }
  17606. static void
  17607. master_thread_run(struct mg_context *ctx)
  17608. {
  17609. struct mg_workerTLS tls;
  17610. struct mg_pollfd *pfd;
  17611. unsigned int i;
  17612. unsigned int workerthreadcount;
  17613. if (!ctx) {
  17614. return;
  17615. }
  17616. mg_set_thread_name("master");
  17617. /* Increase priority of the master thread */
  17618. #if defined(_WIN32)
  17619. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  17620. #elif defined(USE_MASTER_THREAD_PRIORITY)
  17621. int min_prio = sched_get_priority_min(SCHED_RR);
  17622. int max_prio = sched_get_priority_max(SCHED_RR);
  17623. if ((min_prio >= 0) && (max_prio >= 0)
  17624. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  17625. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  17626. struct sched_param sched_param = {0};
  17627. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  17628. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  17629. }
  17630. #endif
  17631. /* Initialize thread local storage */
  17632. #if defined(_WIN32)
  17633. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  17634. #endif
  17635. tls.is_master = 1;
  17636. pthread_setspecific(sTlsKey, &tls);
  17637. if (ctx->callbacks.init_thread) {
  17638. /* Callback for the master thread (type 0) */
  17639. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  17640. } else {
  17641. tls.user_ptr = NULL;
  17642. }
  17643. /* Lua background script "start" event */
  17644. #if defined(USE_LUA)
  17645. if (ctx->lua_background_state) {
  17646. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17647. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17648. /* call "start()" in Lua */
  17649. lua_getglobal(lstate, "start");
  17650. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17651. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17652. if (ret != 0) {
  17653. struct mg_connection fc;
  17654. lua_cry(fake_connection(&fc, ctx),
  17655. ret,
  17656. lstate,
  17657. "lua_background_script",
  17658. "start");
  17659. }
  17660. } else {
  17661. lua_pop(lstate, 1);
  17662. }
  17663. /* determine if there is a "log()" function in Lua background script */
  17664. lua_getglobal(lstate, "log");
  17665. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17666. ctx->lua_bg_log_available = 1;
  17667. }
  17668. lua_pop(lstate, 1);
  17669. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17670. }
  17671. #endif
  17672. /* Server starts *now* */
  17673. ctx->start_time = time(NULL);
  17674. /* Server accept loop */
  17675. pfd = ctx->listening_socket_fds;
  17676. while (STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  17677. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17678. pfd[i].fd = ctx->listening_sockets[i].sock;
  17679. pfd[i].events = POLLIN;
  17680. }
  17681. /* We listen on this socket just so that mg_stop() can cause mg_poll()
  17682. * to return ASAP. Don't worry, we did allocate an extra slot at the end
  17683. * of listening_socket_fds[] just to hold this
  17684. */
  17685. pfd[ctx->num_listening_sockets].fd =
  17686. ctx->thread_shutdown_notification_socket;
  17687. pfd[ctx->num_listening_sockets].events = POLLIN;
  17688. if (mg_poll(pfd,
  17689. ctx->num_listening_sockets
  17690. + 1, // +1 for the thread_shutdown_notification_socket
  17691. SOCKET_TIMEOUT_QUANTUM,
  17692. &(ctx->stop_flag))
  17693. > 0) {
  17694. for (i = 0; i < ctx->num_listening_sockets; i++) {
  17695. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  17696. * successful poll, and POLLIN is defined as
  17697. * (POLLRDNORM | POLLRDBAND)
  17698. * Therefore, we're checking pfd[i].revents & POLLIN, not
  17699. * pfd[i].revents == POLLIN. */
  17700. if (STOP_FLAG_IS_ZERO(&ctx->stop_flag)
  17701. && (pfd[i].revents & POLLIN)) {
  17702. accept_new_connection(&ctx->listening_sockets[i], ctx);
  17703. }
  17704. }
  17705. }
  17706. }
  17707. /* Here stop_flag is 1 - Initiate shutdown. */
  17708. DEBUG_TRACE("%s", "stopping workers");
  17709. /* Stop signal received: somebody called mg_stop. Quit. */
  17710. close_all_listening_sockets(ctx);
  17711. /* Wakeup workers that are waiting for connections to handle. */
  17712. #if defined(ALTERNATIVE_QUEUE)
  17713. for (i = 0; i < ctx->spawned_worker_threads; i++) {
  17714. event_signal(ctx->client_wait_events[i]);
  17715. }
  17716. #else
  17717. (void)pthread_mutex_lock(&ctx->thread_mutex);
  17718. pthread_cond_broadcast(&ctx->sq_full);
  17719. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  17720. #endif
  17721. /* Join all worker threads to avoid leaking threads. */
  17722. workerthreadcount = ctx->spawned_worker_threads;
  17723. for (i = 0; i < workerthreadcount; i++) {
  17724. if (ctx->worker_threadids[i] != 0) {
  17725. mg_join_thread(ctx->worker_threadids[i]);
  17726. }
  17727. }
  17728. #if defined(USE_LUA)
  17729. /* Free Lua state of lua background task */
  17730. if (ctx->lua_background_state) {
  17731. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  17732. ctx->lua_bg_log_available = 0;
  17733. /* call "stop()" in Lua */
  17734. pthread_mutex_lock(&ctx->lua_bg_mutex);
  17735. lua_getglobal(lstate, "stop");
  17736. if (lua_type(lstate, -1) == LUA_TFUNCTION) {
  17737. int ret = lua_pcall(lstate, /* args */ 0, /* results */ 0, 0);
  17738. if (ret != 0) {
  17739. struct mg_connection fc;
  17740. lua_cry(fake_connection(&fc, ctx),
  17741. ret,
  17742. lstate,
  17743. "lua_background_script",
  17744. "stop");
  17745. }
  17746. }
  17747. DEBUG_TRACE("Close Lua background state %p", lstate);
  17748. lua_close(lstate);
  17749. ctx->lua_background_state = 0;
  17750. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  17751. }
  17752. #endif
  17753. DEBUG_TRACE("%s", "exiting");
  17754. /* call exit thread callback */
  17755. if (ctx->callbacks.exit_thread) {
  17756. /* Callback for the master thread (type 0) */
  17757. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  17758. }
  17759. #if defined(_WIN32)
  17760. CloseHandle(tls.pthread_cond_helper_mutex);
  17761. #endif
  17762. pthread_setspecific(sTlsKey, NULL);
  17763. /* Signal mg_stop() that we're done.
  17764. * WARNING: This must be the very last thing this
  17765. * thread does, as ctx becomes invalid after this line. */
  17766. STOP_FLAG_ASSIGN(&ctx->stop_flag, 2);
  17767. }
  17768. /* Threads have different return types on Windows and Unix. */
  17769. #if defined(_WIN32)
  17770. static unsigned __stdcall master_thread(void *thread_func_param)
  17771. {
  17772. master_thread_run((struct mg_context *)thread_func_param);
  17773. return 0;
  17774. }
  17775. #else
  17776. static void *
  17777. master_thread(void *thread_func_param)
  17778. {
  17779. #if !defined(__ZEPHYR__)
  17780. struct sigaction sa;
  17781. /* Ignore SIGPIPE */
  17782. memset(&sa, 0, sizeof(sa));
  17783. sa.sa_handler = SIG_IGN;
  17784. sigaction(SIGPIPE, &sa, NULL);
  17785. #endif
  17786. master_thread_run((struct mg_context *)thread_func_param);
  17787. return NULL;
  17788. }
  17789. #endif /* _WIN32 */
  17790. static void
  17791. free_context(struct mg_context *ctx)
  17792. {
  17793. int i;
  17794. struct mg_handler_info *tmp_rh;
  17795. if (ctx == NULL) {
  17796. return;
  17797. }
  17798. /* Call user callback */
  17799. if (ctx->callbacks.exit_context) {
  17800. ctx->callbacks.exit_context(ctx);
  17801. }
  17802. /* All threads exited, no sync is needed. Destroy thread mutex and
  17803. * condvars
  17804. */
  17805. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  17806. #if defined(ALTERNATIVE_QUEUE)
  17807. mg_free(ctx->client_socks);
  17808. if (ctx->client_wait_events != NULL) {
  17809. for (i = 0; (unsigned)i < ctx->spawned_worker_threads; i++) {
  17810. event_destroy(ctx->client_wait_events[i]);
  17811. }
  17812. mg_free(ctx->client_wait_events);
  17813. }
  17814. #else
  17815. (void)pthread_cond_destroy(&ctx->sq_empty);
  17816. (void)pthread_cond_destroy(&ctx->sq_full);
  17817. mg_free(ctx->squeue);
  17818. #endif
  17819. /* Destroy other context global data structures mutex */
  17820. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  17821. #if defined(USE_LUA)
  17822. (void)pthread_mutex_destroy(&ctx->lua_bg_mutex);
  17823. #endif
  17824. /* Deallocate shutdown-triggering socket-pair */
  17825. if (ctx->user_shutdown_notification_socket >= 0) {
  17826. closesocket(ctx->user_shutdown_notification_socket);
  17827. }
  17828. if (ctx->thread_shutdown_notification_socket >= 0) {
  17829. closesocket(ctx->thread_shutdown_notification_socket);
  17830. }
  17831. /* Deallocate config parameters */
  17832. for (i = 0; i < NUM_OPTIONS; i++) {
  17833. if (ctx->dd.config[i] != NULL) {
  17834. #if defined(_MSC_VER)
  17835. #pragma warning(suppress : 6001)
  17836. #endif
  17837. mg_free(ctx->dd.config[i]);
  17838. }
  17839. }
  17840. /* Deallocate request handlers */
  17841. while (ctx->dd.handlers) {
  17842. tmp_rh = ctx->dd.handlers;
  17843. ctx->dd.handlers = tmp_rh->next;
  17844. mg_free(tmp_rh->uri);
  17845. mg_free(tmp_rh);
  17846. }
  17847. #if defined(USE_MBEDTLS)
  17848. if (ctx->dd.ssl_ctx != NULL) {
  17849. mbed_sslctx_uninit(ctx->dd.ssl_ctx);
  17850. mg_free(ctx->dd.ssl_ctx);
  17851. ctx->dd.ssl_ctx = NULL;
  17852. }
  17853. #elif !defined(NO_SSL)
  17854. /* Deallocate SSL context */
  17855. if (ctx->dd.ssl_ctx != NULL) {
  17856. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  17857. int callback_ret =
  17858. (ctx->callbacks.external_ssl_ctx == NULL)
  17859. ? 0
  17860. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  17861. if (callback_ret == 0) {
  17862. SSL_CTX_free(ctx->dd.ssl_ctx);
  17863. }
  17864. /* else: ignore error and omit SSL_CTX_free in case
  17865. * callback_ret is 1 */
  17866. }
  17867. #endif /* !NO_SSL */
  17868. /* Deallocate worker thread ID array */
  17869. mg_free(ctx->worker_threadids);
  17870. /* Deallocate worker thread ID array */
  17871. mg_free(ctx->worker_connections);
  17872. /* deallocate system name string */
  17873. mg_free(ctx->systemName);
  17874. /* Deallocate context itself */
  17875. mg_free(ctx);
  17876. }
  17877. CIVETWEB_API void
  17878. mg_stop(struct mg_context *ctx)
  17879. {
  17880. pthread_t mt;
  17881. if (!ctx) {
  17882. return;
  17883. }
  17884. /* We don't use a lock here. Calling mg_stop with the same ctx from
  17885. * two threads is not allowed. */
  17886. mt = ctx->masterthreadid;
  17887. if (mt == 0) {
  17888. return;
  17889. }
  17890. ctx->masterthreadid = 0;
  17891. /* Set stop flag, so all threads know they have to exit. */
  17892. STOP_FLAG_ASSIGN(&ctx->stop_flag, 1);
  17893. /* Closing this socket will cause mg_poll() in all the I/O threads to return
  17894. * immediately */
  17895. closesocket(ctx->user_shutdown_notification_socket);
  17896. ctx->user_shutdown_notification_socket =
  17897. -1; /* to avoid calling closesocket() again in free_context() */
  17898. /* Join timer thread */
  17899. #if defined(USE_TIMERS)
  17900. timers_exit(ctx);
  17901. #endif
  17902. /* Wait until everything has stopped. */
  17903. while (!STOP_FLAG_IS_TWO(&ctx->stop_flag)) {
  17904. (void)mg_sleep(10);
  17905. }
  17906. /* Wait to stop master thread */
  17907. mg_join_thread(mt);
  17908. /* Close remaining Lua states */
  17909. #if defined(USE_LUA)
  17910. lua_ctx_exit(ctx);
  17911. #endif
  17912. /* Free memory */
  17913. free_context(ctx);
  17914. }
  17915. static void
  17916. get_system_name(char **sysName)
  17917. {
  17918. #if defined(_WIN32)
  17919. char name[128];
  17920. DWORD dwVersion = 0;
  17921. DWORD dwMajorVersion = 0;
  17922. DWORD dwMinorVersion = 0;
  17923. DWORD dwBuild = 0;
  17924. BOOL wowRet, isWoW = FALSE;
  17925. #if defined(_MSC_VER)
  17926. #pragma warning(push)
  17927. /* GetVersion was declared deprecated */
  17928. #pragma warning(disable : 4996)
  17929. #endif
  17930. dwVersion = GetVersion();
  17931. #if defined(_MSC_VER)
  17932. #pragma warning(pop)
  17933. #endif
  17934. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  17935. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  17936. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  17937. (void)dwBuild;
  17938. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  17939. sprintf(name,
  17940. "Windows %u.%u%s",
  17941. (unsigned)dwMajorVersion,
  17942. (unsigned)dwMinorVersion,
  17943. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  17944. *sysName = mg_strdup(name);
  17945. #elif defined(__ZEPHYR__)
  17946. *sysName = mg_strdup("Zephyr OS");
  17947. #else
  17948. struct utsname name;
  17949. memset(&name, 0, sizeof(name));
  17950. uname(&name);
  17951. *sysName = mg_strdup(name.sysname);
  17952. #endif
  17953. }
  17954. static void
  17955. legacy_init(const char **options)
  17956. {
  17957. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  17958. if (options) {
  17959. const char **run_options = options;
  17960. const char *optname = config_options[LISTENING_PORTS].name;
  17961. /* Try to find the "listening_ports" option */
  17962. while (*run_options) {
  17963. if (!strcmp(*run_options, optname)) {
  17964. ports_option = run_options[1];
  17965. }
  17966. run_options += 2;
  17967. }
  17968. }
  17969. if (is_ssl_port_used(ports_option)) {
  17970. /* Initialize with SSL support */
  17971. mg_init_library(MG_FEATURES_TLS);
  17972. } else {
  17973. /* Initialize without SSL support */
  17974. mg_init_library(MG_FEATURES_DEFAULT);
  17975. }
  17976. }
  17977. /* we'll assume it's only Windows that doesn't have socketpair() available */
  17978. #if !defined(HAVE_SOCKETPAIR) && !defined(_WIN32)
  17979. #define HAVE_SOCKETPAIR 1
  17980. #endif
  17981. static int
  17982. mg_socketpair(int *sockA, int *sockB)
  17983. {
  17984. int temp[2] = {-1, -1};
  17985. int asock = -1;
  17986. /** Default to unallocated */
  17987. *sockA = -1;
  17988. *sockB = -1;
  17989. #if defined(HAVE_SOCKETPAIR)
  17990. int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, temp);
  17991. if (ret == 0) {
  17992. *sockA = temp[0];
  17993. *sockB = temp[1];
  17994. set_close_on_exec(*sockA, NULL, NULL);
  17995. set_close_on_exec(*sockB, NULL, NULL);
  17996. }
  17997. (void)asock; /* not used */
  17998. return ret;
  17999. #else
  18000. /** No socketpair() call is available, so we'll have to roll our own
  18001. * implementation */
  18002. asock = socket(PF_INET, SOCK_STREAM, 0);
  18003. if (asock >= 0) {
  18004. struct sockaddr_in addr;
  18005. struct sockaddr *pa = (struct sockaddr *)&addr;
  18006. socklen_t addrLen = sizeof(addr);
  18007. memset(&addr, 0, sizeof(addr));
  18008. addr.sin_family = AF_INET;
  18009. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  18010. addr.sin_port = 0;
  18011. if ((bind(asock, pa, sizeof(addr)) == 0)
  18012. && (getsockname(asock, pa, &addrLen) == 0)
  18013. && (listen(asock, 1) == 0)) {
  18014. temp[0] = socket(PF_INET, SOCK_STREAM, 0);
  18015. if ((temp[0] >= 0) && (connect(temp[0], pa, sizeof(addr)) == 0)) {
  18016. temp[1] = accept(asock, pa, &addrLen);
  18017. if (temp[1] >= 0) {
  18018. closesocket(asock);
  18019. *sockA = temp[0];
  18020. *sockB = temp[1];
  18021. set_close_on_exec(*sockA, NULL, NULL);
  18022. set_close_on_exec(*sockB, NULL, NULL);
  18023. return 0; /* success! */
  18024. }
  18025. }
  18026. }
  18027. }
  18028. /* Cleanup */
  18029. if (asock >= 0)
  18030. closesocket(asock);
  18031. if (temp[0] >= 0)
  18032. closesocket(temp[0]);
  18033. if (temp[1] >= 0)
  18034. closesocket(temp[1]);
  18035. return -1; /* fail! */
  18036. #endif
  18037. }
  18038. static int
  18039. mg_start_worker_thread(struct mg_context *ctx, int only_if_no_idle_threads)
  18040. {
  18041. const unsigned int i = ctx->spawned_worker_threads;
  18042. if (i >= ctx->cfg_max_worker_threads) {
  18043. return -1; /* Oops, we hit our worker-thread limit! No more worker
  18044. threads, ever! */
  18045. }
  18046. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18047. #if defined(ALTERNATIVE_QUEUE)
  18048. if ((only_if_no_idle_threads) && (ctx->idle_worker_thread_count > 0)) {
  18049. #else
  18050. if ((only_if_no_idle_threads)
  18051. && (ctx->idle_worker_thread_count
  18052. > (unsigned)(ctx->sq_head - ctx->sq_tail))) {
  18053. #endif
  18054. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18055. return -2; /* There are idle threads available, so no need to spawn a
  18056. new worker thread now */
  18057. }
  18058. ctx->idle_worker_thread_count++; /* we do this here to avoid a race
  18059. condition while the thread is starting
  18060. up */
  18061. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18062. ctx->worker_connections[i].phys_ctx = ctx;
  18063. int ret = mg_start_thread_with_id(worker_thread,
  18064. &ctx->worker_connections[i],
  18065. &ctx->worker_threadids[i]);
  18066. if (ret == 0) {
  18067. ctx->spawned_worker_threads++; /* note that we've filled another slot in
  18068. the table */
  18069. DEBUG_TRACE("Started worker_thread #%i", ctx->spawned_worker_threads);
  18070. } else {
  18071. (void)pthread_mutex_lock(&ctx->thread_mutex);
  18072. ctx->idle_worker_thread_count--; /* whoops, roll-back on error */
  18073. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  18074. }
  18075. return ret;
  18076. }
  18077. CIVETWEB_API struct mg_context *
  18078. mg_start2(struct mg_init_data *init, struct mg_error_data *error)
  18079. {
  18080. struct mg_context *ctx;
  18081. const char *name, *value, *default_value;
  18082. int idx, ok, prespawnthreadcount, workerthreadcount;
  18083. unsigned int i;
  18084. int itmp;
  18085. void (*exit_callback)(const struct mg_context *ctx) = 0;
  18086. const char **options =
  18087. ((init != NULL) ? (init->configuration_options) : (NULL));
  18088. struct mg_workerTLS tls;
  18089. if (error != NULL) {
  18090. error->code = MG_ERROR_DATA_CODE_OK;
  18091. error->code_sub = 0;
  18092. if (error->text_buffer_size > 0) {
  18093. *error->text = 0;
  18094. }
  18095. }
  18096. if (mg_init_library_called == 0) {
  18097. /* Legacy INIT, if mg_start is called without mg_init_library.
  18098. * Note: This will cause a memory leak when unloading the library.
  18099. */
  18100. legacy_init(options);
  18101. }
  18102. if (mg_init_library_called == 0) {
  18103. if (error != NULL) {
  18104. error->code = MG_ERROR_DATA_CODE_INIT_LIBRARY_FAILED;
  18105. mg_snprintf(NULL,
  18106. NULL, /* No truncation check for error buffers */
  18107. error->text,
  18108. error->text_buffer_size,
  18109. "%s",
  18110. "Library uninitialized");
  18111. }
  18112. return NULL;
  18113. }
  18114. /* Allocate context and initialize reasonable general case defaults. */
  18115. ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx));
  18116. if (ctx == NULL) {
  18117. if (error != NULL) {
  18118. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18119. error->code_sub = (unsigned)sizeof(*ctx);
  18120. mg_snprintf(NULL,
  18121. NULL, /* No truncation check for error buffers */
  18122. error->text,
  18123. error->text_buffer_size,
  18124. "%s",
  18125. "Out of memory");
  18126. }
  18127. return NULL;
  18128. }
  18129. /* Random number generator will initialize at the first call */
  18130. ctx->dd.auth_nonce_mask =
  18131. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  18132. /* Save started thread index to reuse in other external API calls
  18133. * For the sake of thread synchronization all non-civetweb threads
  18134. * can be considered as single external thread */
  18135. ctx->starter_thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  18136. tls.is_master = -1; /* Thread calling mg_start */
  18137. tls.thread_idx = ctx->starter_thread_idx;
  18138. #if defined(_WIN32)
  18139. tls.pthread_cond_helper_mutex = NULL;
  18140. #endif
  18141. pthread_setspecific(sTlsKey, &tls);
  18142. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  18143. #if !defined(ALTERNATIVE_QUEUE)
  18144. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  18145. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  18146. ctx->sq_blocked = 0;
  18147. #endif
  18148. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  18149. #if defined(USE_LUA)
  18150. ok &= (0 == pthread_mutex_init(&ctx->lua_bg_mutex, &pthread_mutex_attr));
  18151. #endif
  18152. /** mg_stop() will close the user_shutdown_notification_socket, and that
  18153. * will cause poll() to return immediately in the master-thread, so that
  18154. * mg_stop() can also return immediately.
  18155. */
  18156. ok &= (0
  18157. == mg_socketpair(&ctx->user_shutdown_notification_socket,
  18158. &ctx->thread_shutdown_notification_socket));
  18159. if (!ok) {
  18160. unsigned error_id = (unsigned)ERRNO;
  18161. const char *err_msg =
  18162. "Cannot initialize thread synchronization objects";
  18163. /* Fatal error - abort start. However, this situation should never
  18164. * occur in practice. */
  18165. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18166. if (error != NULL) {
  18167. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18168. error->code_sub = error_id;
  18169. mg_snprintf(NULL,
  18170. NULL, /* No truncation check for error buffers */
  18171. error->text,
  18172. error->text_buffer_size,
  18173. "%s",
  18174. err_msg);
  18175. }
  18176. mg_free(ctx);
  18177. pthread_setspecific(sTlsKey, NULL);
  18178. return NULL;
  18179. }
  18180. if ((init != NULL) && (init->callbacks != NULL)) {
  18181. /* Set all callbacks except exit_context. */
  18182. ctx->callbacks = *init->callbacks;
  18183. exit_callback = init->callbacks->exit_context;
  18184. /* The exit callback is activated once the context is successfully
  18185. * created. It should not be called, if an incomplete context object
  18186. * is deleted during a failed initialization. */
  18187. ctx->callbacks.exit_context = 0;
  18188. }
  18189. ctx->user_data = ((init != NULL) ? (init->user_data) : (NULL));
  18190. ctx->dd.handlers = NULL;
  18191. ctx->dd.next = NULL;
  18192. #if defined(USE_LUA)
  18193. lua_ctx_init(ctx);
  18194. #endif
  18195. /* Store options */
  18196. while (options && (name = *options++) != NULL) {
  18197. idx = get_option_index(name);
  18198. if (idx == -1) {
  18199. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18200. if (error != NULL) {
  18201. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18202. error->code_sub = (unsigned)-1;
  18203. mg_snprintf(NULL,
  18204. NULL, /* No truncation check for error buffers */
  18205. error->text,
  18206. error->text_buffer_size,
  18207. "Invalid configuration option: %s",
  18208. name);
  18209. }
  18210. free_context(ctx);
  18211. pthread_setspecific(sTlsKey, NULL);
  18212. return NULL;
  18213. } else if ((value = *options++) == NULL) {
  18214. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18215. if (error != NULL) {
  18216. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18217. error->code_sub = (unsigned)idx;
  18218. mg_snprintf(NULL,
  18219. NULL, /* No truncation check for error buffers */
  18220. error->text,
  18221. error->text_buffer_size,
  18222. "Invalid configuration option value: %s",
  18223. name);
  18224. }
  18225. free_context(ctx);
  18226. pthread_setspecific(sTlsKey, NULL);
  18227. return NULL;
  18228. }
  18229. if (ctx->dd.config[idx] != NULL) {
  18230. /* A duplicate configuration option is not an error - the last
  18231. * option value will be used. */
  18232. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18233. mg_free(ctx->dd.config[idx]);
  18234. }
  18235. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  18236. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18237. }
  18238. /* Set default value if needed */
  18239. for (i = 0; config_options[i].name != NULL; i++) {
  18240. default_value = config_options[i].default_value;
  18241. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  18242. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  18243. }
  18244. }
  18245. /* Request size option */
  18246. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  18247. if (itmp < 1024) {
  18248. mg_cry_ctx_internal(ctx,
  18249. "%s too small",
  18250. config_options[MAX_REQUEST_SIZE].name);
  18251. if (error != NULL) {
  18252. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18253. error->code_sub = (unsigned)MAX_REQUEST_SIZE;
  18254. mg_snprintf(NULL,
  18255. NULL, /* No truncation check for error buffers */
  18256. error->text,
  18257. error->text_buffer_size,
  18258. "Invalid configuration option value: %s",
  18259. config_options[MAX_REQUEST_SIZE].name);
  18260. }
  18261. free_context(ctx);
  18262. pthread_setspecific(sTlsKey, NULL);
  18263. return NULL;
  18264. }
  18265. ctx->max_request_size = (unsigned)itmp;
  18266. /* Queue length */
  18267. #if !defined(ALTERNATIVE_QUEUE)
  18268. itmp = atoi(ctx->dd.config[CONNECTION_QUEUE_SIZE]);
  18269. if (itmp < 1) {
  18270. mg_cry_ctx_internal(ctx,
  18271. "%s too small",
  18272. config_options[CONNECTION_QUEUE_SIZE].name);
  18273. if (error != NULL) {
  18274. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18275. error->code_sub = CONNECTION_QUEUE_SIZE;
  18276. mg_snprintf(NULL,
  18277. NULL, /* No truncation check for error buffers */
  18278. error->text,
  18279. error->text_buffer_size,
  18280. "Invalid configuration option value: %s",
  18281. config_options[CONNECTION_QUEUE_SIZE].name);
  18282. }
  18283. free_context(ctx);
  18284. pthread_setspecific(sTlsKey, NULL);
  18285. return NULL;
  18286. }
  18287. ctx->squeue =
  18288. (struct socket *)mg_calloc((unsigned int)itmp, sizeof(struct socket));
  18289. if (ctx->squeue == NULL) {
  18290. mg_cry_ctx_internal(ctx,
  18291. "Out of memory: Cannot allocate %s",
  18292. config_options[CONNECTION_QUEUE_SIZE].name);
  18293. if (error != NULL) {
  18294. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18295. error->code_sub = (unsigned)itmp * (unsigned)sizeof(struct socket);
  18296. mg_snprintf(NULL,
  18297. NULL, /* No truncation check for error buffers */
  18298. error->text,
  18299. error->text_buffer_size,
  18300. "Out of memory: Cannot allocate %s",
  18301. config_options[CONNECTION_QUEUE_SIZE].name);
  18302. }
  18303. free_context(ctx);
  18304. pthread_setspecific(sTlsKey, NULL);
  18305. return NULL;
  18306. }
  18307. ctx->sq_size = itmp;
  18308. #endif
  18309. /* Worker thread count option */
  18310. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  18311. prespawnthreadcount = atoi(ctx->dd.config[PRESPAWN_THREADS]);
  18312. if ((prespawnthreadcount < 0)
  18313. || (prespawnthreadcount > workerthreadcount)) {
  18314. prespawnthreadcount =
  18315. workerthreadcount; /* can't prespawn more than all of them! */
  18316. }
  18317. if ((workerthreadcount > MAX_WORKER_THREADS) || (workerthreadcount <= 0)) {
  18318. if (workerthreadcount <= 0) {
  18319. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  18320. } else {
  18321. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  18322. }
  18323. if (error != NULL) {
  18324. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18325. error->code_sub = NUM_THREADS;
  18326. mg_snprintf(NULL,
  18327. NULL, /* No truncation check for error buffers */
  18328. error->text,
  18329. error->text_buffer_size,
  18330. "Invalid configuration option value: %s",
  18331. config_options[NUM_THREADS].name);
  18332. }
  18333. free_context(ctx);
  18334. pthread_setspecific(sTlsKey, NULL);
  18335. return NULL;
  18336. }
  18337. /* Document root */
  18338. #if defined(NO_FILES)
  18339. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  18340. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  18341. if (error != NULL) {
  18342. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18343. error->code_sub = (unsigned)DOCUMENT_ROOT;
  18344. mg_snprintf(NULL,
  18345. NULL, /* No truncation check for error buffers */
  18346. error->text,
  18347. error->text_buffer_size,
  18348. "Invalid configuration option value: %s",
  18349. config_options[DOCUMENT_ROOT].name);
  18350. }
  18351. free_context(ctx);
  18352. pthread_setspecific(sTlsKey, NULL);
  18353. return NULL;
  18354. }
  18355. #endif
  18356. get_system_name(&ctx->systemName);
  18357. #if defined(USE_LUA)
  18358. /* If a Lua background script has been configured, start it. */
  18359. ctx->lua_bg_log_available = 0;
  18360. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  18361. char ebuf[256];
  18362. struct vec opt_vec;
  18363. struct vec eq_vec;
  18364. const char *sparams;
  18365. memset(ebuf, 0, sizeof(ebuf));
  18366. pthread_mutex_lock(&ctx->lua_bg_mutex);
  18367. /* Create a Lua state, load all standard libraries and the mg table */
  18368. lua_State *state = mg_lua_context_script_prepare(
  18369. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  18370. if (!state) {
  18371. mg_cry_ctx_internal(ctx,
  18372. "lua_background_script load error: %s",
  18373. ebuf);
  18374. if (error != NULL) {
  18375. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18376. mg_snprintf(NULL,
  18377. NULL, /* No truncation check for error buffers */
  18378. error->text,
  18379. error->text_buffer_size,
  18380. "Error in script %s: %s",
  18381. config_options[LUA_BACKGROUND_SCRIPT].name,
  18382. ebuf);
  18383. }
  18384. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18385. free_context(ctx);
  18386. pthread_setspecific(sTlsKey, NULL);
  18387. return NULL;
  18388. }
  18389. /* Add a table with parameters into mg.params */
  18390. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  18391. if (sparams && sparams[0]) {
  18392. lua_getglobal(state, "mg");
  18393. lua_pushstring(state, "params");
  18394. lua_newtable(state);
  18395. while ((sparams = next_option(sparams, &opt_vec, &eq_vec))
  18396. != NULL) {
  18397. reg_llstring(
  18398. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  18399. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  18400. break;
  18401. }
  18402. lua_rawset(state, -3);
  18403. lua_pop(state, 1);
  18404. }
  18405. /* Call script */
  18406. state = mg_lua_context_script_run(state,
  18407. ctx->dd.config[LUA_BACKGROUND_SCRIPT],
  18408. ctx,
  18409. ebuf,
  18410. sizeof(ebuf));
  18411. if (!state) {
  18412. mg_cry_ctx_internal(ctx,
  18413. "lua_background_script start error: %s",
  18414. ebuf);
  18415. if (error != NULL) {
  18416. error->code = MG_ERROR_DATA_CODE_SCRIPT_ERROR;
  18417. mg_snprintf(NULL,
  18418. NULL, /* No truncation check for error buffers */
  18419. error->text,
  18420. error->text_buffer_size,
  18421. "Error in script %s: %s",
  18422. config_options[DOCUMENT_ROOT].name,
  18423. ebuf);
  18424. }
  18425. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18426. free_context(ctx);
  18427. pthread_setspecific(sTlsKey, NULL);
  18428. return NULL;
  18429. }
  18430. /* state remains valid */
  18431. ctx->lua_background_state = (void *)state;
  18432. pthread_mutex_unlock(&ctx->lua_bg_mutex);
  18433. } else {
  18434. ctx->lua_background_state = 0;
  18435. }
  18436. #endif
  18437. /* Step by step initialization of ctx - depending on build options */
  18438. #if !defined(NO_FILESYSTEMS)
  18439. if (!set_gpass_option(ctx, NULL)) {
  18440. const char *err_msg = "Invalid global password file";
  18441. /* Fatal error - abort start. */
  18442. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18443. if (error != NULL) {
  18444. error->code = MG_ERROR_DATA_CODE_INVALID_PASS_FILE;
  18445. mg_snprintf(NULL,
  18446. NULL, /* No truncation check for error buffers */
  18447. error->text,
  18448. error->text_buffer_size,
  18449. "%s",
  18450. err_msg);
  18451. }
  18452. free_context(ctx);
  18453. pthread_setspecific(sTlsKey, NULL);
  18454. return NULL;
  18455. }
  18456. #endif
  18457. #if defined(USE_MBEDTLS)
  18458. if (!mg_sslctx_init(ctx, NULL)) {
  18459. const char *err_msg = "Error initializing SSL context";
  18460. /* Fatal error - abort start. */
  18461. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18462. if (error != NULL) {
  18463. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18464. mg_snprintf(NULL,
  18465. NULL, /* No truncation check for error buffers */
  18466. error->text,
  18467. error->text_buffer_size,
  18468. "%s",
  18469. err_msg);
  18470. }
  18471. free_context(ctx);
  18472. pthread_setspecific(sTlsKey, NULL);
  18473. return NULL;
  18474. }
  18475. #elif !defined(NO_SSL)
  18476. if (!init_ssl_ctx(ctx, NULL)) {
  18477. const char *err_msg = "Error initializing SSL context";
  18478. /* Fatal error - abort start. */
  18479. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18480. if (error != NULL) {
  18481. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18482. mg_snprintf(NULL,
  18483. NULL, /* No truncation check for error buffers */
  18484. error->text,
  18485. error->text_buffer_size,
  18486. "%s",
  18487. err_msg);
  18488. }
  18489. free_context(ctx);
  18490. pthread_setspecific(sTlsKey, NULL);
  18491. return NULL;
  18492. }
  18493. #endif
  18494. if (!set_ports_option(ctx)) {
  18495. const char *err_msg = "Failed to setup server ports";
  18496. /* Fatal error - abort start. */
  18497. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18498. if (error != NULL) {
  18499. error->code = MG_ERROR_DATA_CODE_INIT_PORTS_FAILED;
  18500. mg_snprintf(NULL,
  18501. NULL, /* No truncation check for error buffers */
  18502. error->text,
  18503. error->text_buffer_size,
  18504. "%s",
  18505. err_msg);
  18506. }
  18507. free_context(ctx);
  18508. pthread_setspecific(sTlsKey, NULL);
  18509. return NULL;
  18510. }
  18511. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  18512. if (!set_uid_option(ctx)) {
  18513. const char *err_msg = "Failed to run as configured user";
  18514. /* Fatal error - abort start. */
  18515. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18516. if (error != NULL) {
  18517. error->code = MG_ERROR_DATA_CODE_INIT_USER_FAILED;
  18518. mg_snprintf(NULL,
  18519. NULL, /* No truncation check for error buffers */
  18520. error->text,
  18521. error->text_buffer_size,
  18522. "%s",
  18523. err_msg);
  18524. }
  18525. free_context(ctx);
  18526. pthread_setspecific(sTlsKey, NULL);
  18527. return NULL;
  18528. }
  18529. #endif
  18530. if (!set_acl_option(ctx)) {
  18531. const char *err_msg = "Failed to setup access control list";
  18532. /* Fatal error - abort start. */
  18533. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18534. if (error != NULL) {
  18535. error->code = MG_ERROR_DATA_CODE_INIT_ACL_FAILED;
  18536. mg_snprintf(NULL,
  18537. NULL, /* No truncation check for error buffers */
  18538. error->text,
  18539. error->text_buffer_size,
  18540. "%s",
  18541. err_msg);
  18542. }
  18543. free_context(ctx);
  18544. pthread_setspecific(sTlsKey, NULL);
  18545. return NULL;
  18546. }
  18547. ctx->cfg_max_worker_threads = ((unsigned int)(workerthreadcount));
  18548. ctx->worker_threadids =
  18549. (pthread_t *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18550. sizeof(pthread_t),
  18551. ctx);
  18552. if (ctx->worker_threadids == NULL) {
  18553. const char *err_msg = "Not enough memory for worker thread ID array";
  18554. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18555. if (error != NULL) {
  18556. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18557. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18558. * (unsigned)sizeof(pthread_t);
  18559. mg_snprintf(NULL,
  18560. NULL, /* No truncation check for error buffers */
  18561. error->text,
  18562. error->text_buffer_size,
  18563. "%s",
  18564. err_msg);
  18565. }
  18566. free_context(ctx);
  18567. pthread_setspecific(sTlsKey, NULL);
  18568. return NULL;
  18569. }
  18570. ctx->worker_connections =
  18571. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18572. sizeof(struct mg_connection),
  18573. ctx);
  18574. if (ctx->worker_connections == NULL) {
  18575. const char *err_msg =
  18576. "Not enough memory for worker thread connection array";
  18577. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18578. if (error != NULL) {
  18579. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18580. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18581. * (unsigned)sizeof(struct mg_connection);
  18582. mg_snprintf(NULL,
  18583. NULL, /* No truncation check for error buffers */
  18584. error->text,
  18585. error->text_buffer_size,
  18586. "%s",
  18587. err_msg);
  18588. }
  18589. free_context(ctx);
  18590. pthread_setspecific(sTlsKey, NULL);
  18591. return NULL;
  18592. }
  18593. #if defined(ALTERNATIVE_QUEUE)
  18594. ctx->client_wait_events =
  18595. (void **)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18596. sizeof(ctx->client_wait_events[0]),
  18597. ctx);
  18598. if (ctx->client_wait_events == NULL) {
  18599. const char *err_msg = "Not enough memory for worker event array";
  18600. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18601. mg_free(ctx->worker_threadids);
  18602. if (error != NULL) {
  18603. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18604. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18605. * (unsigned)sizeof(ctx->client_wait_events[0]);
  18606. mg_snprintf(NULL,
  18607. NULL, /* No truncation check for error buffers */
  18608. error->text,
  18609. error->text_buffer_size,
  18610. "%s",
  18611. err_msg);
  18612. }
  18613. free_context(ctx);
  18614. pthread_setspecific(sTlsKey, NULL);
  18615. return NULL;
  18616. }
  18617. ctx->client_socks =
  18618. (struct socket *)mg_calloc_ctx(ctx->cfg_max_worker_threads,
  18619. sizeof(ctx->client_socks[0]),
  18620. ctx);
  18621. if (ctx->client_socks == NULL) {
  18622. const char *err_msg = "Not enough memory for worker socket array";
  18623. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18624. mg_free(ctx->client_wait_events);
  18625. mg_free(ctx->worker_threadids);
  18626. if (error != NULL) {
  18627. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18628. error->code_sub = (unsigned)ctx->cfg_max_worker_threads
  18629. * (unsigned)sizeof(ctx->client_socks[0]);
  18630. mg_snprintf(NULL,
  18631. NULL, /* No truncation check for error buffers */
  18632. error->text,
  18633. error->text_buffer_size,
  18634. "%s",
  18635. err_msg);
  18636. }
  18637. free_context(ctx);
  18638. pthread_setspecific(sTlsKey, NULL);
  18639. return NULL;
  18640. }
  18641. for (i = 0; (unsigned)i < ctx->cfg_max_worker_threads; i++) {
  18642. ctx->client_wait_events[i] = event_create();
  18643. if (ctx->client_wait_events[i] == 0) {
  18644. const char *err_msg = "Error creating worker event %i";
  18645. mg_cry_ctx_internal(ctx, err_msg, i);
  18646. while (i > 0) {
  18647. i--;
  18648. event_destroy(ctx->client_wait_events[i]);
  18649. }
  18650. mg_free(ctx->client_socks);
  18651. mg_free(ctx->client_wait_events);
  18652. mg_free(ctx->worker_threadids);
  18653. if (error != NULL) {
  18654. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18655. error->code_sub = (unsigned)ERRNO;
  18656. mg_snprintf(NULL,
  18657. NULL, /* No truncation check for error buffers */
  18658. error->text,
  18659. error->text_buffer_size,
  18660. err_msg,
  18661. i);
  18662. }
  18663. free_context(ctx);
  18664. pthread_setspecific(sTlsKey, NULL);
  18665. return NULL;
  18666. }
  18667. }
  18668. #endif
  18669. #if defined(USE_TIMERS)
  18670. if (timers_init(ctx) != 0) {
  18671. const char *err_msg = "Error creating timers";
  18672. mg_cry_ctx_internal(ctx, "%s", err_msg);
  18673. if (error != NULL) {
  18674. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18675. error->code_sub = (unsigned)ERRNO;
  18676. mg_snprintf(NULL,
  18677. NULL, /* No truncation check for error buffers */
  18678. error->text,
  18679. error->text_buffer_size,
  18680. "%s",
  18681. err_msg);
  18682. }
  18683. free_context(ctx);
  18684. pthread_setspecific(sTlsKey, NULL);
  18685. return NULL;
  18686. }
  18687. #endif
  18688. /* Context has been created - init user libraries */
  18689. if (ctx->callbacks.init_context) {
  18690. ctx->callbacks.init_context(ctx);
  18691. }
  18692. /* From now, the context is successfully created.
  18693. * When it is destroyed, the exit callback should be called. */
  18694. ctx->callbacks.exit_context = exit_callback;
  18695. ctx->context_type = CONTEXT_SERVER; /* server context */
  18696. /* Start worker threads */
  18697. for (i = 0; (int)i < prespawnthreadcount; i++) {
  18698. /* worker_thread sets up the other fields */
  18699. if (mg_start_worker_thread(ctx, 0) != 0) {
  18700. long error_no = (long)ERRNO;
  18701. /* thread was not created */
  18702. if (ctx->spawned_worker_threads > 0) {
  18703. /* If the second, third, ... thread cannot be created, set a
  18704. * warning, but keep running. */
  18705. mg_cry_ctx_internal(ctx,
  18706. "Cannot start worker thread %i: error %ld",
  18707. ctx->spawned_worker_threads + 1,
  18708. error_no);
  18709. /* If the server initialization should stop here, all
  18710. * threads that have already been created must be stopped
  18711. * first, before any free_context(ctx) call.
  18712. */
  18713. } else {
  18714. /* If the first worker thread cannot be created, stop
  18715. * initialization and free the entire server context. */
  18716. mg_cry_ctx_internal(ctx,
  18717. "Cannot create threads: error %ld",
  18718. error_no);
  18719. if (error != NULL) {
  18720. error->code = MG_ERROR_DATA_CODE_OS_ERROR;
  18721. error->code_sub = (unsigned)error_no;
  18722. mg_snprintf(
  18723. NULL,
  18724. NULL, /* No truncation check for error buffers */
  18725. error->text,
  18726. error->text_buffer_size,
  18727. "Cannot create first worker thread: error %ld",
  18728. error_no);
  18729. }
  18730. free_context(ctx);
  18731. pthread_setspecific(sTlsKey, NULL);
  18732. return NULL;
  18733. }
  18734. break;
  18735. }
  18736. }
  18737. /* Start master (listening) thread */
  18738. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  18739. pthread_setspecific(sTlsKey, NULL);
  18740. return ctx;
  18741. }
  18742. CIVETWEB_API struct mg_context *
  18743. mg_start(const struct mg_callbacks *callbacks,
  18744. void *user_data,
  18745. const char **options)
  18746. {
  18747. struct mg_init_data init = {0};
  18748. init.callbacks = callbacks;
  18749. init.user_data = user_data;
  18750. init.configuration_options = options;
  18751. return mg_start2(&init, NULL);
  18752. }
  18753. /* Add an additional domain to an already running web server. */
  18754. CIVETWEB_API int
  18755. mg_start_domain2(struct mg_context *ctx,
  18756. const char **options,
  18757. struct mg_error_data *error)
  18758. {
  18759. const char *name;
  18760. const char *value;
  18761. const char *default_value;
  18762. struct mg_domain_context *new_dom;
  18763. struct mg_domain_context *dom;
  18764. int idx, i;
  18765. if (error != NULL) {
  18766. error->code = MG_ERROR_DATA_CODE_OK;
  18767. error->code_sub = 0;
  18768. if (error->text_buffer_size > 0) {
  18769. *error->text = 0;
  18770. }
  18771. }
  18772. if ((ctx == NULL) || (options == NULL)) {
  18773. if (error != NULL) {
  18774. error->code = MG_ERROR_DATA_CODE_INVALID_PARAM;
  18775. mg_snprintf(NULL,
  18776. NULL, /* No truncation check for error buffers */
  18777. error->text,
  18778. error->text_buffer_size,
  18779. "%s",
  18780. "Invalid parameters");
  18781. }
  18782. return -1;
  18783. }
  18784. if (!STOP_FLAG_IS_ZERO(&ctx->stop_flag)) {
  18785. if (error != NULL) {
  18786. error->code = MG_ERROR_DATA_CODE_SERVER_STOPPED;
  18787. mg_snprintf(NULL,
  18788. NULL, /* No truncation check for error buffers */
  18789. error->text,
  18790. error->text_buffer_size,
  18791. "%s",
  18792. "Server already stopped");
  18793. }
  18794. return -7;
  18795. }
  18796. new_dom = (struct mg_domain_context *)
  18797. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  18798. if (!new_dom) {
  18799. /* Out of memory */
  18800. if (error != NULL) {
  18801. error->code = MG_ERROR_DATA_CODE_OUT_OF_MEMORY;
  18802. error->code_sub = (unsigned)sizeof(struct mg_domain_context);
  18803. mg_snprintf(NULL,
  18804. NULL, /* No truncation check for error buffers */
  18805. error->text,
  18806. error->text_buffer_size,
  18807. "%s",
  18808. "Out or memory");
  18809. }
  18810. return -6;
  18811. }
  18812. /* Store options - TODO: unite duplicate code */
  18813. while (options && (name = *options++) != NULL) {
  18814. idx = get_option_index(name);
  18815. if (idx == -1) {
  18816. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  18817. if (error != NULL) {
  18818. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18819. error->code_sub = (unsigned)-1;
  18820. mg_snprintf(NULL,
  18821. NULL, /* No truncation check for error buffers */
  18822. error->text,
  18823. error->text_buffer_size,
  18824. "Invalid option: %s",
  18825. name);
  18826. }
  18827. mg_free(new_dom);
  18828. return -2;
  18829. } else if ((value = *options++) == NULL) {
  18830. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  18831. if (error != NULL) {
  18832. error->code = MG_ERROR_DATA_CODE_INVALID_OPTION;
  18833. error->code_sub = (unsigned)idx;
  18834. mg_snprintf(NULL,
  18835. NULL, /* No truncation check for error buffers */
  18836. error->text,
  18837. error->text_buffer_size,
  18838. "Invalid option value: %s",
  18839. name);
  18840. }
  18841. mg_free(new_dom);
  18842. return -2;
  18843. }
  18844. if (new_dom->config[idx] != NULL) {
  18845. /* Duplicate option: Later values overwrite earlier ones. */
  18846. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  18847. mg_free(new_dom->config[idx]);
  18848. }
  18849. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  18850. DEBUG_TRACE("[%s] -> [%s]", name, value);
  18851. }
  18852. /* Authentication domain is mandatory */
  18853. /* TODO: Maybe use a new option hostname? */
  18854. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  18855. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  18856. if (error != NULL) {
  18857. error->code = MG_ERROR_DATA_CODE_MISSING_OPTION;
  18858. error->code_sub = AUTHENTICATION_DOMAIN;
  18859. mg_snprintf(NULL,
  18860. NULL, /* No truncation check for error buffers */
  18861. error->text,
  18862. error->text_buffer_size,
  18863. "Mandatory option %s missing",
  18864. config_options[AUTHENTICATION_DOMAIN].name);
  18865. }
  18866. mg_free(new_dom);
  18867. return -4;
  18868. }
  18869. /* Set default value if needed. Take the config value from
  18870. * ctx as a default value. */
  18871. for (i = 0; config_options[i].name != NULL; i++) {
  18872. default_value = ctx->dd.config[i];
  18873. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  18874. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  18875. }
  18876. }
  18877. new_dom->handlers = NULL;
  18878. new_dom->next = NULL;
  18879. new_dom->nonce_count = 0;
  18880. new_dom->auth_nonce_mask = get_random() ^ (get_random() << 31);
  18881. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  18882. new_dom->shared_lua_websockets = NULL;
  18883. #endif
  18884. #if !defined(NO_SSL) && !defined(USE_MBEDTLS)
  18885. if (!init_ssl_ctx(ctx, new_dom)) {
  18886. /* Init SSL failed */
  18887. if (error != NULL) {
  18888. error->code = MG_ERROR_DATA_CODE_INIT_TLS_FAILED;
  18889. mg_snprintf(NULL,
  18890. NULL, /* No truncation check for error buffers */
  18891. error->text,
  18892. error->text_buffer_size,
  18893. "%s",
  18894. "Initializing SSL context failed");
  18895. }
  18896. mg_free(new_dom);
  18897. return -3;
  18898. }
  18899. #endif
  18900. /* Add element to linked list. */
  18901. mg_lock_context(ctx);
  18902. idx = 0;
  18903. dom = &(ctx->dd);
  18904. for (;;) {
  18905. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  18906. dom->config[AUTHENTICATION_DOMAIN])) {
  18907. /* Domain collision */
  18908. mg_cry_ctx_internal(ctx,
  18909. "domain %s already in use",
  18910. new_dom->config[AUTHENTICATION_DOMAIN]);
  18911. if (error != NULL) {
  18912. error->code = MG_ERROR_DATA_CODE_DUPLICATE_DOMAIN;
  18913. mg_snprintf(NULL,
  18914. NULL, /* No truncation check for error buffers */
  18915. error->text,
  18916. error->text_buffer_size,
  18917. "Domain %s specified by %s is already in use",
  18918. new_dom->config[AUTHENTICATION_DOMAIN],
  18919. config_options[AUTHENTICATION_DOMAIN].name);
  18920. }
  18921. mg_free(new_dom);
  18922. mg_unlock_context(ctx);
  18923. return -5;
  18924. }
  18925. /* Count number of domains */
  18926. idx++;
  18927. if (dom->next == NULL) {
  18928. dom->next = new_dom;
  18929. break;
  18930. }
  18931. dom = dom->next;
  18932. }
  18933. mg_unlock_context(ctx);
  18934. /* Return domain number */
  18935. return idx;
  18936. }
  18937. CIVETWEB_API int
  18938. mg_start_domain(struct mg_context *ctx, const char **options)
  18939. {
  18940. return mg_start_domain2(ctx, options, NULL);
  18941. }
  18942. /* Feature check API function */
  18943. CIVETWEB_API unsigned
  18944. mg_check_feature(unsigned feature)
  18945. {
  18946. static const unsigned feature_set = 0
  18947. /* Set bits for available features according to API documentation.
  18948. * This bit mask is created at compile time, according to the active
  18949. * preprocessor defines. It is a single const value at runtime. */
  18950. #if !defined(NO_FILES)
  18951. | MG_FEATURES_FILES
  18952. #endif
  18953. #if !defined(NO_SSL) || defined(USE_MBEDTLS)
  18954. | MG_FEATURES_SSL
  18955. #endif
  18956. #if !defined(NO_CGI)
  18957. | MG_FEATURES_CGI
  18958. #endif
  18959. #if defined(USE_IPV6)
  18960. | MG_FEATURES_IPV6
  18961. #endif
  18962. #if defined(USE_WEBSOCKET)
  18963. | MG_FEATURES_WEBSOCKET
  18964. #endif
  18965. #if defined(USE_LUA)
  18966. | MG_FEATURES_LUA
  18967. #endif
  18968. #if defined(USE_DUKTAPE)
  18969. | MG_FEATURES_SSJS
  18970. #endif
  18971. #if !defined(NO_CACHING)
  18972. | MG_FEATURES_CACHE
  18973. #endif
  18974. #if defined(USE_SERVER_STATS)
  18975. | MG_FEATURES_STATS
  18976. #endif
  18977. #if defined(USE_ZLIB)
  18978. | MG_FEATURES_COMPRESSION
  18979. #endif
  18980. #if defined(USE_HTTP2)
  18981. | MG_FEATURES_HTTP2
  18982. #endif
  18983. #if defined(USE_X_DOM_SOCKET)
  18984. | MG_FEATURES_X_DOMAIN_SOCKET
  18985. #endif
  18986. /* Set some extra bits not defined in the API documentation.
  18987. * These bits may change without further notice. */
  18988. #if defined(MG_LEGACY_INTERFACE)
  18989. | 0x80000000u
  18990. #endif
  18991. #if defined(MG_EXPERIMENTAL_INTERFACES)
  18992. | 0x40000000u
  18993. #endif
  18994. #if !defined(NO_RESPONSE_BUFFERING)
  18995. | 0x20000000u
  18996. #endif
  18997. #if defined(MEMORY_DEBUGGING)
  18998. | 0x10000000u
  18999. #endif
  19000. ;
  19001. return (feature & feature_set);
  19002. }
  19003. static size_t
  19004. mg_str_append(char **dst, char *end, const char *src)
  19005. {
  19006. size_t len = strlen(src);
  19007. if (*dst != end) {
  19008. /* Append src if enough space, or close dst. */
  19009. if ((size_t)(end - *dst) > len) {
  19010. strcpy(*dst, src);
  19011. *dst += len;
  19012. } else {
  19013. *dst = end;
  19014. }
  19015. }
  19016. return len;
  19017. }
  19018. /* Get system information. It can be printed or stored by the caller.
  19019. * Return the size of available information. */
  19020. CIVETWEB_API int
  19021. mg_get_system_info(char *buffer, int buflen)
  19022. {
  19023. char *end, *append_eoobj = NULL, block[256];
  19024. size_t system_info_length = 0;
  19025. #if defined(_WIN32)
  19026. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19027. #else
  19028. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19029. #endif
  19030. if ((buffer == NULL) || (buflen < 1)) {
  19031. buflen = 0;
  19032. end = buffer;
  19033. } else {
  19034. *buffer = 0;
  19035. end = buffer + buflen;
  19036. }
  19037. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19038. /* has enough space to append eoobj */
  19039. append_eoobj = buffer;
  19040. if (end) {
  19041. end -= sizeof(eoobj) - 1;
  19042. }
  19043. }
  19044. system_info_length += mg_str_append(&buffer, end, "{");
  19045. /* Server version */
  19046. {
  19047. const char *version = mg_version();
  19048. mg_snprintf(NULL,
  19049. NULL,
  19050. block,
  19051. sizeof(block),
  19052. "%s\"version\" : \"%s\"",
  19053. eol,
  19054. version);
  19055. system_info_length += mg_str_append(&buffer, end, block);
  19056. }
  19057. /* System info */
  19058. {
  19059. #if defined(_WIN32)
  19060. DWORD dwVersion = 0;
  19061. DWORD dwMajorVersion = 0;
  19062. DWORD dwMinorVersion = 0;
  19063. SYSTEM_INFO si;
  19064. GetSystemInfo(&si);
  19065. #if defined(_MSC_VER)
  19066. #pragma warning(push)
  19067. /* GetVersion was declared deprecated */
  19068. #pragma warning(disable : 4996)
  19069. #endif
  19070. dwVersion = GetVersion();
  19071. #if defined(_MSC_VER)
  19072. #pragma warning(pop)
  19073. #endif
  19074. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  19075. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  19076. mg_snprintf(NULL,
  19077. NULL,
  19078. block,
  19079. sizeof(block),
  19080. ",%s\"os\" : \"Windows %u.%u\"",
  19081. eol,
  19082. (unsigned)dwMajorVersion,
  19083. (unsigned)dwMinorVersion);
  19084. system_info_length += mg_str_append(&buffer, end, block);
  19085. mg_snprintf(NULL,
  19086. NULL,
  19087. block,
  19088. sizeof(block),
  19089. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  19090. eol,
  19091. (unsigned)si.wProcessorArchitecture,
  19092. (unsigned)si.dwNumberOfProcessors,
  19093. (unsigned)si.dwActiveProcessorMask);
  19094. system_info_length += mg_str_append(&buffer, end, block);
  19095. #elif defined(__ZEPHYR__)
  19096. mg_snprintf(NULL,
  19097. NULL,
  19098. block,
  19099. sizeof(block),
  19100. ",%s\"os\" : \"%s %s\"",
  19101. eol,
  19102. "Zephyr OS",
  19103. ZEPHYR_VERSION);
  19104. system_info_length += mg_str_append(&buffer, end, block);
  19105. #else
  19106. struct utsname name;
  19107. memset(&name, 0, sizeof(name));
  19108. uname(&name);
  19109. mg_snprintf(NULL,
  19110. NULL,
  19111. block,
  19112. sizeof(block),
  19113. ",%s\"os\" : \"%s %s (%s) - %s\"",
  19114. eol,
  19115. name.sysname,
  19116. name.version,
  19117. name.release,
  19118. name.machine);
  19119. system_info_length += mg_str_append(&buffer, end, block);
  19120. #endif
  19121. }
  19122. /* Features */
  19123. {
  19124. mg_snprintf(NULL,
  19125. NULL,
  19126. block,
  19127. sizeof(block),
  19128. ",%s\"features\" : %lu"
  19129. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  19130. eol,
  19131. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  19132. eol,
  19133. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  19134. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  19135. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  19136. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  19137. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  19138. : "",
  19139. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  19140. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  19141. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  19142. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  19143. system_info_length += mg_str_append(&buffer, end, block);
  19144. #if defined(USE_LUA)
  19145. mg_snprintf(NULL,
  19146. NULL,
  19147. block,
  19148. sizeof(block),
  19149. ",%s\"lua_version\" : \"%u (%s)\"",
  19150. eol,
  19151. (unsigned)LUA_VERSION_NUM,
  19152. LUA_RELEASE);
  19153. system_info_length += mg_str_append(&buffer, end, block);
  19154. #endif
  19155. #if defined(USE_DUKTAPE)
  19156. mg_snprintf(NULL,
  19157. NULL,
  19158. block,
  19159. sizeof(block),
  19160. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  19161. eol,
  19162. (unsigned)DUK_VERSION / 10000,
  19163. ((unsigned)DUK_VERSION / 100) % 100,
  19164. (unsigned)DUK_VERSION % 100);
  19165. system_info_length += mg_str_append(&buffer, end, block);
  19166. #endif
  19167. }
  19168. /* Build identifier. If BUILD_DATE is not set, __DATE__ will be used. */
  19169. {
  19170. #if defined(BUILD_DATE)
  19171. const char *bd = BUILD_DATE;
  19172. #else
  19173. #if defined(GCC_DIAGNOSTIC)
  19174. #if GCC_VERSION >= 40900
  19175. #pragma GCC diagnostic push
  19176. /* Disable idiotic compiler warning -Wdate-time, appeared in gcc5. This
  19177. * does not work in some versions. If "BUILD_DATE" is defined to some
  19178. * string, it is used instead of __DATE__. */
  19179. #pragma GCC diagnostic ignored "-Wdate-time"
  19180. #endif
  19181. #endif
  19182. const char *bd = __DATE__;
  19183. #if defined(GCC_DIAGNOSTIC)
  19184. #if GCC_VERSION >= 40900
  19185. #pragma GCC diagnostic pop
  19186. #endif
  19187. #endif
  19188. #endif
  19189. mg_snprintf(
  19190. NULL, NULL, block, sizeof(block), ",%s\"build\" : \"%s\"", eol, bd);
  19191. system_info_length += mg_str_append(&buffer, end, block);
  19192. }
  19193. /* Compiler information */
  19194. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  19195. {
  19196. #if defined(_MSC_VER)
  19197. mg_snprintf(NULL,
  19198. NULL,
  19199. block,
  19200. sizeof(block),
  19201. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  19202. eol,
  19203. (unsigned)_MSC_VER,
  19204. (unsigned)_MSC_FULL_VER);
  19205. system_info_length += mg_str_append(&buffer, end, block);
  19206. #elif defined(__MINGW64__)
  19207. mg_snprintf(NULL,
  19208. NULL,
  19209. block,
  19210. sizeof(block),
  19211. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  19212. eol,
  19213. (unsigned)__MINGW64_VERSION_MAJOR,
  19214. (unsigned)__MINGW64_VERSION_MINOR);
  19215. system_info_length += mg_str_append(&buffer, end, block);
  19216. mg_snprintf(NULL,
  19217. NULL,
  19218. block,
  19219. sizeof(block),
  19220. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19221. eol,
  19222. (unsigned)__MINGW32_MAJOR_VERSION,
  19223. (unsigned)__MINGW32_MINOR_VERSION);
  19224. system_info_length += mg_str_append(&buffer, end, block);
  19225. #elif defined(__MINGW32__)
  19226. mg_snprintf(NULL,
  19227. NULL,
  19228. block,
  19229. sizeof(block),
  19230. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  19231. eol,
  19232. (unsigned)__MINGW32_MAJOR_VERSION,
  19233. (unsigned)__MINGW32_MINOR_VERSION);
  19234. system_info_length += mg_str_append(&buffer, end, block);
  19235. #elif defined(__clang__)
  19236. mg_snprintf(NULL,
  19237. NULL,
  19238. block,
  19239. sizeof(block),
  19240. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  19241. eol,
  19242. __clang_major__,
  19243. __clang_minor__,
  19244. __clang_patchlevel__,
  19245. __clang_version__);
  19246. system_info_length += mg_str_append(&buffer, end, block);
  19247. #elif defined(__GNUC__)
  19248. mg_snprintf(NULL,
  19249. NULL,
  19250. block,
  19251. sizeof(block),
  19252. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  19253. eol,
  19254. (unsigned)__GNUC__,
  19255. (unsigned)__GNUC_MINOR__,
  19256. (unsigned)__GNUC_PATCHLEVEL__);
  19257. system_info_length += mg_str_append(&buffer, end, block);
  19258. #elif defined(__INTEL_COMPILER)
  19259. mg_snprintf(NULL,
  19260. NULL,
  19261. block,
  19262. sizeof(block),
  19263. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  19264. eol,
  19265. (unsigned)__INTEL_COMPILER);
  19266. system_info_length += mg_str_append(&buffer, end, block);
  19267. #elif defined(__BORLANDC__)
  19268. mg_snprintf(NULL,
  19269. NULL,
  19270. block,
  19271. sizeof(block),
  19272. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  19273. eol,
  19274. (unsigned)__BORLANDC__);
  19275. system_info_length += mg_str_append(&buffer, end, block);
  19276. #elif defined(__SUNPRO_C)
  19277. mg_snprintf(NULL,
  19278. NULL,
  19279. block,
  19280. sizeof(block),
  19281. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  19282. eol,
  19283. (unsigned)__SUNPRO_C);
  19284. system_info_length += mg_str_append(&buffer, end, block);
  19285. #else
  19286. mg_snprintf(NULL,
  19287. NULL,
  19288. block,
  19289. sizeof(block),
  19290. ",%s\"compiler\" : \"other\"",
  19291. eol);
  19292. system_info_length += mg_str_append(&buffer, end, block);
  19293. #endif
  19294. }
  19295. /* Determine 32/64 bit data mode.
  19296. * see https://en.wikipedia.org/wiki/64-bit_computing */
  19297. {
  19298. mg_snprintf(NULL,
  19299. NULL,
  19300. block,
  19301. sizeof(block),
  19302. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  19303. "char:%u/%u, "
  19304. "ptr:%u, size:%u, time:%u\"",
  19305. eol,
  19306. (unsigned)sizeof(short),
  19307. (unsigned)sizeof(int),
  19308. (unsigned)sizeof(long),
  19309. (unsigned)sizeof(long long),
  19310. (unsigned)sizeof(float),
  19311. (unsigned)sizeof(double),
  19312. (unsigned)sizeof(long double),
  19313. (unsigned)sizeof(char),
  19314. (unsigned)sizeof(wchar_t),
  19315. (unsigned)sizeof(void *),
  19316. (unsigned)sizeof(size_t),
  19317. (unsigned)sizeof(time_t));
  19318. system_info_length += mg_str_append(&buffer, end, block);
  19319. }
  19320. /* Terminate string */
  19321. if (append_eoobj) {
  19322. strcat(append_eoobj, eoobj);
  19323. }
  19324. system_info_length += sizeof(eoobj) - 1;
  19325. return (int)system_info_length;
  19326. }
  19327. /* Get context information. It can be printed or stored by the caller.
  19328. * Return the size of available information. */
  19329. CIVETWEB_API int
  19330. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  19331. {
  19332. #if defined(USE_SERVER_STATS)
  19333. char *end, *append_eoobj = NULL, block[256];
  19334. size_t context_info_length = 0;
  19335. #if defined(_WIN32)
  19336. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19337. #else
  19338. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19339. #endif
  19340. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  19341. if ((buffer == NULL) || (buflen < 1)) {
  19342. buflen = 0;
  19343. end = buffer;
  19344. } else {
  19345. *buffer = 0;
  19346. end = buffer + buflen;
  19347. }
  19348. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19349. /* has enough space to append eoobj */
  19350. append_eoobj = buffer;
  19351. end -= sizeof(eoobj) - 1;
  19352. }
  19353. context_info_length += mg_str_append(&buffer, end, "{");
  19354. if (ms) { /* <-- should be always true */
  19355. /* Memory information */
  19356. int blockCount = (int)ms->blockCount;
  19357. int64_t totalMemUsed = ms->totalMemUsed;
  19358. int64_t maxMemUsed = ms->maxMemUsed;
  19359. if (totalMemUsed > maxMemUsed) {
  19360. maxMemUsed = totalMemUsed;
  19361. }
  19362. mg_snprintf(NULL,
  19363. NULL,
  19364. block,
  19365. sizeof(block),
  19366. "%s\"memory\" : {%s"
  19367. "\"blocks\" : %i,%s"
  19368. "\"used\" : %" INT64_FMT ",%s"
  19369. "\"maxUsed\" : %" INT64_FMT "%s"
  19370. "}",
  19371. eol,
  19372. eol,
  19373. blockCount,
  19374. eol,
  19375. totalMemUsed,
  19376. eol,
  19377. maxMemUsed,
  19378. eol);
  19379. context_info_length += mg_str_append(&buffer, end, block);
  19380. }
  19381. if (ctx) {
  19382. /* Declare all variables at begin of the block, to comply
  19383. * with old C standards. */
  19384. char start_time_str[64] = {0};
  19385. char now_str[64] = {0};
  19386. time_t start_time = ctx->start_time;
  19387. time_t now = time(NULL);
  19388. int64_t total_data_read, total_data_written;
  19389. int active_connections = (int)ctx->active_connections;
  19390. int max_active_connections = (int)ctx->max_active_connections;
  19391. int total_connections = (int)ctx->total_connections;
  19392. if (active_connections > max_active_connections) {
  19393. max_active_connections = active_connections;
  19394. }
  19395. if (active_connections > total_connections) {
  19396. total_connections = active_connections;
  19397. }
  19398. /* Connections information */
  19399. mg_snprintf(NULL,
  19400. NULL,
  19401. block,
  19402. sizeof(block),
  19403. ",%s\"connections\" : {%s"
  19404. "\"active\" : %i,%s"
  19405. "\"maxActive\" : %i,%s"
  19406. "\"total\" : %i%s"
  19407. "}",
  19408. eol,
  19409. eol,
  19410. active_connections,
  19411. eol,
  19412. max_active_connections,
  19413. eol,
  19414. total_connections,
  19415. eol);
  19416. context_info_length += mg_str_append(&buffer, end, block);
  19417. /* Queue information */
  19418. #if !defined(ALTERNATIVE_QUEUE)
  19419. mg_snprintf(NULL,
  19420. NULL,
  19421. block,
  19422. sizeof(block),
  19423. ",%s\"queue\" : {%s"
  19424. "\"length\" : %i,%s"
  19425. "\"filled\" : %i,%s"
  19426. "\"maxFilled\" : %i,%s"
  19427. "\"full\" : %s%s"
  19428. "}",
  19429. eol,
  19430. eol,
  19431. ctx->sq_size,
  19432. eol,
  19433. ctx->sq_head - ctx->sq_tail,
  19434. eol,
  19435. ctx->sq_max_fill,
  19436. eol,
  19437. (ctx->sq_blocked ? "true" : "false"),
  19438. eol);
  19439. context_info_length += mg_str_append(&buffer, end, block);
  19440. #endif
  19441. /* Requests information */
  19442. mg_snprintf(NULL,
  19443. NULL,
  19444. block,
  19445. sizeof(block),
  19446. ",%s\"requests\" : {%s"
  19447. "\"total\" : %lu%s"
  19448. "}",
  19449. eol,
  19450. eol,
  19451. (unsigned long)ctx->total_requests,
  19452. eol);
  19453. context_info_length += mg_str_append(&buffer, end, block);
  19454. /* Data information */
  19455. total_data_read =
  19456. mg_atomic_add64((volatile int64_t *)&ctx->total_data_read, 0);
  19457. total_data_written =
  19458. mg_atomic_add64((volatile int64_t *)&ctx->total_data_written, 0);
  19459. mg_snprintf(NULL,
  19460. NULL,
  19461. block,
  19462. sizeof(block),
  19463. ",%s\"data\" : {%s"
  19464. "\"read\" : %" INT64_FMT ",%s"
  19465. "\"written\" : %" INT64_FMT "%s"
  19466. "}",
  19467. eol,
  19468. eol,
  19469. total_data_read,
  19470. eol,
  19471. total_data_written,
  19472. eol);
  19473. context_info_length += mg_str_append(&buffer, end, block);
  19474. /* Execution time information */
  19475. gmt_time_string(start_time_str,
  19476. sizeof(start_time_str) - 1,
  19477. &start_time);
  19478. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  19479. mg_snprintf(NULL,
  19480. NULL,
  19481. block,
  19482. sizeof(block),
  19483. ",%s\"time\" : {%s"
  19484. "\"uptime\" : %.0f,%s"
  19485. "\"start\" : \"%s\",%s"
  19486. "\"now\" : \"%s\"%s"
  19487. "}",
  19488. eol,
  19489. eol,
  19490. difftime(now, start_time),
  19491. eol,
  19492. start_time_str,
  19493. eol,
  19494. now_str,
  19495. eol);
  19496. context_info_length += mg_str_append(&buffer, end, block);
  19497. }
  19498. /* Terminate string */
  19499. if (append_eoobj) {
  19500. strcat(append_eoobj, eoobj);
  19501. }
  19502. context_info_length += sizeof(eoobj) - 1;
  19503. return (int)context_info_length;
  19504. #else
  19505. (void)ctx;
  19506. if ((buffer != NULL) && (buflen > 0)) {
  19507. *buffer = 0;
  19508. }
  19509. return 0;
  19510. #endif
  19511. }
  19512. CIVETWEB_API void
  19513. mg_disable_connection_keep_alive(struct mg_connection *conn)
  19514. {
  19515. /* https://github.com/civetweb/civetweb/issues/727 */
  19516. if (conn != NULL) {
  19517. conn->must_close = 1;
  19518. }
  19519. }
  19520. #if defined(MG_EXPERIMENTAL_INTERFACES)
  19521. /* Get connection information. It can be printed or stored by the caller.
  19522. * Return the size of available information. */
  19523. CIVETWEB_API int
  19524. mg_get_connection_info(const struct mg_context *ctx,
  19525. int idx,
  19526. char *buffer,
  19527. int buflen)
  19528. {
  19529. const struct mg_connection *conn;
  19530. const struct mg_request_info *ri;
  19531. char *end, *append_eoobj = NULL, block[256];
  19532. size_t connection_info_length = 0;
  19533. int state = 0;
  19534. const char *state_str = "unknown";
  19535. #if defined(_WIN32)
  19536. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  19537. #else
  19538. static const char eol[] = "\n", eoobj[] = "\n}\n";
  19539. #endif
  19540. if ((buffer == NULL) || (buflen < 1)) {
  19541. buflen = 0;
  19542. end = buffer;
  19543. } else {
  19544. *buffer = 0;
  19545. end = buffer + buflen;
  19546. }
  19547. if (buflen > (int)(sizeof(eoobj) - 1)) {
  19548. /* has enough space to append eoobj */
  19549. append_eoobj = buffer;
  19550. end -= sizeof(eoobj) - 1;
  19551. }
  19552. if ((ctx == NULL) || (idx < 0)) {
  19553. /* Parameter error */
  19554. return 0;
  19555. }
  19556. if ((unsigned)idx >= ctx->cfg_max_worker_threads) {
  19557. /* Out of range */
  19558. return 0;
  19559. }
  19560. /* Take connection [idx]. This connection is not locked in
  19561. * any way, so some other thread might use it. */
  19562. conn = (ctx->worker_connections) + idx;
  19563. /* Initialize output string */
  19564. connection_info_length += mg_str_append(&buffer, end, "{");
  19565. /* Init variables */
  19566. ri = &(conn->request_info);
  19567. #if defined(USE_SERVER_STATS)
  19568. state = conn->conn_state;
  19569. /* State as string */
  19570. switch (state) {
  19571. case 0:
  19572. state_str = "undefined";
  19573. break;
  19574. case 1:
  19575. state_str = "not used";
  19576. break;
  19577. case 2:
  19578. state_str = "init";
  19579. break;
  19580. case 3:
  19581. state_str = "ready";
  19582. break;
  19583. case 4:
  19584. state_str = "processing";
  19585. break;
  19586. case 5:
  19587. state_str = "processed";
  19588. break;
  19589. case 6:
  19590. state_str = "to close";
  19591. break;
  19592. case 7:
  19593. state_str = "closing";
  19594. break;
  19595. case 8:
  19596. state_str = "closed";
  19597. break;
  19598. case 9:
  19599. state_str = "done";
  19600. break;
  19601. }
  19602. #endif
  19603. /* Connection info */
  19604. if ((state >= 3) && (state < 9)) {
  19605. mg_snprintf(NULL,
  19606. NULL,
  19607. block,
  19608. sizeof(block),
  19609. "%s\"connection\" : {%s"
  19610. "\"remote\" : {%s"
  19611. "\"protocol\" : \"%s\",%s"
  19612. "\"addr\" : \"%s\",%s"
  19613. "\"port\" : %u%s"
  19614. "},%s"
  19615. "\"handled_requests\" : %u%s"
  19616. "}",
  19617. eol,
  19618. eol,
  19619. eol,
  19620. get_proto_name(conn),
  19621. eol,
  19622. ri->remote_addr,
  19623. eol,
  19624. ri->remote_port,
  19625. eol,
  19626. eol,
  19627. conn->handled_requests,
  19628. eol);
  19629. connection_info_length += mg_str_append(&buffer, end, block);
  19630. }
  19631. /* Request info */
  19632. if ((state >= 4) && (state < 6)) {
  19633. mg_snprintf(NULL,
  19634. NULL,
  19635. block,
  19636. sizeof(block),
  19637. "%s%s\"request_info\" : {%s"
  19638. "\"method\" : \"%s\",%s"
  19639. "\"uri\" : \"%s\",%s"
  19640. "\"query\" : %s%s%s%s"
  19641. "}",
  19642. (connection_info_length > 1 ? "," : ""),
  19643. eol,
  19644. eol,
  19645. ri->request_method,
  19646. eol,
  19647. ri->request_uri,
  19648. eol,
  19649. ri->query_string ? "\"" : "",
  19650. ri->query_string ? ri->query_string : "null",
  19651. ri->query_string ? "\"" : "",
  19652. eol);
  19653. connection_info_length += mg_str_append(&buffer, end, block);
  19654. }
  19655. /* Execution time information */
  19656. if ((state >= 2) && (state < 9)) {
  19657. char start_time_str[64] = {0};
  19658. char close_time_str[64] = {0};
  19659. time_t start_time = conn->conn_birth_time;
  19660. time_t close_time = 0;
  19661. double time_diff;
  19662. gmt_time_string(start_time_str,
  19663. sizeof(start_time_str) - 1,
  19664. &start_time);
  19665. #if defined(USE_SERVER_STATS)
  19666. close_time = conn->conn_close_time;
  19667. #endif
  19668. if (close_time != 0) {
  19669. time_diff = difftime(close_time, start_time);
  19670. gmt_time_string(close_time_str,
  19671. sizeof(close_time_str) - 1,
  19672. &close_time);
  19673. } else {
  19674. time_t now = time(NULL);
  19675. time_diff = difftime(now, start_time);
  19676. close_time_str[0] = 0; /* or use "now" ? */
  19677. }
  19678. mg_snprintf(NULL,
  19679. NULL,
  19680. block,
  19681. sizeof(block),
  19682. "%s%s\"time\" : {%s"
  19683. "\"uptime\" : %.0f,%s"
  19684. "\"start\" : \"%s\",%s"
  19685. "\"closed\" : \"%s\"%s"
  19686. "}",
  19687. (connection_info_length > 1 ? "," : ""),
  19688. eol,
  19689. eol,
  19690. time_diff,
  19691. eol,
  19692. start_time_str,
  19693. eol,
  19694. close_time_str,
  19695. eol);
  19696. connection_info_length += mg_str_append(&buffer, end, block);
  19697. }
  19698. /* Remote user name */
  19699. if ((ri->remote_user) && (state < 9)) {
  19700. mg_snprintf(NULL,
  19701. NULL,
  19702. block,
  19703. sizeof(block),
  19704. "%s%s\"user\" : {%s"
  19705. "\"name\" : \"%s\",%s"
  19706. "}",
  19707. (connection_info_length > 1 ? "," : ""),
  19708. eol,
  19709. eol,
  19710. ri->remote_user,
  19711. eol);
  19712. connection_info_length += mg_str_append(&buffer, end, block);
  19713. }
  19714. /* Data block */
  19715. if (state >= 3) {
  19716. mg_snprintf(NULL,
  19717. NULL,
  19718. block,
  19719. sizeof(block),
  19720. "%s%s\"data\" : {%s"
  19721. "\"read\" : %" INT64_FMT ",%s"
  19722. "\"written\" : %" INT64_FMT "%s"
  19723. "}",
  19724. (connection_info_length > 1 ? "," : ""),
  19725. eol,
  19726. eol,
  19727. conn->consumed_content,
  19728. eol,
  19729. conn->num_bytes_sent,
  19730. eol);
  19731. connection_info_length += mg_str_append(&buffer, end, block);
  19732. }
  19733. /* State */
  19734. mg_snprintf(NULL,
  19735. NULL,
  19736. block,
  19737. sizeof(block),
  19738. "%s%s\"state\" : \"%s\"",
  19739. (connection_info_length > 1 ? "," : ""),
  19740. eol,
  19741. state_str);
  19742. connection_info_length += mg_str_append(&buffer, end, block);
  19743. /* Terminate string */
  19744. if (append_eoobj) {
  19745. strcat(append_eoobj, eoobj);
  19746. }
  19747. connection_info_length += sizeof(eoobj) - 1;
  19748. return (int)connection_info_length;
  19749. }
  19750. #if 0
  19751. /* Get handler information. Not fully implemented. Is it required? */
  19752. CIVETWEB_API int
  19753. mg_get_handler_info(struct mg_context *ctx,
  19754. char *buffer,
  19755. int buflen)
  19756. {
  19757. int handler_info_len = 0;
  19758. struct mg_handler_info *tmp_rh;
  19759. mg_lock_context(ctx);
  19760. for (tmp_rh = ctx->dd.handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  19761. if (buflen > handler_info_len + tmp_rh->uri_len) {
  19762. memcpy(buffer + handler_info_len, tmp_rh->uri, tmp_rh->uri_len);
  19763. }
  19764. handler_info_len += tmp_rh->uri_len;
  19765. switch (tmp_rh->handler_type) {
  19766. case REQUEST_HANDLER:
  19767. (void)tmp_rh->handler;
  19768. break;
  19769. case WEBSOCKET_HANDLER:
  19770. (void)tmp_rh->connect_handler;
  19771. (void)tmp_rh->ready_handler;
  19772. (void)tmp_rh->data_handler;
  19773. (void)tmp_rh->close_handler;
  19774. break;
  19775. case AUTH_HANDLER:
  19776. (void)tmp_rh->auth_handler;
  19777. break;
  19778. }
  19779. (void)cbdata;
  19780. }
  19781. mg_unlock_context(ctx);
  19782. return handler_info_len;
  19783. }
  19784. #endif
  19785. #endif
  19786. /* Initialize this library. This function does not need to be thread safe.
  19787. */
  19788. CIVETWEB_API unsigned
  19789. mg_init_library(unsigned features)
  19790. {
  19791. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  19792. unsigned features_inited = features_to_init;
  19793. if (mg_init_library_called <= 0) {
  19794. /* Not initialized yet */
  19795. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  19796. return 0;
  19797. }
  19798. }
  19799. mg_global_lock();
  19800. if (mg_init_library_called <= 0) {
  19801. int i;
  19802. size_t len;
  19803. #if defined(_WIN32)
  19804. int file_mutex_init = 1;
  19805. int wsa = 1;
  19806. #else
  19807. int mutexattr_init = 1;
  19808. #endif
  19809. int failed = 1;
  19810. int key_create = pthread_key_create(&sTlsKey, tls_dtor);
  19811. if (key_create == 0) {
  19812. #if defined(_WIN32)
  19813. file_mutex_init =
  19814. pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  19815. if (file_mutex_init == 0) {
  19816. /* Start WinSock */
  19817. WSADATA data;
  19818. failed = wsa = WSAStartup(MAKEWORD(2, 2), &data);
  19819. }
  19820. #else
  19821. mutexattr_init = pthread_mutexattr_init(&pthread_mutex_attr);
  19822. if (mutexattr_init == 0) {
  19823. failed = pthread_mutexattr_settype(&pthread_mutex_attr,
  19824. PTHREAD_MUTEX_RECURSIVE);
  19825. }
  19826. #endif
  19827. }
  19828. if (failed) {
  19829. #if defined(_WIN32)
  19830. if (wsa == 0) {
  19831. (void)WSACleanup();
  19832. }
  19833. if (file_mutex_init == 0) {
  19834. (void)pthread_mutex_destroy(&global_log_file_lock);
  19835. }
  19836. #else
  19837. if (mutexattr_init == 0) {
  19838. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19839. }
  19840. #endif
  19841. if (key_create == 0) {
  19842. (void)pthread_key_delete(sTlsKey);
  19843. }
  19844. mg_global_unlock();
  19845. (void)pthread_mutex_destroy(&global_lock_mutex);
  19846. return 0;
  19847. }
  19848. len = 1;
  19849. for (i = 0; http_methods[i].name != NULL; i++) {
  19850. size_t sl = strlen(http_methods[i].name);
  19851. len += sl;
  19852. if (i > 0) {
  19853. len += 2;
  19854. }
  19855. }
  19856. all_methods = (char *)mg_malloc(len);
  19857. if (!all_methods) {
  19858. /* Must never happen */
  19859. mg_global_unlock();
  19860. (void)pthread_mutex_destroy(&global_lock_mutex);
  19861. return 0;
  19862. }
  19863. all_methods[0] = 0;
  19864. for (i = 0; http_methods[i].name != NULL; i++) {
  19865. if (i > 0) {
  19866. strcat(all_methods, ", ");
  19867. strcat(all_methods, http_methods[i].name);
  19868. } else {
  19869. strcpy(all_methods, http_methods[i].name);
  19870. }
  19871. }
  19872. }
  19873. #if defined(USE_LUA)
  19874. lua_init_optional_libraries();
  19875. #endif
  19876. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1) \
  19877. || defined(OPENSSL_API_3_0)) \
  19878. && !defined(NO_SSL)
  19879. if (features_to_init & MG_FEATURES_SSL) {
  19880. if (!mg_openssl_initialized) {
  19881. char ebuf[128];
  19882. if (initialize_openssl(ebuf, sizeof(ebuf))) {
  19883. mg_openssl_initialized = 1;
  19884. } else {
  19885. (void)ebuf;
  19886. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  19887. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  19888. }
  19889. } else {
  19890. /* ssl already initialized */
  19891. }
  19892. }
  19893. #endif
  19894. if (mg_init_library_called <= 0) {
  19895. mg_init_library_called = 1;
  19896. } else {
  19897. mg_init_library_called++;
  19898. }
  19899. mg_global_unlock();
  19900. return features_inited;
  19901. }
  19902. /* Un-initialize this library. */
  19903. CIVETWEB_API unsigned
  19904. mg_exit_library(void)
  19905. {
  19906. if (mg_init_library_called <= 0) {
  19907. return 0;
  19908. }
  19909. mg_global_lock();
  19910. mg_init_library_called--;
  19911. if (mg_init_library_called == 0) {
  19912. #if (defined(OPENSSL_API_1_0) || defined(OPENSSL_API_1_1)) && !defined(NO_SSL)
  19913. if (mg_openssl_initialized) {
  19914. uninitialize_openssl();
  19915. mg_openssl_initialized = 0;
  19916. }
  19917. #endif
  19918. #if defined(_WIN32)
  19919. (void)WSACleanup();
  19920. (void)pthread_mutex_destroy(&global_log_file_lock);
  19921. #else
  19922. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  19923. #endif
  19924. (void)pthread_key_delete(sTlsKey);
  19925. #if defined(USE_LUA)
  19926. lua_exit_optional_libraries();
  19927. #endif
  19928. mg_free(all_methods);
  19929. all_methods = NULL;
  19930. mg_global_unlock();
  19931. (void)pthread_mutex_destroy(&global_lock_mutex);
  19932. return 1;
  19933. }
  19934. mg_global_unlock();
  19935. return 1;
  19936. }
  19937. /* End of civetweb.c */